2009
08.16

A man flying in a hot air balloon suddenly realizes he’s lost. He reduces height and spots a man down below. He lowers the balloon further and shouts to get directions, “Excuse me, can you tell me where I am?”

The man below says: “Yes, you’re in a hot air balloon, hovering 30 feet above this field.”

“You must work in Information Technology,” says the balloonist.

“I do” replies the man. “How did you know?”

“Well,” says the balloonist, “everything you have told me is technically correct, but It’s of no use to anyone.”

The man below replies, “You must work in management.”

“I do” replies the balloonist, “But how’d you know?”

“Well”, says the man, “you don’t know where you are, or where you’re going, you expect me to be able to help. You’re in the same position you were before we met, but now it’s my fault.”

2009
08.07

“Give a person a fish and you feed them for a day. Teach that person to use the Internet and they won’t bother you for weeks”

2009
08.06

I’ve been using Dia for ages, but it always had this annoying “feature” that the drawing controls and the drawing window would be in two different GUI windows, here’s a pic: Old Dia window layout
In theory this sounds great as you can move the windows around separately, in practice it sucks. They finally adopted a tabbed approach with everything in the same window: New Dia window layout
And there was much rejoicing.

2009
08.06

1. Walk out.
2. Go up to a person that looks busy.
3. Talk to the person, and follow him/her.
4. If the person walks through a door that can be locked, make sure you get your foot in.
5. Continue talking to the person.
6. If the police shows up, follow them instead.
7. Talk to the police.
8. Follow the police.
9. If the police walks through a door that can be locked, make sure you get your foot in.
10. If you get locked into a room, wait.
11. Go to 1.

2009
08.06

I’m listening to stackoverflow podcast #52 and Joel Spolsky just gave the best explanation of the difference between the Subversion / CVS generation of version control and the new Mercurial / Git / Distributed Version Control, the important part is bolded.

So this is why everybody is abandoning those version control systems that are of the Subversion generation and they’re moving to Mercurial and Git, and, to a lesser extent, the other distributed systems. There’s something that took me a while to understand about Mercurial, but fundamentally Mercurial is – Mercurial thinks of the world as a list of changes, and Subversion thinks of the world as a list of different versions of all your files. And so for Subversion to figure out where you are on a branch to do the merge, all it can do really is do a diff and say ‘well, I don’t know what happened, but the following things – we’re different from you guys in the following ways’, whereas Mercurial has this sort of added info of all the steps that were taken and all the transformations that were done, so it basically has more information to use in the merge and making the merge successful.

2009
08.05

Moved blog

So my last host crashed, after about two months of trying to get my posts back I managed to get *some* of them back at least, but the ones requiring files and images from the old host are useless since I couldn’t save any of the uploaded content.

I also changed my domain since I got my first+lastname under .com after about two years of waiting. Anyway, I’ll pick up blogging soon again.

2009
03.07

Should be self explanatory

def render(tag):
    if not tag:
        return ""
    else:
        if isinstance(tag, str):
            return tag
        else:
            if len(tag) > 1 and isinstance(tag[1], dict):
                return render_tag(tag[0], tag[1], tag[2:])
            else:
                return render_tag(tag[0], None, tag[1:])

def render_tag(tag, attrs, children):
    if not children:
        return "<%s%s/>" % (tag, render_attrs(attrs))
    else:
        return "<%s%s>%s" % (tag, render_attrs(attrs), "\n".join(map(render, children)), tag)

def render_attrs(attrs):
    return "" if not attrs else " " + " ".join(['%s="%s"' % pair for pair in attrs.items()])

if __name__ == "__main__":

    # example

    html =  ("html",
                ("head",
                    ("title", "this is my title"),
                    ("meta", {"name":"keywords", "value":"python, html"}),
                    ("meta", {"name":"description", "value":"outputting html from python dsl"}),
                    ("script", {"src":"static/js/jquery-1.3.2.min.js"}, None) # None forces open
                ),
                ("body",
                    ("div", 

                    )
                )
            )

    print render(html)

Output from the example is something like this:

<html>
    <head>
        <title>this is my title</title>
        <meta name="keywords" value="python, html"/>
        <meta name="description" value="outputting html from python dsl"/>
        <script src="static/js/jquery-1.3.2.min.js"></script>
    </head>
    <body>
        <div/>
    </body>
</html>
2009
03.03

My second (and much nicer) version of a tail call optimization trampoline in python

class recur(object):
    def __init__(self, *args):
        self.args = args

    def __call__(self, func):
        return Inner(func)

class Inner(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args):
        result = recur(*args)
        call   = self.func

        while True:
            result = call(*result.args)

            if isinstance(result, recur):
                if result.args and isinstance(result.args[0], Inner):
                    call = result.args[0].func
                    result.args = result.args[1:]
            else:
                return result

        return result

if __name__ == "__main__":

    # recursively sums a list of integers
    # calling itself for each item

    @recur()
    def req_sum(lst, n=0):
        return n if not lst else recur(lst[1:], n+lst[0])

    print req_sum([1,2,3,4])

    # You can also recurse
    # with another function
    # here you have ping and pong
    # calling eachother forever

    pings = 0
    pongs = 0

    @recur()
    def ping(n=0):
        global pings
        print "pong ponged %d times, now I'll ping" % n
        pings += 1
        return recur(pong, pings)

    @recur()
    def pong(n):
        global pongs
        print "ping pinged %d times, now I'll pong" % n
        pongs += 1
        return recur(ping, pongs)

    # if you uncomment this next statement and
    # run the code it will loop forever  

    #ping()

Again, self explanatory.

2009
01.23

First of all: Last time I used Django was well over a year ago so if this is already possible to do with the current latest code base then shame on me, anyway – after messing around a bit with Django I got annoyed by the simplicity of the views, they’re very simple minded. I wanted some way of calling different functions depending on the request method and an easier way to return different output types, this is what I came up with.

The idea is simple, use a class with __call__ implemented instead of a function, within __call__ you can put custom logic to direct the requests to the appropriate callbacks – here’s my new base view class and a helper decorator (since Python 2.6 you can decorate classes).

def view(cls):
	return cls()

class ClassView(object):

	fallback = "HTML"

	http_accept = {
		"application/xhtml\+xml": "HTML",
		"text/html":"HTML",
		"application/json": "JSON",
		"text/javascript": "JSON",
		"application/xml": "XML"
	}

	request_method = {
		"GET": "READ",
		"POST": "WRITE",
		"PUT": "WRITE",
		"DELETE": "WRITE"
	}

	def __call__(self, request):
		accept = request.META["HTTP_ACCEPT"]
		method = getattr(self, self.request_method[request.META["REQUEST_METHOD"]])

		for regex, call in self.http_accept.items():
			if regex and re.search(regex, accept):
				return getattr(self, call)(request, method(request))

		return getattr(self, self.fallback)(request, method(request))

	def READ(self, request):
		pass

	def WRITE(self, request):
		pass

	def JSON(self, request, method_vars):
		pass

	def HTML(self, request, method_vars):
		pass

	def XML(self, request, method_vars):
		pass

Now when I want to create a new view in django, instead of doing something like this:

def index(request):
     # blah

I do this:

# for python < 2.6 remove/comment out this next line:
@view
class index(ClassView):

	def READ(self, request):
		return {"title": "Hello World!"}

	def HTML(self, request, method_vars):
		return render_to_response("frontend/index.html", method_vars)

	def JSON(self, request, method_vars):
		return HttpResponse('{"title":"%(title)s"}' % method_vars)

# for python < 2.6 uncomment the next line
# index = view(index)

The READ method will be called on all GET requests, while the WRITE method will be called on all POST, PUT and DELETE. After which the appropriate output method will be selected based on the HTTP Accept header. This allows me to group common functionality in READ for all GET requests to one URL and then still be allowed to do output specific (HTML, XML, JSON, etc.) logic and template rendering based on what content types the client accepts (for example I will probably need to load more objects for HTML output since it usually has a rather advanced layout compared to say JSON which probably only wants to return the object collection as JSON string)

2008
10.18

This might be a somewhat unorthodox usage of python decorators, but a very practical and nice one – I got a question on IRC from a friend that wanted to store python functions in a dictionary and was complaining that there is no way to use lambdas in python as anonymous closures because of their limitations and the syntax of: def func(): pass; dict["func"] = func; is ugly, and I agree – so here’s a nicer version utilizing an extension of the built in dict-class:

class MyDict(dict):
  def __call__(self, func):
    self[func.__name__] = func

foo = MyDict()

@foo
def bar(arg):
  print "from bar %s" % arg

foo["bar"]("Hello World!");

The idea and usage is simple: Extend the built in dict class with a subclass that is turned into a decorator, this decorator then stores every function it decorates inside it’s own dictionary.

Simple, practical and elegant.