Skip to content

Create a readonly user in Postgres

2014 April 16
by Richard Knop

This is quite useful to create a user that can be used for backups, reporting and so on. Assuming you have databases foo_db and bar_db and want to create a readonly user for them called backup_user with password qux94874:

CREATE USER backup_user WITH ENCRYPTED PASSWORD 'qux94874';
GRANT CONNECT ON DATABASE foo_db to backup_user;
GRANT CONNECT ON DATABASE bar_db to backup_user;
\c foo
GRANT USAGE ON SCHEMA public to backup_user;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO backup_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup_user;
\c bar
GRANT USAGE ON SCHEMA public to backup_user;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO backup_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup_user;

Round half to even in Go

2013 November 24
by Richard Knop

Rounding half to even is used a lot when dealing with financial transactions. Here is my implementation in Go:

import "math"

// http://en.wikipedia.org/wiki/Rounding#Round_half_to_even
func roundHalfToEven(f float64) float64 {
        integer, fraction := math.Modf(f)
        f = integer
        if 0.5 == math.Abs(fraction) {
                if 0 != math.Mod(f, 2) {
                        f += math.Copysign(1, integer)
                }
        } else {
                f += math.Copysign(float64(int(fraction+math.Copysign(0.5, fraction))), fraction)
        }
        return f
}

And here are unit tests:

import "testing"

func TestRoundHalfToEven(t *testing.T) {

        testCases := []struct {
                numberToRound  float64
                expectedResult float64
        }{
                {
                        // 23.5 =~ 24
                        numberToRound:  23.5,
                        expectedResult: 24,
                },
                {
                        // 24.5 =~ 24
                        numberToRound:  24.5,
                        expectedResult: 24,
                },
                {
                        // 7.58 =~ 8
                        numberToRound:  7.58,
                        expectedResult: 8,
                },
                {
                        // 7.46 =~ 7
                        numberToRound:  7.46,
                        expectedResult: 7,
                },
                {
                        // 5 =~ 5
                        numberToRound:  5,
                        expectedResult: 5,
                },
                {
                        // -23.5 =! -24
                        numberToRound:  -23.5,
                        expectedResult: -24,
                },
                {
                        // -24.5 =~ -24
                        numberToRound:  -24.5,
                        expectedResult: -24,
                },
                {
                        // -7.58 =~ -8
                        numberToRound:  -7.58,
                        expectedResult: -8,
                },
                {
                        // -7.46 =~ -7
                        numberToRound:  -7.46,
                        expectedResult: -7,
                },
                {
                        // -5 =~ -5
                        numberToRound:  -5,
                        expectedResult: -5,
                },
                {
                        // 0 =~ 0
                        numberToRound:  0,
                        expectedResult: 0,
                },
        }

        for i, tc := range testCases {
                actualResult := roundHalfToEven(tc.numberToRound)
                if actualResult != tc.expectedResult {
                        t.Errorf("%v rounded half to even should be %v, instead of %v (%v)", tc.numberToRound, tc.expectedResult, actualResult, i)
                }
        }

}

Permutation algorithm

2013 October 25
by Richard Knop

You might remember me writing several articles explaining different sorting algorithms. I might come back to that series as there are few sorting algorithms I haven’t gone through.

But I wanted to do something else now, this is an interesting algorithm to find all permutations of a string.

Let’s say you have string “bar”. The steps are as follows:

  1. If the string is just a one letter, return it.
  2. Remove the first letter of the string and find all permutations of the new string. Do this recursively.
  3. For each found permutation, insert the remove letter from the previous step at every single position. Add each of these strings as a result.
  4. Return the array of results.

Here is implementation in JavaScript:

function permutations(word) {
    if (word.length <= 1) {
        return [word];
    }
 
    var perms = permutations(word.slice(1, word.length)),
    char = word[0],
    result = [],
    i;
    perms.forEach(function (perm) {
        for (i = 0; i < perm.length + 1; i += 1) {
            result.push(perm.slice(0, i) + char + perm.slice(i, perm.length));
        }
    });
 
    return result;
}

My new iPad game

2013 September 14
by Richard Knop

My new iPad game (School of Alchemy) just got approved by Apple. You can download it from the app store.

It was quite a fun project, I learned a lot about iOS web views and JavaScript / HTML5, the game is funny and features beautiful retina display optimised images, I’m sure you will like it.

Feel free to retweet:

Here are few screenshots:

School of Alchemy #1

School of Alchemy #2

School of Alchemy #3

School of Alchemy #4

School of Alchemy #5

How To Properly Inherit Methods From Prototype

2013 June 29
by Richard Knop

JavaScript is using prototypal inheritance instead of the common class bases inheritance we are all used to from Java or C#. This can be difficult to understand at first. Consider the simple following example:

function Mammal(config) {
    this.config = config;
    console.log(this.config);
}

function Cat(config) {
    // call parent constructor
    Mammal.call(this, config);
}
// inherit all methods from Mammal's prototype
Cat.prototype = new Mammal();

var felix = new Cat({
    "name": "Felix"
});

We have a simple inheritance pattern here. Mammal is a parent class which accepts config as a constructor argument. Cat extends Mammal’s prototype. Everything looks ok but when you run this code in the browser you will see this in the console:

undefined fiddle.jshell.net/_display/:23
Object {name: "Felix"}

The problem is that we calling the Mammal’s constructor twice. First time, when we try to inherit all methods from the Mammal’s prototype in the Cat object. Second time, when creating instance of Cat.

The correct way of inheriting would be:

function Mammal(config) {
    this.config = config;
    console.log(this.config);
}

function Cat(config) {
    // call parent constructor
    Mammal.call(this, config);
}
// inherit all methods from Mammal's prototype
Cat.prototype = Object.create(Mammal.prototype);

var felix = new Cat({
    "name": "Felix"
});

Build Pipeline Plugin’s Main Weakness

2013 June 24
by Richard Knop

Build Pipeline Plugin is one of my favorite Jenkins plugins. It allows you to build a pipeline out of several jobs by defining upstream and downstream jobs. This way you can create a process consisting of multiple steps from running unit tests, various code quality tools (lint, mess detector, copy paste detector etc), BDD tests, through deployment to different environments (integration, functional test, production).

This allows you to manage whole journey of an application from committing to version control (Git, SVN etc) to deployment on production servers. In addition, the Build Pipeline Plugin also represents this journey in a very nice visual way.

The only big issue I have with this plugin relates to manually triggered parametrized jobs. The problem is, when you have a parametrized job which requires a manual submission (deployment to staging or production certainly does), it should ask you to manually enter the required parameters when you trigger the job from the pipeline view. This doesn’t happen and it triggers the build without any parameters.

This is quite annoying and has forced me to remove jobs like this from the pipeline for now (until the plugin is updated to support this very important feature…).

Quick Introduction To BDD Testing With Behat

2013 June 20
tags:
by Richard Knop

Behat is a PHP framework for BDD testing. It us very similar to Cucumber (RoR) or Behave (Django), it uses Gherkin language to define features and scenarions. These are then executed by Behat, which uses one or several drivers. In this short example I will show you how to use two drivers:

  • Goutte (simple HTTP based headless browser)
  • Selenium 2 (full browser emulator with JS support)

First, let’s use Composer to install Behat and the drivers:

{
    "name": "foo-bar",
    "description": "Foo Bar",
    "minimum-stability": "dev",
    "require": {
        "php": ">=5.3",
    },
    "require-dev": {
        "behat/behat": "dev-develop#1f1bead31e96da5e30fd5d499d5cf66d29b68cf6",
        "behat/mink": "v1.4.3",
        "behat/mink-extension": "dev-master#ef2c8639ebc254f0ff6e555b7834700caf5db9c4",
        "behat/mink-goutte-driver": "dev-master#v1.0.8",
        "behat/mink-selenium2-driver": "v1.0.6",
    }
}

Install the dependencies defined in composer.json file (above):

php composer.phar install --dev

Make sure you have Firefox 21 installed as that’s what we will be using for Selenium 2 tests. Also important, make sure you have Selenium 2 server installed and running. I have written a post explaining how to install Selenium 2 on Mac OS as a service.

This is an example behat.yml file I’m using in one of projects I work on:

default:
  paths:
    features: tests/functional/features
    bootstrap: tests/functional/features/bootstrap
  extensions:
    Behat\MinkExtension\Extension:
      base_url: http://virtualhost.local
      goutte: ~
      default_session: goutte 
      javascript_session: selenium2 
      selenium2: 
        browser: firefox
        capabilities: { "browserName": "firefox", "browser": "firefox", "version": "21"}
        wd_host: http://127.0.0.1:4443/wd/hub

Then you can run the tests like this:

vendor/bin/behat --ansi

All tests with @javascript tag will use Selenium 2 driver (so a new Firefox window will pop up and your tests will run inside it), tests without @javascript tag will run using the headless Goutte driver.

You can exclude Selenium 2 tests like this (for example you might not have an external Selenium 2 server for Jenkins so you might want to run Selenium tests only locally and run only tests without @javascript tag on Jenkins as a part of the build process):

vendor/bin/behat --ansi --tags=~@javascript

Installing Selenium 2 On Mac OS As Service

2013 June 20
tags:
by Richard Knop

Selenium 2 is a powerful browser emulator which enables you to automate frontend testing (especially JavaScript heavy pages). It can be used with Behat as well for BDD testing.

I prefer using Goutte headless driver to test basic functionality and flow of the application but sometimes there are critical parts of the app that rely heavily on client side technologies like JavaScript. Only way to test to those is to use a browser emulator (Selenium 2, Sahi etc). Enough talking, here is how I installed Selenium 2 server on Mac OS as a service:

wget https://selenium.googlecode.com/files/selenium-server-standalone-2.33.0.jar

sudo mkdir /usr/lib/selenium

sudo mv selenium-server-standalone-2.33.0.jar /usr/lib/selenium

sudo mkdir /var/log/selenium

sudo chmod -R a+w /var/log/selenium

Then you need to create a new file:

sudo nano ~/Library/LaunchAgents/org.nhabit.Selenium.plist

With contents:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>org.nhabit.Selenium</string>
        <key>OnDemand</key>
        <true/>
        <key>ProgramArguments</key>
        <array>
                <string>/usr/bin/java</string>
                <string>-jar</string>
                <string>/usr/lib/selenium/selenium-server-standalone-2.33.0.jar</string>
                <string>-port</string>
                <string>4443</string>
        </array>
        <key>ServiceDescription</key>
        <string>Selenium Server</string>
        <key>StandardErrorPath</key>
        <string>/var/log/selenium/selenium-error.log</string>
        <key>StandardOutPath</key>
        <string>/var/log/selenium/selenium-output.log</string>
</dict>
</plist>

Load the service:

launchctl load ~/Library/LaunchAgents/org.nhabit.Selenium.plist
launchctl start org.nhabit.Selenium

You can also check it’s running:

ps aux | grep selenium

richardknop    19880   0.0  0.5  2859020  76648   ??  S     2:09pm   0:07.05 /usr/bin/java -jar /usr/lib/selenium/selenium-server-standalone-2.33.0.jar -port 4443
richardknop    20852   0.0  0.0  2432768    596 s001  R+    3:17pm   0:00.00 grep selenium

And error logs, just in case you need them:

tail -f /var/log/selenium/selenium-error.log

Are Backbone Models Singletons?

2013 June 20
by Richard Knop

I have been using Backbone (plus couple of other JavaScript libraries) for my last project. One of the first problems I encountered was this simple code:

var Foo = Backbone.Model.extend({
    defaults: {
        bars: []
    }
});

var foo = new Foo();
foo.get("bars").push("a");
foo.get("bars").push("b");
console.log(foo.get("bars"));

var foo = new Foo();
foo.get("bars").push("c");
foo.get("bars").push("d");
console.log(foo.get("bars"));

A simple model with array as a property, seems pretty straightforward. But when I created two instances of the model, this was logged in the console:

["a", "b", "c", "d"]
["a", "b", "c", "d"]

JSFiddle

Well, the problem was that the property declared in defaults is a global one. In order to avoid this rookie mistake, init all arrays or dictionaries in initialize method:

var Foo = Backbone.Model.extend({
    initialize: function() {
        this.set("bars", []);
    }
});

Here is my related StackOverflow question: Are Backbone Models Singletons?

Faster Autoloading With Zend Framework 2

2013 May 2
by Richard Knop

Standard autoloader that comes with Zend Framework 2 is not and ideal one to use in production environment. I would suggest using a classmap autoloader which is faster. Here is how it works. When installing dependencies specified in composer.json, use -o option in order to generate classmap file:

php composer.phar install -o

It will create a PHP file at vendor/composer/autoload_classmap.php path which contains a static array of all knows classes from dependencies (Zend Framework 2, Doctrine 2 etc) with namespaces and paths to files.

You should also autoload all your modules in the same way. Either do it manually – cd into module folder and generate the classmap file:

cd module/Foo
../../vendor/bin/classmap_generator.php -w

Or use ANT:

<target name="classmapgenerator" description="">
		<exec executable="php">
			<arg value="${basedir}/vendor/zendframework/zendframework/bin/classmap_generator.php" />
			<arg value="-w" />
			<arg value="-l" />
			<arg value="module/Foo" />
		</exec>
		<exec executable="php">
			<arg value="${basedir}/vendor/zendframework/zendframework/bin/classmap_generator.php" />
			<arg value="-w" />
			<arg value="-l" />
			<arg value="module/Bar" />
		</exec>
	</target>

Inside your Module.php, change getAutoloaderConfig() method to look like this:

public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
        );
    }

Finally, change your init_autoloader.php file:

require_once __DIR__ . '/vendor/zendframework/zendframework/library/Zend/Loader/AutoloaderFactory.php';
require_once __DIR__ . '/vendor/zendframework/zendframework/library/Zend/Loader/ClassMapAutoloader.php';
Zend\Loader\AutoloaderFactory::factory(array(
    'Zend\Loader\ClassMapAutoloader' => array(
        'Composer' => __DIR__ . '/vendor/composer/autoload_classmap.php',
    )
));

Done! I don’t have any benchmarks at the moment. If I will have more free time, I will run some benchmarks to see how much faster it is actually.