Javascript Has Gamified Programming

Modern Javascript has gamified programming by creating more micro-success moments (aha! finally got it!).

But we know there is No Silver Bullet[1], so it couldn’t have created more moments where you finally solve your hard problems (“essential complexity”). Instead, it has created many opportunities to beat problems you wouldn’t have in another environment (“accidental complexity”) and made it fun to beat them.

All these small annoyances create a mounting pressure in the Javascript programmer to do anything but work on front-end code, resulting among other things in the Cambrian explosion of development tools that modern Javascript is so famous for, and which is also the source of most of the accidental complexity. Tooling annoys programmers, causing them to create tooling that annoys programmers… A positive feedback loop!

Another way this pressure releases is by writing technical blog posts. Which is to say, I have an important deadline for tomorrow morning. OK, OK, getting back to work.

[1], probably the most important software engineering essay you’ll ever read

Why Sine Wave?

In this post we will understand what it means to say “this song has a lot of high frequencies”, then hunt and capture the waveform that allows us to say this! Some Python code will be used, but understanding it is not necessary. Footnotes are more technically advanced.

The x coordinate of the circle… is frequency?!

A simple sine wave
A sine wave

Sine waves are widely agreed to be the “most basic wave” when doing anything involving periodic signals – whether radio circuit analysis or music synthesis. Indeed, the sine wave is pretty simple as far as waves go, and quite smooth to boot, but I’ve always asked myself: why the sine? There are many other simple, basic waves that could be used as a basis for a theory of frequencies.

A square wave, a triangle wave, a sine wave and a sine wave
A square wave, a triangle wave, a sine wave and a sine wave “fattened” by taking its square root

… and yet mathematicians and engineers, even musicians, always choose the sine[1]. What makes the sine so special? Could a theory of frequency analysis be built around a different waveform, and how different would it be? How different would music sound if we used another simple waveform as our basis? Continue reading

I challenge you to a game of Sokoban Golf!

Graphics of my programmable Sokoban game which this was the prototype for, by Fiverr user applemoment
Graphics of my programmable Sokoban game which this was the prototype for, by Fiverr user applemoment

Before I dived in earnest into writing the new version of my computer game that teaches Python, this time with game mechanics based on the classical puzzle game “Sokoban”, I wanted to make sure that Programmable Sokoban is a fun concept. So I wrote a prototype in a couple of hours.

The programmers among you will enjoy it.

“Golf” is a game played by programmers, where you have to solve a problem in as few keystrokes as possible. I challenge you to solve these Programmable Sokoban levels in as few keystrokes as possible!

Sokoban Golf by Aur Saraf
At line 145 you will find a very naive solution for level 1.
You can easily learn the API from it.
How few lines do you need for solutions to levels 1, 2, and 3?
Do not modify the game or the levels in any way. Just remove the
level 1 solution and uncomment the level 2 and level 3 boards,
and try to solve all three in as few characters as possible.
The challenge is intentionally on ALL THREE LEVELS TOGETHER. You
should be writing utility functions that help with more than one
Good luck, and have fun!
WALL = '#'
EMPTY = ' '
PLAYER = '@'
CRATE = '*'
_dirs = lambda values: dict(zip(DIRECTIONS, values))
(1, 0),
(0, -1),
(-1, 0),
(0, 1),
LEFT = _dirs((DIRECTIONS[(i - 1) % 4] for i in xrange(4)))
RIGHT = _dirs((DIRECTIONS[(i + 1) % 4] for i in xrange(4)))
class QuietBoard(object):
def __init__(self, level):
self.board = [list(row) for row in level.splitlines()]
self.crates_at_large = level.count(CRATE)
self.player = self._player_position(self.board)
self.orientation = SOUTH
self.on_destination = False
def _player_position(self, board):
for i, row in enumerate(board):
if PLAYER in row:
return (i, row.index(PLAYER))
assert False
def __str__(self):
return '\n'.join(''.join(row) for row in self.board) + '\n' + str(self.orientation)
def is_win(self):
return self.crates_at_large == 0
def at(self, (row, column)):
return self.board[row][column]
def forward(self):
in_front = self._in_front(self.player)
if self._is_movable_crate(in_front):
if self._is_empty(in_front):
def left(self):
self.orientation = LEFT[self.orientation]
def right(self):
self.orientation = RIGHT[self.orientation]
def _is_movable_crate(self, position):
return self._is_crate(position) and self._is_empty(self._in_front(position))
def _in_front(self, (row, column)):
drow, dcolumn = DIRECTION_VECTOR[self.orientation]
return row + drow, column + dcolumn
def _is_empty(self, position):
def _is_crate(self, position):
def _slide_crate(self, position):
self.crates_at_large += 1
empty = EMPTY
self._put(empty, position)
destination = self._in_front(position)
self.crates_at_large -= 1
crate = CRATE
self._put(crate, destination)
def _slide_player(self):
destination = self._in_front(self.player)
empty = EMPTY_DESTINATION if self.on_destination else EMPTY
self.on_destination = == EMPTY_DESTINATION
self._put(empty, self.player)
self._put(PLAYER, destination)
self.player = destination
def _put(self, symbol, (row, column)):
assert (symbol in EMPTY_SYMBOLS) != self._is_empty((row, column))
self.board[row][column] = symbol
class Board(QuietBoard):
def __init__(self, level):
super(Board, self).__init__(level)
print self
print 'Start!'
def forward(self):
super(Board, self).forward()
print self
if self.is_win():
print 'You beat this level!'
LEVEL0 = '''\
#@ * X#
b = QuietBoard(LEVEL0)
for _ in range(10): b.forward()
assert b.is_win()
LEVEL1 = '''\
#@ X#
# ##*########
# ########
b = Board(LEVEL1)
for _ in range(9): b.forward()
LEVEL2 = '''\
# ###### #
#@ #
##*#*# ####X#
## ####X#
#b = Board(LEVEL2)
# Mini Cosmos 01 (c) Aymeric Du Peloux
LEVEL3 = '''\
### #
# * # ##
# # X #
# # #
## # #
#@ ###
##### '''
#b = Board(LEVEL3)
view raw hosted with ❤ by GitHub

Cover Letter


Warning: another technical post.The duckrabbitI wrote this cover letter many years ago, when I wanted to get accepted to the Matzov unit of the Israeli Defense Force (in Israeli, every male is conscripted for three years at age 18, and I wanted to put my skills to good use.)

Like the picture above, it can be interpreted two different ways. You could read it as a letter in the English language explaining why my skillset is a good fit Matzov… or you could read it as a program in the Brainfuck programming language (can you tell what it does?) This is made possible because most characters in the English alphabet are considered comments in Brainfuck. Still, writing it required pulling an awful lot of tricks.

On the right you can see a size-optimized hand-coded 8086 assembly language Brainfuck interpreter, and instructions on how to execute it. While writing the letter took a few hours, writing the interpreter took three days without sleep. Shaving the last byte off took almost half a day.

Matzov Cover

Click for full version.

Notice how periods are meaningful commands in Brainfuck, so there’s a question of whether the periods on the right are or aren’t part of the program. In practice, it doesn’t matter because if they were, they would be after an infinite loop and never actually execute.

Edit: Hi HN. At your request, here‘s a .txt I extracted from the .pdf.

Watch behind my shoulder: Debugging

Warning: long-winded tech post. If you don’t want to improve your debugging skills or don’t have lots of free time, don’t read this.

I decided to do some pro-bono debugging, and as I was diving in I thought that some of you might be interested in a glimpse of how I work.

I find that when debugging complex issues, keeping a “lab manual” and documenting every single action you take before you take it, although tedious and boring, gets the problem solved much faster. This time I’ll open my manual.

I will document what I think and what I do. I won’t document general debugging theory and techniques, as that would interrupt my flow too much (and probably make this into a book). I’ll just say this:

When debugging, you should throw all trust you have in yourself out the window. You start knowing that you’re wrong  (there is a bug) despite being confident you’ve done every single thing right, so thinking “I can see the problem is not here” without proving it by experiment is almost thought-crime and will waste you hours and sanity.


I’m considering submitting a talk proposal for PyCon 2014. They have a page with proposal resources. Unfortunately, I cannot click any links on the page. Normally I’d just go do something else, preferring not to waste time on websites that hurt so much to use. Since this is an open source web site for a project that has a lot of value for me, I figured why not exercise those debugging muscles and help them out with the issue.


I click a few times, trying different things and observing the outcomes. Middle click – my habit – fails. Ctrl+left click – another way to “open in new tab” in Firefox – fails. Left click succeeds, but this doesn’t solve the issue to my satisfaction. I like new pages to open in new tabs. I see the same behaviour for different links – HTTP and HTTPS links, same-site and other-site links. The browser seems to register my clicks, in the sense that the link is marked as focused after my mouse leaves it.

Is the issue with the site or my browser? I click the FAQ link on a Paul Graham essay that I have open. It opens the link in a new tab. I click again in – still nothing. The issue is with the site.

Is the issue with the page or the site? I left-click to another page on the menu (turns out middle clicking a menu item closes the menu but doesn’t open the link) and try links there – still nothing. The issue is with the entire site.

Is the issue with my browser or all browsers? I initially think I don’t care enough to install Chrome, but having to write it in my manual it smells wrong. Many scenarios where knowing the answer will narrow my search pop into my mind, and I’d rather spend a few minutes solving some issues with my Arch Linux installations so I can install Chrome than spending a few hours mulling over the PyCon issue.

I’ll have to update my OS first, so in the meantime lets continue. I’ll add TODO: Chrome to the end of this document, keep it after the cursor and remove it when I check, so I don’t forget this.

Is it an HTML issue? A quick right-click-inspect-element shows perfectly normal HTML, so probably not:

<a href="/2014/dashboard/">account dashboard!</a>
<a href="">Proposal Advice</a>

What does the site Javascript look like? I open Firebug “script” tab. There’s a little but of inline JS, an that probably cobbles together all  page-specific JS, jquery.min.js, bootstrap.min.js, and theme.js. jQuery is 1.8.3, bootstrap is 2.3.1.

theme.js is short and has a call to jQuery ajaxSend that looks very suspect, a quick google explains that it sets a hook that runs every time an AJAX request is sent, in this case it seems like the hook adds a CSRF token. Is it responsible? Easy to check: Add a breakpoint in the hook, click a link. The breakpoint is not invoked. Nothing to see here, moving on.

What happens when I middle click a link

In Firebug’s “Script” tab, I click the “pause play” icon – the great “break on next” feature. Nothing happens. Good, no periodic JS to confuse me. Then I click a link. It pauses in minified jQuery, in line 4 of:

}, function(e, t) {
var n = 0,
r = function(e) {
v.event.simulate(t,, v.event.fix(e), !0)
view raw gistfile1.js hosted with ❤ by GitHub

I try again, this time stopping in line 5 of:

v.event = {
add: function(e, n, r, i, s) {
var o, u, a, f, l, c, h, p, d, m, g;
if (e.nodeType === 3 || e.nodeType === 8 || !n || !r || !(o = v._data(e))) return;
r.handler && (d = r, r = d.handler, s = d.selector), r.guid || (r.guid = v.guid++), a =, a || ( = a = {}), u = o.handle, u || (o.handle = u = function(e) {
return typeof v == "undefined" || !! e && v.event.triggered === e.type ? t : v.event.dispatch.apply(u.elem, arguments)
}, u.elem = e), n = v.trim(Z(n)).split(" ");
for (f = 0; f < n.length; f++) {
l = J.exec(n[f]) || [], c = l[1], h = (l[2] || "").split(".").sort(), g = v.event.special[c] || {}, c = (s ? g.delegateType : g.bindType) || c, g = v.event.special[c] || {}, p = v.extend({
type: c,
origType: l[1],
data: i,
handler: r,
guid: r.guid,
selector: s,
needsContext: s && v.expr.match.needsContext.test(s),
namespace: h.join(".")
}, d), m = a[c];
if (!m) {
m = a[c] = [], m.delegateCount = 0;
if (!g.setup ||, i, h, u) === !1) e.addEventListener ? e.addEventListener(c, u, !1) : e.attachEvent && e.attachEvent("on" + c, u)
g.add && (, p), p.handler.guid || (p.handler.guid = r.guid)), s ? m.splice(m.delegateCount++, 0, p) : m.push(p),[c] = !0
e = null
view raw gistfile1.js hosted with ❤ by GitHub

I try a few more times, getting the same two lines.

Actually, at first it always stopped in the one and only line of jquery.min.js. I googled and found Javascript Deminifier, a Firefox extention that prettified the source for me (variables still have one-letter names, but I’ll figure that out later if needed.)

I suddenly remember that I have NoScript installed (although disabled for the site), which tends to cause strange JS problems. Is it responsible for the bug? In a different browser profile with no NoScript, still no middle click.

OK, this would be a good time to stop what I’m doing and search for existing bug reports in jQuery. Who knows, I might be trying to solve a solved problem. I find references to problems with jQuery’s live() function, later deprecated in favour of deleteage() and on(), but I can only find a few uses of delegate() and breakpoints on their hooks don’t trigger when I middle click.

I find a page indicating that I should probably look for return False, .preventDefault() or .stopPropagation() as culprits. I search the code for them, ignoring results in jQuery.min.js and resisting the urge to ignore results in bootstrap.min.js (despite my instinct that well-tested frameworks are bug-free, it might be a Bootstrap behaviour. Note to self: try other Bootstrap sites with the same version).

I find a few uses of said functions, set breakpoints and middle click a link. Break! This might be it. The debugger stopped in bootstrap.min.js, in a piece of code that looks very unashamed:

}).on("click.dropdown-menu", function(e) {
view raw gistfile1.js hosted with ❤ by GitHub

Is this intended Bootstrap behaviour? Googling for bootstrap “on(click.dropdown-menu)” turns out this page that tells me that what I’m looking for is bug 7118 in Bootstrap versions 2.3.1 and 2.3.2 (bingo! That’s the version the site uses!).

So how should they fix it? Upgrade Bootstrap? According to the drupal bug, 2.3.2 – the last release before 3.0 – suffers from the issue. According to the Bootstrap issue tracker, it seems that it was fixed:

Skud commented June 11, 2013

Has this actually been rolled into a bootstrap release yet?

@Skud: #7614 was declined. b9bd82b was rolled into v2.3.2 to fix #7118. Unfortunately, that fix introduced another bug: #7968.

According to my own testing, it doesn’t work in 2.3.1 and does in 2.3.2.

So PyCon webmaster, please upgrade to Bootstrap 2.3.2!


Well, this was a bit anticlimatic. I was hoping for an interesting Javascript bug and found a reported Bootstrap issue. However, this is still a good example of how I debug complex issues in code I don’t understand well (in this example, someone else’s code).

I found the problem and isolated it to a specific line without understanding what the huge codebase does. I didn’t click “step into” even once. I documented everything I did and it made me follow good paths that I wouldn’t have followed otherwise. I resisted my self-confidence many times and one of them proved critical. All in all, I consider this a good learning resource on debugging.

How I made a simple Business Model Canvas for geekar

The power of simple python scripting is one of the themes of this blog, and now I can show a great practical example.

I needed to create something that looks like this:

geekar Business Model Canvas
geekar Business Model Canvas (click for webpage)

This is a simple HTML table with some CSS. But trying to write it in HTML would result in a lot of copy-pasting of stuff that looks like this:

<td colspan="2" rowspan="2">
<h3>Value Propositions</h3>
<div class="postit "><i>Awesome</i> AR Geek Shop</div>
<div class="postit ">Infinite shelf space for long-tail products</div>
<div class="postit cl ">Products connected to info online</div>
<div class="postit ">Products connected to geeks in other stores</div>
<div class="postit cl ">Sense of community</div>
<div class="postit ">Pleasure of random surprises</div>
<div class="postit cl ">Easily to setup mobile shop</div>
<div class="postit ">Platform for interesting promotions</div>

That’s a lot of boring and error prone copy-pasting. And I’ll need to create lots of these in the coming months.

OK, so I need to write a script that will turn this:

"customers": [x + " Fans" for x in ["Comics", "RPG", " MTG", "Anime"]] + [" Gamers"],
"values": [
"<i>Awesome</i> AR Geek Shop",
"Infinite shelf space for long-tail products",
" Products connected to info online",
"Products connected to geeks in other stores",
" Sense of community",
"Pleasure of random surprises",
" Easily to setup mobile shop",
"Platform for interesting promotions",
"channels": ["Conventions as marketing", "Retail (our shops)", " Online", "Geek events we host"],
"relationships": ["Physical", "Online Community", " Promotions", "Geek Events"],
"revenues": ["Asset sales"],
"resources": ["Shops", "Registered users", " Merchandise", "Promotions"],
"activities": ["Sales", "Marketing", " Hosting events"],
"partners": [
" Marvel?",
" DC?",
"costs": ["One time: Development", "Constant: Rent", "Initial Merchandise", "Employee salary"],

Into the correct HTML.

It’s actually really easy:

import sys
HTML = """<?doctype html>
body {
background-color: gray;
// …
.cl {
clear: left;
<h1>The Business Model Canvas</h1>
<h2>Designed for: %%s</h2>
<h2>Designed by: Aur Saraf</h2>
<td rowspan="2">
<h3>Key Partners</h3>
<h3>Key Activities</h3>
<td colspan="2" rowspan="2">
<h3>Value Propositions</h3>
<!– … –!>
<!– … –!>
POSTIT = '<div class="postit %(classes)s">%(content)s</div>'
"customers": [],
"values": [],
"channels": [],
"relationships": [],
"revenues": [],
"resources": [],
"activities": [],
"partners": [],
"costs": [],
def to_postit(caption):
classes = ""
if caption.startswith(" "):
classes = "cl "
caption = caption[1:]
return POSTIT % {"classes": classes, "content": caption}
def write(name, canvas, f):
canvas = dict((k, "\n".join(map(to_postit, v))) for k, v in canvas.iteritems())
html = HTML % canvas % name
def main():
if len(sys.argv) == 3 and sys.argv[1] == "-new":
with file(sys.argv[2] + ".py", "wb") as f:
return 0
elif len(sys.argv) != 2:
print "usage: name"
return 1
name = sys.argv[1]
module = __import__(name)
with file(name + ".html", "wb") as f:
write(name, module.CANVAS, f)
return 0
if __name__ == '__main__':

view raw
hosted with ❤ by GitHub

$ python -new geekar
$ emacs
$ python geekar

view raw
usage example
hosted with ❤ by GitHub

It’s a small command-line tool that knows how to create an empty .py file for a canvas with the correct template, and knows how to read a .py file as a python file (since this is for self-use only I’m fine with no security at all, otherwise reading it as a python file would be very unwise) and do some preprocessing and some search-and-replacin’ to get the right thing into an HTML template.

I needed to be able to control how many notes to have in a row, so I added parsing of a space at the beginning of a note caption to mean “newline before this”. I needed to write many similar notes for “customer segments” – so I used the fact that the canvas definition file is in python to just write some python that generates it:

“customers”: [x + ” Fans” for x in [“Comics”, “RPG”, ” MTG”, “Anime”]] + [” Gamers”],

And that’s all there is to it. One of my students could write this in ten minutes. From now on, something that I will be doing every day will take a few minutes less.

Is It Worth the Time?

The whole code can be found here: and the complete result here:

Business Model Exercise #1: geekar

I started exercising my idea muscles a few days ago.

Every day I think of 10 startup ideas and develop one into a business model. Some will be published here.

Lets begin with the first example – geekar, an Augmented Reality-enhanced retail, in the most early-adopter industry I know: geeks. geekar will sell comic books, tabletop roleplaying sourcebooks, board games, trading card games, manga, anime, computer games and so on.

Continue reading

I — I don’t even see the code. All I see is blonde, brunette, redhead…

I was holding up on posting until I can say more about PythonForAll (it’s not that I didn’t get out of the building, just that it’s becoming a bit more serious so I can’t publish things before they are final) but I just have to write about this:


For a long time I’ve wanted to code a screensaver showing matrix code, just like the gajillion clones you can already find on the internet, but instead of showing random characters, this one would capture (“sniff”) network packets and show them in encoded form.

The theory is that if you watch this long enough, you’ll begin to “see through the code” – at first, you’ll learn to decode the characters into numbers, and at more advanced stages you’ll learn to parse the network protocols intuitively. I have many reasons to believe this:

  • I’ve seen people learning languages and musical instruments (and experienced it myself)
  • I’ve heard that one of the Samba developers can decode raw NBNS packets in his head (one of the most horrible encodings I’ve seen, see here 1.3.1)
  • I knew someone who could synchronize a dial-up modem with his voice
All images, characters, content and text are copyrighted and trademarks of J.D. Frazer except where other ownership applies. Don’t do bad things, we have lawyers.


Announcing Wirematrix

Today I saw this HN thread and was reminded of this idea. I decided that the time had come. A night of work later, an alpha version exists and the main feature works well:

If you'll look closely, you'll see that some patterns can be noticed immediately even from one static screenshot
If you’ll look closely, you’ll see that some patterns can be noticed immediately even from one static screenshot

You can get it on github. If you are not experienced with compiling linux software, I advise you to wait for a more user friendly release. Drop a comment saying you’re interested, it will motivate me to create one.

There’s work to do on friendliness of installation and on shininess of visualization. Other than that it’s complete. Python and Cairo rock!

Lecture 1.5A: Business Models and Customer Development

In this lecture we learn about business models and about the Business Model Canvas as a tool for mapping business models.

We learn that a company is for executing a business model whereas a startup is for finding one and then becoming a company.

I fully agree with the view of a startup as a different kind of entity than a company, it is a very fresh and important realisation. However, I have a problem with companies that view the search as completely over. That’s how record companies find themselves replaced with this new kid called the Internet. If I ever find myself as Chief Executive Officer of a company, I’ll make sure to Search and not only Execute, no matter what profits that the current business model yields.

Then we get introduced to…

The Business Model Canvas

The BMC is a technique for describing a business model, a division into the most important blocks. A map of sorts. When searching for a business model, one is supposed to make an empty canvas, hang it on the wall and tape post-it notes filling the different blocks, which will then be modified many times while iterating on improving the model.

I don’t know whether the BMC is a good map – whether it captures all essential details and no inconsequential details. I’ve never formed a company and I can’t say which are the essential details. I’m taking it as sage advice – Steve has more experience than me and he’s telling me “here are the important things to notice when making a business plan”, so I’m taking his word until I know better. I guess in practice it varies a little depending on the kind of business you’re planning, but it makes sense that it doesn’t vary too much and one canvas design can fit most uses.

To make sure I don’t miss anything important, once in a while I will try to draw different projections of my business plan – perhaps as a story or a roleplaying game – as different projections tend to focus on different details.

The rest of the lecture describes the different blocks in the BMC – The all-important Value Proposition, Customer Segments, Channels and Customer Relationships leading to Revenue Streams and Key Partners, Key Resources and Key Activities leading to the Cost Structure.

I found Steve’s descriptions good but not always sufficient. I found lots of assistance from the grey text on the “Business Model Generation” Business Model Canvas PDF. Where I still didn’t know exactly what to write, the excellent descriptions and two examples (spot ’em) in the free preview of the Business Model Generation book clarified it for me.

To get a good feel of a new idea, it is always a good idea to practice a bit:

Franchisee for Coca Cola

This is my guess of a business model for a Coca Cola franchisee. It was evident while working on this that when dealing with products that have complex distribution chains, there is need to flush distribution channels better than the canvas allows. To partially solve this, I treated distributors also as clients and partners where it was relevant.

Waze Mobile

For those who have never heard of Waze, they make crowdsourced GPS navigation software for smartphones, which is one of the products with most value I’ve ever seen. Once again, I needed a bit more separation between two kinds of clients – users and advertisers, which are treated very differently. Also, I had to guess more because the internet can tell me less about their business practices (and it’s getting late).

Finally, my own toy business idea, Python For Everyone:

Python For Everyone

I highly recommend reading the links introducing the plan. Readers who don’t usually ask questions that are answered in there.

As you can see, I have lots of different entities gaining value, and needed a way to encode what relates to which of them in the right side of the canvas. I chose color coding, and I think it works pretty well. I’m not sure I decided correctly to include the possible future venture of training technology companies.

All in all, I think I like the Business Model Canvas as a map of my business. It made me think about many aspects of my business and feels like a good map. Time will tell, when I try to update it, how well it works for iterating on a changing business model idea.