Three months in Cyprus



Nicosia aqueduct

From March to May I was in Cyprus. Most of time I was in Nicosia, but visited most of Cyprus’s cities. Nicosia located in the middle of the island, 30-50 minutes by bus from the sea (Larnaca). The city split between two countries and has some sort of wall.

For entering country I was using Pro Visa, it’s very easy to obtain, you just need to fill some form and send to consulate by email. It allows to stay 90 days in Cyprus.

In Nicosia I was living in city center, and was renting apartment with shared kitchen for €300 including water, electricity and internet. Internet was like 20 MBit/s.

Mobile internet is a bit pricey, I was using MTN and paid €15 for 1.5GB for month. LTE available in almost all cities.

Food is relatively cheap, for everyday meat/fish/seafood I spend around €40 per week. Prices is supermarket near my apartment was €4-5 for pork, €5-6 for chicken, €5-10 for fish and €8-10 for octopus and other seafood, €0.3-1 for vegetables.

Alcohol is also cheap, €1-1.5 for can of beer, €4-5 for six pack. Local wine was around €4-5. Local strong drinks like Ouzo and Zivania was €5-10.

Main problem with shopping in Cyprus, is that shops close very early on Wednesday and Saturday, and they doesn’t work on Sundays.

Although, Nicosia is very comfortable place to live.

In this trip I also visited Israel for two weeks, lived in Tel-Aviv. And Georgia, for two weeks too, lived in Tbilisi. They’re both very nice and interesting places.

The Performance of Open Source Applications



book cover I already read all other books from this series (The Architecture of Open Source Applications volumes I and II) so I decided to read latest book – The Performance of Open Source Applications. And it’s quite a nice book. Not all chapters were interesting for me. But it was lovely to read about network stack of Chrome and about performance problems in it and about Mozilla’s stack problems and solutions.

Also the book contains great explanation why pings on mobile devices can be big, and what problems can it cause.

Lightweight events in Kotlin



In one of my applications I needed some minimalistic event system and all I can found was require creating a ton of classes or use a lot of annotations, or was magick-scala-like with overloaded -=, += and () just because author can do it.

So I decided to write something very simple, with interface like:

ClickEvent on {
    println("CLICK: ${it.x} ${it.y}")
}

ClickEvent(10, 20).emit()

And it was implemented easily:

open class Event<T> {
    var handlers = listOf<(T) -> Unit>()

    infix fun on(handler: (T) -> Unit) {
        handlers += handler
    }

    fun emit(event: T) {
        for (subscriber in handlers) {
            subscriber(event)
        }
    }
}

data class ClickEvent(val x: Int, val y: Int) {
    companion object : Event<ClickEvent>()

    fun emit() = Companion.emit(this)
}

ClickEvent on {
    println("CLICK: ${it.x} ${it.y}")
}

ClickEvent(10, 20).emit()

>>> CLICK: 10 20

You can notice a bit of boilerplate, main reason to have it is because in Kotlin we don’t have static methods, we can’t use inheritance with data classes and also we can’t use companion object of interface (or even parent class) in class that implements it. So in each event we have to duplicate some redundant code:

data class MyEvent(val data: String) {
    companion object : Event<MyEvent>()

    fun emit() = Companion.emit(this)
}

Back to positive side, let’s implement a few other events and try it in action. Start from event without arguments, it can’t be a data class:

class ConnectionLostEvent {
    companion object : Event<ConnectionLostEvent>()

    fun emit() = Companion.emit(this)
}

ConnectionLostEvent on {
    println("Oh, snap!")
}

ConnectionLostEvent().emit()

>>> Oh, snap!

What if we want events hierarchy, we can use sealed class for event type and few classes for events. They also can’t be data classes:

sealed class MouseEvent {
    companion object : Event<MouseEvent>()

    class Click(val x: Int, val y: Int) : MouseEvent() {
        fun emit() = Companion.emit(this)
    }

    class Move(val fromX: Int, val fromY: Int, val toX: Int, val toY: Int) : MouseEvent() {
        fun emit() = Companion.emit(this)
    }
}

MouseEvent on {
    when (it) {
        is MouseEvent.Click -> println("Click x:${it.x} y:${it.y}")
        is MouseEvent.Move -> println(
                "Move from ${it.fromX}:${it.fromY} to ${it.toX}:${it.toY}")
    }
}

MouseEvent.Click(50, 40).emit()
MouseEvent.Move(0, 0, 9, 12).emit()

>>> Click x:50 y:40
>>> Move from 0:0 to 9:12

As you can see it isn’t that nice that it can be implemented with Scala or Clojure. Kotlin isn’t rich language, but it’s simple and works pretty well on Android.

Also you notice that code highlighting in the article looks wrong, it’s because rouge, highlighting engine used by github pages, doesn’t support Kotlin right now, and I just used one for Scala.

Daniel Holden: Build Your Own Lisp



book cover On Reddit I stumbled on Build Your Own Lisp by Daniel Holden and decided to read it. And it’s one of the most interesting technical book I’m read. Reading this book I refreshed my knowledge of C, got few ideas for my own projects and even almost built my own Lisp.

Although in this book explains building process of not actual Lisp, it doesn’t have quotation '(f x), it uses Q-Expressions {f x}. And also it doesn’t have macros. But the book suggested readers to write all of that in the last chapter.

Freeze time in tests even with GAE datastore



It’s not so rare thing to freeze time in tests and for that task I’m using freezegun and it works nice almost every time:

from freezegun import freeze_time


def test_get_date():
    with freeze_time("2016.1.1"):
        assert get_date() == datetime(2016, 1, 1)

But not with GAE datastore. Assume that we have a model Document with created_at = db.DateTimeProperty(auto_now_add=True), so test like:

from freezegun import freeze_time


def test_created_at():
    with freeze_time('2016.1.1'):
        doc = Document()
        doc.put()
        assert doc.created_at == datetime(2016, 1, 1)

Will fail with:

BadValueError: Unsupported type for property created_at: <class 'freezegun.api.FakeDatetime'>

But it can be easily fixed if we monkey patch GAE internals:

from contextlib import contextmanager
from google.appengine.api import datastore_types
from mock import patch
from freezegun import freeze_time as _freeze_time
from freezegun.api import FakeDatetime


@contextmanager
def freeze_time(*args, **kwargs):
    with patch('google.appengine.ext.db.DateTimeProperty.data_type',
                new=FakeDatetime):
        datastore_types._VALIDATE_PROPERTY_VALUES[FakeDatetime] = \
            datastore_types.ValidatePropertyNothing
        datastore_types._PACK_PROPERTY_VALUES[FakeDatetime] = \
            datastore_types.PackDatetime
        datastore_types._PROPERTY_MEANINGS[FakeDatetime] = \
            datastore_types.entity_pb.Property.GD_WHEN
            
        with _freeze_time(*args, **kwargs):
            yield

And now it works!

Conway's Game of Life for Web and Android with ClojureScript



Recently I’ve been working on rerenderer – cross-platform react-like library for drawing on canvas. So I though it would be nice to implement Conway’s Game of Life with it.

All rerenderer applications have two essential parts: controller, that manipulates state and handle events, and view, that renders it. It’s actually MVC, but model (state) here is just an atom.

Let’s start with view:

(ns example.game-of-life.view
  (:require [rerenderer.primitives :refer [rectangle]]))

(def cell-size 40)

(defn cell
  [[x y]]
  (let [cell-x (* cell-size x)
        cell-y (* cell-size y)]
    (rectangle {:x cell-x
                :y cell-y
                :width cell-size
                :height cell-size
                :color "green"})))

(defn root-view
  [{:keys [cells]}]
  (rectangle {:x 0
              :y 0
              :width 1920
              :height 1080
              :color "white"}
    (for [cell-data cells]
      (cell cell-data))))

Here cell is the game cell, it will be rendered as a green rectangle. And root-view is the game scene that will contain all cells.

One nice thing about rerenderer, that it just renders state, so you can change :cells in editor below and see how root-view will rerender it:

Now it’s time for controller. Game logic already was implemented million times, it’s not so interesting, so I’ve just took it from sebastianbenz/clojure-game-of-life and we’ll use tick function from there:

(ns example.game-of-life.controller
  (:require-macros [cljs.core.async.macros :refer [go-loop]])
  (:require [cljs.core.async :refer [<! timeout]]))

(defn main-controller
  [_ state-atom _]
  (go-loop []
    (<! (timeout 100))
    (swap! state-atom update :cells tick)
    (recur)))

It’s very simple, every 100ms we’ll get new game state with tick and update rendering state.

And now the final part, glue that connect controller with view and state:

(ns example.game-of-life.core
  (:require [rerenderer.core :refer [init!]]
            [example.game-of-life.view :refer [root-view]]
            [example.game-of-life.controller :refer [main-controller]]))

(def inital-state {:cells [[1 5] [2 5] [1 6] [2 6]
                           [11 5] [11 6] [11 7] [12 4] [12 8] [13 3] [13 9] [14 3] [14 9]
                           [15 6] [16 4] [16 8] [17 5] [17 6] [17 7] [18 6]
                           [21 3] [21 4] [21 5] [22 3] [22 4] [22 5] [23 2] [23 6] [25 1] [25 2] [25 6] [25 7]
                           [35 3] [35 4] [36 3] [36 4]]})

(init! :root-view root-view
       :event-handler main-controller
       :state inital-state)

And that’s all, in action:

And it works on Android (apk), not without problems, it has some performance issues. And there’s strange behaviour, it’s like ten times slower when screen recorder is on. But it works without changes in code and renders on Android native Canvas:

Source code on github.

Steve Krug: Don't Make Me Think



book cover I’ve always wanted to learn more about UX and found Don’t Make Me Think by Steve Krug. It’s a short book, and it’s interesting and easy to read. It explains usability concepts by examples of web and mobile apps. The book even contains accessibility advices.

I don’t know much about UX, but in my opinion this book is nice.

Lorin Hochstein: Ansible: Up and Running



book cover white Recently I’m started to use Ansible. Before that I mostly worked with Puppet, so I decided to read something about Ansible and read Ansible: Up and Running by Lorin Hochstein.

And it’s a nice book, explains most aspects of Ansible. Shows real world use cases and a lot of playbooks.

Definitely it’s a nice book for whom who start working with Ansible.

Robert C. Martin: The Clean Coder



book cover Friends recommended me to read The Clean Coder: A Code of Conduct for Professional Programmers by Robert C. Martin. And recently I read it. The book explains some parts of engineer’s work, makes some useful points. And proves them with real life stories. Most of things in the book are well known, but it’s nice that author describes not only “good path”, but also situations when something gone wrong.

By the way, the book is interesting to read.

Writing breakout clone with micropython



I have pyboard, OLED display (SSD1306) and joystick (Keyes_SJoys), so I decided to try to make breakout clone. First of all I decided to create something like a little framework, that will be a bit similar to React, and all game can be formalized just in two functions:

  • (state) → new-state – controller that updates state;
  • (state) → primitives – view that converts state to generator of primitives.

For example, code that draws chess cells and invert it on click, will be like:

from lib.ssd1306 import Display
from lib.keyes import Joystick
from lib.engine import Game, rectangle, text


def is_filled(x, y, inverted):
    fill = (x + y) % 40 == 0
    if inverted:
        return not fill
    else:
        return fill


def view(state):
    # Display data available in state['display']
    for x in range(0, state['display']['width'], 20):
        for y in range(0, state['display']['height'], 20):
            # rectangle is bundled view that yields points
            yield from rectangle(x=x, y=y, w=20, h=20,
                                 fill=is_filled(x, y, state['inverted']))


def controller(state):
    # Joystick data available in state['display']
    if state['joystick']['clicked']:
        return dict(state, inverted=not state['inverted'])
    else:
        return state

initial_state = {'inverted': False}
chess_deck = Game(display=Display(pinout={'sda': 'Y10',
                                          'scl': 'Y9'},
                                  height=64,
                                  external_vcc=False),
                  joystick=Joystick('X1', 'X2', 'X3'),
                  initial_state=initial_state,
                  view=view,
                  controller=controller)

if __name__ == '__main__':
    chess_deck.run()

In action:

Chess photo

From the code you can see, that views can be easily nested with yield from. So if we want to move cell to separate view:

def cell(x, y, inverted):
    yield from rectangle(x=x, y=y, w=20, h=20,
                         fill=is_filled(x, y, inverted))


def view(state):
    for x in range(0, state['display']['width'], 20):
        for y in range(0, state['display']['height'], 20):
            yield from cell(x, y, state['inverted'])

And another nice thing about this approach, is that because of generators we consume not a lot of memory, if we’ll make it eager, we’ll fail with MemoryError: memory allocation failed soon.

Back to breakout, let’s start with views, first of all implement splash screen:

def splash(w, h):
    for n in range(0, w, 20):
        yield from rectangle(x=n, y=0, w=10, h=h, fill=True)

    yield from rectangle(x=0, y=17, w=w, h=30, fill=False)
    # text is bundled view
    yield from text(x=0, y=20, string='BREAKOUT', size=3)


def view(state):
    yield from splash(state['display']['width'],
                      state['display']['height'])

It will draw a nice splash screen:

Splash screen

On splash screen game should be started when user press joystick, so we should update code a bit:

GAME_NOT_STARTED = 0
GAME_ACTIVE = 1
GAME_OVER = 2

def controller(state):
    if state['status'] == GAME_NOT_STARTED and state['joystick']['clicked']:
        state['status'] = GAME_ACTIVE
    return state


initial_state = {'status': GAME_NOT_STARTED}

Now when joystick is pressed, game changes status to GAME_ACTIVE. And now it’s time to create view for game screen:

BRICK_W = 8
BRICK_H = 4
BRICK_BORDER = 1
BRICK_ROWS = 4

PADDLE_W = 16
PADDLE_H = 4

BALL_W = 3
BALL_H = 3


def brick(data):
    yield from rectangle(x=data['x'] + BRICK_BORDER,
                         y=data['y'] + BRICK_BORDER,
                         w=BRICK_W - BRICK_BORDER,
                         h=BRICK_H - BRICK_BORDER,
                         fill=True)


def paddle(data):
    yield from rectangle(x=data['x'], y=data['y'],
                         w=PADDLE_W, h=PADDLE_H,
                         fill=True)


def ball(data):
    yield from rectangle(x=data['x'], y=data['y'],
                         w=BALL_W, h=BALL_H, fill=True)


def deck(state):
    for brick_data in state['bricks']:
        yield from brick(brick_data)

    yield from paddle(state['paddle'])
    yield from ball(state['ball'])


def view(state):
    if state['status'] == GAME_NOT_STARTED:
        yield from splash(state['display']['width'],
                          state['display']['height'])
    else:
        yield from deck(state)


def get_initial_game_state(state):
    state['status'] = GAME_ACTIVE
    state['bricks'] = [{'x': x, 'y': yn * BRICK_H}
                       for x in range(0, state['display']['width'], BRICK_W)
                       for yn in range(BRICK_ROWS)]
    state['paddle'] = {'x': (state['display']['width'] - PADDLE_W) / 2,
                       'y': state['display']['height'] - PADDLE_H}
    state['ball'] = {'x': (state['display']['width'] - BALL_W) / 2,
                     'y': state['display']['height'] - PADDLE_H * 2 - BALL_W}
    return state


def controller(state):
    if state['status'] == GAME_NOT_STARTED and state['joystick']['clicked']:
        state = get_initial_game_state(state)
    return state

Game screen

And last part of views – game over screen:

def game_over():
    yield from text(x=0, y=20, string='GAMEOVER', size=3)


def view(state):
    if state['status'] == GAME_NOT_STARTED:
        yield from splash(state['display']['width'],
                          state['display']['height'])
    else:
        yield from deck(state)
        if state['status'] == GAME_OVER:
            yield from game_over()

Game screen

So we ended up with views, now we should add ability to move paddle with joystick:

def update_paddle(paddle, joystick, w):
    paddle['x'] += int(joystick['x'] / 10)
    if paddle['x'] < 0:
        paddle['x'] = 0
    elif paddle['x'] > (w - PADDLE_W):
        paddle['x'] = w - PADDLE_W
    return paddle


def controller(state):
    if state['status'] == GAME_NOT_STARTED and state['joystick']['clicked']:
        state = get_initial_game_state(state)
    elif state['status'] == GAME_ACTIVE:
        state['paddle'] = update_paddle(state['paddle'], state['joystick'],
                                        state['display']['width'])
    return state

Never mind performance, it’ll be fixed in the end of the article:

Now it’s time for the hardest thing – moving and bouncing ball, so there’s no real physics, for simplification ball movements will be represented as vx and vy, so when ball:

  • initialised: vx = rand(SPEED), vy = √SPEED^2 - vx^2;
  • hits the top wall: vy = -vy;
  • hits the left or right wall: vx = -vx:
  • hits the brick or paddle: vx = vx + (0.5 - intersection) * SPEED, where intersection is between 0 and 1; vy = √SPEED^2 - vx^2.

And I implemented something like this with a few hacks:

BALL_SPEED = 6
BALL_SPEED_BORDER = 0.5


def get_initial_game_state(state):
    state['status'] = GAME_ACTIVE
    state['bricks'] = [{'x': x, 'y': yn * BRICK_H}
                       for x in range(0, state['display']['width'], BRICK_W)
                       for yn in range(BRICK_ROWS)]
    state['paddle'] = {'x': (state['display']['width'] - PADDLE_W) / 2,
                       'y': state['display']['height'] - PADDLE_H}

    # Initial velocity for ball:
    ball_vx = BALL_SPEED_BORDER + pyb.rng() % (BALL_SPEED - BALL_SPEED_BORDER)
    ball_vy = -math.sqrt(BALL_SPEED ** 2 - ball_vx ** 2)
    state['ball'] = {'x': (state['display']['width'] - BALL_W) / 2,
                     'y': state['display']['height'] - PADDLE_H * 2 - BALL_W,
                     'vx': ball_vx,
                     'vy': ball_vy}
    return state


def calculate_velocity(ball, item_x, item_w):
    """Calculates velocity for collision."""
    intersection = (item_x + item_w - ball['x']) / item_w
    vx = ball['vx'] + BALL_SPEED * (0.5 - intersection)
    if vx > BALL_SPEED - BALL_SPEED_BORDER:
        vx = BALL_SPEED - BALL_SPEED_BORDER
    elif vx < BALL_SPEED_BORDER - BALL_SPEED:
        vx = BALL_SPEED_BORDER - BALL_SPEED

    vy = math.sqrt(BALL_SPEED ** 2 - vx ** 2)
    if ball['vy'] > 0:
        vy = - vy
    return vx, vy


def collide(ball, item, item_w, item_h):
    return item['x'] - BALL_W < ball['x'] < item['x'] + item_w \
           and item['y'] - BALL_H < ball['y'] < item['y'] + item_h


def update_ball(state):
    state['ball']['x'] += state['ball']['vx']
    state['ball']['y'] += state['ball']['vy']

    # Collide with left/right wall
    if state['ball']['x'] <= 0 or state['ball']['x'] >= state['display']['width']:
        state['ball']['vx'] = - state['ball']['vx']

    # Collide with top wall
    if state['ball']['y'] <= 0:
        state['ball']['vy'] = -state['ball']['vy']

    # Collide with paddle
    if collide(state['ball'], state['paddle'], PADDLE_W, PADDLE_H):
        vx, vy = calculate_velocity(state['ball'], state['paddle']['x'], PADDLE_W)
        state['ball'].update(vx=vx, vy=vy)

    # Collide with brick
    for n, brick in enumerate(state['bricks']):
        if collide(state['ball'], brick, BRICK_W, BRICK_H):
            vx, vy = calculate_velocity(state['ball'], brick['x'], BRICK_W)
            state['ball'].update(vx=vx, vy=vy)
            state['bricks'].pop(n)

    return state


def controller(state):
    if state['status'] == GAME_NOT_STARTED and state['joystick']['clicked']:
        state = get_initial_game_state(state)
    elif state['status'] == GAME_ACTIVE:
        state['paddle'] = update_paddle(state['paddle'], state['joystick'],
                                        state['display']['width'])
        state = update_ball(state)
    return state

And it seems to be wroking:

So now the last part, we should show “Game Over” when ball hits the bottom wall or when all bricks destroyed, and then start game again if user clicks joystick:

def is_game_over(state):
    return not state['bricks'] or state['ball']['y'] > state['display']['height']


def controller(state):
    if state['status'] in (GAME_NOT_STARTED, GAME_OVER)\
            and state['joystick']['clicked']:
        state = get_initial_game_state(state)
    elif state['status'] == GAME_ACTIVE:
        state['paddle'] = update_paddle(state['paddle'], state['joystick'],
                                        state['display']['width'])
        state = update_ball(state)
        if is_game_over(state):
            state['status'] = GAME_OVER
    return state

And it works too:

Performance so bad because drawing pixel on the screen is relatively time consuming operation, and we can easily fix performance by just decreasing count of bricks:

BRICK_W = 12
BRICK_H = 6
BRICK_BORDER = 4
BRICK_ROWS = 3

And now it’s smooth:

Source code.