Tuesday, 16 June 2009

UK to get 'World Class' Broadband?

I had to laugh at this article on the BBC: a new 50p tax on fixed lines in the UK to enable 'digital Britain' providing, among other things (up to) 50Mbps by 2017. A special highlight from our wonderfully inept Prime Minister:


"Britain is going to lead the world. This is us taking the next step into the future to being the digital capital of the world. -- Gordon Brown


Step back a bit... having 50Mbps broadband by 2017 is going to make us the 'the digital capital of the world'? Is he aware that South Korea is aiming for 1Gbps by 2012?!? (in case you're wondering, that's 20 times faster, five years earlier). Japan has 100Mbps now.

I sometimes wonder exactly which planet Gordon Brown is living on.

Monday, 8 June 2009

Clojure: First Steps into Compilation and Class Generation

I've never quite understood class generation in Clojure. The documentation is a little terse, and working examples seem to be hard to come by. So here's my walkthrough.

First, I'm assuming that we'll be creating Clojure objects from Java, calling methods on those Clojure objects from bog-standard Java code. This, I think, is the most likely scenario for the budding Clojure hacker who wants to write part of an existing Java system in Clojure.

Environment



First, you'll need to have obtained your clojure.jar, either from the snapshots here, or from the Subversion repository and building yourself.

Next, in whatever environment you're using, add the full path to clojure.jar to your CLASSPATH. Also add "." and "classes" (both relative paths, not absolute). You'll see why later.

The Clojure Code



In the directory you're building from, create the directory structure for your package, Java-style. I'm going to be putting my Clojure code in org/djw/sample.clj, so org/djw will have to exist beforehand.

In sample.clj, most of the magic's in the namespace declaration.


(ns org.djw.sample ;; 1
(:import (javax.swing JFrame)) ;; 2
(:gen-class ;; 3
:name org.djw.DJW ;; 4
:extends javax.swing.JFrame ;; 5
:constructors {[String] [String]} ;; 6
:init initialise ;; 7
:implements [Runnable] ;; 8
:state fiddlyBits)) ;; 9



  • 1. This is your Clojure namespace. It doesn't mean much from Java-land.

  • 2. You can import any classes used by your Clojure file here.

  • 3. :gen-class allows the compiler to generate Java bytecode files.

  • 4. This is the fully-qualified name of the Java class you want to emit. The Clojure compile directive generates quite a few class files that your Java code doesn't need to know about: the one in :name is an exception: it's what your Java code will import

  • 5. If your class subclasses something other than Object, name it here, as normal

  • 6. I want to have a String constructor that calls the String constructor in JFrame.

  • 7. The initialiser function for new instances. I lack imagination, so have called it initialise here.

  • 8. Horribly, my new class is both a GUI element (a JFrame) and a Runnable. Since you can implement many interfaces, this appears in a literal vector.

  • 9. The initialise function gets to attach some Clojure-side state to the object being created (you'll see that in a bit). The :state specifier creates a final instance method to access that state from Java.



This leaves two functions to implement in the Clojure code: initialise and run (the latter required by Runnable).


(defn -initialise [message]
[[message] (ref {:message message})])

(defn -run [instance]
(let [message (:message @(.fiddlyBits instance))]
(println message)))


Note the dash in front of the function names (this is the default :prefix from :gen-class). Also, note that the function specified by :init in :gen-class didn't get an instance to play with, whereas run (an instance method), does. This instance is the object that the method was invoked against, effectively this from Java.

initialise has to return a vector of two elements: the first consists of the arguments to pass to the superclass constructor. The second is the state that should be attached on a per-instance basis.

run is a Runnable.run implementation, and just prints out the message that the instance was created with. Note that the state is accessed with (.fiddlyBits instance), returning the ref-wrapped Clojure map, dereferenced with '@' as normal and with the :message key used to look up the associated value.

Compiling the Clojure Code to .class Files



Create a directory called classes/[package-name], in my case classes/org/djw. Why classes? Well, that's what Clojure's global *compile-path* variable is by default, so is the root where the compile command emits .class files. That's why you added it to your CLASSPATH above (you did do that, didn't you..?)

Since clojure.jar is on your CLASSPATH, you can start a Clojure REPL with just 'java clojure.main'. You can now compile the ./org/djw/sample.clj like this:


danny@mirror Desktop [10] % java clojure.main
Clojure 1.1.0-alpha-SNAPSHOT
user=> (compile 'org.djw.sample)
org.djw.sample
user=>


And that's it. classes/org/djw will now contain org.djw.DJW (as per gen-class's :name field). It'll also contain a bunch of other .class files: don't delete these, they are required! Clojure creates a .class file per function (including unnamed functions), as well as another for initialisation.

The Java Code



This has been a lot of effort so far. But the good news that this allows Java to talk to Clojure-generated class files without having any idea that Clojure was the source language. The Java code in Test.java to use it might look like this:


import org.djw.DJW;

public class Test
{
public static void main(String [] args)
{
DJW djw = new DJW("Hello");
new Thread(djw).start();
}
}


And that's it. DJW is the class name, and a new instance is obtained just as with any other class. It faithfully implements Runnable, as specified in the Clojure code, and it can be duly run from a Thread created from Java.

Compiling and Running the Java Code



The Java can be compiled just as with any other. Remember that the classes folder must be in your CLASSPATH for javac to see the definition of DJW.

With clojure.jar, '.' and classes in your CLASSPATH, you can just run as you'd expect:


danny@mirror Desktop [30] % javac Test.java
danny@mirror Desktop [31] % java Test
Hello
danny@mirror Desktop [32] %


By now, you've defined a class definition in Clojure, prompted instance creation from Java, initialised the object in Clojure, handed it to a thread in Java, and printed out a message in Clojure. That's a fair amount of bouncing around, especially for such a trivial example, but hopefully you've found it useful for what you need.

Sunday, 24 May 2009

Goodbye, Old Man

I buried Garfield's ashes today, under his favourite tree (claw marks included) at my mother's house. He went in the best way possible, but I've shed more than a few tears since his death.

He did well.

Rest in peace, old man.

Clojure on FreeBSD 7

Getting a native Java on FreeBSD 7 is not straightforward. It involves going through the instructions at freebsd.org/java and manually fetching packages that have generally since been superseded by point-versions (which you can't use or the ports system won't install them). Once they're all in /usr/ports/distfiles, a make install in /usr/ports/java/jdk16 will, several hours of hard compilation later, enable you to checkout a fresh copy of Clojure.

Finally, success:

Friday, 22 May 2009

Switching between Header and Implementation Files with Emacs

I often find myself working with C or C++ code that follows the pattern of parallel source/include directories, probably with lots of layers in between (e.g. project/include/some-controller/some-aspect/something.h and project/src/some-controller/some-aspect/something.cpp). Quickly switching between both saves on keystrokes and sanity, so I wrote this little chunk of elisp, bound to ctrl-alt-g (for no particular reason other than the combination is easy to mash):


(defun djw-c-toggle-impl-header-view (create-if-nonexistent)
(interactive "P")
(let* ((mode (if (string-equal (file-name-extension (buffer-file-name))
"h")
:switch-to-implementation :switch-to-header))
(toggle-tags (list (cons "/Include/" "/Src/")
(cons "/include/" "/src/")))
(from-fn (if (eq mode :switch-to-implementation)
#'car #'cdr))
(to-fn (if (eq mode :switch-to-implementation)
#'cdr #'car))
(source-file-name (buffer-file-name))
(case-fold-search nil)) ;; I want case-sensitive matching throughout this block.
(dolist (pair toggle-tags)
(setf source-file-name (replace-regexp-in-string (funcall from-fn pair)
(funcall to-fn pair)
source-file-name)))
(setf source-file-name
(replace-regexp-in-string
(if (eq mode :switch-to-implementation)
"h\$" "cpp\$")
(if (eq mode :switch-to-implementation)
"cpp" "h")
source-file-name))
(message (format "Looking for %s" source-file-name))
(if (or (file-exists-p source-file-name)
create-if-nonexistent)
(find-file source-file-name)
(message (format "Can't find '%s'" source-file-name)))))


If the counterpart file is missing, it won't be created unless the function is invoked with a prefix argument (C-u C-M-g).

There's probably some extension to CC mode or the like that already does something like this, but in the absence of reading the manual, this works well for me.

Wednesday, 13 May 2009

Sad Day

My cat died today.

His name was Garfield, and he was 19. I got him as a kitten when I was 13. I came downstairs this morning to find him on his favourite cushion on the couch; it was the only time that he didn't raise his head to meow/croak back at me.

He had a good life. His last day was spent sunning himself in the back garden; his last meal was his favourite roast chicken; and last night, when I was working at my computer, he came up for a cuddle and a purr.

As the vet said to me a few months ago, "You don't last that long without good bits". Garfield was made with the best.

garfield.jpg


Goodbye, old man.

Tuesday, 28 April 2009

Setting Colours with JavaScript

Something I thought would be easy turns out to have lots of different answers, none of which are particularly convenient: how do you compute a colour value in JavaScript, and then update some element on the page to use that colour?

Most solutions I've seen involve some kind of hard-coded hexadecimal conversion table, which is more than a little clunky. So here's another approach. Here, the value used to compute the colours is a ratio, with a value from 0.0 and up (normally in the 0.0 to 2.0 region, but theoretically unbounded at the top). I want to use red to indicate a ratio of 0.0, green for ratios of 2.0 or more, and a smooth range of colours in between.

So, onto th JavaScript (yes, I have the ratio conveniently in a hash table):


var ratio = parseFloat(data["ratio"]);
var red = 255 - (ratio * 255); // calculate
var green = ratio * 128;
if (red < 0) red = 0; // clamp
if (green > 255) green = 255;
var colour = ((red << 16) | (green << 8) | 0).toString(16);
while (colour.length < 6) colour = '0' + colour;
document.getElementById("ratio").style.color = '#' + colour;


The magic is in knowing that colours are typically represented as a red-green-blue triplet, with a byte in each channel (range 0-255). Blue doesn't feature in our range, so it's always zero. So, assembling the necessary triplet is just a matter of getting the clamped value for the right fields, and then OR-ing them together in a bitwise fashion after putting the red and green values in the correct place with the appropriate shifting. Then the toString(16) returns that integer in base-16, which happens to be what makes sense in CSS land. Finally, pad the string out with zeroes on the left (the string needs to be six characters long, then slap on the '#' to have it make sense in CSS land and you're done.