Jeroen Pelgrims 2019-07-08T18:34:59.000Z Jeroen Pelgrims Hexo Typescript flexible entity type 2019-06-07T10:21:00.000Z 2019-07-08T18:34:59.000Z TLDR of what’s going on in this post: creating a typescript type definition for a database entity that has a property which can be either an array of references to other entities OR that can be an array of those entities nested in it.
Click here to skip the introduction and go straight to the solution.

On a project I worked on we used API Platform for the backend and React + Typescript for the frontend.

Database diagram

Assume we have the following database diagram:

Example database diagram

With the following data:






Matthew McConaughey1969-11-4

API platform endpoints

In API platform you can define which REST endpoints you want to generate for which entities.
In this example we’ll look at GET /films.

If you’d execute that GET you’d get a JSON response similar to this:

{  "@context": "/contexts/Film",  "@id": "/films",  "@type": "hydra:Collection",  "hydra:member": [    {      "@id": "/films/1",      "@type": "",      "title": "Interstellar",      "rating": 10,      "roles": [        "/roles/1"      ]    }  ],  "hydra:totalItems": 1,  "hydra:view": {    "@id": "/books?page=1",    "@type": "hydra:PartialCollectionView",    "hydra:first": "/books?page=1",    "hydra:last": "/books?page=2",    "hydra:next": "/books?page=2"  }}

You’ll see that every Film has a property “roles” which is an array of IRIs pointing to the related Role entities.

Modeling a Typescript type for the response

If we’d model types for this response in Typescript, a generic approach could be:
(I left out some of the fields I won’t use)

type EntityReference = string;type Entity = {  "@id": EntityReference};type HydraCollectionResponse<T extends Entity> = {  "hydra:totalItems": number,  "hydra:view": {    "hydra:first": string,    "hydra:last": string,    "hydra:next": string  },  "hydra:member": T[]};

The Film entity would look like this:

type Film = Entity & {  title: string,  rating: number,  roles: EntityReference[]};

The full type for a collection response of Films would then just be:

type FilmsResponse = HydraCollectionResponse<Film>;

Embedding relations

API Platform also supports the nesting/embedding of related entities in the response.
So that array of “roles” which are now IRIs could be full “Role” objects if we want it to be.
This is done by adding a parameter in the GET request to define which entities should be embedded.
GET /films?embed[]=roles

Now instead of an array of IRIs, we’ll receive an array of Role objects for the “roles” property:

{  ...  "hydra:member": [    {      "@id": "/films/1",      "@type": "",      "title": "Interstellar",      "rating": 10,      "roles": [        {          "name": "Cooper",          "actor": "actors/1"        }      ]    }  ],  ...}

To model this in Typescript we could make a completely new type FilmWithRole where the roles property is Role[] instead of EntityReference[], but then we’d have to re-define every other property as well.
It would be better to re-use the definition we already have.

Your first thought might be to just “overwrite” that single property with a different definition:

type FilmWithRole = Film & {  roles: Role[]}

But that won’t work. Because then the roles property is of type EntityReference[] & Role[]. Which is impossible to fulfill.

A generics solution

We need to define a type for Film where the roles property can be defined by a parameter.
So that one place we can say “It’s just a list of references” and in an other place we can say “It’s a list of Role objects”.
This we can do with generics:

interface WithRoleReferences {  roles: EntityReference[];}interface WithRoles {  roles: Role[];}type Film<T = WithRoleReferences> = Entity & T & {  title: string,  rating: number};

This way when we use just use the Film type, it’s exactly the same as before. roles is an array of references to roles.
But now, when we embed the Role entities, we can also easily use the type with a generic parameter: Film<WithRoles>.
In this case the “roles” property will be an array of Role objects.

What if we also want the actors?

Then the embed query parameter in the get call would also include the actors entity:

And the modeling of the types would work exactly the same as before.

type Actor = Entity & {  name: string,  birthDate: string}interface WithActorReference {  actor: EntityReference;}interface WithActor {  actor: Actor;}type Role<T = WithActorReference> = Entity & T & {  name: string};interface WithRoles<T extends WithActor | WithActorReference = WithActorReference> {  roles: Role<T>[];}

You can then define a Film that also has the Roles embedded and the Actors in each role:


You’ll run into a small issue when you have more than 1 property you need to be able to switch types of.
Say if our film would also have a reference to Showings:

interface WithRoleReferences {  roles: EntityReference[];}interface WithRoles {  roles: Role[];}interface WithShowingReferences {  showings: EntityReference[];}interface WithShowings {  sowings: Showing[];}type Film<T = WithRoleReferences & WithShowingReferences> = Entity & T & {  title: string,  rating: number};

You’d expect to be able to use Film<WithShowings> to only embed the showings objects.
But now the roles property isn’t defined on that type!
The correct way to use it would be Film<WithShowings & WithRoleReferences>.

Quick and dirty React Reason HMR (Hot module reloading) 2017-09-15T18:28:00.000Z 2019-07-08T18:34:59.000Z It proved quite hard to find a way to do HMR in ReasonReact.
Here’s a quick but dirty way of doing it:

Initialize an app using reason-scripts
After having installed the bucklescript platform you can run:
yarn create react-app reasonreact-hmr -- --scripts-version reason-scripts

Replace your src/ file with this:

[%%bs.raw {|  require('./index.css')  var App = require("./app.js");  var ReactDOMRe = require("reason-react/lib/js/src/reactDOMRe.js");  var ReasonReact = require("reason-react/lib/js/src/reasonReact.js");  function render(Component) {    ReactDOMRe.renderToElementWithId(      ReasonReact.element(0, 0, Component.make("Welcome to React and Reason", [])), "root");  }  render(App);  if ( { => {      const NextApp = require('./app').default;      render(NextApp);    });  }|}];

So what we’ve done here is replace the rendering code which was in Reason before with raw Javascript code which supports hot reloading right from Reason. (The same JS code you can use in any javascript react project to make it support HMR)

Why Javascript and not Reason? Because I don’t know enough of Reason/Ocaml yet to implement this using that.

What’s actually going on?

I took the js code that is generated from the original and modified it to support HMR.
The require statements you see are the ones generated by reason when you run the project for the first time.

Arduino solar aimer 2017-06-25T10:26:00.000Z 2019-07-08T18:34:59.000Z This is the first “more advanced” thing I did with an Arduino. Well, more advanced than just turning on and off some leds that is.
I wanted to build something that would aim solar panels towards the sun, increasing their efficiency.

I did this in 3 iterations, each one extending the previous one.

  • First a construction where I steer the servos by buttons myself
  • Then a construction where the servos are steered by light resistors
  • And finally a construction where I add a bigger frame so I can put solar panels on it.


So you can build this for less than 10 USD. (Prices shown are at time of writing)

Iteration 1: Manual aiming

The first iteration is being able to steer the servos manually.
When I press the right button the pointer should move right, when I press the forward button it should move forward et cetera.

2 servos will be placed on top eachother. The bottom servo determines the movement on the horizontal plane and the top servo the vertical plane.
The top servo is attached to the bottom one by it’s side.

A video of this in action

A schematic of the breadboard:

Breadboard schematic

The code

The code can be found on GitLab
This repo also includes a Fritzing file which includes the breadboard schematic.
If you change the MOVE_STEP variable to for example 5, the servo will move more per tick.
You’ll then get something that moves like this.

Iteration 2: Replacing the buttons by Photoresistors

Instead of me manually directing where the pointer should aim we’ll add some automation by using photoresistors. (Light dependent resistors)
Most of this is based on this Instructables post.

The main idea is that you have 4 sensors which are partitioned into 4 quadrants (Top Right, Bottom Right, Bottom Left, Top Left).
A division is made by 4 flat pieces of wood so that the resistor is not influenced by the light from the other resistors’ partitions.
In the code you will then determine which direction receives more light and instruct the servos to point the “stick” to that direction.

Video of this in action

A schematic of the breadboard:

Breadboard schematic

The code

This can again be found on GitLab
And includes another Fritzing file with the breadboard schematics.

3rd Iteration: Building a frame for the solar panels

Instead of taping the servos together I made something more permanent with wood and glue.
The wood sticks I also bought from AliExpress :D.


The code

The only thing that changed is the construction. The actual aiming system is still the same.
We just want to point to where the most light is coming from, so the code is exactly the same as in Iteration 2.

Final Notes

As you can maybe see in the last video the construction is quite wobbly.
That’s because all the weight is being beared by the thin axes of the servos and the thin ice cream wood sticks aren’t the ideal construction material.
I’d like to try making a construction where I make use of gears or a belt transmission so the weight can be beared by the surface below it.

But the next project will be actually mounting the solar panels I ordered on the construction and powering the arduino setup with them!
But I need to wait a while for that because it takes a while to receive the goods from AliExpress.

Pushing to Dokku from GitLab CI 2016-03-05T02:01:00.000Z 2019-07-08T18:34:59.000Z GitLab CI logo

I had heard about GitLab for a while ago but it was only recently that I actually tried it out a bit more thorougly and discovered they have quite a few cool features.
Just like Bitbucket they have a free tier which includes private repositories, or projects in GitLab lingo.

But on their free solution on —the .org domain is for the project itself— you can also make use of their CI service GitLab CI. Making use of the CI service is as easy as adding a file called .gitlab-ci.yml.
This makes the CI usage so much faster and easier than configuring everything on a separate site like CodeShip or Semaphore. Another big benefit is that there are no limitations of how many builds you can do per month or restrictions on private projects.

My projects are hosted on my own Dokku setup and I needed to find a way to automatically push from my GitLab repo to my Dokku server (using ssh authentication) on a successful build by GitLab CI.

Getting Gitlab CI to push to Dokku

Generating an SSH keypair

$ ssh-keygen -t rsaEnter file in which to save the key (/home/<username>/.ssh/id_rsa): /home/<username>/.ssh/exampleEnter passphrase (empty for no passphrase):Enter same passphrase again:Your identification has been saved in /home/<username>/.ssh/example.Your public key has been saved in /home/<username>/.ssh/

For the rest of the tutorial I’ll assume you left the passphrase empty.

Adding the keypair to Dokku #

sshcommand should already be installed on your server by Dokku by default.

$ cat /home/<username>/.ssh/ | ssh root@<yourdokkuinstance> "sudo sshcommand acl-add dokku <description>"

Where <yourdokkuinstance> is the domain or ip where your dokku is running.
It’ll show a bunch of hexadecimal numbers separated by parentheses here if successful.

Adding the private key to GitLab

Print out the contents of your private key and copy them to your keyboard.

cat /home/resurge/.ssh/example

Copy everything from

  • Open GitLab.
  • Go to the project you want to deploy
  • Open the settings
  • Open the Variables tab
  • Add a new variable with the key SSH_PRIVATE_KEY and paste the contents of the private key file.

Using the private key in the GitLab CI script

Create a file called .gitlab-ci.yml in your project repository.

Add the following contents:

before_script:  - mkdir -p ~/.ssh  - echo "$SSH_PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa  - chmod 600 ~/.ssh/id_rsa  - ssh-keyscan -H '<yourdokkuinstance>' >> ~/.ssh/known_hostsstages:  - deploydeploy_to_dokku:  stage: deploy  script:    - git push dokku@<yourdokkuinstance>:<projectname> master

Useful info: Removing the key from Dokku when it’s obsolete

To remove the key you added earlier to the server where your Dokku installation is running you can SSH into the server and run the following command:
sshcommand acl-remove dokku <description>
Where <description> is the description you entered at the sshcommand acl-add step.

Other Paas providers

Most of the steps in this post should be easily usable for other Paas providers as well like Heroku or OpenShift.
You’ll have to ignore step 2 (Adding the keypair to Dokku) and possibly step 1 as well (Generating an SSH keypair). Instead, you should attach the generated key to your repository or account on your Paas provider’s site or it’s possible you’ll be provided with one (and thus don’t need to generate one).

This post was deployed using Gitlab CI as described in the post above :)

Clean & efficient namespacing/routing in express 4 2014-07-20T23:06:00.000Z 2019-07-08T18:34:59.000Z A full example for both express 3 and 4 can be found on github.

I have a bunch of routes which are under the same namespace.

GET /api/personPOST /api/personGET /api/person/:idPUT /api/person/:idDELETE /api/person/:id

I could start implementing these as follows:

app.get '/api/person', (req, res) ->    #return peopleapp.get '/api/person/:id', (req, res) ->    #etc. 

But I have a problem.
I’m lazy, so fuck that shit.

Express 3

In express 3 you had the express-namespace module which could alleviate your problems as follows:

express = require 'express'require 'express-namespace' #Be sure to include this *before* creating your app objectapp = express()app.namespace '/api', ->    app.get '/person', (req, res) ->        #return people    app.get '/person/:id', (req, res) ->        #return person   #etc.

Express 4

In express 4 the Router class received a rework.

You can now do the following:

Router = (require 'express').RouterpersonRouter = Router()personRouter.get '/', (req, res) ->    #return peoplepersonRouter.get '/:id', (req, res) ->    #return person by idapiRouter = Router()apiRouter.use '/person', personRouterapp.use '/api', apiRouter

Looks more cluttered than the v3 example you say?
Well keep in mind that with this way you can more easily put everything in separate files without passing your app object everywhere.

Express 4 - shorthand

In the previous example we’ve always attached a verb directly to a route, but you can also define a route on it’s own and then attach verbs to that.

#app.coffeeexpress = require 'express'app = express()apiRouter = express.Router()app.use '/api', apiRouterapiRouter.use (require './person')
#person.coffeeRouter = (require 'express').RouterpeopleRouter = Router()peopleRouter.route ''    .get (req, res) ->        #return people    .post (req, res) ->        #create personpeopleRouter.route '/:id'    .get (req, res) ->        #return person    .put (req, res) ->        #update person    .delete (req, res) ->        #delete personmodule.exports = peopleRouter
Node streams in CoffeeScript 2014-05-30T14:50:00.000Z 2019-07-08T18:34:59.000Z I was looking for a way to make a search on Google and getting the results back on a one-by-one basis instead of getting them by 10 per query to the api.
In Python I’d use generators for this and I was looking for something similar in Node. As far as I could figure out actual generators are only available starting from v11.x and thus not yet in 10.28, the current stable version. And even if they were, they wouldn’t be in CoffeeScript yet.

The closest solution that I found was Streams.
It was a bit tricky figuring these out and getting them to work in CoffeeScript, hence this post.

String/Buffer streams

Streams in node by default handle with Buffer values. (Which can also be seen as strings since calling .toString() on one will convert it to a string.)

stream = require 'stream'class CharStream extends stream.Readable    constructor: (@s) ->        super    _read: ->        for c in @s            @push c        @push nullclass UpperCaseStream extends stream.Transform    _transform: (chunk, enc, next) ->        @push chunk.toString().toUpperCase()        next()class LogStream extends stream.Writable    _write: (chunk, enc, next) ->        console.log chunk.toString()        next()

Now when we run this:

new CharStream 'ab c'    .pipe new UpperCaseStream    .pipe new LogStream

The console output will be:

  1. CharStream takes a string and it’s output is each character in that string one by one
  2. UpperCaseStream then takes the results from step 1 and transforms them to uppercase characters.
  3. Finally LogStream takes those uppercased values and logs them in the console

Pushing null

Note that in _read at the end null is pushed, this is to tell the consumer of the stream that the stream has ended.
If you don’t do this the consumer will call _read again, causing the stream to effectively never end. The output will then be an infinite sequence of ['a', 'b', ' ', 'c', 'a', 'b', ...]
Pushing things will (might?) trigger _read to be called again.

Object streams

If you want to use regular javascript objects instead of just strings you’ll need to set objectMode = true.
It’s important to do this in the call to super and not just setting it on this (@)

stream = require 'stream'class ObjectStream extends stream.Readable    constructor: (@xs) ->        super            objectMode: true    _read: ->        for x in @xs            @push x        @push nullclass GetPropertyStream extends stream.Transform    constructor: (@getter) ->        super            objectMode: true    _transform: (chunk, enc, next) ->        @push @getter(chunk)        next()class UpperCaseStream extends stream.Transform    _transform: (chunk, enc, next) ->        @push chunk.toString().toUpperCase()        next()class LogStream extends stream.Writable    _write: (chunk, enc, next) ->        console.log chunk.toString()        next()

Running the following will cause the values of the name properties to be logged in uppercase.

new ObjectStream [        { name: 'Jake' }        { name: 'Fred' }        { name: 'Mark' }        { name: 'Jeroen' }    ]    .pipe new GetPropertyStream (x) ->    .pipe new UpperCaseStream    .pipe new LogStream



Google search results as a stream

What I eventually ended up with for getting the search results from Google one-by-one is the following:

stream = require 'stream'request = require 'request'class GoogleSearchStream extends stream.Readable    #    constructor: (@query, @resultCount=8) ->        super            objectMode: true        @resultsetSize = 8        @pushed = 0        @apiUrl = -> "{@query}&start=#{@pushed}&rsz=#{@resultsetSize}"        @pushBlock()    _read: ->        #do nothing    pushBlock: () ->        request.get            headers:                referer: 'http://localhost'            url: @apiUrl(),            (err, response, body) =>                if not err and body and response.statusCode is 200                    data = (JSON.parse body).responseData                    for result in data.results                        @pushed += 1                        @push result                        if @pushed >= @resultCount                            @push null                            return                    @pushBlock()                else                    @push null

Note that the Google web search api is deprecated.
This is just some example code demonstrating what I could figure out from streams.
I’m sure that there is a cleaner way of doing something like this and would love tips and improvements in the comments.

Ghost upgrade script 2014-05-25T17:22:00.000Z 2019-07-08T18:34:59.000Z The following is a bash script to upgrade your Ghost installation automatically to the latest version.
The script is meant to be used on an Arch linux installation but should be pretty generic. On other distro’s you should only have to change the lines to start/stop ghost. (see “Stopping Ghost” & “Starting Ghost” below)

Important: This does not update your template, in case you’ve made modifications to it yourself. This will still have to be done manually.

#!/bin/bashBACKUP_FILE=/tmp/backup.tgzGHOST_UPDATE_URL= [ "$1" == "" ]; then    echo "Arg 1 must be the path to the blog folder!"    exit 1fiBLOG_PATH=$1echo 'Stopping Ghost'sudo systemctl stop <servicename>echo 'BACKUP starting'tar -capf $BACKUP_FILE -C $BLOG_PATH .echo 'BACKUP done'{    LATEST_FOLDER=/tmp/ghost-latest    echo 'Downloading latest Ghost version'    wget -q $GHOST_UPDATE_URL -P /tmp/    rm -rf $LATEST_FOLDER    unzip -q /tmp/ -d $LATEST_FOLDER    echo 'Overwriting root files'    (        cd $LATEST_FOLDER;        cp *.js *.json *.md LICENSE $BLOG_PATH    )    echo 'Replacing core directory'    rm -rf "$BLOG_PATH/core"    cp -r "$LATEST_FOLDER/core" "$BLOG_PATH/core"    echo 'Installing Ghost dependencies'    (        cd $BLOG_PATH;        npm install --production --quiet    )    echo 'Upgrade done!'} || {    echo 'BACKUP restore'    rm -rf $BLOG_PATH    mkdir $BLOG_PATH    tar -xf $BACKUP_FILE -C $BLOG_PATH    echo 'BACKUP restore done'}echo 'Starting Ghost'sudo systemctl start <servicename>
Token based, sessionless auth using express and passport 2014-04-20T15:04:00.000Z 2019-07-08T18:34:59.000Z Problem at hand

What I wanted to make was a webservice with which I could authenticate through facebook initially and using a token in subsequent requests. I found a bunch of clear information about each individual part but not how to integrate everything, hence this post.
A working example containing all the code can be found on bitbucket.

I’ll be using:

  1. express
  2. mongoose: for storing the users, could just have used an array for the example, but this made it a bit more complete.
  3. passport
  4. passport-facebook
  5. passport-http-bearer: token based authentication for express

Facebook auth

Passport made this incredibly easy with their facebook strategy.
This sample code shows that the token returned by Facebook is stored on the user connected to the id of the facebook profile that’s returned.
For the source of what User.findOrCreate does you can look at the repo.

This strategy could be replaced by implementing your own OAuth strategy using passport.

options = {    clientID: process.env.FACEBOOK_APP_ID,    clientSecret: process.env.FACEBOOK_APP_SECRET,    callbackURL: 'http://localhost:3000/auth/facebook/callback'};passport.use(    new FacebookStrategy(        options,        function(accessToken, refreshToken, profile, done) {            User.findOrCreate(                { facebookId: },                function (err, result) {                    if(result) {                        result.access_token = accessToken;              , doc) {                            done(err, doc);                        });                    } else {                        done(err, result);                    }                }            );        }    ));

Halfway through writing this I regretted not just writing it in CoffeeScript, which was the case for my original code. Because }})}}));
As you see I’m just storing the token returned by Facebook to be used by the client but you could just as well generate your own token here and store that.
I’m also storing the token in mongodb here but maybe storing the token in redis and pointing to the user’s id would be better. Because with this implementation the user won’t be able to be logged in from 2 different clients at once.
(The 2nd time the token will be different and thus overwritten in the DB, invalidating the first client’s token).

Making it sessionless

I had 2 problems with this.

  1. After successfully authenticating with facebook, passport wanted to serialize the user and save hir in the session.
  2. How to return the token to the client. In the documentation of passport-facebook it is only shown how to set static success and failure routes:
app.get(  '/auth/facebook/callback',  passport.authenticate('facebook', {    successRedirect: '/',    failureRedirect: '/login'}));

I needed a way to add the token to the successRedirect route.

app.get(  '/auth/facebook',    passport.authenticate('facebook', { session: false, scope: [] }));app.get('/auth/facebook/callback',  passport.authenticate('facebook', { session: false, failureRedirect: "/" }),  function(req, res) {    res.redirect("/profile?access_token=" + req.user.access_token);  });

Note that it is very important that the query parameter is called access_token. I couldn’t find this anywhere in the passport-http-bearer docs and had to search to the source code to figure that out.

Authenticating using a token

The following piece is pretty much a copy from the passport-http-bearer docs.

passport.use(    new BearerStrategy(        function(token, done) {            User.findOne({ access_token: token },                function(err, user) {                    if(err) {                        return done(err)                    }                    if(!user) {                        return done(null, false)                    }                    return done(null, user, { scope: 'all' })                }            );        }    ));

Setting up a route to require a token is done like this:

app.get(    '/profile',    passport.authenticate('bearer', { session: false }),    function(req, res) {        res.send("LOGGED IN as " + req.user.facebookId + " - <a href=\"/logout\">Log out</a>");    });

We’re authenticating using bearer and no session. Easy as that.


Getting http://localhost:3000/profile will return a 401 since you’re not providing a token (using the access_token query parameter).
Getting http://localhost:3000/profile?access_token=<foo>, where <foo> is the correct token stored in database on the user, will give you the expected result.
You can also choose to pass the token in the request body or as a request header.

Don’t forget to invalidate the token when implementing the logout handler.


Because you’re sending authentication data with every request it is important that your communications are protected using SSL.

Cordova & Phonegap

All this redirecting won’t work cleanly within a phonegap app.
A solution for that can be found here
For now you can check the source of his solution how to make it work, but I plan to make an other blog post in the future explaining it in detail. (The solution is to open an in-app browser window and do the redirecting in there)

Farewell Opera 2014-01-09T20:15:00.000Z 2019-07-08T18:34:59.000Z Opera browser logo

About 10-something years ago I was introduced to Opera by a friend of mine. Yes, that was when Opera’s free version still came with a banner ad but that didn’t stop me from loving the browser.

Some of the features I liked and eventually even started to regard as essential for a browser are:

  • Tabs on multiple lines
  • Mouse “rocker” features. (holding of RMB and clicking LMB would navigate back in history and holding LMB and clicking RMB would navigate forward)
  • More tab management and navigation: Ctrl-W, double/middle clicking tab bar to open new tab, backspace to navigate backwards (Really, Chrome and FF still don’t have this by default!?)
  • F2: being able to quickly enter a new url to browse to
  • Everything I wanted was included in the Opera installer. I didn’t need to fiddle around with any addons, plugins or extensions.
  • custom search keywords. Typing i The Time Machine in the address bar would cause the browser to go to and search for “The Time Machine” automatically. The shortcuts are customizable. (In my case w for wikipedia, wn for the Dutch wikipedia, d for, …)
  • Fast startup and immediately available. After opening Opera the address bar was focused enabling me to type what I wanted and pressing enter. (I remember this not being the case for older versions of other browsers)

I admit, some of these are more habits than features other browsers don’t have.
Examples that come to mind are F2 in Opera vs F6 in Firefox/Chrome and various plugins for FF with the same functionality of some Opera features.

Unfortunately a while ago Opera Software chose to discontinue work on Presto, their layout engine, instead to fork the Webkit project.
Initially I didn’t see a big problem in this, most likely because I didn’t know how extensive the impact would be on the browser. This would also not have been a problem as long as the browser would have still been the same in essence.


But it was not. Right after the release of Opera 15, the first version of the browser based on Blink, it was clear there was still a long way to go before it would be possible to “upgrade” without losing some features Opera 12.16 had (Last version with Presto).
Even now, half a year after the release of the “new” Opera, a lot is still missing.

Opera 12.x getting out of date

I myself was still using the last Presto version but lately it has become unbearable to use. There were huge memory leaks in the application. 4 tabs would consume about 1 GB of memory easily and when leaving your pc on for the night and coming back the day after the memory usage would have crept up to 1.6-2 GB and would cause the program to become unresponsive with the smallest of usage.

While Opera once had the fastest javascript engine (Carakan), leaving even the major browsers in it’s wake, currently it’s lagging behind because the lack of updates to 12.x.
It was also a forerunner in implementing W3C standards but currently a lot of features are just not fully there.
Even though it’s not that widely used yet, WebGL is a big gaping hole.

An alternative to my beloved Opera


Especially pre-Chrome a lot of preople were raving about Firefox. As with the well known catchphrase “there’s an app for that” there was also “an addon for that” in Firefox.
I was never a big fan though.
As I said before I liked that with Opera I could install it and know that everything I wanted was right there. No need to remind myself of what addon I used to fix that problem.


The same went for Chrome. When it was released it was the fastest browser there was but without any sugar to it, it was very simple.
A while later extensions were added. But this left me with the same concerns as I had with Firefox addons.

My fear of addon configuring have become moot though since both Chrome and Firefox have a feature where you can sync your Addon (settings) provided you have a Google account or an account with a server which supports Firefox Sync.

My choice

As you see I’ve only listed these 2 options here because I’m looking for something cross platform and you can be pretty sure that these 2 will always be up-to-date with the latest new things.

Why Firefox over Chrome? Well it’s a case of disliking the direction Google is going and liking Mozilla’s vision on things concerning the web.

#Final words
Seeing from when I’ve started I’ve been a big fan of Opera for quite some time now.
I’ve always laughed with Firefox copying a lot of features of Opera shortly after they were released, but now I’m glad they did. This made the switch that much easier.

I’ve set up the addon syncing and it seems to be working fine accross pcs excluding syncing the addon’s settings although I’ve read this is a responsability of the addon’s authors.

Now let’s just hope I’ll stay satisfied with Firefox.

Sightseeing in Antwerp 2012-04-09T17:00:00.000Z 2019-07-08T18:34:59.000Z Antwerp skyline
Skyline antwerp with Big 3 by Kschotanus / CC-BY-3.0

Somewhere in the first week of January (when I begun writing this post) was the first time that I hosted a fellow CouchSurfer. Jacob comes from Alabama, USA and is currently studying in Birmingham, UK. During the Christmas holidays he wanted to visit mainland Europe a bit, and I offered to host him in Antwerp.

Of course, people don’t come over to just sit/sleep on your couch, they want to see things!
That’s why I made a list of interesting things to see and do in the center of Antwerp. You’ll find the things on that list below with some added explanation and history for each item.
It might also come in handy when an other CouchSurfer comes over.

This is just a list of places and explanations, not a path you can follow.
Also, all prices listed here are the ones at the time of writing for adults without any sort of discount.
Antwerp has special discounts for many of it’s museums if your age is either <26 or >65 or you’re in a group. (-26 is often € 1 entrance)


All the locations mentioned below are pinned on this map.

View this in a larger map


‘t MAS (Het Museum aan de Stroom)

Museum aan de stroom

Our newest museum. It’s a modern looking building which consists of a big staircase wrapped around a central column. The stairs are free to ascend and lead to the roof of ‘t MAS where you’ll have a good (but windy) view over the city. At every floor you’ll have the opportunity to enter the large central column which houses the museum’s collections. However, to be able to enter these rooms you’ll need an entrance pass which you can buy at the ground level.

The museum houses a permanent and a temporary collection.
The price to be able to enter both collections is € 10.
Address: Hanzestedenplaats 1

Diamond museum

Diamond museum

Currently closed

Middelheim Sculpture Museum

Middelheim Sculpture Museum

This museum, which lies outside the city limits and is partly an open-air museum, has a collection of modern and contemporary sculptures.
In total there are 480 sculptures, 280 medals and 600 sketches and prints.
A big part of the sculptures are spread out over a park of 25 hectares (62 acres) in size.

Entrance cost: Free
Address: Middelheimlaan 61



Without a doubt the most impressive and well known building in Antwerp. It’s the largest Gothic church in the Low Countries, built between 1352 and 1521.
Beside the abundance of sculpted artwork on the exterior of the building you can also find various works of art by famous artists, one of which Rubens, inside.

A lot of tourists come to visit Antwerp because of the story “A Dog of Flanders” . In the square in front of a cathedral, de Handschoenmarkt, is a plaque dedicated to it.
Also on de Handschoenmarkt is “Het Putje Van Quinten Massijs”, a well built in 1490.

Entrance cost: € 6
Address: Groenplaats 21

Plantijn-Moretus Museum

Plantijn-Moretus Museum interior

Museum of the Plantin and Moretus print shop. At it’s time (one of?) the biggest print shop of mainland Europe. Had 16 active printing presses at all times, for comparison, the largest print shop in France at that time had 4 presses.
The museum contains the oldest printing presses on the earth (around 1600).

Entrance cost: € 8
Address: Vrijdagmarkt 22-23


Rockoxhuis facade

Like the Rubenshuis, the Rockoxhuis is an excellent way to get an image of how the nobility lived around the end of the 16th, beginning of the 17th century here in Antwerp.
Nicolaas Rockox had various roles in Antwerp. He was elected councilor 7 times and mayor of external affairs for 8 times.
The house contains lots of paintings and authentic furniture.

Entrance is € 8.
Address: Keizerstraat 10-12


Rubenshuis facade

Peter Paul Rubens, a Flemish painter known world wide had his home and atelier right here in the center of Antwerp. Of course a big part of the things to see in the house are paintings he made himself or paintings he acquired of other painters but even if you’re not a paintings fan it could still be an interesting visit. The house gives you a good view of how the nobility lived in the 16th-17th century, especially the inner court of the house is astonishing.

Entrance is € 8.
Address: Wapper 9


Vleeshuis facade

In the middle ages a lot of professions had guild houses, het Vleeshuis (the meat house) was one of them. In this case it was the guild house of the butchers.
The building was constructed 50 years after ‘t Steen in 1250 to sell slaughtered animals. Currently the building is used as a museum containing 600 years of history about music and dance.

Entrance costs € 5.
Address: Vleeshouwersstraat 38

Buildings & Places to see

‘t Steen

't Steen facade

Het Steen was constructed at the beginning of the 13th century, between 1200 and 1225. This makes it the oldest building in the city.
Unfortunately part of the building was deconstructed in the 19th century when de Schelde was widened to expand the harbor of Antwerp. Currently only the front of the stronghold is still standing.

For a very long time the building was used as a prison (1307-1827). From 1952 the building was used as a maritime history museum which later moved to the newer MAS museum.

At the beginning of the walkway to the castle there is a statue called “de Lange Wapper”. The statue depicts a giant from Antwerp folklore.
De Lange Wapper can shapeshift and he uses this ability to trick people. A much used trick of his is to follow drunks home, constantly growing while following. Eventually when the drunk arrives home de Lange Wapper is so tall that he can peek through the top level windows of the drunk’s house.

Address: Suikerrui 7

Bourla Schouwburg

Bourla Schouwburg facade

A theater with an impressive front built in 1834. It is still used as a theater by 2 theater groups.
Every Sunday and national holiday an extensive brunch buffet is hosted in the Schouwburg.

Address: Komedieplaats 18

Centraal Station

Centraal Station facade

This station, a key stop between the Paris and Amsterdam, is considered one of the most beautiful train stations of the world.
Interesting parts of the building to view are the front of the building, the entrance hall and the glass dome over the top level of rails.

If the NMBS/B-Rail is not on strike you might be able to ride the train somewhere too.

Address: Koningin Astridplein 27

Hendrik Conscience Plein & Carolus Borromeus kerk

Carolus Borromeus kerk facade

On the square in front of the Carolus Borromeus kerk you’ll find a statue of the Flemish writer Hendrik Conscience, after whom the square was named when the statue was installed in 1880.
The interior of the church exists of marble, wood sculptures and paintings.

Address: Hendrik Conscienceplein 6-12

Koninklijk Museum voor Schone Kunsten (Royal Museum of Fine Arts)

Unfortunately the museum is closed for renovatuion until 2017.
But it does organize expositions in other places in and around Antwerp.
Where it hosts these you can see on it’s website.


South of the cathedral is the Groenplaats. It’s surrounded by a few protected buildings, among which the building that currently houses the Hilton hotel.

Grote Markt

Grote Markt

Like pretty much any larger European city Antwerp also has a Grote markt/Grand Place. It’s situated North West of the Cathedral. On de Grote Markt you will find Antwerp city hall, the statue of Brabo en Antigoon and surrounding the square, guild houses.

The statue is based on an old city legend.
There is a giant, Druon Antigoon, who demands toll of the people who want to cross de Schelde. If they couldn’t pay the toll he would cut of their hand. He was eventually slain by Silvius Brabo, supposedly the nephew of the roman emperor Julius Caesar. He gave him a taste of his own medicine and cut off his hand.
The statue depicts Silvius throwing away Antigoon’s severed hand.
According to another myth this is also where Antwerp has it’s name from. Hand werpen (Hand throwing) => Handwerpen => Antwerpen.

Each of the houses along the square belonged to a guild. Some of the houses have statues on the top of their roof which is in some way connected to the guild to which the house belonged.


De Meir is the largest shopping street of Antwerp and possibly of entire Belgium (She’s competing for the title with the Nieuwstraat in Brussels). Even if you’re not interested in shopping you should still walk it’s distance to take a look at the decorated buildings that surround it.
It also connects the old city center with the Rooseveltplaats (which is close to the central station) so you can easily go from one to another if you don’t mind a walk.

Stadsfeestzaal (City festivities hall)

At present this big hall with it’s decorated ceiling is being used as the central space of a shopping center.

Address: Hopland 31, Meir 78



De Vlaaikensgang is an alley which runs behind the backsides of some old medieval houses.
At about halfway in the Pelgrimsstraat you will find a gate leading to this alley. Look closely! It’s not very obvious.
Inside the Vlaaikensgang there are a few pittoresque spots.

Entrance point: Oude Koornmarkt 16

Voetgangerstunnel (Sint-Annatunnel)

Antwerp is largely situated on the east bank (right side) of de Schelde. Across de Schelde the area is known as de Linkeroever.
Boths sides are connected by a pedestrian tunnel which dates back from 1933. Is it still widely used today.
The tunnel itself could be an interesting look because of it’s old wooden escalators and tiled interior.
Even if that can’t pique your interest, you have a nice view of the other side, especially at night when the city is lighted.

Address: Sint-Jansvliet

Zoo van Antwerpen

Maybe not very special when compared to other zoos, but there are some older buildings inside which might be interesting to see.
Pretty much anyone who has gone to school around Antwerp has visited the zoo multiple times on a school trip.

Entrance: €22
Address: Koningin Astridplein 26



This Neighborhood is situated around de Dageraadplaats, a square with lots of cozy cafes and restaurants surrounding it. A bit further, after passing the Railroads is the Cogels-Osylei which has a lot of old beautiful mansions.

Food & Drink (Delicacies)

Désiré de Lille

Laquemant waffles

Belgian Waffles are a worldwide known sweet snack but they are nothing compared to the other unhealthy goodnesses we have here. Most of them can be bought at stands on a so called Kermis or Foor (Carnival).
Unfortunately they travel around so it can be hard to know if there’s one close when you’re visiting Antwerp. Désiré de Lille is a snack restaurant / take out shop which has these snacks available all year round.
The original founder of the restaurant is also the inventor of the Lacquemant, a flat waffle with a syrup in it of which the recipe is a secret.

I highly recommend trying out the Laquemants and the Smoutebollen.
Address: Schrijnwerkersstraat 14

Het Elfde gebod

This cafe is right next to the cathedral. It’s walls are completely decorated with statues of various sizes. It’s not necessarily a must-see, but it’s more of a unique thing you won’t quickly find somewhere else.

Address: Torfbrug 10

De Pelgrom

De Pelgrom interior

This was an old storage space for valuable goods which has now been transformed to a cozy cafe.
Supposedly on weekends there is also a guide available at the entrance of the cafe who will guide you (for €3) through the house above the cellar which is decorated authentically.

Address: Pelgrimstraat 15

De Vagant

Jenever is the Dutch and Flemish vodka. We have them in all kinds of flavours and strengths.
The ideal spot to try them is de Vagant, which offers more than 150 varieties of them.

Address: Reyndersstraat 25

Other delicacies

I’m sure you’ve heard of our chocolate and beer, which are all widely available in Antwerp.
But have you tried our fries? Take this recommendation and go to a frituur once. Order a “puntzak” with (Belgian) mayonnaise. Yes, mayonnaise. If you’re from the US/Australia/..(?) I can assure you, our mayonnaise is a different sauce entirely. There is a good frituur cart near ‘t Steen.
From then on, start calling them Belgian fries instead of French fries please.



De Vrijdagmarkt, literally translated Friday market, is as the name says a market that is hosted every Friday (Vrijdag in Dutch) from 9:00-13:00 on the square called … Vrijdagmarkt.
On this market second hand goods ranging from clothing to furniture get sold. Often these goods are confiscated goods of people who defaulted on their bills.
Therefore there will most likely be an auctioneer yelling for bids. Below a video of the market in action.

Other suggestions found on the internet

Kassa 4: A student bar on de Ossemarkt.

Cafe de Muze: A jazzy bar on the Melkmarkt.

Caffénation: A coffee shop which offers all sorts of coffees created by all sorts of brewing methods.

Amadeus: A restaurant which offers an all you can eat menu for spare ribs.

‘t Waagstuk: Similar to De Vagant mentioned above, except it’s variety is in beer. It offers a few hundred kinds of beer.

De Koninck brewery: A well known brewery in Antwerp, they offer a tour through the brewery.

Public transportation

Of course you’ll want to get around at an acceptable pace.
In the city center I recommend going by foot since everything is so close together anyway and otherwise you might miss out on the city life itself.

For longer distances (city to city) you can take the train, which is operated by B-rail (formerly NMBS).

For inside Antwerp itself you’re best off using the buses and trams(/metro), which are run by De Lijn.
Or you can purchase a day/week pass for the excellent Velo bike system.

Samsung Galaxy SII battery/USB problems 2012-02-29T20:39:00.000Z 2019-07-08T18:34:59.000Z Problem description

I recently had some nasty trouble with my Galaxy SII.
The problem I was having was that after working normally the phone would suddenly act like I was pulling out and putting in the usb cable constantly.
The battery would indicate being charged, discharged and then charged again (etc.).
After shutting the phone down and trying to reboot it I would get an image showing the big battery image you get when charging the phone while it’s off.
A few seconds later it would also display an exclamation mark and a thermometer.

I tried letting the battery “cool” to no avail (It didn’t feel exceptionally warm to the touch anyway)
Switching to a different battery did seem to fix the problem, at least for a short while. A day later I was having the exact same symptoms. Time for some more Googling I thought.


Eventually I found this topic on Android Forums. The solution to my page was found on page 2.
Apparently even a small amount of dirt in the micro usb port can cause these problems.
It’s easily cleaned with a toothpick. To get in the thin space away from the battery you can split a toothpick with scissors.
You can dip the tip of the toothpick in rubbing alcohol to get even the last bits of dirt.

If even this doesn’t work and you’re sure it’s the usb port (water damage maybe) the port itself is quite easily and cheaply (€15) replaced.
In the same topic someone did this and posted an image of the port’s package showing all the product info.

Also posted was a video showing how to disassemble and reassemble the phone.

Updated SoundSwitch 2011-06-23T23:39:00.000Z 2019-07-08T18:34:59.000Z

I updated my SoundSwitch Application.
You can install it by going here.

The purpose of SoundSwitch is to be able to easily switch between 2 or more Audio output devices.
For example, I have a wireless headset and my regular speakers.
Both are detected as a separate audio card in the sound panel.
The only way to switch between them is to open the playback devices panel and select one of them and choose to put it as default device.

That’s such a hassle!
With SoundSwitch you just press Ctrl+Alt+F11 and it toggles between the cards you selected.


  1. Let the application start up when the user logs in. (currently you have to start it yourself)
  2. Allow users to set their own shortcut (instead of Ctrl+Alt+F11)
  3. Make the configuration easier. (Won’t be possible I’m afraid though)

Changed the hosting to CodePlex, apparently you can host ClickOnce applications there!

jQuery scroll to element plugin 2011-06-14T23:39:00.000Z 2019-07-08T18:34:59.000Z This small plugin will scroll to a selected element when calling .scrollTo() on it.
It has an optional parameter which specifies the duration of the scroll.

$.fn.scrollTo = function(duration) {  if (duration == null) {      duration = 1000;  }  var offset = $(this).offset().top - $(window).height()/2 + $(this).height();  $('html,body').animate({    scrollTop: offset  }, duration);};

For example, if i would have a div with the id “#mydiv” I would let the screen scroll to it using this code:

Or, if you want the animation to be slower

The top of the selected element will be displayed at 50% of the screen unless the scrollbar is too short, then the element will be lower on the screen.

Learning Norwegian - Some resources 2011-04-11T01:03:00.000Z 2019-07-08T18:34:59.000Z Norwegian flag graphic
Norwegian flag in grunge style by Gabriel Oliveira

With only 5 million speakers it’s not very easy to find resources on learning Norwegian compared to other languages. Listed below is a compilation of the resources I found while looking for learning materials.
Norwegian is the first language I’m consciously learning on my own, not in a school environment. (I say consciously because I learned English by watching a load of movies and series, I didn’t really have to make an effort then) I’m currently a complete beginner in Norwegian with only 25/30 Pimsleur lessons done and some extra vocabulary with Anki.


Full fledged learning tools containing a textbook explaining grammar and spelling rules, audio tapes for pronunciation and often also workbooks to apply the acquired knowledge.

Pimsleur Norwegian

30 audio lessons of 30 minutes each. I started learning with this. After each lesson of Pimsleur’s completed I could clearly notice that I had learned something. The rate at which I learned stuff using Pimsleur is very high. Unfortunately Pimsleur Norwegian has only 1 level of lessons, compared to 2 or 3 levels for larger languages like French or Chinese. If I had to suggest a starting point to learning Norwegian, this would be it.
Pimsleur Norwegian website

Ny I Norge & Bo I Norge

Ny I Norge contains a textbook, audio readings of the conversations in the textbook, a workbook and listening comprehension exercises. Bo I Norge is a textbook for more advanced learners (after Ny I Norge). This will be the second resource I’ll be using, after Pimsleur.

Colloquial Norwegian

Similar to Ny I Norge, consists of a textbook with exercises and audio readings. I do have the impression that the learning curve of the book is higher.

På vei, Stein På Stein, Her På Berget

All three books consist of a textbook, a workbook and audio files. They consist of three levels of which På Vei is the 1st, Stein På Stein the second and finally Her På Berget the third.
Each of the books have free exercises online. (På vei, Stein På Stein, Her på berget)

Praktisk Norsk I & II

From the same series as På vei etc. Also has free exercises online here and here.

Teach Yourself Norwegian

A book with conversations both in English and in Norwegian. Seems to rely heavily of cross referencing the dialogues in both languages. Also contains audio recordings for the conversations.

Sett i gang I & II

A textbook, workbook and audio files. The audio files are freely downloadable after creating an account on the website.

My Little Norway

A blog about 2 people in Norway, one native speaker and one who’s learning Norwegian. They also have a bunch of lessons on the blog for learning Norwegian.

Assimil (for German or French speakers)

Norwegisch ohne Mühe (For German speakers) | Assimil site
Le Norvegien sans Peine (For French speakers)



NRK is the Norwegian national broadcaster. A lot of the programs are visible freely (Click A-Å on the top and choose a starting letter of a program). For example, the news is something that is updated daily.
UPdate: SinceTwriting this post the NRK nett-tv site has changed. You can find a list of programs available for viewing outside of Norway here.


TV3 broadcasts more foreign (to Norway) programs which are more limited by drm. But those are most likely not the programs you want to watch anyways cause they are in different languages :)
Watch out, they also have some Swedish programs.



Only short clips of programs are free, full programs require a subscription.


Extra resources

Anki flashcards

Anki is a program to exercise flashcards using spaced repetition. I use this to exercise vocabulary. The great thing about Anki is that you can also add audio files to your flashcards, so you can train pronunciation and spelling in one go.

I don’t like having to record every word manually, so I made this site to automatically generate sound files for words you type in. (Link currently broken but I’ll remake the app some time in the future)
Here is a list of the 1000 most used Norwegian words to get you started. Be sure to use Bokmål (see below).

News in “Simple Norwegian”

Klar Taleis a news website written in simple Norwegian. If you use their website together with a browser plugin which can translate (unknown) words you select then this is another good way of learning.

Lessons on Youtube

Crienexzy on Youtube has a bunch of videos on Norwegian pronunciation.


A great way to passively (but slowly) learn is by watching movies and series. Some Norwegian films I liked were:

A big list of Norwegian films can be found on IMDB.


Livemocha uses the same teaching style as Rosetta Stone. I’m not particularly fond of this way of learning, I learned a bunch more by just a few lessons of Pimsleur. However, it’s a great way to find native speaking partners.


Duolingo offers a course of Norwegian online for free as well. It’s a pretty well known language learning site which uses gamification in it’s learning process.
Maybe you have a friend learning a different language on the site? Then you can compete with each other to learn the most.


A site aimed at bringing penpals together. Has quite a large user base.

Linguistic tools & sound files of Norwegian dialects

This site contains sound files of texts in various Norwegian dialects.

More info

This sitehas a bunch of links to Norwegian related things.

Bokmål & Nynorsk

Norwegian has 2 written forms, Bokmål and Nynorsk. Unlike what Nynorsk’s (new-Norwegian) name seems to suggest it is actually older than Bokmål. The grand majority of (newly) written material is in Bokmål, so you’ll have the most use of learning Bokmål. As far as I know, all textbooks listed above use Bokmål.

Get started

I found a torrent (magnet url) which contains a lot of the resources mentioned above. Credit where credit is due: a lot of the resources mentioned here came from this post on reddit.
Found a site with good explanations on grammar rules. And a site which will show you ALL conjugations of a given verb! Super useful.

Bulktts - Text to speech using Google Translate 2011-03-14T04:47:00.000Z 2019-07-08T18:34:59.000Z
Note (18/10/2015): Right now the bulktts link doesn’t work any more since Google shut down apps using the old App Engine datastore, but I’ll create an updated version of bulktts in the near future.

The project I was talking about in the previous post was this one, bulktts.
With Google Translate you can only listen to the sound of the text you typed in, but you can’t download it.
I found a url which with the right parameters lets you download the mp3 file generated by Google Translate, but if you need a bunch of words converted to speech this is a tedious job of changing the url, save as.. etc.

Bulktts allows you to choose a language, paste your list of words in and download a zip file with the mp3’s.

There are still some bugs though, at the moment words with special characters won’t product the correct sound.

Update: SoundTbug fixed. Only the filenames for special character words in zip files are still not correct.

Python in-memory zip file 2011-03-06T13:16:00.000Z 2019-07-08T18:34:59.000Z I needed this for something where I wanted to send the visitor of a website a bunch of files he selected at once.
An easy way to do this would be to add the files to a zip file and then send that zip file to the user.
Unfortunately Python doesn’t have an in-memory zip file library, you can only interact with zip files on disk.

After a bit of googling around I came to this StackOverflow answer.
That worked like a charm, and here is my more reusable version:

from zipfile import ZipFilefrom StringIO import StringIOclass InMemoryZipFile(object):    def __init__(self):        self.inMemoryOutputFile = StringIO()    def write(self, inzipfilename, data):        zip = ZipFile(self.inMemoryOutputFile, 'a')        zip.writestr(inzipfilename, data)        zip.close()    def read(self):        return self.inMemoryOutputFile.getvalue()    def writetofile(self, filename):        open('', 'wb').write(

Save as “” and import it as “inmemoryzip”.
This is quite limited compared to the standard ZipFile class, but this gets the job done for what I needed it.

This post describes creating a zip file in-memory using Python.
Solving 8 Queens problem on an 8x8 board with a Genetic Algorithm. 2011-01-20T02:55:00.000Z 2019-07-08T18:34:59.000Z I have an Artificial Intelligence course and one type of search algorithm handled is Genetic Algorithms.
Very interesting because it uses the principle of evolution to find a solution to a problem.

You start with a population of begin states and each state has a ‘fitness’ which indicates how close it is to a solution.
Based on that fitness you will crossjoin or mate 2 states. Higher fitness = higher chance of mating.

I implemented the example given in my AI course’s slides in python.
The example is trying to find a solution to solve an n-queens problem, in this case 8 queens on an 8x8 chessboard.
Briefly explained: you need to place 8 queens on a chessboard so that none of the queens can attack eachother.
(A queen can move like a Bishop and a Tower, horizontally and diagonally)

from __future__ import divisionfrom random import Random, randomclass State(object):    MUTATION_RATE = 0.03    def __init__(self, parents=None):        r = Random()        self._fitness = None        self._probability = None        if parents==None:            self.state = [r.randint(1,8) for y in range(8)]        else:            parent1 = parents[0]            parent2 = parents[1]            self.state = self.crossover(parent1, parent2)            self.mutate()    def fitness(self):        if not self._fitness:            state = self.state            horizontal_collisions = sum([state.count(col)-1 for col in state])/2            diagonal_collisions = 0            for i, col in enumerate(state):                for j, diagonal in enumerate(state):                    mod = abs(i-j)                    if mod < 0: #we don't want to count the current queen in a collision with herself                        if diagonal + mod == col or diagonal - mod == col:                            diagonal_collisions += 1            diagonal_collisions /= 2 #we were counting the diagonal collisions double            self._fitness = int(28 - (horizontal_collisions + diagonal_collisions))        return self._fitness    def probability(self, population):        if not self._probability:            self._probability = / sum([ for x in population])        return self._probability    def crossover(self, parent1, parent2):        r = Random()        crossover_index = r.randint(0,8)        left = parent1.state[0:crossover_index]        right = parent2.state[crossover_index:8]        left.extend(right)        return left    def mutate(self):        r = Random()        for i in range(len(self.state)):            if random() < State.MUTATION_RATE:                self.state[i] = r.randint(1,8)    def __str__(self):        r = ''        r += '   '        for i in range(8):            r += '%d ' % (i+1)        r += 'n  ' + '--'*8 + 'n'        for i in range(8,0,-1):            r += '%d|' % i            for j, queen in enumerate(self.state):                if queen == i:                    r += ' O'                else:                    r += '  '            r += '|n'        r += '  ' + '--'*8 + 'n'        print        return rdef pickRandomByProbability(populationByProbability):    i = 0    selectedState = None    while selectedState == None:        current = populationByProbability[i]        if current[0] <= random():            return current[1]        if i+1 <= len(populationByProbability):            i = 0        else:            i += 1def generateNextPopulation(population, n):    newPopulation = []    while len(newPopulation) < n:        populationByProbability = [(x.probability(population), x) for x in population]        parent1 = pickRandomByProbability(populationByProbability)        populationByProbability = [x for x in populationByProbability if x[1] != parent1]        parent2 = pickRandomByProbability(populationByProbability)        newPopulation.append(State((parent1, parent2)))    return newPopulationif __name__ == '__main__':    populationSize = 100    generation = 1    population = [State() for x in range(populationSize)]    while not 28 in [ for x in population]:        print "generation %dtMax fitness: %d" % (generation, max([ for x in population]))        population = generateNextPopulation(population, populationSize)        generation += 1    for x in population:        if <= 28:            print x


The State class keeps track of a state. In this case that is a list of 8 integers ranging from 1 to 8.
Each integer represents the position of a queen in a column (which row).
Since queens can attack vertically each queen has to be in a different column by default.


A collision is two queens who are able to attack each other. This means they are in the same diagonal, the same row or the same column.
The maximum amount of collisions that can occur is 28. The fitness function is a higher-is-better function, so we calculate it by substracting the amount of collisions that occur in the current state from 28.
A solution would have 0 collisions and thus a fitness of 28.

Probability of mating

When we generate the next population of states we will need to have something on which we can base which 2 states can ‘mate’.
We want only the best states (the one closest to a solution) to mate, so the best heuristic to define the chance of a state being allowed to mate is it’s fitness.

Crossover (mating), mutation

When we crossover 2 states we choose a point in the states where we will ‘chop’ them in 2 parts. We will for example take the left 3 columns of the 1st parent and the 5 last of the second parent. The child state is then the combination of these columns.
We don’t want to stay stuck in the same state pool because what if the initially randomly generated population has no queen in row 3?
We would never be able to get a solution because a solution requires a queen in each row.
No matter how many times we crossover 2 states, we will never get a state in row 3.
Therefore we need to include a random mutation when crossing over 2 parents.
Each column in the child state has a specific percentage chance of changing it’s value to a random number from 1 to 8.


I’ve noticed that this doesn’t find a solution as fast as I initially expected. It can quickly take over a few (ten)thousand generations before a solution is found.
I haven’t noticed any noticeable speed increase in finding a solution when taking a population of 100, 1000 or 10000. (Didn’t do any benchmarks, just a few runs per population size)
Maybe a solution would be found more quickly if the percentage chance of mating weren’t on a linear scale but an exponential one.
I’m not sure if i’m expressing this correctly but what I mean is that the chance of mating for bad fitnesses and good ones is currently too close. Good ones should be picked way easier than bad ones. Now the chance differs only by a few percent or even a few tenths of a percent depending on the size of the population.

Programming Praxis - Happy Numbers 2010-07-24T01:09:00.000Z 2019-07-08T18:34:59.000Z Today’s problem had to do with Happy Numbers.

I split the problem up in two parts, splitting up a number up in to digits and checking whether or not the number is a Happy Number.

The first part I implemented in two different ways.

Method 1:

def chop(x):  r = []  length = int(ceil(log(x, 10)))  if ceil(log(x, 10)) == int(ceil(log(x, 10))):    length += 1  #a(dd), s(ubstract)  for a,s in zip(range(0, length), range(length-1, -1, -1)):    temp = x/(10**s)    for i,e in enumerate(r):      pass      temp -= e * 10**(len(r)-i)    r.append(temp)  return r

Method 2:

def chop2(x):  return [int(x) for x in str(x)]

Method 2 is shorter and faster, but I really wanted to try solving it by just using numbers.
String conversions feel a bit “dirty”.

Then finally, checking whether a number is a happy number or not:

def isHappyNumber(x):  if x &lt;= 0:    return False  numbers = [x]  while x != 1:    x = sum([a**2 for a in chop(x)])    if x in numbers:      return False    numbers.append(x)  return True

The source can also be found on Bitbucket.

<p><a href="" target="_blank" rel="noopener">Today’s problem</a> had to do with Happy Numbers.</p> <p>I split the problem up in two parts, splitting up a number up in to digits and checking whether or not the number is a Happy Number.</p>
Programming Praxis - Word Cube 2010-07-20T22:41:00.000Z 2019-07-08T18:34:59.000Z This is my first solution for a Programming Praxis assignment, the Word Cube problem.

It’s definitely not an elegant solution. It’s almost as brute force as it can get, but I have only a negligible amount of training in this field so I’m satisfied for now with being able to find a solution at all.
It takes a few minutes to find all the possible words. I did however find quite a few more than the ones mentioned in the assignment.
Click here to see the source code.

After solving it I read the comments and discovered an (in hindsight) obvious better way of doing it.
Why check all possible permutations of the different combinations of the letters when you can just check every English word in the word file if it matches.
I tend to take assignments very literally (See the nested list to indicate a cube in my code? ;))…

At first it sounds like checking every word of the English language is way more than just checking the combinations of the given letters, since there are a huge amount of words in the English language, but actually the opposite is very true.

My word file contains 51248 words. Not exactly every word in the English language, but for this word cube problem it will suffice.
On the contrary we have all the permutations of the combinations of the different letters in the Cube.
(I’m sure that someone who’s better at combinatorics than me who reads this will most likely have just received a heart attack because I’m sure there must be something wrong with that statement)
Which comes out to, by a quick alteration of my solution, 876624. More than ten times the words in the word file.

I’ll now try to solve it following the newly discovered method :)

Source code:

from re import findallfrom itertools import combinations, permutationsfrom zipfile import ZipFiledef readWords():  data = ZipFile('').open('en_US.dic').read()  return [word for word,crap in findall('''([^/s]+)(/.*)?''', data)]#bonnie, bunion, coin, concubine, conic, cubic, ennui, icon, nice, nine, nuncio, and unioncube = [  ['n', 'c', 'b'],  ['c', 'i', 'o'],  ['u', 'n', 'e']]flatcube = [cube[x][y] for x in range(len(cube)) for y in range(len(cube[0]))]middleIndex = len(flatcube)/2obligatedChar  = flatcube[middleIndex]del flatcube[middleIndex]words = readWords()foundWords = set()for wordLength in range(3, len(flatcube) + 1): #wordlength minus obligated char  for combination in combinations(flatcube, wordLength):    x = [obligatedChar]    x.extend(combination)    for w in permutations(x):      word = ''.join(w)      if word in words and not word in foundWords:        print word        foundWords.add(word)


I tried solving it using the new method and came to this.
The improvement in speed is immense. My previous version used to take a couple of minutes to find all solutions, but this one does it in a fraction of a second.
Although I’m sure it can still be improved further.

And something else I found while browsing the Programming Praxis comments:

<p>This is my first solution for a Programming Praxis assignment, the <a href="" target="_blank" rel="noopener">Word Cube</a> problem.</p> <p>It’s definitely not an elegant solution. It’s almost as brute force as it can get, but I have only a negligible amount of training in this field so I’m satisfied for now with being able to find a solution at all.<br>It takes a few minutes to find all the possible words. I did however find quite a few more than the ones mentioned in the assignment.<br><a href="" target="_blank" rel="noopener">Click here</a> to see the source code.</p>
Bachelor in Applied Computer Science 2010-06-30T00:44:00.000Z 2019-07-08T18:34:59.000Z Yesterday evening I received my diploma.

This post isn’t in line with the previous posts I made but it is in line with the general content of this blog, things I learned.

When I entered college I had a basic knowledge of programming. I knew some PHP and some VB. These past three years I learned a bunch, possibly more than I thought I would learn when entering college.

Onwards in education!

I am now preparing myself to further my education.
The next two years I’ll be working for my master’s degree, also in Applied Computer Science.
I am not yet officially signed up for a University yet –signups start begin July– but I’m pretty sure I’ll be attending Vrije Universiteit Brussel (VUB).

Why more?

I’ve gotten a lot of questions as to why I want to go for a master’s degree, especially from the people I’ve worked with in my internship at Item Solutions (of which the majority are also Karel de Grote Alumni).

The main reason is simple, I want to learn more. Some specifics include:

  • Functional Programming
  • Machine Learning
    • Evolutionary programming
    • Genetic algorithms/programming
    • Neural networks
  • Algorithms to compare images
  • The principles of optimization (O(n) etc.)
  • Secret Santa problem

The Secret Santa problem was something I read about while participating in the Reddit Secret Santa. This is a very specific problem I’m mentioning here because that’s what I wrote down in my “want to learn list” I created in the course of last year. But what I actually want to learn is more general of course, think every problem on Programming Praxis.
The site is often described as having less “mathy” problems than Project Euler, yet I can only sporadically solve one of them, and most of the time in an as brute-forced-way as possible.

Another reason I want to get my master’s degree is because I’m interested in living abroad for a short period of time (1-2 years) and from what I’ve read countries are a lot easier to get in to for a long period of time when you have a degree. Now, I don’t know what the difference is between a Master’s and a Bachelor’s degree when it comes to getting in to countries but I assume the higher the degree, the easier it is to get in.

In the last three years I’ve noticed I also enjoy explaining things to classmates. So I’ve also thought about a possible future as a college professor, in CS related fields of course.

And finally a reason that is completely not connected to computers: Since VUB is quite a bit further from home I’ll need to have a “kot” (student home/dorm). I believe this is a great stepping stone to becoming more independent.

Java doesn't support inheriting twice from the same interface with a different generic parameter 2010-06-10T04:30:00.000Z 2019-07-08T18:34:59.000Z I created this:

public class Observable <T> {  private List<Observer<T>> observers = new ArrayList<Observer<T>>();  public void addObserver(Observer<T> observer){    observers.add(observer);  }  public void removeObserver(Observer<T> observer){    observers.remove(observer);  }  public void removeAllObservers(){    observers.removeAll(observers);  }  public void notifyObservers(Observable<T> observable){    for(Observer<T> observer : observers){      observer.update(observable);    }  }}

And this:

public interface Observer <T> {  void update (Observable<T> observable);}

So I could do this:

public class SomeClass implements Observer<SomeObservableA>, Observer<SomeObservableB>{  @override  public void update(Observable<SomeObservableA> observable){    //do stuff for Observable A  }  @override  public void update(Observable<SomeObservableB> observable){    //do stuff for Observable B  }}

But apparently java only takes into account the class you’re implementing and not the extra generics you’re adding.
So I ended up doing it this way (using the standard Observer and Observable):

public class SomeClass implements Observer{  @Override  public void update(Observable o, Object arg) {    if(o instanceof SomeObservableA){      //do stuff for Observable A    }    if(o instanceof SomeObservableB){      //do stuff for Observable B    }  }}
Automatically add library jar contents to executable jar with Netbeans 2010-06-05T17:29:00.000Z 2019-07-08T18:34:59.000Z Say you have a Java project in Netbeans with a library jar added.
In my case this was SQLiteJDBC, an SQLite JDBC driver for Java applications.

When you build the project (“Clean and build project”) a folder ‘dist’ will be created with as contents:

  • Your executable jar file
  • A ‘lib’ folder with the jar files of your added libraries inside

In your executable jar file (it’s actually a zip file, you can open it with Winrar for example) there is a folder called ‘META-INF’ with inside a file called ‘MANIFEST.MF’.

Class-Path: lib/sqlitejdbc-v056.jar

This line in ‘MANIFEST.MF’ makes sure that your executable jar file knows that the jar file for the SQLiteJDBC driver library is in ‘lib/sqlitejdbc-v056.jar’

Now, the problem for me was that I wanted a single executable, not an executable with some added library files.
With Java you can easily solve this problem by copying the contents of your library jars into your executable jar.
This means opening sqlitejdbc-v056.jar and opening the created executable jar with Winrar and dragging all the contents from the library jar to the executable jar.

Now, I’m quite lazy and I want that when I click the ‘Clean and Build’ button this all happens automatically.

In your Netbeans project folder (“nbproject”) there is a file called ‘build-impl.xml’. This file defines how your executable jar will be built.

Look for this line:

<target depends="init,compile,-pre-pre-jar,-pre-jar" if="manifest.available+main.class+mkdist.available" name="-do-jar-with-libraries">

Within this block there is a block called ‘copylibs’.

<fileset dir="${build.classes.dir}"/> defines the files that will be copied in to the executable jar. (your compiled .java files)

What we want to add is this line:
<zipfileset src="lib/SqliteJDBC/sqlitejdbc-v056.jar" includes="**/*.java **/*.class"/>

This will make sure that the content of sqlitejdbc-v056.jar will be copied into the executable jar file.

The only downside is that in the manifest file the library jars still get added to the classpath and the files still get copied into the dist/lib folder.


Apparently since last working on that project where I needed this I changed some stuff.
A somewhat updated explanation:

In the root directory of your project you should have a build.xml file.
You need to open this file and look for the tag <copylibs>

Within that tag there should be a tag called <fileset>

like this: <fileset dir="${build.classes.dir}"/>

Below that line paste the zipfileset one.
(One for each library jar you need included, I’ve only tried it with one library though.)

<p>Say you have a Java project in Netbeans with a library jar added.<br>In my case this was <a href="" target="_blank" rel="noopener">SQLiteJDBC</a>, an SQLite JDBC driver for Java applications.</p> <p>When you build the project (“Clean and build project”) a folder ‘dist’ will be created with as contents:</p> <ul> <li>Your executable jar file</li> <li>A ‘lib’ folder with the jar files of your added libraries inside</li> </ul> <p>In your executable jar file (it’s actually a zip file, you can open it with Winrar for example) there is a folder called ‘META-INF’ with inside a file called ‘MANIFEST.MF’.</p> <p><code>Class-Path: lib/sqlitejdbc-v056.jar</code></p> <p>This line in ‘MANIFEST.MF’ makes sure that your executable jar file knows that the jar file for the SQLiteJDBC driver library is in ‘lib/sqlitejdbc-v056.jar’</p> <p>Now, the problem for me was that I wanted a single executable, not an executable with some added library files.<br>With Java you can easily solve this problem by copying the contents of your library jars into your executable jar.<br>This means opening sqlitejdbc-v056.jar and opening the created executable jar with Winrar and dragging all the contents from the library jar to the executable jar.</p> <p>Now, I’m quite lazy and I want that when I click the ‘Clean and Build’ button this all happens automatically.</p> <p>