Posts de December, 2012

[Igor Sobreira] Unnecessary classes

Monday, December 31st, 2012

Today I opened a python module that made me feel sad. It has two classes: one of them has 4 methods, all of them static, and no attributes; the other has only one method: __init__, and 5 attributes.

Why people still write classes like these?

Use functions

…instead of classes with just static methods. If you have this class just to group the functions in a common namespace then create a new module (.py file), this is how python organize namespaces, and it’s good, use it!

Here is the first class I saw today

class Buttonate(object):

    def find_files(quiet=False):
        # ...

    def find_links(files):
        # ...

    def buttonate(buttons, overwrite=False, quiet=False):
        # ...

    def link_parser(file):
        # ...

and here is how I would rewrite it:

def buttonate_find_files(quiet=False):
    # ...

def buttonate_find_links(files):
    # ...

def buttonate_buttonate(buttons, overwrite=False, quiet=False):
    # ...

def buttonate_link_parser(file):
    # ...

I usually just start creating the functions I need, and if I get to this point where I have multiple functions doing related work I just create a module and move them there:

# new file:

def find_files(quiet=False):
    # ...

def find_links(files):
    # ...

def buttonate(buttons, overwrite=False, quiet=False):
    # ...

def link_parser(file):
    # ...

Use builtin data structures

…instead of attributes-only-classes. Here is the other class I saw today:

class ButtonLink(object):
    def __init__(self, matchobject, l):
      self.__dict__ = matchobject.groupdict() =
      self.size = int(self.size)
      self.colors = self.colors[1:].split(".")
      self.line = l

This is a class being used similar to a struct in C. We could use a dictionary here, and a factory function doing the work __init__ is doing in this example:

def create_button_link(matchobject, line):
    button_link = matchobject.groupdict()
        'size': int(button_link['size']),
        'colors': button_link['colors'][1:].split("."),
        'line': line
    return button_link

Dictionaries are fast, well designed and are always being improved by smart people.

Another interesting builtin data structure is namedtuple. And it has a clever implementation, you should check it out :)

One rule I follow when using dictionaries like the example above is to always modify them with specialized functions. You’ll end up with well defined structures and modules that know how to build and manage these structures inside your application.

What I’m suggesting here is actually the opposite of OO, instead of writing a class with state and methods, keep the state on dictionaries (or tuples, lists, sets) and write functions to manipulate the state. I’ve been using this approach much more that classes lately.


Stop writing classes is a great talk by Jack Diederich at PyCon 2012, showing examples where classes are overused.

[Tiago Peczenyj] Spell Correct in GNU AWK

Saturday, December 29th, 2012

Based on Peter Norvig Spell Correct

# Usage: gawk -v word=some_word_to_verify -f spelling.awk [ big.txt
[ big2.txt ... ]]
# Gawk version with 15 lines -- 04/13/2008
# Author: tiago (dot) peczenyj (at) gmail (dot) com
# Based on :
function edits(w,max,candidates,list,        i,j){
       for(i=0;i<  max ;++i) ++list[substr(w,0,i) substr(w,i+2)]
       for(i=0;i< max-1;++i) ++list[substr(w,0,i) substr(w,i+2,1)
substr(w,i+1,1) substr(w,i+3)]
       for(i=0;i<  max ;++i) for(j in alpha) ++list[substr(w,0,i)
alpha[j] substr(w,i+2)]
       for(i=0;i<= max ;++i) for(j in alpha) ++list[substr(w,0,i)
alpha[j] substr(w,i+1)]
       for(i in list) if(i in NWORDS) candidates[i] = NWORDS[i] }

function correct(word            ,candidates,i,list,max,temp){
       if (!asort(candidates,temp)) for(i in list)
       return (max = asorti(candidates)) ? candidates[max] : word }

BEGIN{ if (ARGC == 1) ARGV[ARGC++] = "big.txt" #
       IGNORECASE=RS="[^"x"]+" }

{      ++NWORDS[tolower($1)]   }

END{   print (word in NWORDS) ? word : "correct("word")=> "
correct(tolower(word)) }

[Tiago Peczenyj] hello

Saturday, December 29th, 2012

Hello World!

[Andrews Medina] Usando splinter em ambientes sem display

Thursday, December 27th, 2012

Splinter é uma ferramenta para automatizar ações de navegadores web. Você pode usar ele para escrever testes, crawlers e etc. Com o splinter você pode rodar o mesmo código em vários navegadores diferentes.

A maioria desses navegadores como o firefox, chrome necessitam de um display para funcionarem. Então, se você tentar usar o splinter para executar ações no firefox em um ambiente sem display você vai se deparar com o seguinte erro:

Error: no display specified

Se você estiver usando linux existe um projeto chamado xvfb que permite que você crie displays virtuais. Para que o splinter com firefox ou chrome funcione em um ambiente sem display, basta instalar o xvfb e usar ele para criar um display virtual.

Para fazer isso no ubuntu, primeiramente instale o xvfb:

$ [sudo] apt-get instal xvfb

Agora vamos criar um display chamado :99

Xvfb :99 &

E exportar uma variável de ambiente que informe o número do display a ser utilizado

export DISPLAY=:99

Assim é possível usar o splinter normalmente!

[Bernardo Heynemann] – a story of fun, iterative development and a boatload of javascript

Sunday, December 2nd, 2012 is a game where you use your javascript skills to code a robot that goes into an arena against other robot.

It’s a project for the Github Game-Off 2012 contest. It’s a different kind of hacking contest, in that you have a month instead of a day, two or a week.

It might seem like a minor detail, but it makes all the difference. At least it did for our team. We worked it like we would any other iterative project we might work with at our daily jobs.

The team is composed by myself, Cezar Sá, Guilherme Souza, Fábio Costa and Rafael Carício as devs. The incredible designer Marcela Abbade did the layout for our product.

A small team set for building a product that we didn’t actually believe could be built in such a small timeframe.

TL;DR was developed iteratively and uses Javascript for both client and server.

We run node.js at it’s serverside components and the code for the engine is EXACTLY the same running in the browser or the server.

This was the first time I actually benefitted from running the same Javascript in the server and the client, so I found it interesting enough to share. The code can be found at

How did you come up with the idea for it?

As all such ideas begin: in a table with friends. Someone said: “What if we did an arena where robots fought each other and you did the robot coding with javascript?”.

We all laughed like “yeah like that’s possible”, but the idea started growing on us. A couple months later and here we are.

Some Stats

Before I start I’d like to share some stats with you, because I’m actually very impressed with them.

At the time of this post, we have in the database more than 1500 fights.

Since we launched the website at 4pm of the 28th of November (date of the first fight in the database), that means roughly 14 fights an hour. It’s A LOT more than we expected.

We also have more than 200 people registered and above 150 robots created. Amazing, right?

What REALLY got me, though, is our stats in Google Analytics:

  • About 1000 visits in just a couple days;
  • About 500 unique visitors;
  • More than 11 thousand page views;
  • An incredible average page duration of 11 minutes;
  • Bounce rate of 30%, which means that most people entering the website navigate through it.

I gotta say that again - 11 thousand page views. Even if that counts our own page views, it’s still amazing in a couple days.

You said iterative?

Yep, we worked VERY iteratively. First, we didn’t have anything. Then we had the engine. And then we had the animation.

We spent the whole month of the project iterating and improving over the previous iteration.

And you know what? Iterative development CAN be fun. People spoil all the fun with metrics, meetings and other useless bureaucracy.

What about the game?

Well, the game is pretty simple. Build you robot, we’ll run your code against the other person’s code and see who wins. The easiest way is to go there and play a little bit.

What’s really interesting about it is how we calculate things and how we render the fight in the browser.

The first peculiarity about our game is that it’s engine needs to be 100% deterministic, since we can’t have different results in the server and the browser.

What that means is that we DO NOT store the rounds of the fight. We calculate them in the server based solely in the code of both robots and some initial info (like robots positions).

The engine is 100% javascript. That helps us A LOT in running it in both the server and the client. We used Coffeescript for it and were very positively surprised. If you are wondering what the engine looks like, go take a look at it.

The Engine‘s engine is a turn-based engine. It might seem realtime in the browser, but it’s not. I’ll cover how we do it’s animation below.

The engine loops on the robots codes, logging everything until one of the following happen:

  • Only one main robot (not a clone) is left alive;
  • The fight times out (after a fixed number of rounds), in which case it’s a draw.

The really interesting part of the engine is it’s code: collision detection, line of sight and a lot of interesting stuff there. The end result is an array of rounds that will get passed to the interface to be animated.

The code for the engine can be found at the file.

The Animation

The animation part was tricky for myself, since I didn’t have much experience with RequestAnimationFrame. I couldn’t be more pleased. It was so easy making animation that actually renders the same across different computers.

Other than animating, we calculate the fight (run the engine) in WebWorkers so that we can maintain a responsive UI even when hardcore CPU cycles are being demanded. If you haven’t tried them, I seriously advise you to play with this amazing browser technology.

The fight goes like this:

  1. WebWorkers calculate the entire fight;
  2. We animate the resulting rounds with RequestAnimationFrame.

The RequestAnimationFrame method takes a callback function as argument. The function should receive a timestamp that represents the time at which the animation you requested is scheduled to occur.

What this means is that you can easily find out how many milliseconds of animation you have to run in this “step”.

In our case, we just subtracted the timestamp from the last processed timestamp to find out how many rounds should be rendered by the browser.

The code for the main portion of the animation is in the file.

What’s next?

I have an amazing robot and I want more! What’s next?

Glad you asked. I’m not sure what’s next. If you feel that there’s something missing, please feel free to create an issue at our github repository and we’ll consider it for our next release.

Right now we can’t do anything. We have to wait until the judges try the app for themselves.

Hope you guys have as much fun as we did.