“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay who are based in Denmark...”

Rob Lacey
Senior Software Engineer, Copenhagen, Denmark

Raspberry Pi - part 1

This year my main festive gift from the mighty Kat was a long awaited Raspberry Pi. Just never seemed to have the funds to nab one myself and I am pretty chuffed. If you’ve not heard of one then you’ve been living under a rock for the last year. The Raspberry Pi is basically just a very small, barebones computer. In fact its so minimal that it doesn’t even come with a case.

Raspberry Pi

You can see on the board that the mounted interfaces are a dual USB port, micro-USB power supply, HDMI output to monitor, audio out, video out, GPIO pins.

You might have enough bits and bobs lurking in your cupboard full of cables and old hardware to get going but alas I do not. So in order to get started I need some way of hooking this up to a monitor, keyboard and powering the thing.

USB Keyboard

No PS2 ports so its all USB, so a USB Keyboard is needed. Relatively cheap, I’ve spotted a great wireless one with a touch pad for £25 but for now this one will do.

Monitor

While the Raspberry Pi can be easily used with a modern television I can’t see myself sitting in the front room while I’m playing with it for the time being. You can use any monitor or television with an HDMI or DVI connection. So you’ll need a cable

My spare monitor is a VGA which won’t work without an adapter to convert the signal. £30 for an adapter is a bit much really. I’ve secured a DVI monitor from a friend for £10, so I’ve opted for the HDMI to DVI while I’m playing.

SD Card / Operating System

You’ll need an SD Card to install the operating system on. Fortunately we have an old 4Gb card from a Camera. So cost £0. Yay. average cost on Amazon about £6 so not bad.

Install it yourself

You can follow the tutorial on the Raspberry Pi Downloads page to copy an OS onto a card.

Pre-installed

You can get an 8Gb (and upwards) SD Card from ThePiHut with one of two distributions from £8.99.

  • Raspbian – pre-installed Raspian is an optimised version of Debian, containing LXDE, Midori, development tools and example source code for multimedia functions.
  • OpenElec / XBMC – pre-installed Open Embedded Linux Entertainment Center, or OpenELEC for short, is a small Linux distribution built from scratch as a platform to turn your computer into a complete XBMC media center.

That’s a start I’ve ordered what I need so now I have to sit and wait. I’ve got a few ideas about what I’d like to build.

  • MAME centre
  • Media centre
  • Spotify streaming straight into the HiFi

So I’ll do a bit of research and buy a book or two.

Resources

There’s plenty of resources out there as well as some physical publications to get started with.

More useful links…

Installing 'therubyracer' grrrr

Robs-iMac:testapp rl$ gem install therubyracer
Building native extensions. This could take a while…
ERROR: Error installing therubyracer:
ERROR: Failed to build gem native extension.

/Users/rl/.rvm/rubies/ruby-1.8.7-p370/bin/ruby extconf.rb
  • extconf.rb failed *
    Could not create Makefile due to some reason, probably lack of
    necessary libraries and/or headers. Check the mkmf.log file for more
    details. You may need configuration options.

Provided configuration options:
—with-opt-dir
—without-opt-dir
—with-opt-include
—without-opt-include=${opt-dir}/include
—with-opt-lib
—without-opt-lib=${opt-dir}/lib
—with-make-prog
—without-make-prog
—srcdir=.
—curdir
—ruby=/Users/rl/.rvm/rubies/ruby-1.8.7-p370/bin/ruby
extconf.rb:13: uninitialized constant Gem (NameError)
Checking for Python…

Gem files will remain installed in /Users/rl/.rvm/gems/ruby-1.8.7-p370@thebevy/gems/libv8-3.3.10.4 for inspection.
Results logged to /Users/rl/.rvm/gems/ruby-1.8.7-p370@thebevy/gems/libv8-3.3.10.4/ext/libv8/gem_make.out

It seems that libv8 requires Gem to exist, however rubygems is not available by default in Ruby 1.8.7. Ruby 1.9.x it is.

Thanks to Olly Smith for the solution

Robs-iMac:thebevy rl$ RUBYOPT=-rrubygems gem install therubyracer
Building native extensions.  This could take a while...
Fetching: therubyracer-0.10.2.gem (100%)
Building native extensions.  This could take a while...
Successfully installed libv8-3.3.10.4
Successfully installed therubyracer-0.10.2
2 gems installed
Installing ri documentation for libv8-3.3.10.4...
Installing ri documentation for therubyracer-0.10.2...
Installing RDoc documentation for libv8-3.3.10.4...
Installing RDoc documentation for therubyracer-0.10.2...

Apache Rewrite because I can never remember how to do it

I seem to use Apache less and less these days, so every year or so I have to try and remember the syntax for VirtualHost configs, redirects and the like.

<VirtualHost *:80>
  ServerName duncanwilkinson.com
  DocumentRoot /home/duncan/www.duncanwilkinson.com/
  RackEnv production
  RewriteEngine on
  RewriteCond %{HTTP_HOST} !^duncanwilkinson\.com
  RewriteRule ^/(.*)$ http://duncanwilkinson.com/$1 [R=permanent,L]
  CustomLog /var/log/apache2/loathsome-access.log combined
  ErrorLog  /var/log/apache2/loathsome-error.log
</VirtualHost>
<VirtualHost *:80>
  ServerName www.duncanwilkinson.com
  ServerAlias www.dna-labs.net dna-labs.net www.triplebinary.com triplebinary.com www.needleye.net needleye.net
  RewriteEngine on
  RedirectMatch (.*) http://duncanwilkinson.com
</VirtualHost>
<VirtualHost *:80>
  ServerName www.collapse.co
  ServerAlias collapse.co
  DocumentRoot /home/duncan/www.collapse.co/
</VirtualHost>

iptables reminder

Forgot all about iptables….

rails # iptables -A INPUT -s <naughty ip> -j DROP
 rails # iptables --list
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
DROP       all  --  bl16-108-238.dsl.telepac.pt  anywhere            

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Resize multiple images in one bash script

Badoom……!!!

#!/bin/bash
for i in *.JPG; do echo $i; base=`basename "$i" .JPG`; convert "$i" -resize 50% "thumbs/$base.jpg"; done

Delete files created more than 14 days ago

When you’ve got lots of temporary files on a unix server and you never clean them out this might help. Remove files that were created more than 14 days ago like so…

find . -type f -mtime +14 -exec rm {} \;

doing away with www.

“www.” for the most part is a pointless idea. We all know what a web page is. The “www.” prefix is outdated although necessary evil. I guess the same could be said of http:// and https:// for web requests …we all know what it means.

Here’s a quick snippet of my apache config to push all traffic from www.loathso.me to loathso.me

<VirtualHost *>
  ServerName www.loathso.me
  ServerAlias loathso.me
  DocumentRoot /var/www/loathsome/current/public/
  RackEnv production
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.loathso\.me
  RewriteRule ^/(.*)$ http://loathso.me/$1 [R=permanent,L]
  CustomLog /var/log/apache2/loathsome-access.log common
  ErrorLog  /var/log/apache2/loathsome-error.log
</VirtualHost>

Rails Serializers and INET_NTOA

MySQL doesn’t have a built in type for an IP Address, PostgreSQL does though. You’ll find that ip addresses are often stored as an integer. You can translate between an integer and ip address and vice versa with a built in MySQL functions. In a recent piece of work we had to detect a user’s country code based on their incoming IP via against a range of IPs (stored as integers).

mysql> SELECT INET_ATON('192.168.0.1');
+--------------------------+
| INET_ATON('192.168.0.1') |
+--------------------------+
|               3232235521 |
+--------------------------+
1 row in set (0.00 sec)

mysql> SELECT INET_NTOA('3232235521');
+-------------------------+
| INET_NTOA('3232235521') |
+-------------------------+
| 192.168.0.1             |
+-------------------------+
1 row in set (0.00 sec)

Wouldn’t it be nice to get a Rails model to accept an ip address and store it as an integer. Well its basically serializing the ip address and using Rails 3.1’s new serialization api we can do the following.

class IpEncoder
  #
  # Converts IP to number
  # inet_aton
  #
  def load(n)
    return unless n
    [n].pack("N").unpack("C*").join "."
  end

  #
  # Converts number to IP
  # inet_ntoa
  #
  def dump(n)
    n.split(/\./).map(&:to_i).pack("C*").unpack("N").first
  end

end

Basicially a class with two methods IpEncoder#load encodes its input, and IpEncoder#dump decodes it. Then you simply add the following to your model.

require 'ip_encoder'
class Log < ActiveRecord::Base
  serialize :ip_address,  IpEncoder.new
end

And there you have it.

Rob-Laceys-MacBook-Pro:loathsome roblacey$ ./script/rails c
Loading development environment (Rails 3.1.2)
>> Log.create(:ip_address => '192.168.0.1')
  SQL (0.5ms)  INSERT INTO "logs" ("ip_address") VALUES (?)  [["ip_address", 3232235521]]
=> #<Log id: 1, ip_address: "192.168.0.1">

JRuby Swing

I was mulling at the end of last year that while I’ve been programming for far too many years now its been for the most part web development and databases. But I don’t know how to build a GUI, and least of all one that would be cross platform. Time to learn.

I’ve just picked myself up a copy of O’Reilly Java Swing 2nd Edition which, while its old, should help me get to grips with building my first GUIs.

As an interesting learning process I’ve decided that while of course this is all about Java that I am going to read the book in Java, I shall translate it all into JRuby since I use Ruby as my programming language of choice. So I’ll learn three skills in one;

  • GUI Development
  • Java
  • JRuby

I think the best way to pick it up is to go through every last example until it becomes second nature so all the Java AWT and Swing examples I come across in the book I shall be adding in a new jruby-swing github repository are here as JRuby.

https://github.com/braindeaf/jruby-swing

In fact here’s the first example

https://raw.github.com/braindeaf/jruby-swing/master/chapter2/ToolbarFrame1.rb

Desktop app here I come.

Disable startup items in Debian / Ubuntu

Needed to get rid of PostegreSQL on start up. That’s freeing up 8Mb of memory….its better than nothing.

rails@cool-server-name-001:~$ sudo update-rc.d -f postgresql-8.3 remove
 Removing any system startup links for /etc/init.d/postgresql-8.3 ...
   /etc/rc0.d/K21postgresql-8.3
   /etc/rc1.d/K21postgresql-8.3
   /etc/rc3.d/S19postgresql-8.3
   /etc/rc4.d/S19postgresql-8.3
   /etc/rc5.d/S19postgresql-8.3
   /etc/rc6.d/K21postgresql-8.3