Importing from __future__ under the Python debugger pdb

This is mostly a short note about a question we encountered when planning a joint project with a company where students buy book reports so we decided to publish this information to help other programmers who end up looking for something like "why doesn't floating point division work in pdb".

Short version: the from __future__ import magic doesn't work in pdb.

Long version: when debugging a program that (a) runs under Python 2 and (b) relies on from __future__ import division to get floating point rather than integer division, it would be nice to have expressions typed at the pdb prompt behave the same way as expression evaluated in the file. However, this doesn't work:

$ python -m pdb test ...
more ...

Evolving strategies for an Iterated Prisoner's Dilemma tournament

Heads up to readers: this is a long article with lots of code samples and interactive charts. If you're reading on a mobile device, you might want to save this one until you can get to a wider screen! It may take a while to load all the charts.

Introduction

This is a longish post about using a simple evolutionary algorithm in Python to create a strategy for playing the famous Prisoner's Dilemma game (actually, the version known as Iterated Prisoner's Dilemma, hereafter referred to as IPD). If you're not already familiar with the Prisoner's ...

more ...

How dictionaries really work

Preface

This rather long post is my attempt to explain to novice programmers how hash tables work. A hash table is a data structure for storing key-value pairs and is part of the standard library of many languages. Depending on your language of choice, you might know hash tables as hashes, HashMaps, dictionaries, dicts, associative arrays, or symbol tables

If you're already familiar with hash tables, you'll probably spot many points in this post where I have either simplified things, or avoided talking about them entirely. If you think that any of these simplifications hinder rather than help ...

more ...

How to pick bad function and variable names

I teach a lot of beginner-targeted programming courses, and something that I've experimented with recently is trying to introduce the idea of self-documenting code early on in the learning process. I usually start off by talking about the difference between good and bad names for things (mostly functions and variables, though many of the same arguments apply to class names) , and I've noticed a few common patterns that tend to crop up in beginners code. I thought it might be useful to lay out these common errors in one place.

Single-letter names

OK, we're writing a program ...

more ...

How to use jQuery to send JSON data to a Grails app

This took me a while to figure out, so here it is for anyone else who’d like to know. Firstly, I was quite surprised to learn that jQuery doesn’t have a built in method for turning objects into JSON, so you’ll need the JSON parser/creator from json.org. Then you can write your javascript POST function using the jQuery ajax method. Here I’ve left the content type as text/plain, which is not strictly correct but works with the Groovy code.

function postTreeData(){
    $.ajax({
        type: "POST",
        url: "savedata",
        contentType : "text/plain",
        dataType: 'json',
        data: JSON ...
more ...

Radial transparent gradients in Processing.org

I’ve been playing around a bit with Processing.org – a kinda-graphical programming language. One of the effect that I wanted to play with was a kind of radial transparency – a blob of colour that faded out toward the edges. After playing around for a while with drawing multiple ellipses, I settled on a pixel-based subroutine.

We create a new PGraphics object to hold the blob, then for each pixel calculate the distance from the centre as a proportion of the radius using the handy Math.hypot() method. Then, to get nice smooth fade-outs near the edges, we invert it ...

more ...

Hibernate magic with lazy evaluation

I’ve just run across this phenomenon for the first time and it turns out that hibernate can be even lazier than I thought! To illustrate lets use this time-honoured example in Grails.

Here are our domain objects:

class Book {  
    String title  
    static belongsTo = [author : Author]  
    static constraints = {  
    }  
}  
class Author {  
    String name  
    static hasMany = [books : Book]  
    static constraints = {  
    }  
}

and we’ll add some sample data in our bootstrap.groovy:

def init = { servletContext ->  
    def alice = new Author(name: 'alice').save()  
    def book1 = new Book(title: 'book1')  
    def book2 = new Book(title: 'book2')  
    alice.addToBooks(book1)  
    alice.addToBooks(book2)  
}

Now we’ll ...

more ...

Functional Abstraction examples from SCIP in Groovy

I've been checking out the legendary MIT Structure and Interpretation of Computer Programs course from 1986 on YouTube, and it's fascinating for many reasons, not least the hypnotic synthesized Bach that bookends each lecture. I don't think I will ever be able to hear Jesu, joy of man's desiring again without seeing that purple wizard. What's really striking to me is how quickly the course gets into territory that I (coming from a self-taught Perl/Java background) think of as pretty advanced. In the first three lectures we are introduced to:

  • Recursive subroutines
  • big-O notation ...
more ...

Extending Java number classes with random functions in Groovy

Recently I’ve been playing around quite a bit with Processing.org, and one of the things that I often want to do is add a bit of noise to variables that represent positions, sizes, colours, etc. Most of the Processing functions that actually draw something (like lines, ellipses, etc) take their arguments in the form of floats, but most floating number operations in Java/Groovy return BigDecimal data types so we have to use casts a lot. Also, there’s no concise way to get a floating random number in a certain range that can be either negative or ...

more ...

Beware of the default acegi Grails plugin setup

This is firmly in the “putting it up here just in case anyone else has the same problem” category. There is a gotcha that bites when writing a Grails application that uses the acegi security plugin along with a postgresql database as the data source. The problem is that the acegi plugin will, by default, create a domain class with the name User. When you try to run the application with a postgresql datasource, GORM will try to create a table with the name user, which postgresql will not like as it is a reserved word.

This is a particularly ...

more ...