# JavaFX 3D Line

I have no experience in 3D programming whatsoever. Last week, I took my first steps in JavaFX 3D, but hit a wall when I wanted to draw a line between two points: There is no `Line` shape! The only out-of-the-box `Shape3D` classes are `Box`, `Cylinder`, `Sphere`, and `MeshView` – wow…

Well, it shouldn’t be too difficult to connect the points with a slender cylinder, right?

I was wrong, it took me an embarrassingly long time to get the trigonometry right :-)

Here’s my magic crutch:

To illustrate what’s going on, I created a 2D representation of all individual steps, starting off with the creation of the cylinder. By default, its center is placed at the origin:

The `moveToMidpoint` transformation moves its center to the final location (the yellow midpoint in the above image):

And finally, the `rotateAroundCenter` transformation corrects the cylinder’s direction:

Obviously, the tricky part is finding the proper axis and angle of rotation. Both are calculated relative to the `yAxis` because of the cylinder’s initial direction. The `axisOfRotation` must be perpendicular to the plane defined by the `yAxis` and the `diff` vector. To find such a perpendicular vector, we can (by definition) calculate the cross product of the two vectors. In the 2D case, the result is equivalent to the z-axis, but in 3D it may be tilted.

The angle is calculated based on the dot product (aka scalar product) of the two vectors, which is defined by

`A • B = |A| |B| cos(alpha)`

If `A` and `B` are both unit vectors, this becomes

`A • B = cos(alpha)`

which we can resolve to

`alpha = acos(A • B)`

That’s it!

# Scala Gems #9: Regex Extractors

Suppose you have a simple date string: `"2015-02-27"`

Regular expressions allow to parse the date and extract parts thereof1: `(\d\d\d\d)-(\d\d)-(\d\d)` defines a pattern which matches the digits and defines capturing groups for the year, month, and day parts.

In Java, a simple example usage would look like this:

Accessing the groups by index is rather awkward and error prone. Luckily, Java 7 introduced support for named groups:

That’s better, but I personally don’t like how the group names pollute the pattern. Regular expressions are hard to read already, the Java escape characters add yet more clutter, and the additional `?<group>` constructs are a kiss of death.

Let’s look at how the same problem can be tackled in Scala:

According to the docs, the canonical way to create a `Regex` is by using the method `r`, which is provided implicitly for strings:

Note the triple quotes, which allow to use the backslashes without further escaping. While this is nice, the true advantage of Scala is that regular expressions can be used as extractors in a pattern match. The pattern stays plain and simple, and yet we have all the freedom to name groups as we please:

Look ma, no clutter!

1. Yes, using java.time.format.DateTimeFormatter would be easier in this simple case.

# Java 8 Optional

Tony Hoare, inventor of the `null` reference, apologetically called it “the billion dollar mistake”.

The problem with `null` is not that it was invented back in 1965, but that we are still struggling with it 50 years later. Any Java developer has probably seen and written code like this:

In fact, most Java monoglots have probably seen and written code like this so many times, that they don’t even see the problem anymore. And yet, with Java 8, they have to deal with a solution: the `Optional` type.

I recently came across this popular article: Embracing the Void: 6 Refined Tricks for Dealing with Nulls in Java. It gives a nice rundown of strategies around the `null` reference. Sadly, it discourages the use of Java 8’s `Optional`. In this post I will explain why the argumentation is flawed.

# Types to the rescue

One way to re-write the above snippet using `Optional` could look like this:

The service returns an `Optional<String>` and the caller is working her way around it. From a complexity point of view, the change is argueably not much of an improvement: We still need a mutable `value` variable, and the overall logic is roughly the same. And yet, the expressiveness has improved. The signature of the service has clearer semantics now. Originally, the caller of the service could not distinguish between “the implementor of the service made a programming error” and “the value has not been found” – both were resulting in `null`. This is possible now and – even better – the type system forces the caller to deal with absents values.

# But wait, there’s more

Now that the semantics are straight, let’s make the `value` variable immutable and eliminate the `if .. else` construct:

This code is safer, more expressive, and more concise than the original version, but the `() -> "..."` clutter makes my Scala heart cringe, so I’m offering yet another variant:

We are taking advantage of the fact that `Optional` behaves like a collection: If it is absent, it behaves like an empty list, the call to `map` is never executed, and the result is an empty `Optional` (which we handle via `orElse`). If the result is present, it behaves like a list with one element, which we trim and return.

# Wrapping legacy code

Imagine that our original `service` interface is actually coming from a 3rd party library. You can’t simply change all the signatures to properly return `Option<T>`. But you can wrap the service calls and create yourself a `null`-safe world:

# Unboxing a cat in a box in a box

And finally: The holy grail of functional programming, `flatMap`.

Let’s start with a simple `User` which has an optional middle name:

Looking up the user via service is straightforward, but look at all those types:

The outer `Optional` is the result of the `map` call (presence/absence of `User`), while the inner `Optional` is wrapping the middle name value.

`flatMap` is our power tool to unwrap the value from nested `Optional`s:

So next time you can’t remember the semantics of `flatMap`, just think of all those cats stuck in their nested boxes:

(via @channingwalton)

I highly recommend The Neophyte’s Guide to Scala - Part 5: The Option Type for anyone interested in further details.

# Guava Lazy Init

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

# 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

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

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

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:

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`

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).

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:

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