If you’re getting the following error when trying to activate an account using Django 1.4 and django-registration:

can't compare offset-naive and offset-aware datetimes

Then you need to update the source of django-registration manually.

The error file will tell you exactly what file to edit. In this case we need to edit:

registration/models.py

the full path to my file was:

/usr/local/lib/python2.6/dist-packages/registration/models.py

The next step is to import new timezone support:

from django.utils.timezone import utc

Next go to the bottom of the file, and find:

return self.activation_key == self.ACTIVATED or \
    (self.user.date_joined + expiration_date <= datetime.datetime.now())

And replace with:

 return self.activation_key == self.ACTIVATED or \
    (self.user.date_joined + expiration_date <= datetime.datetime.utcnow().replace(tzinfo=utc)) 

That should work now!

This is only a hack. I'm not even sure if it's correct. So if you do come across this and you can do better, please let me know.

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·

As you should know, the Django team released has released version 1.4 

My servers are running on Ubuntu, and to upgrade all I needed to do was use setup-tools:

easy_install --upgrade django

This will find Django 1.4 and upgrade your current version for you.

To check what version you’re currently running:

django-admin --version

Tags: , , , ,

· · · ◊ ◊ ◊ · · ·

I hacked together this basic script to detect faces in images using OpenCV, Python, Web.py and ImageMagick. It’s a fun wee learning experience.

At the moment it tries to replace a face with an image. Some more tweaking, and it should be good to go. :)

To run it:

import web, sys, os, subprocess, uuid
from opencv.cv import *
from opencv.highgui import *
from shutil import copy

def detectObjects(image, imagefile):
  """Converts an image to grayscale and prints the locations of any
     faces found"""
  grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
  cvCvtColor(image, grayscale, CV_BGR2GRAY)

  storage = cvCreateMemStorage(0)
  cvClearMemStorage(storage)
  cvEqualizeHist(grayscale, grayscale)
  cascade = cvLoadHaarClassifierCascade(
    '/usr/share/doc/opencv-doc/examples/haarcascades/haarcascades/haarcascade_frontalface_default.xml.gz',
    cvSize(1,1))
  faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2,
                             CV_HAAR_DO_CANNY_PRUNING, cvSize(50,50))

  if faces.total > 0:
    for f in faces:
        print("found a face: [(%d,%d) -> (%d,%d)]" % (f.x, f.y, f.x+f.width, f.y+f.height))
        foundFace(imagefile, f)
  return faces.total

def foundFace(imagefile, f):
    #os.system("convert {image} -stroke red -fill red -draw \"rectangle {a},{b} {c},{d}\" {output}".format(
    os.system("convert {image} -draw \"image SrcOver {a},{b} {c},{d} biglazer.png\" {output}".format(
                    image=imagefile,
                    a=f.x+6,
                    b=f.y,
                    c=f.width,
                    d=f.height,
                    output=imagefile));

urls = (
    '/upload', 'Upload',
)

class Upload:
    def GET(self):
        web.header("Content-Type","text/html; charset=utf-8")
        return """<html><head><link rel="shortcut icon" href="/static/favicon.ico"
type="image/x-icon"></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="myfile" />
<br/>
<input type="submit" />
</form>
</body></html>"""
    def POST(self):
        x = web.input(myfile={})
        filedir = '/home/mike/python/uploads' # change this to the directory you want to store the file in.
        if 'myfile' in x: # to check if the file-object is created
            filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
            #filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
            filename = str(uuid.uuid4())
            fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
            fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file.
            fout.close() # closes the file, upload complete.
            # detect face
            imagefile = filedir +'/'+ filename;
            image = cvLoadImage(imagefile);
            unique_name = str(uuid.uuid4())
            output_path = '/home/mike/python/static/%s.png' % unique_name
            if (detectObjects(image, imagefile) > 0):
                copy(imagefile, output_path)
                web.redirect("static/%s.png" % unique_name)
            else:
                return """No face found."""
        raise web.seeother('/upload')

if __name__ == "__main__":
   app = web.application(urls, globals(), True)
   app.run()

There are some problems – it doesn’t like bitmap (*.BMP) nor cartoon type images. Here are some examples of images that worked:

Tags: , , , , , , , ,

· · · ◊ ◊ ◊ · · ·

Pygame vs love2d

29 Dec 2010

The pygame vs love2d debate is a new one. They both specialise in 2d and are fast at pumping out games.

I started making a few games in pygame.

  • python language is great, and has many libraries
  • python is more object-oriented and popular (finding help is easy)
  • medium – large games are best made in pygame
The new kid on the block, love2d has some good points too:
  • distribution is easier
  • coding in lua is faster
  • love2d’s API is better
  • love2d is being updated
I love2d is the winner. Especially if you’re participating in a gamejam. However, if you’re making a more serious game, make it in pygame. You’ll run into less trouble, as coding OO in lua is a bit finicky. I also noticed there are some garbage collection issues, this should be fixed soon (as of this writing love2d is at v.7)

Tags: , ,

· · · ◊ ◊ ◊ · · ·

Inspired by this article, I got thinking about the overall effectiveness of my programming methods.

Component modeling is far better.

I started prgramming python just after irrlicht (c++), which promoted tight hierarchies:

Game programmers quickly will notice there’s limitations with the traditional OOP method. Too much code ends up in the core object.

Notice how the behaviour overlaps unrelated OO objects (eg player and little monster). You can inherit from a core object, and override it for all other objects – but it soon grows too big. Everyone hates digging through a 10k line file, especially working with multiple people.

What I did was experiment with a component class , and a component Collection class . This creates solder, gives it behavour that can be reused:

class Solder (ComponentCollection):
    def __init__(self):
    components = [
        ComponentChase(player),
        ComponentShoots(Laser),
        ComponentASearch(),
        ComponentRunAway(20),
        ComponentTakeDamage()
    ]
    Component.__init__(self, components)

By defining the objects behaviour right away, instead of obfuscating it in large functions, we can see instantly what the solder does. Defining small chuncks of behaviour in components leads to quicker debugging.

The componentCollection will rearrange the components, according to the components definition. Example: ASearch must happen before Chase, so will be rearranged before it in the loop.

Tags: ,

· · · ◊ ◊ ◊ · · ·