NodeJS on Heroku

I've recently tried both Heroku and Node.js for the first time. Both are very simple, and work very nicely together. This is a quick guide to deploying a Node.js app to Heroku. To make it simple, I'll walk through deploying a Node.js sample project I ...

Display List as Table in IPython Notebook

IPython Notebook provides hook methods like _repr_html_ which can be defined by Python objects to allow richer representations. Here's an example:

In [1]:
class ListTable(list):
""" Overridden list class which takes a 2-dimensional list of
the form [[1,2,3],[4,5,6]], and renders an HTML Table in ...

How To Draw Lines With Matplotlib

Simple example to show how to draw lines with Matplotlib (in IPython Notebook).

ipython notebook --pylab inline


In [5]:
import matplotlib.lines as lines
fig, ax = plt.subplots()

fig.set_size_inches(6,6)          # Make graph square
scatter([-0.1],[-0.1],s=0.01)     # Move graph window a little left and ...

Opposite of zip function in Python

Is there a way to do the opposite of what the zip() function does? It turns out, there is - the zip() function with list unpacking...

Normal zip() usage

In [5]:
x = [1,2,3,4,5]
y = [10,20,30,40,50]
points = zip(x,y)
points

Out[5]:
[(1 ...

Monte Carlo In Python

Monte Carlo Estimation is a method of numerically estimating things which we don't (or can't) calculate numerically by randomly generating samples. In this IPython Notebook, I'm going to use Monte Carlo Estimation to estimate:

1. The area under a curve
2. The value of pi

Wordpress to Pelican Reasons

I recently migrated my blog from Wordpress to Pelican. Pelican is a static-site generating blog system which is written in Python and uses Jinja2 for templating. I'll probably do a post about the migration process later, but for now, I'll just give my reasons for moving to Pelican ...

IPython Notebook on a VPS

Overview

This is a guide to set up IPython Notebook on a Server - specifically, on a DigitalOcean VPS. This will allow you to access your iPython Notebooks from anywhere.

Overview of Steps:

• Set up a domain name
• Get a VPS
• Install IPython Notebook (and all dependencies)
• Configure IPython Notebook to ...

Big graphs in IPython Notebook

I've been doing a good bit of graphing in IPython Notebook recently, and I often wanted to make the graphs larger. I also often wanted to label the graph axes. So I wrote this simple function and have been using it a lot.

# Graphing helper function
def setup_graph(title ...

Pandas Into

I've recently been playing with the pandas Python data analysis framework while reading the Python for Data Analysis book (which is written by the author of the pandas library). Here are 2 of my IPython Notebooks that demonstrate some of the basics:

Finding the Golden Ratio

I recently was exploring the Golden Ratio. I was really surprised what a simple (and recursive) relationship it comes from:

Starting with this this image, here is the derivation of the golden ratio...

From this relationship we see in this image, we can derive this equation: \[\frac{a}{b} = \frac ...

How to graph with IPython Notebook

IPython Notebook / Matplotlib / Pylab / Numpy is great for graphing (among other things). Below is a simple demo of how to graph with it.

To run IPython Notebook, use this command: ipython notebook --pylab inline

Here's a screenshot:

Here's an embedded IPython Notebook showing a slightly easier way:

In ...

Running Ubuntu on VirtualBox in Windows

I'm mostly a Mac user and I also really like Linux (especially Ubuntu), but I hate Windows. However, I'm occasionally required to use Windows at work, so I've found a way to make using Windows more enjoyable: to use Ubuntu (installed on VirtualBox inside of Windows) instead ...

Pyknon Intro, Chords, and Intervals

I've continued on my (hopefully) short-term fascination with music+math (it's fun, but really bad for productivity). So I found this great library for generating music in Python called Pyknon. And it can be installed using pip: pip install pyknon.

I wrote a little python script just to ...

Music Theory and Math Notes

For the last day, I've done some reading on music theory (trying to understand why things are the way they are in terms of math). Here are my raw unedited notes:

Important musical ratios:

• Unison: 1:1 frequency
• Octave: 2:1 frequency
• 12 semitone increase
• Fifth: 3:2 frequency ...

Reduce with Python and Clojure

I was just playing around writing an annuity calculator function. Here is my first version:

def calculate_annuity(years, interest=0, addition_per_year=0, starting_amount=0):
result = []
running_total = starting_amount
for year in range(years+1):
result.append(running_total)
running_total = (running_total + addition_per_year) * (1 + interest)
return result


Here is a 2nd version, written using ...

Vim run current file

I just added a nice command to my .vimrc file to allow me to run the current file I am working on by typing :R:

command R !./%


On the VIM note, here is a link to my current vim config (.vimrc file and .vim directory) on github: Vim config.

Barcamp Milwaukee 2012

Barcamp Milwaukee 2012 is being held October 6th-7th. I had a good time last year, so I can definitely recommend it :)

Secret to not having road rage

I have found the secret to not getting road rage: audiobooks. Try it. Right now, I'm listening to Dune by Frank Herbert.

Facial Detection with OpenCV and Python

I was able to get some basic facial detection working in OpenCV with Python. Here's what it looks like:

And here is the 34-line python script to draw boxes around all detected faces in live video:

import cv

CAMERA_INDEX = 0

def ...

Intro to OpenCV with Python

I have started my journey into the world of OpenCV using Python on my Mac. These are my first steps with it.

Installing OpenCV for Python on the Mac

# Install numpy as a prerequisite
sudo port install numpy

# Install OpenCV with the Python API
sudo port install opencv +python27


(The ...

NSArray+FP

I realized that I utilize the [NSArray head] and [NSArray tail] functions in various code snippets, but haven.t shared the actual code for that category. So here is my NSArray+FPcode.

NSArray+FP.h

#import <Foundation/Foundation.h>
typedef id(^MapBlock)(id);
@interface NSArray (FP)
- (NSArray *)map:(MapBlock)block ...

Eye movement on web pages

• I've always preferred bulleted lists (and the like) over flat paragraph formats
• I believe they can be visually parsed much faster than paragraphs
• Now I have evidence: F-shaped reading pattern study :)

Here is an image which shows the eye movement of users on web pages (where red means more ...

Functional programming to deal with asynchronicity in Objective-C

In the last few weeks, I've used the [ALAssetsLibrary loadImages:callback:] method to load a list of images. For what I was doing, I wanted to wait till all the images were loaded before proceeding. I found that I could solve this problem very elegantly using a recursive solution ...

First look at Pylab/Matplotlib

Since I've been getting into Machine Learning/Artificial Intelligence recently, I've been looking at various computing environments recently. Some of the contenders are:

• MATLAB - The traditional software stack for doing machine learning and statistical analysis
• GNU Octave - An open-source MATLAB clone.
• R - An open source clone of a ...

How to reference self in a block in Objective-C

When using ARC (automatic reference counting) in Objective-C, you need to be careful to avoid causing retain cycles. One place where a retain cycle can occur is where self is referenced in a block. To avoid a retain cycle, you can use the __unsafe_unretained modifier as such:

__unsafe_unretained id unretained_self ...

Probability and Statistics book for Python programmers

This seems like a nice, concise book on probability and statistics for Python programmers: Think Stats.

Premature generalization is the new premature optimization

A co-worker was just showing me a situation where another developer had written a validation framework which was only used on 2 pages. I've seen this pattern again and again, and I've put a phrase to the thought:

Premature generalization is the new premature optimization.


And it, too ...

I'm taking the Stanford Machine Learning class. The first algorithm we covered is Linear Regression using Gradient Descent. I implemented this algorithm is Python. Here's what it looks like:

import subprocess

def create_hypothesis(slope, y0):
return lambda x: slope*x + y0

def linear_regression(data_points, learning_rate=0.01, variance ...

Embedding an XSLT in an XML document

Today, I had this XML document which I was wanting to make viewable in a browser. My plan was to run the XML document through an XSLT engine to transform it into an HTML document (which could then be opened in a browser).

Instead, I found that I could just ...

Resampling Wheel Algorithm

I've been taking the Udacity CS373 (Robotic Car) class, and this week the topic was Particle filters. Particle filters are basically a localization algorithm that accounts for error in measurements and sensors.

Anyway, part of the Particle Filter algorithm requires the generation of a new set of these things ...

JSONP for cross-origin AJAX

I was recently wanting to enable a webpage to utilize some server-side functionality which was on a different server than the one serving the original page. Traditionally, this has been problematic due to browsers' Same origin policy. JSONP is a solution to this problem. Here is how to do it ...

Tail call optimization in Python

Since I've been getting into functional programming more recently, the fact that Python doesn't do tail-call optimization has been bothering me. So I did a bit of searching, and found this gem: Tail Call Optimization Decorator.

Here is a snippet from it:

import sys

class TailRecurseException:
def __init__ ...

Standard Deviation in Python

I just wanted to go through the process of calculating standard deviation today, and this is how I did it in Python. Python makes such a nice calculator :)

>>> s = [2,4,4,4,5,5,7,9]
>>> def average(s): return sum(s) * 1.0 / len(s)
...
>>> avg = average(s ...

Django on Hostmonster

I just finished going through the process of installing and configuring Django (with FastCGI) on Hostmonster's Shared hosting. It was more painful than I expected, so I decided write a post about how I got it working...

First, I wanted to create a subdomain which would host my django ...

String to Base64 String in Objective-C

Today, I needed to convert an ASCII-encoded NSString to a base64 NSString. I found a number of methods that convert from an NSString to a Base64 NSData, or from NSData to a Base64 string, but couldn't find one that did exactly what I needed. So here is a method ...

Function application and function composition in Haskell

In the process of learning haskell, I've been trying to become comfortable with the function applicator (\$) and function composition (.). Here is some code to show how they relate (and how they relate to using parenthesis to enforce order of operations):

let dict = [(1,'a'),(2,'b'),(3,'c')]
-- The ...

Map in Objective-C

Today, I was faced with an issue several times where I had an array of items of one type, and had to convert this into an array of items of a different type. This made me really want a map() function. So I added one to NSArray like so:

NSArray ...

How to place custom image in UITextField in iOS

Here is how to put an image in the right portion of a UITextField:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(55, 10, 660, 30)];
textField.rightViewMode = UITextFieldViewModeWhileEditing;

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
imageView.image = [UIImage imageNamed:@"invalidFieldCircle"];
textField.rightView = imageView;


This also assumes that an ...

Force weak reference in Objective-C

Today, I was trying to add an object to an NSDictionary and force it to be a weak reference. This can be done with the [NSValue valueWithNonretainedObject] call:

NSValue *weakRef = [NSValue valueWithNonretainedObject:loadDelegate];
NSDictionary *userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:weakRef, @"loadDelegate", nil];


Just started looking into the Haskell programming language by going through the first few chapters of the awesome book: Learn You a Haskell which is free to read online. Here are some things I really like about what I have seen of Haskell so far:

• Type inference allows you to ...

Consuming web service in Python with SUDS

import datetime
from suds.client import Client
url = "http://localhost:9080/dataplanws/DataPlanWebService/WEB-INF/wsdl/DataPlanWebService.wsdl"
client = Client(url)
print client.service.hello("Caleb")


Periods in Powershell

For running most commands, powershell and CMD work the same. One big difference I've found is that, when you use periods (.) in a command, they must be surrounded by quotation marks. For instance, this won't work:

mvn clean install -U -Docns.web.dynamic.content.version=2.6.0 ...