Entries tagged “programming”

Charting languages

Guillaume Marceau, who made a guest post here on how to make comparison charts, has an excellent demonstration of this technique over on his blog, charting performance against code verbosity in programming languages:

The speed, size and dependability of programming languages

If you drew the benchmark results on an XY chart you could name the four corners. The fast but verbose languages would cluster at the top left. Let’s call them system languages. The elegantly concise but sluggish languages would cluster at the bottom right. Let’s call them script languages. On the top right you would find the obsolete languages. That is, languages which have since been outclassed by newer languages, unless they offer some quirky attraction that is not captured by the data here. And finally, in the bottom left corner you would find probably nothing, since this is the space of the ideal language, the one which is at the same time fast and short and a joy to use.

Gtk# on Mac OS X revisited

So much for the fuss with getting Gtk# installed. I threw out the Mono framework package this evening, reinstalled it and the Gtk# packages from Fink, and now it all just works. No mucking with DYLD_LIBRARY_PATH and miscellaneous symlinks involved.

I’m looking forward to writing first class Windows apps on OS X.

.Net, Mono, Gtk# and IronPython on Mac OS X

Today’s development platform test was on Mono and IronPython with Gtk#. I was testing the feasibility of achieving three goals:

  1. Support both Windows and Linux with a single codebase, using either Microsoft’s .Net Framework or Mono.
  2. Provide a smooth learning curve for my existing .Net dev team.
  3. Use Python for rapid development, without resulting in disjoint codebases.

My current requirement is for several hundred Windows desktops that I’d rather be using a more maintainable operating system on. I’m bound to Windows by third party software that I must support, but don’t want my team’s own work to become a barrier to migration in future.

Mono doesn’t support Windows.Forms very well, so if I am to adopt it, the first task will be to replace WinForms with Gtk# in existing apps. For the evaluation today, I tried the most basic: getting Mono and Gtk# working, and maybe writing a “Hello, World” Gtk# app in Python. My primary environment is a Mac, which made this evaluation more interesting. Could I actually do my development on OS X and deploy on Windows and Linux? The Mono distribution for Mac OS X includes IronPython but not Gtk# (Cocoa# is bundled instead). Gtk# requires the Gtk+ library, which is not a standard component on OS X, and hence Mono’s understandable omission.

Compiling Gtk# involved jumping a few hoops. Basically: symlink the Mono C# compiler /usr/bin/mcs to /usr/local/bin/csc.exe, because Gtk#’s configure script assumes a Microsoft .Net Framework environment, and then edit all Makefiles to set RUNTIME = mono. That compiled it. To install, I had to create gtk-sharp-2.0 under /Library/Frameworks/Mono.framework/Versions/1.2.1/lib/mono and throw in symlinks to all the DLLs from their source location in ../gac.

I then tried this simple Gtk# example in C#:

using Gtk;
using System;

class Hello {

    static void Main()
    {
        Application.Init ();

        Window window = new Window ("helloworld");
        window.Show();

        Application.Run ();

    }
}

But it wouldn’t compile:

$ mcs HelloGtk.cs -pkg:gtk-sharp-2.0
Package gtk-sharp-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `gtk-sharp-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'gtk-sharp-2.0' found
error CS8027: Error running pkg-config. Check the above output.

Turned out there were two copies of pkg-config, one from Fink and one from Mono. The solution was to set a common environment variable:

export PKG_CONFIG_PATH=/sw/lib/pkgconfig\
:/usr/lib/pkgconfig\
:/Library/Frameworks/Mono.framework/Versions/1.2.1/lib/pkgconfig

The code compiled but still wouldn’t run:

$ mono HelloGtk.exe 

Unhandled Exception: System.DllNotFoundException: libgtk-x11-2.0.0.dylib
  at (wrapper managed-to-native) Gtk.Application:gtk_init (int&,intptr&)
  at Gtk.Application.Init () [0x00000] 
  at Hello.Main () [0x00000] 

Mono couldn’t find the Gtk+ libraries in /sw/lib. Fixing this was uglier; it required messing with the DYLD_LIBRARY_PATH environment variable:

$ export DYLD_LIBRARY_PATH=/sw/lib\
:/Library/Frameworks/Mono.framework/Versions/1.2.1/lib

HelloGtk.exe would run after this, but if I tried anything else, it failed complaining about missing libraries. I couldn’t find a solution. Anyway, I moved on Gtk# from Python, translating the code above line for line. It wouldn’t work. No known module named “Gtk”. Much head-scratching and Googling later, I learnt that IronPython needs a special invocation for .Net assemblies (that’s .Net speak for “libraries”). Here’s the code:

import clr
clr.AddReference('gtk-sharp')

import Gtk

Gtk.Application.Init()
window = Gtk.Window("helloworld")
window.Show()
Gtk.Application.Run()

Kushal has a slightly more elaborate example.

Generating combinations in Python

I recently wrote some code that required iterating through all combinations of a list of lists. I couldn’t find an existing function to do this, so wrote one:

def listcombinations(listoflists, curlist=[], parents=[]):
    """
    Generator that yields all possible combinations from a list of lists.

    >>> a = [[1, 2], [3, 4], [5, 6], [7, 8]]
    >>> for c in listcombinations(a): print c
    ...
    [1, 3, 5, 7]
    [1, 3, 5, 8]
    [1, 3, 6, 7]
    [1, 3, 6, 8]
    [1, 4, 5, 7]
    [1, 4, 5, 8]
    [1, 4, 6, 7]
    [1, 4, 6, 8]
    [2, 3, 5, 7]
    [2, 3, 5, 8]
    [2, 3, 6, 7]
    [2, 3, 6, 8]
    [2, 4, 5, 7]
    [2, 4, 5, 8]
    [2, 4, 6, 7]
    [2, 4, 6, 8]
    """
    if curlist == []:
        curlist = listoflists[0]
        remlist = listoflists[1:]
    else:
        remlist = listoflists
    for item in curlist:
        if len(remlist) > 0:
            for c in listcombinations(remlist[1:], remlist[0], parents+[item]):
                yield c
        else:
            yield parents+[item]

In the code above, the function returns combinations in a sequence such that each consecutive combination differs by only one item. My use case required consecutive combinations to be as unlike each other as possible. After mulling over it a bit, I figured I’d just randomise the entire set. This presented a new problem. On a production run, it turned out my list of lists summed up to over three million combinations. I only needed about ten and, neither picking the first ten nor generating the full list and picking a random ten was feasible: insufficiently distinct or took too long, respectively.

The solution? A lazy list instead of a generator:

class Combinations:
    """
    Holds all possible combinations of a given list of lists. Behaves like
    a lazy list.

    >>> a = [[1, 2], [3, 4], [5, 6], [7, 8]]
    >>> for c in Combinations(a): print c
    ...
    [1, 3, 5, 7]
    [2, 3, 5, 7]
    [1, 4, 5, 7]
    [2, 4, 5, 7]
    [1, 3, 6, 7]
    [2, 3, 6, 7]
    [1, 4, 6, 7]
    [2, 4, 6, 7]
    [1, 3, 5, 8]
    [2, 3, 5, 8]
    [1, 4, 5, 8]
    [2, 4, 5, 8]
    [1, 3, 6, 8]
    [2, 3, 6, 8]
    [1, 4, 6, 8]
    [2, 4, 6, 8]
    >>> print Combinations(a)[12]
    [1, 3, 6, 8]
    """
    def _product(self, sequence):
        "Returns product of items in sequence."
        if not sequence: return 0
        return reduce(lambda x,y: x*y, sequence)

    def __init__(self, listoflists):
        self.length = self._product([len(col) for col in listoflists])
        self.listoflists = listoflists

    def __len__(self):
        return self.length

    def __getitem__(self, index):
        if index >= self.length:
            raise IndexError, "Index out of range."
        r = []
        p = 1
        for col in range(len(self.listoflists)):
            i = int(index/p) % len(self.listoflists[col])
            r.append(self.listoflists[col][i])
            p *= len(self.listoflists[col])
        return r

Here’s the code packaged as a Python module.

jQuery

jQuery is a new type of Javascript library that looks like it’ll have me doing some real Javascript programming within this lifetime. Under 20kB compressed, your choice of MIT or GPL license. What does the code look like? From their site:

$("p.surprise").addClass("ohmy").show("slow");

Sweet!