Simulating Chutes and Ladders

I was inspired by reading Ethan Markowtiz’ article on Chutes and Ladder simulation but I wanted to simulate a lot of games, not just 10,000. I wanted to simulate 100,000,000 or more. I decided to do it in my current language of choice Ruby. So I did and you can find all my code on github at twohlix/chutes_and_ladders.

With my initial setup it took about 34 seconds to simulate 1M games, but that was 100x fewer than I wanted. Also I didn’t want to wait around for an hour for the results and I knew there was a common way to speed up simulations like this: multi-threading. So I threw in some threading.

I ran the app with 2 threads and… zero speedup. zilch. nada. It still took about 34 seconds real time to get the results. What the eff? Apparently Ruby, or at least Matz’ Ruby out of the box supports native threads but they’re never run in parallel due to the Global Interpreter Lock. A quick googling and I decided to install Rubinius (aka rbx). A few minutes later and I was down to about 20s for 1M. Almost 50% faster, nice. 4 threads and I was at 12s. 8 threads and I was at 10s. 16 threads it was hanging for over 2minutes. Okay, so maybe my cpu only really can bother with 8 threads anyway. All that work got me down to ~18minutes to simulate 100M 2 player games of Chutes and Ladders with a maximum of 150 turns per game.

Here’s some output from all the simulation:

Locally Caching API Backed Rails Models

So I was working on a project that had some fairly high coupling between our system and the data we got from an API. Then someone wanted a dashboard to summarize a bunch of stuff and instead of building some “cache models” in some database I decided to just cache the attributes the API sent us using standard Rails cache. What caching engine you use is up to you, but this will be faster if held in a memory based cache (duh).

Since this was at least 3 models being fed by the API I figured lets use a Concern! Check it out:

Since we had to define the class level find for our API Backed models anyway, we decided to couple that find method with the write_local_cache method

So to grab a model from the cache I simply had to do

ModelName.local id

in the controllers feeding this dashboard. Alternatively you can do this in relationship methods on a model.

So this ended up taking us from a 65 second page load that result in 400 API requests to about a 1.5 second page load with 0 API requests. And the business was fine with this data being anywhere from 1-12 hours out of date. And since this cache is so long lived I wrote a rake task to preheat the cache that I run every day at 6am before the app starts getting used heavily:

namespace :app_name do
  desc "Pre-heats the cache based off current work assignments"
  task preheat_cache: :environment do
    Assignment.not_worked.find_each do |assignment|
      customer = Customer.find assignment.customer_id
      customer.total_due # this preheats a relationship to another API backed model

Ruby Array#each vs Enumerable#any?

So I had a little snippet of code that a coworker of mine mentioned I could replace:

collection_thingy.each do |val|
  return if val.prop == :particular_thing


return if collection_thingy.any? { |val| val.prop == :particular_thing }

And that got me thinking about which was faster. So I did some quick benchmarking. Results and code are embedded below.

Clearly Array#each is faster than using the equivalent Enumerable#any?, and by 13-28% depending on the array size. That seems like a lot. I’m not enitrely sure why it’s that much faster but it’s interesting. Still, for most cases there is a negligble difference (especially in a Rails app), just be aware of the difference if you’re traversing giant arrays (on 1Billion elements its as much as 14 second difference in my environment).

Here are some graphs showing the speedup more visually (imgur album of graphs):
1M Elements
10M Elements
100M Elements
1B Elements

All that being said, if performance isn’t an issue in the particular codeblock Enumerable#any? is more readable. Feel free to post your own results as actual runtimes will vary from environment to environment.

Sublime Text 2 Build System for Mono

So I was struggling to find a good build system for mono. After much struggling with regexes I finally got the file_regex down so it’ll take you the right line and column.

If you’d like to contribute to it every gist is also a pushable repo.

Clone that gist or copy paste it into a build system of your own. You might have to remove the .json file extension, that’s in there to get github to do syntax highlighting.

If you don’t have javascript enabled you cannot see the gist above. Check it out on my github.

Apartment Buzzer Unlocker

I got tired of walking down to the front door to let my friends into my apartment building and I also didn’t want people calling my phone from the front door. So I took a cue from Jared Tame and decided to use twilio to automatically buzz people in.

One little script later and I’m up and running.

It costs me $1/mo + 1cent per unlock and about an hour of fiddling around with everything. Twilio even started me off with $30 free so I added $30 more to my account once and now I can be up and running for ~4 years (assuming 300 unlocks over 4 years) for a total of $30 + hour of my life.

giggity. This project also made me want to start playing with twilio. Video to come later.

Gawker Multi-Display Support

I got frustrated with Gawker’s lack of Multi-Display support. So I did what you do with OpenSource software and added it.

You can find the source that is up to date on my github.

Warning: Youtube doesnt like super wide videos. heh.

Artiss YouTube Embed: An error occured accessing the YouTube API for video ID XgTBG2V1i8E - Body: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Using HostingScripts by twohlix

The HostingScripts I’m talking about are on github at Feel free to fork it for your own setup.

Step 1. Download the Code using Git

[csmith@two ~]$ cd /wherever/you/want/the/scripts/to/go/
[csmith@two go]$ git clone

Now you should have a bleeding edge version of my HostingScripts under your current directory/HostingScripts/
You can read the README or just keep reading here.

Step 1b. You Might Have to Change Permissions
Check permissions on the scripts and change them to appropriate permissions.

[csmith@two HostingScripts]$ ls -l
total 16
-rwxrwxr-x 1 csmith csmith  281  Jun  3 16:01 disablewww
-rwxrwxr-x 1 csmith csmith 3190  Jun  3 16:01 enablewww
-rwxrwxr-x 1 csmith csmith  945  Jun  3 16:01 listwww
-rwxrwxr-x 1 csmith csmith  843  Jun  3 16:01 README

Those permissions will let anyone run your scripts, but I’m guessing thats not what you want. You might want to chmod away some of those permissions or add them if they’re missing.

[csmith@two HostingScripts]$ chmod go-x *www

That will remove any executable permissions for everyone and the group. Change up the chmod accordingly: If you needed to add permissions so you can execute it, or your group wants to execute it

[csmith@two HostingScripts]$ chmod ug+x *www

Step 2. Alter the Scripts for Your Setup
I’m going to add a configuration file to the project so you only have to change things in one place, but for now you’ll have to edit some things (maybe).

This script assumes some things:
1. You’re using CentOS’s basic setup with httpd for the webserver (not apache2). Particularly HostGator’s VPS setup. If you’re on a HostGator VPS I’m fairly certain you don’t need to change anything.
2. You’re hosting your own DNS server: named.
3. Your users’ home directories are /home/username

These are all changeable, just bust out your favorite text editor and go to town on the scripts (especially enablewww). I’ll leave it up to you to figure out what you have to change.

Step 3. Enable a Site
Enabling a site is easy. For example if I wanted to enable hosting of in my user I would do this:

[csmith@two HostingScripts]$ ./enablewww csmith

The site should be up and running under ~csmith/www/ and the servable files are in htdocs/. I’ll often create a symlink named htdocs to whatever directory I want. For example this site uses a symlink from htdocs to my wordpress directory. If i want to put the site in a special maintenance mode I could just recreate the htdocs symlink to some other directory and httpd will serve that up instead.

[csmith@two]$ ln -s wordpress htdocs

Step 4. Disable a Site
Disabling a site is fairly easy, although you have to alter the named.conf file if you want to stop the DNS. I plan to add in the changes for that, but not this second.

[csmith@two HostingScripts]$ ./disablewww csmith

Setting up Mercurial on CentOS x86_64

Mercurial is a badass distributed version control system. Most likely, you know what mercurial is if you’re reading this, so I won’t bother explaining it. If you don’t know what it is, go to

Step 1. Get the RPM of Mercurial for Your Version
I got my package from Make sure to choose the right version. I chose mercurial-1.8.2-1.e15.rf.x86_64.rpm, but there may be more up to date versions or more appropriate versions for you.

[root@two]# cd /home
[root@two home]# wget
--2011-05-11 22:17:43--
Connecting to||:80... connected.

Step 2. Install the RPM

[root@two home]# rpm -Uvh mercurial-1.8.2-1.el5.rf.x86_64.rpm
warning: mercurial-1.8.2-1.el5.rf.x86_64.rpm: Header V3 DSA signature: NOKEY, key ID 6b8d79e6
Preparing...                ########################################### [100%]
   1:mercurial              ########################################### [100%]

I used a few options in the install: ‘-U’ upgrades or installs (whichever it has to) the rpm. ‘-v’ makes it verbose so you can see it do things. ‘-h’ adds the #(h for hash) marks so you can see the progress over time.
If you didn’t use your root account for this be sure to use sudo:

[totally_not_root@two home]# sudo rpm -Uvh mercurial-1.8.2-1.el5.rf.x86_64.rpm

Step 3. Check on Mercurial

[root@two home]# hg

that command should result in:

Mercurial Distributed SCM

basic commands:

 add        add the specified files on the next commit
 annotate   show changeset information by line for each file

If that happened, you’re all done. You may need to install python if it broke.

Setting up Apache Virtual Hosts on CentOS

So you’ve got a new VPS host from HostGator. You want to host yours and your 5,000 closest friends’ sites too: but in order to do that you have to setup your apache server’s virtual hosts.

Step 1. Make a Directory to contain your Virtual Host files

[root@two]# cd /etc/httpd/
[root@two httpd]# mkdir sites-available
[root@two httpd]# mkdir sites-enabled

Now that you’ve created ‘sites-enabled’ and ‘sites-available’, we’re going to make Apache check any of the conf files you have in ‘sites-enabled’.

Step 2. Tell Apache to Look for your Conf Files

[root@two httpd]# vim conf/httpd.conf

Add these lines to the end of your ‘httpd.conf’ file:

NameVirtualHost *:80
Include /etc/httpd/sites-enabled/

Step 3. Create Some Configuration Files for your Sites

[root@two httpd]# cd sites-available/
[root@two sites-available]# cat >
# (/etc/httpd/sites-available/
<VirtualHost *:80>
        ServerAlias *

        #Indexes + Directory Root
        DocumentRoot /home/csmith/www/
        <Directory "/home/csmith/www/">
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                Allow from all

        #LOG FILES
        ErrorLog  /home/csmith/www/
        CustomLog /home/csmith/www/ combined

Change the DocumentRoot to wherever you want to host your website for example ‘/opt/development/username/’ and make sure that directory exists (user mkdir).
Make sure your log’s directory exists also.

Step 4. Symlink the Conf Files To ‘sites-enabled’

[root@two sites-available]# ln -s /etc/httpd/sites-available/ /etc/httpd/sites-enabled/

I symlink my sites into ‘sites-enabled’ because that way its easy to turn on and off sites (for development) without having to make/remake VHost files. Just ‘rm’ the file from sites-enabled if you want apache to stop serving it.

Step 5. Restart Apache

[root@two sites-available]# /etc/init.d/httpd restart


[root@two sites-available]# /etc/init.d/httpd graceful

That should work. Just place all your servable documents (or symlink things) into the DocumentRoot you specified. Voila…i hope.
I’ll throw a script to make this easy up on Github.

A New Beginning

Finally I’ve moved onto rehosting (and all my domains) on my fresh new VPS.

The past couple of days since purchasing my VPS has been setting up my environment. Hell I’m even hosting my buddy’s site on here. He’s still learning css and whatnot.

I’m sure i’ll have some growing pains as I host more and more sites on here (maybe Two Guys Rally or even Marshsmith).