Posts for Tag: programming

I got bored and recreated donut.c in C# (aka donut.NET)

While waiting on a release to finish, I got thinking about donut.c, then got more bored and made it in C#

Sincerest apologies to Andy Sloane, the formatting is awful and to be honest it's pretty much just his code line-for-line but in c#. I'm not sure if the worst part is my templated memset() or the nl() function (which inserts a new line in the buffer passed to Console.Write()). Hideous. It does manage to generate a passable torus rotating through two axes, however:

Blackbox on Mac OS X

Blackbox is a lightweight X11 window manager I used to use when I used linux as my main OS. The only UI elements on display by default is a small bar down the bottom to control what workspace you are using (called the "slit") and you can launch programs and configure blackbox from a menu visible when you right click the desktop:

It's quite nice to use something so uncluttered after the colourful noisy UIs I'm used to, so I figured I'd see if it's possible to use it under OS X and share the steps involved.

As a prerequisite make sure you have XQuartz installed as well as either Xcode or the Command Line Tools for Xcode. To get a working copy of blackbox you can either use MacPorts or build it from source by hand:

1a. MacPorts (easy)

First install macports, and open up a terminal window and enter the following

   $ sudo port install blackbox   

All the requisite dependencies should be downloaded for you and once it's complete you should have a functional blackbox binary installed in your system.

1b. Build by hand (less easy)

You'll likely need to download and install the following, as they're not provided by default in OS X (well one version of libtool is, but it's not what you want. To prevent overwriting this we'll use --prefix=/usr/local). I hacked together a script you can just copy + paste into your terminal (you'll need to enter your password to allow the `sudo make install` step to work.

Next grab the blackbox sources:

 $ cvs login </br>   
 $ cvs -z3 co blackbox   
 $ aclocal & autoheader && automake && autoreconf -i 
And do the standard ./configure && make && sudo make install malarkey. I ran into an odd error during ./configure where something to do with xft was dying. Running with -disable-xft didn't help, so I opted to skip it from the build by hand - you can do this by downloading this patch...

and then applying it + building:

 $ patch -P0 < fix_xft.patch 
 $ ./configure   
 $ make   
 $ sudo make install 

2. Configuration

By now you should have a working blackbox binary in /usr/local/bin. Now create an .xinitrc

 $ cat << END > ~/.xinitrc   
 export PATH   xterm &   
 exec /usr/local/bin/blackbox   

3. Launch!

Open up XQuartz, go to Preferences and tick the "Full-screen mode" box, and on your keyboard hit ⌘-⌥-a (press and hold command, option and "a") and you'll see a lovely blackbox desktop. You can use the same sequence to switch back out of XQuartz and see your OS X desktop again.

Stupid Post-it Art Creator

I recently moved into a new floor in work which has giant windows - an excellent opportunity for post-it art. So knocked up a quick program in Processing (as it's easy and I'm lazy) to approximate given the fairly standard palette of colours below:

There's bound to be millions of such programs floating around the internet, but hey-ho it filled a half-hour or so. Fire up the code here into Processing and use the following controls to adjust the image. 

key action
- decrease size of postit (increasing resolution)
+ or = increase size of postit (decreasing resolution)
w toggle dark lines between postits
[mouse click] open another file

It'll display an image, together with the post-it approximation to the right, like so:

That's not particularly good, but if I hit "-" a couple of times...

... a better approximation is displayed. Based on a size of roughly 72.6mm x 72.6mm per post-it, the real world dimensions of the post-it masterpiece are dumped to the Processing console:

I just need to find a suitable pack of post-its and an interesting image, and I'm all set :)

C No Evil - In Practice

John Regehr, an Associate Professor at University of Utah, posed an interesting question recently:

Your mortal enemy would like to ship a really great product in a week or two. Towards the goal of maximally delaying this product, you may inject a single C preprocessor definition into one of their header files. What is it?

There was also an interesting discussion on HN where a number of people offered their own suggestions which ranged from cruel to downright devious. I was curious to see what would happen if you were to inject any of these into the sources of some commonly used Open Source software. Which changes would cause a catastrophic failure to run, and which cause slightly more subtle runtime errors that permit reasonably normal use (albeit with the odd confusing moment).

First I selected a couple of programs I use fairly frequently:

Application Testing
GNU grep 2.9 make check after rebuild
Python 3.2.1 make test after rebuild
Emacs 23.3 mess around a bit (really scientific, eh)

Next I selected a number of the macros to test, I picked the ones which I thought were likely to build and run fine for the most part but introduce weird isolated errors:


#define unsigned signed
#define long short
#define volatile
#define continue break
#define struct union
#define if(x) if(rand()<0.0001 && (x))


The location I chose to change was in Include/Python.h, right at the top. Either this was a bad choice or Python itself was a bad choice, because only one of the builds completed, and even then there was no effect to the results of the testing. Take a look at the screenshots for the failures, the failures are mostly at the same step in the build.

Macro Result
#define unsigned signed Build failure.
#define long short Build failure.
#define volatile Build succeeds. Tests fine too.
#define struct union Build failure.
#define continue break Build failure.
#define if(x) if(rand()<0.0001 && (x)) Build failure.

Oh well, onwards and upwards.


Again I chose one of the "included everywhere" headers - src/grep.h - and put my macros right at the top. The unadulerated grep actually fails `make check` because one test unexpected passes (word-delim-multibyte). I'll do as the message tells me to and report the failure, and for the purposes of this post I'll ignore the word-delim-multibyte failure.

Macro Result
#define unsigned signed Build succeeds. Tests fine
#define long short Build failure.
#define volatile Build succeeds. Tests fine
#define struct union Build failure.
#define continue break Build succeeds. One test (fmbtest) fails!
#define if(x) if(rand()<0.0001 && (x)) Build succeeds, all sorts of random runtime failures, brilliant!


The file I changed this time was src/s/darwin.h. Unfortunately there's no automated testing for emacs, so when it built fine I just had to play around for a while. As I said earlier, not very scientific really.

Macro Result
#define unsigned signed Build failure (executable built fine, emacs is invoked to build lisp libs and dies)
#define long short Build failure
#define volatile Build succeeds, runs OK
#define struct union Build failure
#define continue break Build failure (executable built fine, emacs is invoked to build lisp libs and dies)
#define if(x) if(rand()<0.0001 && (x)) Build failure


Well this wasn't the greatest experiment ever, I was hoping for odd random behaviour and dramatic failures. Alas I was stuck with build failure after build failure. Perhaps the problem was that I wasn't devious enough with where the macros were inserted - the locations I chose tended to affect the entire codebase. I could also have selected the programs I was testing a little better, maybe a few more with automated 'make test' steps.

@NotBrianCox - I can code while drunk

After a night out in Edinburgh I woke up and discovered that when I got back in I had created a twitter account (@NotBrianCox) and a program to generate new tweets from Markov Chains of @ProfBrianCox' tweets. Words fail me.

When I sobered up I scrubbed the drunken (profane) test tweets, the rest had "poop" at the end for some reason so I chucked them out as well and started again. I've also applied my triangly-image-scrambler to his twitter picture to generate a not-quite-Brian-Cox picture. Here are a few pearls of Not Brian's wisdom:

Here's the code, if anyone's interested (need to fill in the access keys, choose the user and run with `python -i`. Running tweet() will generate and send a new tweet). 

More Processing - Colorcube

More messing around with primitive graphics in Processing, this time using OpenGL which I haven't touched since 3rd year at University. It's a little frightening to think that was five years ago! I thought it would be cool to see what it would look like you were to use each of the Red, Green and Blue components of a pixel's colour as it's co-ordinates across the X, Y and Z axes and plot it inside a cube.

I'll spare you the details, but this was another little one-evening job - after manhandling horrible legacy VB code all day I've rarely felt like doing anything particularly brain intensive when I get home at night. Anyway my favourite is the image comprised of a number of individual images to make a little spectrum. You can see little tendrils of alike colours arcing from one corner of the cube (0,0,0 - Black) to the other (255, 255, 255 - White):

Annoyingly something's up with OpenGL for Applets on recent-ish JVM versions so I can only embed the Applet using Processing's slightly lame P3D software renderer, which mangles the colours beyond belief. It's so ugly I'm not going to bother uploading it and embedding it on this page. You can view the video further down the page or download the program itself at the bottom of the page (to see it in all its technicolour OpenGL glory), or if you're sadistic you can download it and use the P3D renderer. Wash your eyes afterwards though. Anyway if you do download it, here are the keys to manipulate what's on screen:

Key(s) Function
←, ↑, →, or ↓ change the cube's angle
=/- reduce/increase the amount of points on display (if your frame rate is too low)
n cycle through the images

increase/decrease amount of points per "shape"

The last function is a little odd, when I was having trouble with performance I started looking for ways to improve speed. After a couple of straight forward ones (no plotting duplicate points, precompute the co-ordinates rather than calling red(), blue() and green() on each point each frame) I noticed that I was creating a new shape for each vertex (i.e. beginShape(POINTS); /* add vertex */ endShape();). After a bit of playing around it turns out that the sweet spot is somewhere between 100 - 1000 points vertices per shape (this is a little vague as I've not been particulary scientific about it).

Here are some videos of a few of the images together with their rotating colorcubes. They're a tad jerky due to the capture software, it's a lot smoother when you run the actual software.

You can download the source code here, just load the PDE in Processing and run (the images used in the video demo are contained within so you don't need to fiddle around with anything).


Fine Art With Processing

I started playing with Processing (simple C/javascript-ish looking language which compiles to JVM bytecode) the other night. After scanning through the tutorials, I started messing around with a very primitive algorithm to approximate an input image by continually randomly drawing triangles on screen (discarding any which make the screen less like the input)

Think "Infinite Monkey Theorem" but with only a single monkey, and I whack him with a rolled up newspaper when he types something incorrect. OK that was slightly contrived, and not particularly accurate but who amongst us can resist a good "spank the monkey" metaphor?

To test things out I wanted to keep things simple by using a monochrome and contrasty image, so my first input image was a picture of a West Highland Terrier I took with my Kiev 6C on some cheapo Chinese black & white 120 film.

The first attempt was less than successful. I killed it off after a while, as it started to look a little eery.

Whoops, the problem was that only pure white or pure black triangles were drawn, so anything which wasn't white or black tended to be shaded with lots of thin spikey polygons. Let's try with a few more colours:

Once I was a confident that I was able to produce a reasonable image I messed around with full RGB colour, and with circles instead of triangles. Here's a few more images (click to embiggen):

Of course these pale in comparison to some of the things other people have created with Processing. It does just look like I've run images through a crude Photoshop or GIMP filter, but all the same I was impressed with how easy it was to get proficient enough to do this - a couple of hours at most. Code available here.

Relationship on the rocks

Why, Haskell? We've been getting along so well, why you gotta play me like that? 

Couldn't match Int with Integer eh? Aggh just give it a try! Throw caution to the wind for once!

Perhaps the below, a separate program excreted late last night, is why we're struggling to get along. Beer + all day using VisualBasic = far too much enthusiasm for "concise" one liners in Haskell. Oh and unsurprisingly it didn't work.