Update: Disregard this post. The solution is Html.Keyed. Thanks to Ilias Van Peer for pointing this out.

Elm is an interesting functional language for the web. It compiles to very fast JavaScript and through its strong static type system leads to virtually no runtime errors: If the program compiles, it is most certain it does not crash.

Elm Architecture

In Elm the only mutable variable is the model variable. Everything else is forced to be immutable. In the model you store the internal state of the application, but not the DOM; you only store the data it depends on.
The desired DOM is specified by defining functions which map that model to the DOM. Functions are to be understand in a mathematical way: They cannot access anything else than their input arguments and cannot do anything else than choosing their output.

Architecture Example

Say we want to show online users on a web page. Then the model would include the list of users:
type alias Model = {
online_users: List String,
-- optionally other state information for the website

One of its transformation to DOM could look something like this:
div [id usercounter] [text ("users online: "++toString (List.length model.online_users))]
This generates a div element with id “usercounter” and the content “users online: ” and then the number of online users.
At another position in the DOM you might put the online user names in a ul element etc.

CSS Transitions

The CSS transition style property allows to easily animate things efficiently (i.e. without calculating the animation path in JavaScript). You just have to specify the property transition: width 2s and whenever you change the width style property, it will change continuously over the course of two seconds instead of abruptly.

Elm vs Transitions

Elm does not have a notion of the additional state attached to a DOM element by CSS transitions. It just sees the complete DOM before the latest model update and the complete DOM after that update. It then calculates some steps that will transform the old DOM into the new DOM. There is no guarantee which former element will end up where in the DOM. The only guarantee is that the resulting DOM will reflect the new state. There is no correspondance between elements in the old and new DOM. But CSS animations build upon that correspondance.

Failing Example

Assume you want to create a slide show with nice slide transition effects. At every point in time there would be three slides in the DOM: the old slide in its faded out state, the current slide in a visible state and the next slide in the state before fading in. If the animation just uses the opacity CSS property for fade-in and fade-out, the DOM would look like this (the opening “<" is omitted because WordPress sucks):

div style="transition: opacity 2s; opacity: 0;">last slide content

div style="transition: opacity 2s; opacity: 1;">current slide content

div style="transition: opacity 2s; opacity: 0;">upcoming slide content

Now to transition smoothly to the next slide you have to remove the last slide from the DOM, set the opacity of the current slide to 0, set the opacity of the upcoming slide to 1, and add a new div for the slide after that with opacity 0. Then the DOM looks like this:

div style="transition: opacity 2s; opacity: 0;">current slide content

div style="transition: opacity 2s; opacity: 1;">upcoming slide content

div style="transition: opacity 2s; opacity: 0;">content of slide after that

There is by design no way to tell Elm to do these steps. Instead Elm will look at the old and the new DOM and calculate an efficient series of operations turning the old into the new DOM. This results in these changes: change content of the first div to “current slide content”, the content of the second div to “upcoming slide content” and change the content of the third div to “content of slide after that”. This process does not change any div’s opacity property, so no opacity transition is triggered.

How to fix this

The DOM diff algorithm needs an option to force specific nodes in the old and new DOM to be identified with each other. This could be the HTML id attribute or a new, special attribute that is not rendered to the DOM.

Categories Uncategorized

Rusty Factory

So I saw this post asking for a translation of these Java design patterns to Rust. I will present a quite literal translation of the factory pattern and comment on its Rust idiomaticity in the progress. You can find the full code here. Be sure to have a look at all the commits.

The Java Factory Pattern

This section uses Java terminology.

The example contains an interface “Shape” with the method “draw”. Three classes (“Circle”, “Square”, “Rectangle”) implement that interface. Now I don’t find this example very well-chosen, as one could argue wether the “Square” class should be a subclass of the “Rectangle” class. In the example they are not subclasses and the geometrical relation between squares and rectangles is not used in any way. So to remove unnecessary confusion I will replace “Square” by “Triangle” in the following.

Furthermore we have a class “ShapeFactory” with a non-static method “getShape”, which receives a String and creates an instance of a class for it (e.g. String “circle” will result in a Circle object being returned). Then there is the main class “FactoryPatternDemo”, which serves the sole purpose of containing the main method, the start of the execution.

The Literal Translation


A Java “interface” can be translated to a Rust “trait”. They both define common methods to interact with different things.

A Java “interface” defines “methods”. “Methods” are functions, which always get a reference to an instance of their associated class as the first parameter “this”. If a “class” has all these methods, with the same type signature as defined by the interface, the class “implements” that interface (you also have to declare that it does so).

A Rust “trait” defines functions. These functions often take as first argument a “self” in some way (as a reference “&self”, as a mutable reference “&mut self” or by taking complete ownership “self”). This is optional tough. If there is an “implementation” of a trait for a “struct” (or “enum”), that “struct” (or “enum”) “satisfies” that trait.

So let’s look at some code:

trait Shape {
    fn draw(&self);

struct Rectangle;
struct Circle;
struct Triangle;

impl Shape for Rectangle {
    fn draw(&self) {
        println!("Inside Rectangle::draw function");

impl Shape for Circle {
    fn draw(&self) {
        println!("Inside Circle::draw function");

impl Shape for Triangle {
    fn draw(&self) {
        println!("Inside Triangle::draw function");

The lines with “struct” would usually contain information about the representation of the respective objects. A more realistic example could look like this:

struct Rectangle {
    origin: (f64,f64),
    size: (f64,f64),

But this is besides the point, as the original Java pattern PDF also uses dummy objects without member data.

The Factory

In the Java version there is a class “ShapeFactory” with a method “getShape” which returns an object of type “Shape”

Java uses dynamic dispatch by default. This means I can have a variable with the type “Shape” and it will check at runtime which “draw” function to call. Rust doesn’t like to do things at runtime (because it makes program execution slower), so dynamic dispatch is not enabled by default.

In Rust, there can’t be a variable with the type “Shape”! But Rust supports dynamic dispatch, if we really want it. We just have to box the variable: A variable of type “Box<Shape>” is perfectly fine.

But there is another pitfall with the return type of getShape: If the given string matches none of the available shapes, the factory will return “null”. In Java every function which is supposed to return an object can return “null” instead. In Rust we are only allowed to do that if we explicitly say so in the type of the function. Instead of returning a “Thing” we must return an “Option<Thing>” (Option documentation). So the Java return type of “Shape” becomes “Option<Box<Shape>>”.

struct ShapeFactory;

impl ShapeFactory {
    pub fn new() -> ShapeFactory {
    pub fn get_shape(&self, shape_type: &str) -> Option<Box<Shape>> {
        let shape_type_uppercase = shape_type.to_uppercase();
        match shape_type_uppercase.as_ref() {
            "CIRCLE" => Some(Box::new(Circle)),
            "RECTANGLE" => Some(Box::new(Rectangle)),
            "TRIANGLE" => Some(Box::new(Triangle)),
            _ => None,

The Main Function

In Java there are no functions. Everything is a method. To start execution, there is a class which has a method named “main”. Execution will start there. In Rust execution starts at the function named “main”. I will not literally translate this Java-madness OOP-for-the-sake-of-it main method to a Rust struct, but instead I will keep my sanity and translate the Java main method to the Rust main function.

Also instead of implicitly breaking the whole program in the case that we get a “None” (Rust’s version of Java’s “null”), we actually have to handle that case in Rust, because Rust does not like failing implicitly.

fn main() {
    let shape_factory : ShapeFactory = ShapeFactory::new();
    let shape1_option : Option<Box<Shape>> = shape_factory.get_shape("CIRCLE");
    match shape1_option {
        Some(shape1) => {
            // shape1 has type Box<Shape>
        None => {
            panic!("No shape found!");

Splitting it up

In the Java example everything is split up in multiple files. We just put the code in one file so far. Let’s change that.

Making it More Idiomatic

Throwing out the Factory

In the above version, we use the ShapeFactory as an object. It has only one method and no internal state. In rust we would definitely just use a function for that and throw out the ShapeFactory.

pub fn get_shape_by_name(shape_type: &str) -> Option<Box<Shape>> {
    let shape_type_uppercase = shape_type.to_uppercase();
    match shape_type_uppercase.as_ref() {
        "CIRCLE" => Some(Box::new(Circle)),
        "RECTANGLE" => Some(Box::new(Rectangle)),
        "TRIANGLE" => Some(Box::new(Triangle)),
        _ => None,

Or even not have that function at all and just directly construct what you want (e.g. Rectangle). To create more complicated things, we use the builder pattern in Rust.

Throwing out Dynamic Dispatch

Dynamic dispatch is a nice feature and in most situations its performance penalty is not even noticeable. If execution speed is of importance, we want to avoid dynamic dispatch. Rust provides means to write generic code but at the same time avoid dynamic dispatch.

fn show_shape<T:Shape>(shape: &T) {
    println!("Have a look at this marvelous shape:");

fn main() {
    let shape2 = triangle::Triangle;

The function “show_shape” is defined for any type that satisfies the trait “Shape”. The compiler will see what type the actually used shape object has and select the respective function call at compile-time! It cannot be used on a “Box<Shape>”! Repeat, the following does not work:

// shape1 has type Box<Shape>


Rust supports many different programming styles. You can program very javaesque code with it and it won’t complain. It will just run a little slower, which is probably fine for 99% of all code. If you need some fast code, don’t try to translate what you would do in another language to Rust; read about Rust, read Rust code, write Rust code and learn to think in a Rusty way for optimal results!

Tags , , ,
Categories Uncategorized

Force HTTPS for ownCloud 8 in a subdirectory

uberspace.de has a wildcard certificate for *.servername.uberspace.de. So if you want to use it, your ownCloud-installation must go in a subdirectory like so:


…because you have no certificate for https://owncloud.accountname.servername.uberspace.de (unless you buy one)

Sadly the server hardening information for HTTPS apply only if you installed ownCloud in a subdomain.

There used to be a config option for ownCloud telling it to secure everything using PHP code, but it’s gone now, so we have to use the “.htaccess” file for hardening and we do it like this:

Redirect to HTTPS

After the line “RewriteEngine On” add these lines:

RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This redirects every access to HTTPS. But there is one problem: If a user enters the HTTP address of the ownCloud instance, the session cookie might leak over HTTP before the redirect to HTTPS happens.

Harden the cookies

After the line “<IfModule mod_env.c>” add this line:

Header always edit Set-Cookie (.*) "$1; Secure"

This tells the browser to never transmit the ownCloud cookies over an insecure channel.

Categories Uncategorized

Using Systemd User Services

The information you need to actually use systemctl --user stuff is scattered all over the internet. So let me show you how it works for me, including all the necessary tweaking to actually make it work.

I am using Debian Testing. If you use something else, you might need more or fewer tweaking. In that case: Good luck.

As an example I use an X application: Redshift. X applications are harder to start than non-X apps. This is caused by their need for two environment variables: DISPLAY and XAUTHORITY. More on that later.

First we need to assure that the systemd user stuff is enabled. To check it run systemctl --user status. If it fails, look here.

Now let’s put a redshift.service file into ~/.config/systemd/user
Description=Daemon to adjust display brightness and color temperature to the current time

Wouldn’t it be nice if this just worked? Well it doesn’t. This solution only works for non-graphical applications. So now let’s give the necessary X variables (i.e. DISPLAY and XAUTHORITY) to the program. At many places it is stated that you can put the environment variables into the DefaultEnvironment of the ~/.config/systemd/user.conf file. This didn’t work for me and I don’t know why. This however works:
Description=Daemon to adjust display brightness and redness to the current time

Where the content of /home/username/.config/systemd/xenv is

However on Debian testing this alone still doesn’t do the trick because ~/.Xauthority doesn’t contain the actual cookie. The actual cookie location is varying on restart:

If the above command yields /home/username/.Xauthority for your system, everything should work fine and you don’t need to do the following step.
Put this code in your ~/.profile as suggested here:

    # DISPLAY is set and points to a local display, and XAUTHORITY is
    # set, so merge the contents of `$XAUTHORITY` into ~/.Xauthority.
    XAUTHORITY=~/.Xauthority xauth merge "$XAUTHORITY";;

This copies the X connection credentials to your .Xauthority-file. Note: This may be unsafe if other people can read your home directory.

Now we can actually start our service via systemctl --user start redshift, which is nice. However you may want to start it automatically (“autostart” behaviour). For this you need to add to your “.service” file:

Then you can do systemctl --user enable redshift. It will then be started if you boot to graphical mode and are logged in. Now you can use the whole power of Systemd to observe all your custom user-space daemons, which is nice.

Wrap-Up: You need to do these steps

  1. Assure systemd --user is active
  2. create /home/username/.config/systemd/user/redshift.service with the code from above
  3. create /home/username/.config/systemd/xenv with the environment variables from above (btw: the location for that file is irrelevant, just use the same location in the service file)
  4. add the magic case-statement from above to your /home/username/.profile
  5. systemctl --user enable redshift
Tags , , , , , ,
Categories Uncategorized

qrencode SVG: avoid white lines between pixels

If you have ever used the program qrencode to generate QR-Codes as SVG files, (e.g. qrencode -t SVG -o test.svg 'yourdata') then you have probably encountered this problem: Between every two adjacent lines of blocks/pixels there seems to be a thin white line.

QR code from qrencode -t SVG rendered to PNG with Inkscape

QR code from qrencode -t SVG rendered to PNG with Inkscape

This is because qrencode builds up svg files line by line using only rectangular black blocks. When two of these blocks are near each other, they should theoretically (as there is no space between them) not have a white line between them. However, due to the attempts of anti-aliasing by the SVG renderer (both rectangles’ edges try to fade to the white background for a smoother image), you see a white line between them.

The obvious solution would be for the adjacent blocks to be merged to one polygon line. Probably due to efficiency-reasons, qrencode doesn’t do that. So I’ll explain to you how to fix this with Inkscape.

Open up the generated SVG file in Inkscape. Select the QR code. Go to “Object”->”Ungroup”. You should now have two  selections: the QR code itself and a bigger white square in the background. Now select only the QR code itself (click outside the image to deselect, then click in the QR code). Go to “Path”->”Combine”. This is it. You can now save the file and don’t have to worry about the white lines anymore.

result: no white lines

QR code after the fix, rendered to PNG with Inkscape.

Some day maybe somebody should look into that qrencode source code and write a patch for “high quality high compatibility svg output” and generate those polygons directly.

Update: There is a patch for this in the pipeline: https://github.com/fukuchi/libqrencode/pull/41
However it is not accepted yet because of unrelated changes it makes and which require the librsvg to be updated.

Categories Uncategorized

Hardware Dual Boot

Note: I’m not a professional electrician. My plans and explanations could be wrong and if you follow them you might break your computer or get electrocuted. The following project documentation is provided without any warranties of any kind.

Some people want to use multiple operating systems and often they do not want to buy multiple computers for that purpose. So they install multiple OSes on one computer. This works well if all the involved OSes are aware of each other and try not to interfere with each other.

In practice this is not always the case. There are OSes which always want to reformat hard drives of (to them) unknown file systems. There are updates, which rewrite the boot loader code in such a way, that the other OS is not bootable anymore. So I wanted a hardware way to disallow any interference between the two OSes.

circuit diagramThe idea is, that there are two hard drives in the computer, with one operating system on each. Both are connected to the motherboard via SATA data connector cables, but only one at a time is connected to the power supply unit. If a hard drive does not have power, it can neither read nor write data. It can’t event power up its controller to tell the motherboard that it is there.

Note that we only need to switch the actual power cables and not the black ground cables. Ground alone does not provide any power and plugging in only ground is not harmful to the hard disk drives.

The parts I used are a SATA power Y cable and a 3xOn/On switch. On the tool side you need scissors to cut the cables and soldering stuff to put them back together in the way you want. Furthermore you need a continuity tester (present in most multimeters) to make sure, you soldered this correctly. If the wrong voltage arrives at the wrong pins of a hard drive, it will probably break. If you solder a power cable to ground, your PSU might break or even explode. Potentially other parts of your computer are also in danger. So please be very careful if you try this at home.

Categories Uncategorized

small rant: hp linux drivers

Some time ago I needed to use an Hewlett-Packard printer. For this task I installed hplip-3.14.4. Printing worked, but on system start-up, there was always this blue HP symbol in my KDE tray, which only vanished after right clicking on the symbol and choosing “quit”.

Why does a printer driver need a system tray icon?

So, I recently decided to remove the driver, as the printer was no longer in use by me. This took a very long time and some serious disk activity. htop revealed, that the uninstaller (written in Python 2) executed the command
find /home -name .hplip
This means, the hplip uninstaller literally looks at every single file and directory you own to check if it is the “.hplip” directory. Note: The “.hplip” directory is always in the root of a user home directory, so searching sub folders of sub folders doesn’t find you anything at all. I literally can’t think of a more stupid way to do this.

Better ways to uninstall files include (ordered descendingly by quality):

This is only a small rant on a very rantable topic: Linux drivers by hardware companies. At least there are some Linux drivers for most printers out there. How well they work and how well they are written however leaves much room for future improvement.

Categories Uncategorized