WordPress for Programmers & My New Theme

Overall

WordPress for Programmers & Coders: Advice, Themes & Plugins.

Themes

google:  best free wordpress themes for programmer

webdesignerdepot

Now I use: “Silver is the New Black” – Silver is the New Black. Howdy! This theme, Silver is the New Black, is now retired.

I am going to try these until i get one i like. But first

google how to backup my wordpress.com blog

I am now doing Download your content

I Choose the New Theme

[copied from my notes in MS Word]:

webdesignerdepot

·         OneColumn

·         White Paper

·         WP Jurist

·         Best Theme

None of the above show up for free in wordpress.com

I try

·        TRVL – it’s OK [too dark, nice and wide & big]

·        Truly Minimal – seems better than TRVL – I like it – my pic shows up – Python Notes page might be a bit goofy ala code – kind of OK

·        Ryu – TOO BIG – NO MAYBE

·        Superhero – not bad – goofy black bar follows down NG!– Truly Minimal is better

·        Responsive – Feature-full theme with numerous page layouts, widget areas, custom menu areas, breadcrumb naviagtion, a homepage template, social icons, and responsive CSS. PRETTY GOOD

·        Forever – I am using this in the web2py book – not for here

·        White as Milk – NO GOOD

·        Sapphire – bad paragraph spacing like my present theme

·

between Responsive & Truly Minimal

Responsive – looks confused with my formatting

Truly Minimal – looks less confused with my formatting

I choose Truly Minimal

Result – Better than a jab in the eye with a sharp stick. The pages aren’t compact enough top to bottom.

#programming, #wordpress

My Python Idioms

Here are some Python links and idioms.

Python Links

recipes , pyDocs , DiveIn, FredrikLundh , FredrikLundhPython
wiki, examples, community, questions
idioms.colorado.edu, idioms.c2.com, idioms.python.org, idioms.caltech
samples.python.org.moin, samples.wikibooks.org, samples.python.org.doc
bruce.eckel.artima, bruce.eckel.lovePython, bruce.eckel.TIPython

Python Idoms

class

class BankAccount(object):
    def __init__(self, initial_balance=0):
        self.balance = initial_balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount
    def overdrawn(self):
        return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance

looping dicts

for k, v in knights.iteritems():
  print k, v

looping enumerated sequences

for i, v in enumerate(Seq):
  print i, v

dict from k v lists

dict(zip(keyList, valList))

dict from k v strings

dict(zip(keyStr.split(' '), valString.split(' ')))

dict from obj attribs

dict((name, getattr(ob, name)) for name in dir(ob) if not name.startswith('__'))

concat strings 1

''.join([xStr, yStr])

concat strings 2

xStr = ''.join([xStr, yStr])

map 1

seq = range(10)
def cube(x): return x*x*x
map(cube, seq)

map 2

seq = range(10)
def add(x, y): return x+y
map(add, seq, seq)
reduce
seq = range(10)
def add(x, y): return x+y
reduce(add, seq)
list 2 string
s = ''.join(L)
list creations
iota=range(5)
zeros=[0]*5
foos=['foo']*8
L=[0,1,2] + [3,4]
four=L[-1]
three=L[-2]
zero_1=L[:2]
two_3_4=L[2:]
one_2_3=L[1:4]
del(L[1])
listoflists=[ [0]*4 ] *5
listoflists=[[0]*4 for i in range(5)]
list comprehension [simple]
vec = [2, 4, 6]
[3*x for x in vec]
list comprehension [if]
vec = [2, 4, 6]
[3*x for x in vec if x > 3]
list comprehension [list]
vec = [2, 4, 6]
[[x,x**2] for x in vec]
list comprehension [dict]
l1=1,2,3,4,5; l2=6,7,8,9,0
dict([(k, v) for k,v in zip(l1,l2)])
# {1: 6, 2: 7, 3: 8, 4: 9, 5: 0}
list comprehension [v1, v2]
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
# rightmost for varies first
# [8, 6, -18, 16, 12, -36, 24, 18, -54]

list comprehension [tuples l1, l2]
l1=1,2,3; l2=6,7,8
[{x:y} for x in l1 for y in l2]
# rightmost for varies first
# [{1: 6}, {1: 7}, {1: 8}, {2: 6}, {2: 7}, {2: 8}, {3: 6}, {3: 7}, {3: 8}]
list comprehension [nested]
mat = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
      ]
[[row[i] for row in mat] for i in range(len(mat[0]))]
# Above list comprehension inverts the matrix
# :)To avoid apprehension when nesting list comprehensions,
#    read them from right to left. :)
zip
x = ['1', '2', '3']
y = ('4', '5', '6')
z = "789"
zip(x, y, z)
# [('1', '4', '7'), ('2', '5', '8'), ('3', '6', '9')]
# returns a list of tuples, where the i-th tuple contains the i-th
#   element from each of the argument sequences or iterables.
readFile2String
f = open('c:/', 'r') #on windows add 'b'==binary
s = f.read()
f.close()
readFile2String 1 liner
f = open('c:/test.txt', 'r'); s = f.read(); f.close()
readLines 1 liner
for line in file('fileName.txt').readlines():
readLines
f = open('c:/', 'r') #on windows add 'b'==binary
for line in f:
  # process(line)
f.close()
writeString
f = open('c:/', 'w') #on windows add 'b'==binary
f.write('This is a test\n')  # newline is NOT automatically added!
f.close()
writeString 1 liner
f = open('c:/', 'w'); f.write('This is a test\n'); f.close()
cd
import os
os.chdir(r"C: d\GoogleDev ppEnginePjs")
pwd
import os
os.path.abspath(os.curdir)
string replace
s = 'spam bacon ham spam ham bacon spam'
s.replace('spam', 'eggs',1) #one
s.replace('spam', 'eggs')   #all
string2list
L = list(s)
string2list [split]
L = s.split('#')
sorted dict print formatted
cnid = chordNameIntervalDict= {
    'maj':    (0,  4,  7),
    'min':    (0,  3,  7),
    'aug':    (0,  4,  8),
    'dim':    (0,  3,  6),
    'sus2':   (0,  2,  7),
    'sus4':   (0,  5,  7),
    '6':      (0,  4,  7,  9),
    'm6':     (0,  3,  7,  9),
    '7':      (0,  4,  7, 10),
    'maj7':   (0,  4,  7, 11),
    'm7':     (0,  3,  7, 10),
    'dim7':   (0,  3,  6, 10),
    }

#make the keys be the vals and the vals the keys
icnd = intervalChordNameDict = dict([(cnid[k],k) for k in cnid.keys()])

chordNameL = 'maj,min,aug,dim,sus2,sus4,6,m6,7,maj7,m7,dim7'.split(',')

print 'cnid'
for k in chordNameL:
    print ('%7s %s')%(str(k),str(cnid[k]))

print 'icnd'
for k in sorted(icnd):
    print ('%-16s %s ')%(k, icnd[k])
enum_string 2 dict
enum_string = es = "state, county, city_state, city_name, city_url"
ed = dict(zip(es.split(", "), range(len(es))))
print ed
{'county': 1, 'city_name': 3, 'state': 0, 'city_url': 4, 'city_state': 2}
try except
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
cgi
#!/usr/bin/env python
# from: http://webpython.codepoint.net/cgi_file_upload
import cgi, os
import cgitb; cgitb.enable()

try: # Windows needs stdio set for binary mode.
    import msvcrt
    msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
    msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
    pass

form = cgi.FieldStorage()


def upload():
    """ upload the file into files/ """
    fileitem = form['file']

    # Test if the file was uploaded
    if fileitem.filename:
       
       # strip leading path from file name to avoid 
       #    directory traversal attacks
       fn = os.path.basename(fileitem.filename)
       open('files/' + fn, 'wb').write(fileitem.file.read())
       message = 'The file "' + fn + 
               '" was uploaded successfully'
       
    else:
       message = 'No file was uploaded'
       
    print """\
    Content-Type: text/html\n
    
    %s
    
    """ % (message,)

def main():
    #cgi.test()
    message = 'from main
' for k in form.keys(): if k != 'file': message = ''.join([message, k+': '+form.getvalue(k)+'
']) print """\ Content-Type: text/html\n %s """ % (message,) main()

var lastId = 36;

function dr(id){
// http://www.javascriptf1.com/tutorial/javascript-hide-table-row.html
var row = document.getElementById(id);
if (row.style.display == ”)
row.style.display = ‘none’;
else
row.style.display = ”;
}
function collapseAll(){
//alert(lastId)
for(id=0;id<=lastId;id++){
var row = document.getElementById(id);
row.style.display = 'none';
}
}
function expandAll(){
//alert(lastId)
for(id=0;id<=lastId;id++){
var row = document.getElementById(id);
row.style.display = '';
}
}
collapseAll()

#idioms, #programming, #python

App Engine MVC

I just scratched an itch to break out the App Engine Guestbook Tutorial into what satisfies me as a simple MVC framework (file/directory structure). The main benefit is to do data hiding on the model and controller (handler) classes to get them into different modules and so improve readability for me.

Small Changes

  • Figuring out the imports was a bit tricky.
    There may be a better way but this worked.
    GuestbookM.py (the Guestbook Module) contains the class Guestbook, etc..
  • In class MainPage
    NOW:
    path = os.path.join(os.path.dirname(file), ‘../v/templates/MainPage.html’)
    WAS:
    path = os.path.join(os.path.dirname(file), ‘index.html’)

  • I used the guestbook6_templates.py version available here. The index.html file is now in MainPage.html. The app name is jmvc. Here is the file structure:

jmvc/
    c/
        __init__.py
        GuestbookM.py
        MainPageM.py
    m/
        __init__.py
        GreetingM.py
    v/
        stylesheets/
            main.css
        templates/
            MainPage.html
            __init__.py
    app.yaml
    main.py

All init.py files are blank. As I said before MainPage.html is the same as index.html in the non MVC code. Here is the source for each of the remaining files :

# app.yaml

application: jmvc
version: 1
runtime: python
api_version: 1

handlers:

- url: /v/stylesheets
static_dir: v/stylesheets

- url: /.*
script: main.py

# main.py

import cgi
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from c import MainPageM
MainPage = MainPageM.MainPage

from c import Guestbook
Guestbook = GuestbookM.Guestbook

application = webapp.WSGIApplication(
    [('/', MainPage),
    ('/sign', Guestbook)],
    debug=True)
def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

# GuestbookM.py

from google.appengine.ext import webapp
from google.appengine.api import users

from m import GreetingM
Greeting = GreetingM.Greeting

class Guestbook(webapp.RequestHandler):
def post(self):
    greeting = Greeting()

    if users.get_current_user():
        greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')


#MainPage.py


from google.appengine.ext import webapp
from google.appengine.api import users
import os
from google.appengine.ext.webapp import template

from m import GreetingM
Greeting = GreetingM.Greeting


class MainPage(webapp.RequestHandler):
def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
    else:
        url = users.create_login_url(self.request.uri)
        url_linktext = 'Login'

template_values = {
    'greetings': greetings,
    'url': url,
    'url_linktext': url_linktext,
}

path = os.path.join(os.path.dirname(__file__), 
    '../v/templates/MainPage.html')
    self.response.out.write(template.render(path, 
    template_values))

# GuestbookM.py

from google.appengine.ext import webapp
from google.appengine.api import users

from m import GreetingM
Greeting = GreetingM.Greeting

class Guestbook(webapp.RequestHandler):
    def post(self):
        greeting = Greeting()

    if users.get_current_user():
        greeting.author = users.get_current_user()
        greeting.content = self.request.get('content')
        greeting.put()
        self.redirect('/')

# MainPage.py


from google.appengine.ext import webapp
from google.appengine.api import users
import os
from google.appengine.ext.webapp import template

from m import GreetingM
Greeting = GreetingM.Greeting


class MainPage(webapp.RequestHandler):
    def get(self):
        greetings_query = Greeting.all().order('-date')
        greetings = greetings_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

template_values = {
    'greetings': greetings,
    'url': url,
    'url_linktext': url_linktext,
}

path = os.path.join(os.path.dirname(__file__), 
    '../v/templates/MainPage.html')
    self.response.out.write(template.render(path, 
    template_values))


# GreetingM.py


from google.appengine.ext import db
from google.appengine.api import users

class Greeting(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)


# main.css

body {
    font-family: Verdana, Helvetica, sans-serif;
    background-color: #DDDDDD;
}

Please comment.

Thanks.
Love and peace,
Joe 🙂

#google-app-engine, #mvc, #programming