Comments

I was 7 the first time I watched Jurassic Park. It has remained my favorite childhood movie and greatly influenced how I was going to play with my toys for the next few years.

Fast forward 20 years, the man child in me was stoked to see the trailers for Jurassic World, the fourth installment in the franchise. This time around, I decided to get the Jurassic Park book by Michael Crichton, because why the hell not! It has Dinosaurs.

The book is racy and easy to read and I ended up finishing it in two sittings. However,

Never have I been so pissed off by a fictional little girl in a book than the annoying little irritating piece of shit, Lex.

In the book, the boy is the elder one; a dinosaur nerd savvy with computers although having his parade pissed on by his younger brat of a sister all the time. The little girl is of no help, whines constantly and is always hungry without any human emotion.

If Satan was a little girl, it would have been Lex.

Looking back, it has made me appreciate Spielberg’s direction by having both the kids do something. The sister in the movie was the elder one, was a ‘hacker of the unixes’ but atleast she had something for us to root for. Always on the lookout and cautious of Dinosaurs. Added to that she bails her brother out in the scary kitchen scene.

Lex in the movie was of some help and has her moments.

However, Lex from the book has only made me think of imaginative ways to kill her off.

My favorite, Dr. Grant using her as a distraction to escape from the T-Rex. The big rex gets her snack and everyone is happy that no one is whining anymore!

After countless unsuccessful attempts of getting fit by waking up early in the morning and run around the neighbourhood, realisation dawned on me. I needed some extra motivation to help me get started.

The timing was perfect as I got that motivation (or atleast I thought I did) in the form of a very thoughtful gift from someone very special to me.

Unfortunately, my Laziness has been trouncing my Motivation without any hint of mercy whatsoever.

That said, I absolutely adore this little bugger of a gadget that has seamlessly merged into my daily routine.

Has a long battery life, is hackable, has customizable faces, syncs with my phone and has a rather nice app ecosystem.

However, if you are like me and somehow think that splurging money on a smart wearable with sensors is going to make you wake up in the morning and go do that run that you had been procastinating all along, please! Don’t kid yourself.

No gadget with any fancy wizardry is going to solve the vice of Laziness. This is a challenge at a more human level.

A challenge that millions including me, face every morning at 6.

I was never a big fan of Royal Enfields

I happened to get hold of a Classic 500 Desert Storm for a short ride to Wayanad recently. I have to admit I started the ride with a very unfair negative bias towards the machine. I hated the handling, the brakes, the vibrations and even the turd-sandwich colour. But as the miles were being munched, it grew on me and I was actually enjoying myself.

This bike had this knack of preventing me from pushing my limits. Instead it was demanding me to take it slow, relax and soak myself into the environment. As the milestones whizzed past me, I found myself not really caring about the vibrations or the uninspiring brakes or the boat-like handling; things that I felt were big deal-breakers for me in the beginning.

Towards the end of the ride, I realised it’s not the machines I was having a problem with. But the RE fans who always seem to fall into these two polarising buckets.

  • On one hand we have the rabid fanboys with a hardon for these bikes who bought them just because it comes with a very fast 350cc mill and surprise! has very less number of plastic parts. I always find them loaded with this Master Race mentality just because they happen to own a Royal Enfield. Screw these guys. They are a Royal Pain in the Ass to deal with.
  • On the other hand, I love talking to those Bull owners who take a lot of pride in their machines, at times to a point of being very vocal but are ready to acknowledge the fact that Royal Enfields aren’t perfect; that they might not be the best tourer out there (IMO they are not), that it’s the awesome legacy that they are owning.

You could argue there are fanatics for any brand, motorcycles or otherwise, out there. But the thing is, nowhere have I seen this much of a stark contrast in a fanbase before, where I despise one set of the populace and have complete respect for the other. (I am guilty of being in the first category myself when it comes to Apple notebooks :D)

I like Royal Enfields now. I love its iconic thump and the styling that remains faithful to its roots. I love the posture and the sheer road presence that these machines ooze out. I enjoyed being respected on the road a lot more than the other bikes of seemingly lesser pedigree. Heck! I even love their classy promotional videos,

However, for the love of all things holy, Dear RE owners, please stop pretending it’s the best motorcycle out there. It’s not!

Comments

I am one of those people with a very volatile memory. Unless I jot down things even if it is as mundane as getting a haircut, I find myself with a nagging sense of incompleteness in my head. It is a very uncomfortable feeling to have.

I had been trying to use Evernote, Wunderlist and org-mode to help solve this. No god damn luck. Only org-mode worked for me in the beginning but I found myself slowly starting to worry about how to format my fricking lists instead.

My brain had started to bikeshed with itself!

For me, these tools turned out to be hard to focus with. And lo! I fell back to using a Pen and a Notebook instead.

Writing down todo lists feels much more satisfying than typing them. The contents somehow ‘sticks’ to my head and I don’t need reminders on my phone anymore (which I mostly used to ignore anyways).

Of course, there are a lot of productivity problems solved successfully by software but I have come to a conclusion that simple personal todo lists is NOT one of them.

Pen and Paper beats the Computer in this case.

I gifted myself an Arduino Starter Kit from Simplelabs to kill some time during the weekends. Needless to say, I felt really proud of myself once I got the LED blink example working without breaking anything.

My next project was a simple Jenkins build monitor, very popular amongst the Arduino beginners out there who write code.

Here is my version of this hack. In addition to the usual ‘traffic light’, I also plonked on a 16x2 LCD to the circuit which displays the build number along with the status. Scroll down to the end of this post to see this in action.

Schema

I used Fritzing to draw this schema and I know it’s a little bit ugly.

Anyway, successful builds turn on the Green LED; Unstable builds, yellow; Failed builds, red and my favorite of all, builds in progress makes the LEDs turn into KITT from Knight Rider :P.

Code

The code is pretty simple. There is a Python script that uses the Jenkins REST API to get the latest build and its status for a given a job. This is translated into a crude command for the Arduino board to pick up using the Serial interface.

Python side of things

(jenkins_status.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# Copyright 2013 Sudharshan S
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
import sys
import time
import glob
import os

import serial

from jenkinsapi.jenkins import Jenkins

led_states = {
    "BLINKING": 2,
    "ALWAYS": 3,
    "OFF": 4
}

led_pins = {
    "RED": 6,
    "YELLOW": 7,
    "GREEN": 8
}

# LED behaviour for each Jenkins State
jenkins_states = {
    "SUCCESS": {"GREEN": "ALWAYS"},
    "FAILURE": {"RED": "ALWAYS"},
    "UNSTABLE": {"YELLOW": "ALWAYS"},
    "RUNNING": {
        "GREEN" : "BLINKING",
        "RED"   : "BLINKING",
        "YELLOW": "BLINKING"
    },
    "NOT_BUILT": {
        "YELLOW": "BLINKING"
    }
}


def ttymodem(baudrate=9600):
    # Change this Glob if you are using Linux
    devices = glob.glob("/dev/tty.usbmodem*")
    if not devices:
        raise Exception("Probably modem not connected")
    board = devices[0]
    return serial.Serial(board, baudrate=baudrate)

def connect(url, job):
    print "Connecting to the jenkins url: {0}".format(url)
    j = Jenkins(url)
    return j[job]

def write(board, command, msg, padding=16):
    padded = msg.ljust(padding)
    # The first character of every line that is sent to the board
    # is a 'command' that will be read by the Arduino Sketch to do
    # something
    message = "{0}{1}\n".format(command, padded)
    print "Writing message --{0}--".format(message.strip())
    board.write(message)

def get_leds(build_state):
    """Given a build state, get the line messages to be sent to the board
    For now, just handle RUNNING, FAILURE and SUCCESS builds"""
    commands = []
    if build_state not in jenkins_states:
        return commands
    led_behaviour = jenkins_states[build_state]
    for led_color, led_state in led_behaviour.items():
        pin = led_pins[led_color]
        state = led_states[led_state]
        commands.append(pin)
        commands.append(state)
    return commands

def loop(board, job, poll_interval=15):
    print "Sleeping for a bit"
    time.sleep(1)
    print "Poll interval set to {0}".format(poll_interval)
    while True:
        build = job.get_last_build_or_none()
        if not build:
            print "No build found"
            continue
        build_status = build.get_status()
        if not build_status:
            build_status = "RUNNING" if build.is_running else "QUEUED"
        status = "{0} - {1}".format(build_status, build.get_number())
        print "Writing build status {0} to the board".format(status)
        write(board, 1, status)
        led_commands = get_leds(build_status)
        for c in led_commands:
            write(board, c, "", padding=0);
        if build_status in ["RUNNING", "NOT_BUILT"]:
            # Continuosly bombard the board with the
            # blink commands. Looks Knight Riderish
            pass
        else:
            time.sleep(poll_interval)

if __name__ == '__main__':
    # Run this like so
    # python jenkins_status.py <jenkins_url> <job_name>
    # eg: $ python jenkins_status.py https://builds.apache.org Kafra
    url = sys.argv[1]
    job_name = sys.argv[2]
    board = ttymodem()
    job = connect(url, job_name)
    write(board, 0, job_name)
    write(board, 1, "Connecting...")
    loop(board, job)

The ‘Sketch’

(jenkins.ino) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/*
  Copyright 2013 Sudharshan S
  This work is free. You can redistribute it and/or modify it under the
  terms of the Do What The Fuck You Want To Public License, Version 2,
  as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
*/
#include <LiquidCrystal.h>
#include <Serial.h>

LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

/* The input data to the board */
String d_input;
int print_lcd = 0;

int led_pins[] = { 6, 7, 8 };
int led_state;

#define LCD_BACKLIGHT_PIN 13
#define LED_COUNT 3
#define BAUD_RATE 9600

enum SerialCommands {
    // LCD Cursor control
    LCD_SET_ROW_FIRST = 0x30,
    LCD_SET_ROW_SECOND = 0x31,

    // LED States
    LED_SET_BLINKING = 0x32,
    LED_SET_ALWAYS = 0x33,
    LED_SET_OFF = 0x34,

    // LED PINs
    LED_RED = 0x36,
    LED_YELLOW = 0x37,
    LED_GREEN = 0x38
};

void setup()
{
    // Init Serial
    Serial.begin(BAUD_RATE);

    // LCD Display initialization
    pinMode(LCD_BACKLIGHT_PIN, OUTPUT);
    digitalWrite(LCD_BACKLIGHT_PIN, HIGH);
    lcd.begin(16, 2);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Waiting...");
    lcd.setCursor(0, 1);
    lcd.print("for Input");

    // Activate all the LEDs
    for (int i=0; i < LED_COUNT; i++) {
        pinMode(led_pins[i], OUTPUT);
        digitalWrite(led_pins[i], HIGH);
    }
}

int command_mode = 1;
int last_led;
int last_led_state;

// Switch off all LEDs
void clearLEDs() {
    for (int i=0; i < LED_COUNT; i++) {
        digitalWrite(led_pins[i], LOW);
    }
}

void clearLCD() {
    d_input = "";
    print_lcd = 0;
}

/* Every input line to the board starts with a single character
   which acts as the command to be executed.
   In our case, these commands do one of the following
   - Set LCD cursor to corresponding row
   - Set the LED whose state has to be changed
   - Set the state of the LED
   Granted, we can have only 9 commands in this implementation ;)
*/
void execCommand(int command) {
    switch(command) {
    case LCD_SET_ROW_FIRST:
        Serial.print("Setting cursor to Row 0");
        lcd.setCursor(0, 0);
        break;
    case LCD_SET_ROW_SECOND:
        Serial.print("Setting cursor to Row 1");
        lcd.setCursor(0, 1);
        break;
    case LED_SET_BLINKING:
        // Cue the Knight Rider theme music
        digitalWrite(last_led, HIGH);
        delay(200);
        digitalWrite(last_led, LOW);
        delay(100);
        break;
    case LED_SET_ALWAYS:
        clearLEDs();
        digitalWrite(last_led, HIGH);
        break;
    case LED_SET_OFF:
        clearLEDs();
        digitalWrite(last_led, LOW);
        break;
    case LED_RED:
        last_led = 6;
        break;
    case LED_YELLOW:
        last_led = 7;
        break;
    case LED_GREEN:
        last_led = 8;
        break;
    }
}

void readSerial()
{
    if (Serial.available() > 0) {
        char recvd = Serial.read();
        /* The first character of each line to the board
           is the command to be executed
        */
        if (command_mode) {
            execCommand(recvd);
            command_mode = 0;
            return;
        }
        switch(recvd) {
        case '\n':
            Serial.print("Board received: ");
            Serial.print(d_input);
            // Setting this flag flushes the data onto the LCD
            print_lcd = 1;
            command_mode = 1;
            break;
        default:
            d_input += recvd;
        }
    }
}


void loop()
{
    readSerial();
    if (print_lcd > 0) {
        lcd.print(d_input);
        clearLCD();
    }
}

In Action

Here it is in action. As you can see, the LCD displays the Job, the last build number and its state. The wiring is a huge mess, but hey, it works! :)

Components used

  • Arduino UNO R3
  • 5 220-ohm resistors
  • 3 LEDs; Green, Red and Yellow
  • A bunch of wires
  • HD44780 16x2 LCD

Next step, maybe build a bigger housing for the entire system.

Comments

Here’s a rather crude way in clojure to get the IP of the current host given a network interface

1
2
3
4
5
6
(defn ip-for-interface [interface]
  (first (->> (java.net.NetworkInterface/getByName interface)
              .getInetAddresses
              enumeration-seq
              (filter #(instance? java.net.Inet4Address %1))
              (map #(.getHostAddress %1)))))

Of course, fails horribly with an NullPointerException if the interface is not present :)

Comments

There are two major templating libraries for Clojure, Enlive and Hiccup. Since I am not that much of a designer, I chose Hiccup for my side project written in Clojure. I liked the DSL’s unification of code and templating; right in my comfort zone. This post is a little log on how I ended up using multimethods for organizing my Hiccup template functions.

DRY in Jinja

In my previous Flask projects, Jinja was my templating engine of choice. The DRY flow in Jinja templates consists of setting up a base.html with a common layout markup. The ‘children’ would then ‘inherit’ and optionally override those blocks in their own templates.

Composition in Hiccup

However, In the world of Clojure (and therefore Hiccup), functions (duh!) are used to modularize templates. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(ns foobar.views
  (:require [hiccup.core :as h]
            [hiccup.page :as hp]))

(defn head [title]
  [:head
   [:title title]
   (hp/include-css "/static/css/bootstrap.min.css"
                   "/static/css/bootstrap-theme.min.css")
   (hp/include-js "/static/js/jquery-1.10.2.min.js"
                  "/static/js/bootstrap.min.js"
                  "/static/js/bluth.js")])

(defn get-page [title context]
  (hp/html5
    ;; Since hiccup DSL is just code, we will just inject the
    ;; <head> right here
    (head title)
    ;; Rest of the template
    ;; I'd probably have a (body..) somewhere
    (body context)
    ;; Rest of the template
))

Multi-methods

In the above example, there is a chance of repetitiveness of functions like get-page as the number of routes increases. In most cases, there is one (or few) container div that changes across the templates. To avoid this, I have found using multimethods to be a great way of dispatching templates at runtime.

For instance,

1
2
3
4
5
6
7
8
9
10
11
(defmulti container :template :default :not-found)

(defmethod container :home [context]
 [:h2 "Welcome to the Bluth Company"]
 [:button#queue-button.btn.btn-info "Backup"])

(defmethod container :users [{:keys [query-params]}]
 [:h2 (str query-params)])

(defmethod container :not-found [context]
 [:h2 "Generic Content"])

Now that I have a group of ‘container’ divs, I can invoke them from get-page like so,

1
2
3
4
5
6
7
8
9
10
11
12
(defn get-page [{:keys [title]
             :or {title "Bluth Co. - Welcome"}
             :as context }]
  (hp/html5
   (head title)
   [:body
    [:div#wrap
     [:div.container
      ;; Invoke container here
      ;; and dispatch the right template function
      (container context)
      ]]]))

Meanwhile, my routes will end up looking something like this,

1
2
3
4
5
6
7
8
9
10
11
12
13
(defroutes app-routes
  (GET "/" [] (get-page { :template :home }))
  ;; Due to the destructuring in get-page,
  ;; I can pass in arbitrary context to be handled by
  ;; the container multimethods. In this case, we
  ;; are passing in the query-params
  (GET "/users" [& query-params] (get-page
                                       {:title "User list"
                                        :template :users
                                        :query-params query-params}))
  (route/not-found (get-page
                    {:title "Pluto - Not found!"
                     :template :not-found}))

As you can see, get-page is the point of entry for my templates and the container div is injected according to the dispatched function. In fact, by abusing using compojure’s route destructuring, we can have true runtime dispatching of templates!

1
2
3
4
5
(defroutes app-routes
  (GET "/foo/:template [template]
     ;; We don't know which container will be invoked until runtime
     ;; Instead of adding more routes, I can just add more multimethods
     (get-page {:template template})))

get-page function isn’t going to change much and I can mix and match templates as much as I want.

I must admit that I am super new to Clojure. Therefore I am not sure if this approach is idiomatic enough in the Clojure world. Would love to hear suggestions on how it is usually done.

Comments

I started working on Cloudcraft as a toy project over the weekend. It aims to be an end-to-end toolbelt for managing minecraft servers on EC2. As of now it’s very Alpha quality but it can spawn instances and setup minecraft servers automatically with just a couple of commands. For example in the screenshot below, cloudcraft started the minecraft server on a spawned EC2 instance and reported the address needed for a multiplayer game.

Autoscaling instances, plugin management, automatic updates are some of the things that are in the pipeline.

The project is on github and as usual, suggestions, bug reports, bug fixes are welcome.

Comments

More than Death, losing my memory scares the shit out of me. It makes me queasy to think that all the wonderful experiences I had, the secrets in my head, my tough times and failures can go poof; slowly or in an instant without warning.

Doesn’t matter if its due to some fucked up illness like Alzheimer’s or a freak accident from sheer bad luck. It is very possible that I won’t be me one day.

The only bright side is that at least parts of my identity will live on as memories in people close to me if that happens. Coming to think of it, things won’t be that bad after all :). As they say,

Comments

Minor spoilers ahead

Like many others I love Shawshank Redemption. The scene where Brooks is out of prison and is unable to catch up with the world is just plain sad. One of my favorite all time movie scenes that gives me the chills every time.

I keep hoping Brooks found his Freedom.