Feb 19

Partially Instantiate Python Template Strings

"""
    Template Dictionary module
    
    An enhancement to python's template stuff.  At present you must supply all
    parameters to instantiate a string template.  We want to be able to 
    instantiate only the paramaters that we have right now, and leave the 
    others for instantiation later.
    
    Without TDict:
    
    >>> "%(greeting)s %(person)s"%{'greeting': 'Hello', 'person': 'World'}
    'Hello World'
    >>> "%(greeting)s %(person)s"%{'greeting': 'Hello'}
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'person'    
    
    This module provides class TDict (template dictionary) that, if you try 
    to read a non-existent key "keyname", returns "%(keyname)s".  Hence, it
    "passes through" any undefined names.
    
    >>> from TDict import *
    >>> a=TDict({})
    >>> a['a']='bibble'
    >>> a['a']
    'bibble'
    >>> a['b']
    '%(b)s'
    >>> "%(greeting)s %(person)s"%TDict({'greeting': 'Hello'})
    'Hello %(person)s'
    >>> tdict("%(greeting)s %(person)s",{'greeting': 'Hello'})
    'Hello %(person)s'
    
"""

class TDict(dict):
    
    def __init__(self,d={}):
        dict.__init__(self)
        for k in d.keys():
            self[k]=d[k]
    
    def __getitem__(self, key):
        try:
            return dict.__getitem__(self, key)
        except KeyError:
            return "%%(%s)s"%key

def tdict(template,dict):
    d=TDict(dict)
    return template%d


Feb 5

… and the python needed to get wordpress to show the code properly

#!/usr/bin/python

“”"
py2html

Prepare a python script for posting on a wordpress blog

USAGE:

py2html <mypython.py >myhtml.html

“”"

import sys,re

mapping=[
('&','&'),
("'",'''),
(' ',' '),
('"','"'),
('<','<'),
('>','>')
]

print [...]


Feb 5

Python Generator Example

#!/usr/bin/python

"""
    yield.py

    Demonstrates a recursive generator method.  This allows very large nested
    Container structures to be created, and when rendering to a string, we don't
    need to create the whole thing in memory (handy if, like me, you want to
    create 160,000 line XML files.
"""

class Container(object):
    def __init__(self, name, contents=[]):
        self.tag=name
        self.contents=contents
    def lines(self):
        """ Iterate over the text representing the Container and its contents. """
        # This is a generator function; really it returns an iterable object.  The
        # only reason you know this is that it contains the yield statement.  On
        # one hand, a nasty gotcha for the rookie pythoneer, on the other hand, a
        # lovely concise way of doing something you will want to do often.
        yield "<%s>"%(self.tag.upper())
        if isinstance(self.contents, str):
            yield self.contents
        else:
            for x in self.contents:
                if isinstance(x,Container):
                    for l in x.lines():
                        yield l
                else:
                    yield x
        yield "</%s>"%self.tag

# Declare a structure of nested Container objects
c=Container('HTML', [
    Container('HEAD', [
        Container('TITLE',[
            "The quick and the Dead"
        ])
    ]),
    Container('BODY', [
        "The quick, that's me, and the dead, that's you.",
        Container('Blockquote', "Ar wuz never wun te be hackin' about this here county")
    ]),
])

# Now write the structure's text representation out.
for l in c.lines():
    print "Line: %s"%l


Nov 23

Start new bash window in arbitrary location

This is a three-part solution to something I’ve always wanted to do but never applied myself to. Doubtless there will be a dozen better ways to do it that have remained hidden until I solved it myself.
The aim is to start a new bash session in a directory of your choice, but keeping all [...]


Dec 14

Love Sprouts!

I’ve got a Thing at the moment about loving our regular ingredients. British food is generally rubbish and Italian, French, American, Spanish, South American, African, Chinese, Thai, and Indian food are all great. Well I decided it probably wasn’t the ingredients. I decided it was probably the Brits’ attitude to food. [...]


Jul 22

Berk Chicken

This is my variant on Jerk Chicken, with a smoky, slightly toxic flavour, that I made tonight.
Ingredients:

Thyme
Garlic
Spring Onions
Vegetable Oil
Chili pepper
Allspice
Cinnamon
a Towel
Nutmeg
Black Pepper
Ginger
Lime Juice
Lots of water
Metal Saw
Bay Leaves
Axe
Angle Grinder
1lb of Chicken Breasts

Put the spring onions, oil, lime juice, ginger, herbs and spices in a blender and mix to a paste. Place the chicken breasts in [...]


Jan 20

Aubergine (Eggplant)

Yum! This is for my own future reference, dead simple, tasty and probably de-toxifying too. Serves two as a snack or starter.
* An aubergine
* 2 cloves garlic
* 4 outer leaves iceberg lettuce or equivalent
* Cherry tomatoes
* Balsamic Vinegar
* Olive Oil (make it a tasty extra virgin one!)
* Ryvita
Slice Aubergine, peel and chop the [...]


 

March 2010
S M T W T F S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031  

Archives

Meta