Yay! Programmer art!
Yay! Programmer art!

In A Row Activity in Development for the XO (fancy Tic Tac Toe)

Earlier this month I decided to write my first activity for the OLPC XO laptop since I believe the best way to learn is by doing. Since I have a background in computer games I choose to make a simple game. I decided to write the ever-popular-with-kids game Tic Tac Toe. My primary thought was that if the computer could play Tic Tac Toe then I wouldn’t have to.

As it turns out, writing a Tic Tac Toe game is about as boring as playing one but since I’d already written code to create a grid, draw Xs and Os, and come up with a plan for a grid based computer AI, I decided that instead of dropping the activity all together I’d alter it to allow larger grids and more tokens in a row to win. This would allow playing games like Go-moku which I remember playing against the computer when I was in high school. That was the birth of the In A Row Activity.

The activity is based on the OLPCGames wrapper for pygame which is already installed on the XO. I highly recommend using it if you plan to write a game activity.

In any case, click here to download the In A Row Activity and try it for yourself. You can take a look at a screenshot here. Let me know what you think or if you find any problems.

In A Row Activity screenshot

A cross browser changeCSS function to alter, add, or delete CSS rules

Last year I needed a function to change CSS rules for one of my projects, so I put together a function called changeCSS() which allowed me to change, add or delete a CSS rule. I looked at various resources and the work was heavily influenced by code from David Flanagan and Shawn Olson. It worked great for all the cases I needed it in my project. My plan was to rigorously test it to make sure it worked in other cases I hadn’t used then post it here, but over time it has become clear that isn’t going to happen. So I decided I’d just put it out here as “yet another semi-tested but handy function” that people can look at for reference.

Anywhere, here is the function.

var exfer = window.exfer || {};
exfer.changeCSS = function (selector, stylename, value) {
  var ss, rules;
  // make sure there is a stylesheet available
  if (document.styleSheets.length <= 0) {
    if (document.createStyleSheet) {
    } else {
      var styleTag = document.createElement("style");
      styleTag.type = "text/css";
  // convert the stylename to camel case if necessary
  ccstylename = (stylename || "").replace(/\-(\w)/g, function (m, c) { return (c.toUpperCase()); });
  ccstylename = (ccstylename == 'float') ? 'cssFloat' : ccstylename;
  selector = selector.toLowerCase();
  // loop to delete or change the css
  for (var i = 0; i < document.styleSheets.length; i++) {
    ss = document.styleSheets[i];
    try {
      rules = ss.cssRules || ss.rules;
    } catch (e) {
      rules = []
    for (var j = 0, len = rules.length; j < len; j++) {
      if (rules[j].selectorText && rules[j].selectorText.toLowerCase() == selector) {
        if (value != null) {
          rules[j].style[ccstylename] = value;
        } else {
          if (ss.deleteRule) {
          } else if (ss.removeRule) {
          } else {
            // poor man's delete
            rules[j].style.cssText = "";
  if (stylename && value) {
    // if the selector wasn't found and isn't supposed to be deleted then add it
    ss = document.styleSheets[0];
    rules = ss.cssRules || ss.rules;
    if (ss.insertRule) {
      ss.insertRule(selector + "{" + stylename + ":" + value + "; }", rules.length);
    } else if (ss.addRule) {
      ss.addRule(selector, stylename + ":" + value + ";", rules.length);
    } else {
      throw new Error("Selector not found and add/insert rule not supported.");

Below is a test div that starts bold and you can change the color. You can even delete the whole rule and remake it.

A test DIV

exfer.changeCSS(”#changediv”, “background-color”, “yellow”);

exfer.changeCSS(”#changediv”, “background-color”, “green”);

exfer.changeCSS(”#changediv”, “background-color”, “”);

exfer.changeCSS(”#changediv”, “background-color”);

Overall I think it is a handy function. I did my minimal testing in IE6/7, FF2, Opera 9, and Safari 3 all in Windows.

Happy Holidays

Well I’m off for a vacation for the next few weeks. I have my OLPC and some time so I’m looking forward to messing around with it. Although it is difficult to touch type, so far I love this little thing. It feels so very compact and durable. Unlike my Dell, I actually unplug this laptop and take it to different areas of my house.

Anyway, here is a picture of my new laptop in living color. :)


I Purchased Two OLPC XOs Today

Well I went ahead and bought two OLPC XO laptop computers today using the OLPC Give One, Get One program. I’ve been following the program since it was first announce when it seemed like a pipe dream. Yes, the price has almost doubled from the goal of $100 but it’s amazing what a powerful idea can do. The whole computer industry has been shaken by these little laptops with both Microsoft and Intel, who initially slammed the idea, trying to figure out how to get on board before their global market share starts eroding in big chunks.

Now I’ll wait impatiently for them to arrive. I can’t wait because I have access to a few older DOS programs that I’m planning to try to port to the XO. It’s going to be fun. :)

Another Curry Function for more Closure Options

There are a lot of curry functions examples out there so I decided I’d share mine as well. The code was inspired by a blog posting from Dustin Diaz who was in turn inspired by one from Dan Webb. Those posts can probably do an overall better job of explaining currying than I can so I’m not going to go in to the idea of currying in any great detail. So I’ll just say the currying pattern is useful for attaching data to a function in a way that avoids using global variables and simplifies the use of closure.

When people first start programming in JavaScript they often use global variables to save data for later function calls like this:

Global Demo

<script type="text/javascript">
  var global_target;
  var global_oldText;
  function doItGlobal(e) {
    e = e || window.event;
    global_target = e.target || e.srcElement;
    global_oldText = global_target.innerHTML;
    global_target.innerHTML = "Click!";
    setTimeout(function () {
          global_target.innerHTML = global_oldText;
        }, 1000);
    return (false);
<a href="#" onclick="return doItGlobal(event);">Global test</a>
<a href="#" onclick="return doItGlobal(event);">Test 2</a>
<a href="#" onclick="return doItGlobal(event);">Test 3</a>

Global test Test 2 Test 3

Here you see a couple global variables are used to save the link that was clicked and the old text that was inside. When clicking just one link at a time it works, but if you click more than one (in the one second time frame) the next click corrupts the global variables and the first link won’t reset to its old text correctly.

One way to solve this problem is using closure instead of global variables like this:

Closure Demo

<script type="text/javascript">
  function doItClosure(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    var oldText = target.innerHTML;
    target.innerHTML = "Click!";
    setTimeout(function () {
          target.innerHTML = oldText;
        }, 1000);
    return (false);
<a href="#" onclick="return doItClosure(event);">Closure test</a>
<a href="#" onclick="return doItClosure(event);">Closure test 2</a>
<a href="#" onclick="return doItClosure(event);">Closure test 3</a>

Closure test Closure test 2 Closure test 3

This saves a unique copy of the data for each call and solves the previous problem. Often this is a very clear and concise way to handle the problem. But other times, usually when functions start getting more complex with multiple callbacks for multiple events, it can be hard to follow the trail of closure to see exactly which variables are attached to which internal functions. That is when I find the curry pattern like this very useful:

Curry Demo

<script type="text/javascript">
  function doItCurry(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    var oldText = target.innerHTML;
    target.innerHTML = "Click!";
    setTimeout(exfer.curry(target, function (text) {
          this.innerHTML = text;
        }, oldText), 1000);
    return (false);
<a href="#" onclick="return doItCurry(event);">Curry test</a>
<a href="#" onclick="return doItCurry(event);">Curry test 2</a>
<a href="#" onclick="return doItCurry(event);">Curry test 3</a>

Curry test Curry test 2 Curry test 3

Once you get used to the pattern you can see clearly that target and oldText are passed in to time timeout function callback where they are operated upon. Internally the curry function also uses closure but it is hidden from the event handler. Also a curry function can be used to assign scope to the “this” identifier in a function.

In any case, here is my curry function:

var exfer = window.exfer || {};
exfer.curry = function (scope, func) {
  var s, f, n;
  // make the scope parameter optional such that it keeps the original this value
  if (typeof scope == 'function' && typeof func != 'function') {
    s = null; f = scope; n = 1;
  } else {
    s = scope; f = func; n = 2;
  // save the arguments to pass to the new function
  var args = Array.prototype.slice.call(arguments, n);
  return (function () {
        // override the this scope if desired
        var o = s || this;
        // add the arguments passed in to the other arguments
        var allArgs = args.concat(Array.prototype.slice.call(arguments, 0));
        // call the function with the new scope and arguments
        return (f.apply(o, allArgs));

It differs from Dustin’s in two ways. First of all it can return a value which can be useful for some callbacks even if it isn’t so useful in the example I have above. Second, it can accept arguments from the calling function. Perhaps another example is in order.

Another Curry Demo

<a id="demo1" href="#">Curry demo</a>
<a id="demo2" href="#">Curry demo 2</a>
<a id="demo3" href="#">Curry demo 3</a>
<script type="text/javascript">
  var arr = [ document.getElementById("demo1"),
              document.getElementById("demo3") ];
  for (i in arr) {
    arr[i].onclick = exfer.curry(arr[i], function (e) {
                                           e = e || window.event;
                                           this.innerHTML = this.innerHTML + "!";
                                           if (e.preventDefault) {
                                           } else {
                                             e.returnValue = false;
                                           return (false);

Curry demo Curry demo 2 Curry demo 3

Here you can see an argument is passed to the curry function and it also returns a value. These are the two additional features added to Dustin’s curry function. They are pretty simple additions but very useful. I recommend playing around with a curry function if you use a lot of callbacks to see how you like it.

Yet another jQuery convert

As I’ve mentioned in previous posts, I have been going through a process of reviewing various JavaScript libraries and frameworks. So yesterday I started looking at jQuery. And I have to admit what I saw was impressive. Not that it does anything that other libraries can’t do. But rather that the design of the library is wonderfully simple while still being powerful. Within about an hour of reviewing the core jQuery library I felt comfortable with it.

So today I decided to toss out my own home rolled library and go with jQuery. Although the custom library I wrote was working fine, I decided the cross browser issues that are bound to come up in testing would be easier to deal with if I used jQuery. So the Chatkik internal chat application has been complete refactored with jQuery. The chat container still uses YUI (which I also like but just isn’t quite as elegant as jQuery for simple tasks).

That being said, if you find something failing to work that used to work in Chatkik, this change is likely the reason. Just let me know and I’ll take care of it ASAP.

Chat with Chatkik

I’ve been working recently with chatkik.com to develop an Ajax chat system. Although there is still a lot of work to do, I received permission to put the current dev version up on my blog for some pre-alpha testing. I know chat isn’t much fun without more than one person in the channel, but please feel free to check it out and comment if you have any thoughts about design or bugs or questions or anything else. Just click on the red chatkik tab in the upper right if you want to see the current version.

Python grep Script with Multiple Files

The other day I was looking for a command-line grep I could use in Windows. There were several options so I picked a python script that I found on Wikipedia (I chose a script since I have a health paranoia about spyware and such).

Overall, the script had enough functionality for my purposes with one exception. It didn’t accept wildcards for multiple files. It was only a few lines of code so I went ahead and added glob functionality and it seems to work fine. In case it is useful to anyone else, here is the altered script. Thanks Vivian De Smedt for the original.


Usage: grep [OPTION]... PATTERN [FILE] ...
Search for PATTERN in each FILE or standard input.
Example: grep -i 'hello world' menu.h main.c
Regexp selection and interpretation:
  -E, --extended-regexp     PATTERN is an extended regular expression
  -F, --fixed-strings       PATTERN is a set of newline-separated strings
  -G, --basic-regexp        PATTERN is a basic regular expression
  -e, --regexp=PATTERN      use PATTERN as a regular expression
  -f, --file=FILE           obtain PATTERN from FILE
  -w, --word-regexp         force PATTERN to match only whole words
  -x, --line-regexp         force PATTERN to match only whole lines
  -z, --null-data           a data line ends in 0 byte, not newline
  -s, --no-messages         suppress error messages
  -v, --invert-match        select non-matching lines
      --mmap                use memory-mapped input if possible
Output control:
  -b, --byte-offset         print the byte offset with output lines
  -H, --with-filename       print the filename for each match
  -h, --no-filename         suppress the prefixing filename on output
  -q, --quiet, --silent     suppress all normal output
      --binary-files=TYPE   assume that binary files are TYPE
                            TYPE is 'binary', 'text', or 'without-match'.
  -a, --text                equivalent to --binary-files=text
  -I                        equivalent to --binary-files=without-match
  -d, --directories=ACTION  how to handle directories
                            ACTION is 'read', 'recurse', or 'skip'.
  -r, --recursive           equivalent to --directories=recurse.
  -L, --files-without-match only print FILE names containing no match
  -l, --files-with-matches  only print FILE names containing matches
  -c, --count               only print a count of matching lines per FILE
  -Z, --null                print 0 byte after FILE name
Context control:
  -NUM                      same as --context=NUM
  -U, --binary              do not strip CR characters at EOL (MSDOS)
  -u, --unix-byte-offsets   report offsets as if CRs were not there (MSDOS)
`egrep' means `grep -E'.  `fgrep' means `grep -F'.
With no FILE, or when FILE is -, read standard input.  If less than
two FILEs given, assume -h.  Exit status is 0 if match, 1 if no match,
and 2 if trouble.
Report bugs to <bug-gnu-utils@gnu.org>."""
import sys, re, getopt, glob
class Queue:
  def __init__(self, size):
    self.size = size
    self.values = []
  def append(self, value):
    if self.size:
      while len(self.values) > self.size:
  def pop(self):
    if self.values:
      return self.values.pop(0)
    return None
  def __len__(self):
    return len(self.values)
  def __getitem__(self, n):
    return self.values[n]
def grep(pattern, f, options):
  if options.ignore_case:
    p = re.compile(pattern, re.I)
    p = re.compile(pattern)
  queue = Queue(options.before_context)
  line_nb = 0
  from_line = -1
  to_line = -1
  last_line = 0 # Last printed line.
  while 1:
    l = f.readline()
    line_nb += 1
    if not l:
    match = 0
    if re.search(p, l):
      from_line = line_nb - options.before_context
      to_line = line_nb + options.after_context
      match = 1
    if line_nb <= to_line:
      if options.before_context or options.after_context:
        if last_line and from_line > last_line + 1:
      from_line = max(from_line, last_line + 1, -len(queue))
      for i in range(from_line - line_nb, 0):
        if options.line_number:
          sys.stdout.write("%d-" % (i + line_nb))
      if options.line_number:
        if match:
          sys.stdout.write("%d:" % line_nb)
          sys.stdout.write("%d-" % line_nb)
      last_line = line_nb
def printUsage():
  """Print the help string that should printed by grep.py -h"""
  print "usage: grep.py [options] pattern [file]"
  print """
  -i, --ignore-case         ignore case distinctions
  -B, --before-context=NUM  print NUM lines of leading context
  -A, --after-context=NUM   print NUM lines of trailing context
  -C, --context[=NUM]       print NUM (default 2) lines of output context
                            unless overridden by -A or -B
  -n, --line-number         print line number with output lines
  -V, --version             print version information and exit
      --help                display this help and exit
See http://www.vdesmedt.com/~vds2212/grep.html for informations and updates.
Send an email to vivian@vdesmedt.com for comments and bug reports."""
def printVersion():
  print "grep.py version 0.5.0"
class Options:
  def __init__(self):
    self.ignore_case = 0
    self.before_context = 0
    self.after_context = 0
    self.line_number = 0
def main(argv):
  options = Options()
  opts, args = getopt.getopt(argv, "ViA:B:C:n", ["help", "version", "ignore-case", "before-context=", "after-context=", "context=", "line-number"])
  for o, v in opts:
    if o in ["-i", "--ignore-case"]:
      options.ignore_case = 1
    if o in ["-A", "--after-context"]:
      options.after_context = int(v)
    if o in ["-B", "--before-context"]:
      options.before_context = int(v)
    if o in ["-C", "--context"]:
      if not v:
        v = 2
      options.after_context = int(v)
      options.before_context = int(v)
    if o in ["-n", "--line-number"]:
      options.line_number = 1
    elif o in ["-V", "--version"]:
      return 0
    elif o in ["--help"]:
      return 0
  if len(args) <= 0:
    return 1
  pattern = args[0]
  if len(args) == 1:
    return grep(pattern, sys.stdin, options)
  fileList = glob.glob(args[1])
  for fileName in fileList:
    f = open(fileName)
    print fileName + " : "
    r = grep(pattern, f, options)
  return r
if __name__ == "__main__":

Debugging Ajax PHP with Logging and Firebug

I was recently trying to debug some Ajax PHP code. I was logging but it was cumbersome trying to look at both the php log file and Javascript logging in Firebug so I started going some searching. I found post from Mika Tuupola about Debugging PHP With Firebug, so I took his advice and moved to the PEAR:Log package with a Firebug handler.

But I still had a problem since I was debugging Ajax requests. The way the system works is it tacks on Javascript code to your page in a script tag that will be run when the page loads. This is fine for a standard page but for an Ajax request the result isn’t run. Basically the response would look something like this.

<script type="text/javascript">
  console.log("there are 2 results");

So all I did was write a function to strip out that Javascript code and execute it. The code is here

exfer.extractDebugMessage = function (s) {
  var beginIndex = s.indexOf("<script");
  if (beginIndex != -1) {
    var str = s.substring(beginIndex); // extract the script tag at the end of the response
    str = str.replace(/\n/g, "[N]"); // converts carriage returns into "[N]" so the regular expression can work without the "m" option
    var result = str.match(new RegExp("<script.*>(.*)<\/" + "script>")); // get the code from the tag
    if (result && result[1]) {
      str = result[1].replace(/\[N\]/g, "\n"); // put the CRs back in
      if (typeof console != "undefined") { // if console is available execute the code
    s = s.substring(0, beginIndex);
  return (s);

Then the code is called with the XMLHttpRequest responseText.

var realResponseText = exfer.extractDebugMessage(xhr.responseText);

Which pulls out the debug message and executes it, then returns what is left over to be passed along.

There are potential holes in the code of course. For example someone might have the string “<script” in their Ajax response but since it’s a debugging tool I’m not too worried about it. One quick note, since the code looks for the existence of console instead of Firebug it should also work with Firebug Lite although I haven’t yet tested it.

Enumerating Local Variables in JavaScript

One day I was trying to do some debugging in browsers other than FireFox (FireBug rocks and is highly recommended). I decided it would be useful if I could enumerate local variables such that I could quickly find and display their values in an alert box. Unfortunately, there didn’t appear to be any way to do that in some browsers. So the solution I came up with was to parse the function text itself (which can be found with func.toString()) to find all the local variables.

Of course there are a couple problems with this method. First of all my parsing is very limited. I didn’t want to write a JavaScript interpreter. Second, to get the values of the variables an evaluation function has to be passed in (trick found from TrimBreakpoint). And I’m sure there are other problems I can’t think of at the moment. :)

Anyway, on to the example. One of the interesting aspects of this method is the ability to see closure values from outside the function (click the third button in the example). Use View Source to get the full source from the example.

Example of Enumerate Local Variables

Example Calls to Show Locals

      function doItInside(s) {
        var x = 5, y = 9;
        var re = /^test$/;
        for (var i = 0; i < 5; i++) {
          var arr = [ 2, 4, 6, 8 ];
          if (arr[i] == i) {
        var ob = { x: 7, y: 5 };
        showLocals(function($$$$){return(eval($$$$))}, arguments);
      var outsideCheckerFunc;
      function doItOutside(str_param, num_param) {
        var timer = 100;
        outsideCheckerFunc = function($$$$){return(eval($$$$))};
        var f = function(){alert("hi")};
        var a = 55, b = 66, c = 77;
        var regE = new RegExp("^s*tart?");
      function doItOutsideCaller(withEvalFunc) {
        if (withEvalFunc) {
          doItOutside('test param string', 9);
          showLocals(outsideCheckerFunc, doItOutside);
        } else {
          showLocals(null, doItOutside);