Above, Below, and Beyond Tech Talk

by Rahel Lüthy

Guava Lazy Init

Note to self: How to lazily initialize a value with Java/Guava

1
2
3
4
5
private final Supplier<Integer> lazyValue = Suppliers.memoize(new Supplier<Integer>() {
  public Integer get() {
    return 42;
  };
});

Scala Gems #8: Breeze

I have recently bought Hilary Mason’s An Introduction to Machine Learning with Web Data to refresh my rusty ML memory. The video class offers a very solid, yet entertaining mix of coding and theory, and is definitely worth watching.

Hilary is coding in Python, but I took her excellent examples as an inspiration to further practice my Scala. Based on Breeze, a set of libraries for machine learning and numerical computing, I wrote my first little classifier.

My classifier uses a support vector machine (SVM) to distinguish images of two distinct categories — one containing circles, the other containing crosses. I used 10 different fonts to create the two sets of test images:

I used the red component of each pixel’s RGB value as a feature vector. Given that all images are in grey scale, this seemed like a good first choice. And indeed, after training the SVM with 9 images of each category, the 10th image can be classified with a probability of roughly 0.75.

All code can be found on GitHub.

Octopress

I have just completed the migration of the old & slooow WordPress thingie to a blazingly fast Octopress setup. The static files are now hosted via GitHub Pages, and the new feed can be reached at netzwerg.ch/atom.xml. Stay tuned!

Scala Gems #7: this.type

Assume you have a simple class hierarchy with an API optimized for method chaining:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
abstract class Carnivore {

  def eat: Carnivore = {
    println("eating meat, yummy!")
    this
  }

}

class Dog extends Carnivore {

  def bark: Dog = {
    println("wuff!")
    this
  }

}

For obvious reasons, the compiler will only allow to chain methods in a certain order:

1
2
3
4
5
val dog = new Dog()
// compiles ok
dog.bark.eat
// does not compile ('eat' returns a Carnivore, which cannot bark)
dog.eat.bark

In the Java world, possible work-arounds involve generics. Either via overriding, or with a self-reference trick. Here’s how it would look in Scala:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
abstract class Carnivore[T] {

  def eat: T = {
    println("eating meat, yummy!")
    self
  }

  abstract def self: T

}

class Dog extends Carnivore[Dog] {

  def bark: Dog = {
    println("wuff!")
    this
  }

  def self = this

}

While this works just fine, it involves quite some clutter. And Scala can actually do better! A powerful (but yet not very well-known) construct can solve the problem: this.type

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
abstract class Carnivore {

  def eat: this.type = {
    println("eating meat, yummy!")
    this
  }

}

class Dog extends Carnivore {

  def bark: Dog = {
    println("wuff!")
    this
  }

}

And now go spread the word!

Bloxorz

Unfortunately, the Scala course at Coursera is over. It was really an excellent experience and I am desperately waiting for part two. The lectures were a bit on the slow side (luckily the player featured nice high-speed playback), but the assignments were rather challenging. As far as I know, the course material will stay available indefinitely, so if you missed the course, you can still sign up and watch the videos or download the exercises just for fun.

Due to the official code of honour, I am not allowed to discuss any actual code here, but the last assignment is still worth mentioning: Based on the concept of lazy data structures, we were asked to find a generic solution to the Bloxorz game. When I initially read the assignment, I doubted that this would be possible within a reasonable amount of time. But the exercises were so well crafted, that they guided us in a step-by-step fashion – in the end, I managed to get the maximal score within less than two hours.

Inspired by the addictive block-rolling, I was recently playing around with CSS3. I really have no 3D experience whatsoever, but here’s my quick shot at some basic transformations (webkit only; put focus on cube and press left/right arrows):

Scala Gems #6: Giter8

When building Scala projects, your best bets are to either use the official sbt, the simple build tool which is actually not so simple, or Gradle, my personal preference.

Both of them are very much based on conventions, i.e. they require only minimal configuration if you stick to the rules of a default project structure. But what is the default project structure? And how can you set one up with minimal effort?

Enter giter8: A command line tool to generate files and directories from templates published on github.

For sbt:

The official sbt templates maintained by Typesafe can be found here (note that they publish g8 templates for their complete stack, even for examples & tutorials).

For Gradle:

There’s no official Gradle counterpart, but https://github.com/coacoas/scala-gradle.g8 works like a charm.

As usual, just fork & improve if you need the templates to behave differently.

Scala Gems #5: FP @ Coursera

Along with more than 40k others, I am in the second week of Odersky’s free online course titled “Functional Programming Principles in Scala”. The video lectures are really well structured and very entertaining – it’s great to learn from the master himself. Given that the course only requires 1 year of programming background, the assignments are not too complex yet, but I have no doubt that things will get trickier soon!

Afaik, it’s still not too late to register, and it’s FREE: http://www.coursera.org/course/progfun

Regarding tool setup: Don’t even download the Eclipse-based Scala IDE, it sucks big time. How can these people get anything done with a piece of crap that crashes every few minutes, even with just a 2-file project?! Luckily, the assignments can as well be completed with IntelliJ IDEA, with the community edition Scala plugin.

To end this post with some code, this is how the first exercise looks like:

1
def pascal(c: Int, r: Int): Int = ???

The cool thing is that this code compiles – Scala method naming FTW!

Mac Tips & Tricks #8: Changing Application Icons

There are many reasons why you might want to change an application’s icon. In my case, I wanted to be able to distinguish the stable IntelliJ IDEA 11 version from an early access 11.1 build:

Here’s how I changed the default (blue) icon to the new (pink) one:

First, reveal the application’s installation location in Finder (from the Dock context menu: Options » Show in Finder). From within Finder, invoke the context menu on the selected application, and Show Package Contents. Locate the icon file (*.icns) inside Contents » Resources. Make a backup copy, edit the icon in your favorite image editor (I simply overlaid a red color filter in Acorn), and save it as a *.png.

Now comes the tricky part: Apple’s icon format includes more than just an image, it actually contains a collection of images in different sizes, resolutions & states. To create a new *.icns file, launch Icon Composer (which ships with OSX). Open the original application icon to check which sizes your new icon should support:

Create a new file, drag & drop your edited *.png to the required image size containers, and save the result. Re-launch your application – tada!

IntelliJ IDEA: Reveal in Terminal

IntelliJ IDEA ships with a very handy Reveal in Finder action, but unfortunately, I am still a terminal person. Today I put together a tiny AppleScript which creates a new iTerm2 session and changes to a directory of choice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
on run dir
  tell application "iTerm"
    activate
    tell last terminal
      set mysession to (make new session at the beginning of sessions)
      tell mysession
        set name to "Default"
        exec command "/bin/bash -l"
      end tell
      tell mysession
        write text "cd " & dir
      end tell
    end tell
  end tell
end run

IDEA allows to add custom actions via Settings » External Tools. Save the above script to a file (e.g. launchTerminalAndChangeDir.scpt) and configure a new Reveal in Terminal action as follows:

Additionally, you may want to associate a key binding via Settings » Keymap. I chose Ctrl-Shift-T, which seems intuitive and is not conflicting with any OSX defaults.

The Setup

I started my new job at edorasware last week, with a new & shiny 15-inch MacBook Pro. A fresh computer with a blank OS is both, a blessing and a curse – it takes quite a while until it feels like home again. And even after a week, I still miss a few configuration settings or shortcuts here and there.

Setting up the new machine was certainly an opportunity to consolidate the apps and tools I like and need. Inspired by The Setup, here’s what I currently use to get things done:

As a Java developer, I spend most of my time in IntelliJ IDEA, the best IDE ever (weight this statement by the fact that I used Eclipse for 7+ years before). My second home is the command line. I use iTerm2, which has excellent search support, provides mouseless copying, and is more unixy than the official Terminal. I’m still learning to use _ Finder efficiently. The TotalFinder plug-in, with tab support and its Folders on Top_ mode, is my latest attempt at making friends.

A few crucial things help me organize & navigate my workspace: I use three virtual desktops (via Mission Control) which I access by keyboard shortcuts – 1 for Mail/Calendar, 2 for Browser, and 3 for IDEA. A launcher helps me kick-start applications. I switched from Quicksilver to Alfred – it provides the same features and is under active development. Divvy tames all window sizes & positions, clearly a missing feature in OSX.

Transitioning from Snow Leopard to Lion was more challenging than anticipated, mainly because of its different mouse usage paradigms. Most of the built-in gestures are easy to use, but some of them collide with my old habits (how the heck can I turn off horizontal scrolling in order to re-map the swipe gesture to back/forward navigation in IDEA?!). A while back I forced myself to exclusively use taps (rather than clicks) on the trackpad. Wow – the absence of the mechanical noise makes such a difference, everything suddenly feels very light and smooth!

These are pretty much the apps at the core. In addition, I like Chrome, 1Password, TextMate, Dropbox, Skype, Spotify, Acorn, Inkscape, Lightroom and OmniGraffle – just to name a few.

What are your favorite tools we should all know about?