Attempted peace

10 10 2009

Sideshow Bob: Attempted murder? Now honestly, what is that? Do they give a Nobel prize for attempted chemistry? Do they?
—-
Nope, only for attempted peace it seems.


What's new pussycat?

06 10 2009

Quite a bit actually:


unsavory now available as gem

08 09 2009

unsavory is now available as a gem, which means that you can comfortably install it like this:

# Only if GitHub isn't in your gem sources yet
$ gem sources -a http://gems.github.com 
$ sudo gem install citizen428-unsavory

Rubygems will automatically create a wrapper-script named “unsavory”, which you can use to start the program so you finally can get rid of all these outdated bookmarks.


Using Java libraries from Clojure

06 09 2009

After reading Scripting Java Libraries With Ruby on the Engine Yard blog, I decided to translate the two example programs to Clojure. Please keep in mind though that I'm pretty much a Clojure newbie myself, so the code shown here might not be very idiomatic. In case you have any suggestions on how to improve the code examples presented here, please leave a comment, thank you! To get the most out of this post, you should probably read the section on Java Interoperability in Mark Volkmann's excellent Clojure tutorial first.

A MIDI Keyboard

The first example listens for a line of text which then gets converted into a playable MIDI sequence. Let's start with importing the classes we need. (ns midi/keyboard (:import [javax.sound.midi MidiSystem Sequence MidiEvent ShortMessage]) (:use [clojure.contrib.seq-utils :only (indexed)]))
Next we set up a loop and an exit clause. In case the user enters the word "exit", we call System.exit to shut down all the threads that got started by Java's MIDI support. (loop [line (read-line)] (if (re-find #"exit" line) (System/exit 0)) ... other code snipped... (recur (read-line)))
The main part of the application constructs a new MIDI sequence by creating a NOTE_ON event for every character in the entered text and then finishing the sequence with a STOP event. The original article states that it favors simplicity over efficiency, so the same also holds true for my "translation". (def sq (Sequence. Sequence/PPQ 2)) (def track (.createTrack sq)) (doseq [[idx note] (indexed line)] (let [msg (ShortMessage.)] (.setMessage msg ShortMessage/NOTE_ON (int note) 64) (.add track (MidiEvent. msg idx)))) (let [msg (ShortMessage.)] (.setMessage msg ShortMessage/STOP) (.add track (MidiEvent. msg (+ (.length line) 1))))
To finish off our first program we play the sequence before prompting for more input (see the loop snippet above). (doto (MidiSystem/getSequencer) (.open) (.setSequence sq) (.start))
Full source for the first example

Making It More Interactive

While the first example was fun, it wasn't as interactive as it could be. Therefore the second program launches a GUI window to receive keystroke events, turning a note on or off when a key is pressed or released. Since we don't have to create MIDI sequences this time, our import statement becomes a lot shorter: (ns midi/interactive (:import [javax.sound.midi MidiSystem] [javax.swing JFrame] [java.awt.event KeyListener]))
This example directly accesses the system synthesizer. The following lines open the default synthesizer's channel 0 (and also create a JFrame object which we'll use later): (let [synth (MidiSystem/getSynthesizer) frame (JFrame. "Music Frame")] (.open synth) (let [channel (aget (.getChannels synth) 0)]
We then launch a GUI frame as a simple and cross-platform way to receive keystroke events. The KeyListener interface is implemented using Clojure's proxy macro, using keyPressed and keyReleased events to turn notes on or off. (doto frame (.setSize 300 300) (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) (.addKeyListener (proxy [KeyListener] [] (keyPressed [e] (.noteOn channel (int (.getKeyChar e)) 64)) (keyReleased [e] (.noteOff channel (int (.getKeyChar e)))) (keyTyped [e])))
Last but not least we display our frame to let the fun begin. (.setVisible true)))) Full source for the second example

I hope this article helped to illustrate how easy it is to use the plethora of existing Java libraries from Clojure. In case you have any feedback or questions, please feel free to leave a comment!

First small Clojure program

26 08 2009

After I recently got interested in Clojure, I decided to use it for a small “project”, namely a script which will download all the enclosures from an RSS 2.0 feed to the current working directory. The program itself is very concise, with only 9 lines of actual code (the rest are comments and library imports).

My impressions: for somebody with little previous exposure to Lisp (some CL and very little Scheme and no Java background the learning curve can be a bit steep in the beginning, especially since documentation is still a bit (too) sparse. However, if you are willing to spend some time on Google or reading the actual source code of Clojure and clojure-contrib you’ll generally find what you are looking for. Besides that people in the Clojure community seem to be quite friendly and my question on #clojure got satisfactorily answered within a minute.

It’s a definitely too early for any real assessment of the language, but I quite like what I saw so far, so there probably will be some more Clojure-related posts in the near future.

Some links to get you started:
Clojure API
An overview of clojure.contrib
Clojure – Functional Programming for the JVM
20 Clojure links to get you up to speed
Learning Clojure and Emacs


Easy setup for Clojure on Mac OS X Leopard

24 08 2009

Clojure definitely is one of the hottest new programming languages around and just recently hit a very important milestone. Setting up a nice Clojure development environment on OS X still can be a bit of a pain though, which can be seen by the number of HOWTOs and installation notes floating around on the web. I therefore decided to expand one of those into ClojureX, which I believe is the easiest way to get up to speed with Clojure development on Leopard.

ClojureX can


  • download and build the source code for Clojure, clojure-contrib and JLine (a readline like library for Java)
  • download editor support packages for TextMate and Emacs
  • create a symlink for the Clojure startup script in /usr/local/bin
  • install support for TextMate via the clojure-tmbundle
  • configure Emacs to use clojure-mode, Slime and swank-clojure
  • keep your Clojure installation up to date via a simple “git submodule update && ant”

I hope this will come in handy for other people interested in trying out Clojure on Mac OS X, if you have any feedback please post it in the comment section.


Pascal vs. Ruby

29 06 2009

On ruby-talk somebody was asking for a method which will be used to generate a random string, by returning either a lowercase letter or one of the digits 0-9 when called. As an example he posted the following Pascal program:

function GetRandomChar: char;
var
 r: integer;
begin
 r := random(36);
 case r of
   0..25: result := chr(ord('a') + r);
   else : result := chr(ord('0') + r);
 end;
end;

“Translating” this to Ruby, this is what I got:

In your face, Niklaus Wirth! ;-)

P.S. Actually I do have fond memories of the good old Turbo Pascal days.


Quick and dirty lazy lists in Ruby

18 06 2009

Hash.new with a block is a sexy beast: you can specify default hash values and when a key is first used, the value will be calculated and inserted into the Hash. Based on that behavior I took a couple of minutes to hack together a small proof of concept class for lazy lists:

As I said, this is quick and dirty, especially since you have to pass the entire Hash.new block to LazyList.new right now. Other than that I quite like it though. I know there are at least two other lazy list implementations for Ruby, but it seems like both haven’t been updated in a while and I don’t particularly like their interfaces. Dunno, if I manage to simplify list definition, I may actually try to develop this into something. Don’t hold your breath though…


Unsavory updates

16 06 2009

Today I felt like playing around with unsavory a bit more, which led to some minor improvements:


  • code reorganization: the delicious class got moved to a separate file in lib/ and got a new method for easier retrieval of the URLs array

  • login credentials can now be read from a config file, thus making HighLine optional


Next on my list is packaging this up as a gem so people can simply install it with ‘gem install unsavory’.


Review: The Well-Grounded Rubyist (Manning Publications)

09 06 2009

As part of Rubylearning’s current book promotion I’m reading The Well-Grounded Rubyist by David A. Black. Here are my thoughts on the book:

If you are new to Ruby, this may very well be the book you are looking for, since the author was really serious about the “well-grounded” in the title. Together the first six chapters form Part 1, aptly called “Ruby Foundations”. Here you’ll learn about objects, modules, classes, self and control-flow techniques. Although this part may not be the most interesting for more experienced Rubyists, it’s certainly well-written and manages to present a lot of very fundamental Ruby right at the beginning. True, at first I was a bit surprised to see that singleton methods were – implicitly – introduced before classes, but when you follow the author’s logic, it all makes a lot of sense. What I really like about this approach is that it exposes the reader to concepts needed for some quite advanced Ruby coding right away, and in a very light-hearted and “natural” manner. Well done!

Part 2 (“Built-in classes and modules”) covers everything from strings, over symbols to regular expressions and file I/O. What I really like about this part is that the author dedicated two whole chapters to collections and iterators/enumerators, which are essential for everyone striving to become fluent in Ruby.

Last but not least Part 3 (“Ruby dynamics”) talks about singleton methods, procs, lambdas, Symbol#to_proc, the various eval methods, bindings and introspection, thus equipping the reader with all the necessary tools for metaprogramming, one of the many things that make Ruby that sexy little beast it is.

Oh yeah, since I didn’t mention this before, “The Well-Grounded” Rubyist” covers Ruby 1.9.1, which means you’ll learn about the coolest Ruby around. Don’t worry though, most of what you read will also apply to 1.8.6, but isn’t it about time that we all slowly moved on?


Fitness galore

07 06 2009

Since my trip last year I have been fitter than I’ve been for ages, thanks to a weight-loss of about 25kg, more exercise and a healthier diet. Through kyrah’s tweets I learned about a workout program called one hundred pushups and decided to have a closer look today. I took the initial test and only managed a meager 12 good-form pushups, but they were always one of my weak spots. At least I start from the most challenging category. Through the site I also found the two related programs two hundred situps and two hundred squats, where the initial tests looked a lot friendlier: with 35 situps and 40+ squats both programs suggest that I start from week 3. :-)

Now let’s see how effective these workouts will turn out to be.


unsavory — get rid of stale Delicious bookmarks

06 06 2009

While browsing through my Delicious bookmarks the other day, I realized that over time I had accumulated quite a few dead links (about 5% of my collection). I then looked for a simple tool to automatically remove them, but couldn’t find one that appealed to me, so I wrote my own script called unsavory which you can find on GitHub:

http://github.com/citizen428/unsavory/tree/master

It uses HTTParty to generate a list of all your bookmarks, which then get checked individually with Net::HTTP. Every link that returns an HTTP status code of 404 will automatically be removed (no questions asked, no undo), links with a status code other than 200 (OK) won’t be changed but will display some information in case you want to fix them manually. Here’s some example output (links anonymized for this post):

  Enter Delicious username: citizen428
  Enter Delicious password: *********

citizen428 has 664 bookmarks. Processing URL #0001: OK Processing URL #0002: OK Processing URL #0003: OK Processing URL #0004: OK Processing URL #0005: OK ... Processing URL #0013: 405: http://... ... Processing URL #0074: 302: http://... ... Processing URL #0086: Connection reset by peer – https://...

Not bad for under 60 lines of code. :-) I hope this is useful to some of you, I do have some features I plan on adding to this in the future.


Review: Functional Programming with Clojure (PeepCode screencast)

25 05 2009

A couple of month ago I first heard about Clojure, a Lisp-like language sitting on top of the JVM. Alas I didn’t yet have time to have a closer look at it, so I decided to get myself the PeepCode screencast.

This 65 minute video is the first to use PeepCode’s new post-production workflow, and it’s very well done! In just a little over an hour you go from learning about Clojure’s basic concepts and syntax to writing a multi-user text based adventure game, tackling topics such as data structures, thread safety, lazy collections, unit testing and packaging of Clojure apps. All of that is clearly presented and easy to follow, which makes for an ideal first overview of the language. If you are curious about Clojure but have little time, consider investing the money for this screencast!

On a more general note it’s interesting to see that more and more languages seem to target the JVM. I never really had any interest in Java and also totally ignored Groovy, but now that JRuby, Scala and Clojure entered the stage, I might start looking into the Java platform a bit more. Especially Scala with its mixed Ruby/Haskell feel appeals to me, but as antifuchs showed, there’s also pretty neat stuff (GitHub project) one can do with Clojure.


Most used shell commands

25 05 2009

I recently found a bash snippet which creates a list of the commands in your .bash_history file and how many times you invoked them:

history | awk '{a[$2]++ } END{for(i in a){print a[i] " " i}}'|sort -rn|head

Although there was no real point in doing so, I felt the need to write a short Ruby script to do the same:

Here’s the output on my MacBook:

$ command_stats | head
time: 75
cd: 68
ls: 66
git: 35
cat: 32
irb: 20
awk: 17
ruby: 15
scala: 15
vim: 12

If you are surprised by how many times (no pun intended) I called time, it’s just because I was benchmarking Project Euler solutions in several languages, everything else is quite regular (and suggests I don’t use the Finder much ;-) ).


Review: Meet MacRuby (PeepCode screencast)

24 05 2009

This afternoon I had the time to finally watch the PeepCode Meet MacRuby screencast.

In case you don’t know MacRuby, it’s a Ruby interpreter sitting on top of Objective-C and OS X core technologies (see also here).

During the 74 minute screencast you will build a basic but functional Twitter client, and in the process learn about MacRuby and Cocoa basics, using Xcode and InterfaceBuilder to develop and bundle your application and many other interesting topics.

The screencast is very well structured, easy to follow and full of good and practical information, including perks and rough edges of the current MacRuby version. All in all a really enjoyable and informative video, which is well worth US$9 (or less if you buy packs of credits)!