Custom JSON Marshalling in Go

Go’s encoding/json package makes it really easy to marshal structs to JSON data.

package main

import (

type MyUser struct {
	ID       int64     `json:"id"`
	Name     string    `json:"name"`
	LastSeen time.Time `json:"lastSeen"`

func main() {
	_ = json.NewEncoder(os.Stdout).Encode(
		&MyUser{1, "Ken", time.Now()},



But what if we want to change how one of the field values are displayed? For example, say I wanted LastSeen to be a unix timestamp.

The simple solution is to introduce another auxiliary struct and populate it with the correctly formatted values in the MarshalJSON method.

func (u *MyUser) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		ID       int64  `json:"id"`
		Name     string `json:"name"`
		LastSeen int64  `json:"lastSeen"`
		ID:       u.ID,
		Name:     u.Name,
		LastSeen: u.LastSeen.Unix(),

This works, but it can get cumbersome when there are lots of fields. It would be nice if we could embed the original struct into the auxiliary struct and have it inherit all the fields that do not need to be changed.

func (u *MyUser) MarshalJSON() ([]byte, error) {
	return json.Marshal(&struct {
		LastSeen int64 `json:"lastSeen"`
		LastSeen: u.LastSeen.Unix(),
		MyUser:   u,

The problem here is that the auxiliary struct will also inherit the original’s MarshalJSON method, causing it to go into an infinite loop. The solution is to alias the original type. This alias will have all the same fields, but none of the methods.

func (u *MyUser) MarshalJSON() ([]byte, error) {
	type Alias MyUser
	return json.Marshal(&struct {
		LastSeen int64 `json:"lastSeen"`
		LastSeen: u.LastSeen.Unix(),
		Alias:    (*Alias)(u),

The same technique can be used for implementing an UnmarshalJSON method.

func (u *MyUser) UnmarshalJSON(data []byte) error {
	type Alias MyUser
	aux := &struct {
		LastSeen int64 `json:"lastSeen"`
		Alias: (*Alias)(u),
	if err := json.Unmarshal(data, &aux); err != nil {
		return err
	u.LastSeen = time.Unix(aux.LastSeen, 0)
	return nil

TypeScript completion in Vim

One of the main advantages of using static types is that you get much better support from your tools. I recently got TypeScript auto-completion working in vim and I’m documenting how to do it here.



1. Install TSS

git clone
cd typescript-tools
git checkout testing_ts1.4
sudo npm install -g

2. Install Vim Plugin

I’m using Vundle to manage my plugins.

Bundle "icholy/typescript-tools.git"
au BufRead,BufNewFile *.ts  setlocal filetype=typescript

3. Install TSD

sudo npm install tsd@next -g

4. Create Project

mkdir project
cd project
tsd init

tsd install jquery --save
tsd install angularjs --save

5. Create tsconfig.json

  "compilerOptions": {
    "target": "es5",
    "noImplicitAny": false,
  "files": [

    "all.ts", "your.ts",
    "other.ts", "files.ts"

6. Start TSS in vim

Make sure you’re cwd is somewhere in the directory containing tsconfig.json


You might get some errors, but it should still work.

7. (Optional) Making it work with YouCompleteMe

if !exists("g:ycm_semantic_triggers")
   let g:ycm_semantic_triggers = {}
let g:ycm_semantic_triggers['typescript'] = ['.']
set completeopt-=preview

interactive filtering with less

I discovered a cool little feature in less (not less.css) today. You can interactively filter the data.


	Display only lines which match the pattern; lines which do not match the pattern are not displayed. If pattern is empty (if you type & immediately followed by ENTER), any filtering is turned off, and all lines are displayed. While filtering is in effect, an ampersand is displayed at the beginning of the prompt, as a reminder that some lines in the file may be hidden.

	Certain characters are special as in the / command:

Activate: &pattern hit enter
Disable: & hit enter



C++: Make Repl

One of the things I really like about dynamic languages like javascript & python is the repl. After you’ve gotten used to that type of exploratory programming, it’s hard to go back to the edit/compile/run cycle.

Luckily that has finally changed with cling. It’s an interactive C++ environment that behaves pretty much like a repl. In my recent projects I’ve been adding a new make rule: repl which lets me interactively play with the code I’m working on and it has drastically improved my productivity.

Here’s how I set it up. Compiling cling is the first step. Below are how I did it on OSX.

brew install gcc
brew install make

# Check out the sources:

mkdir src
cd src
svn co llvm
cd llvm/tools
svn co clang
svn co cling
cd ..

# Apply some patches

cat tools/cling/patches/* | patch -p0

# Configure, build and install them

cd ..
mkdir build
cd build
../llvm/configure --enable-targets=host
make install

Next there’s an init_repl.cpp file I keep in the root of my project. It’s responsible for pulling in all the required headers and doing some initial setup. For the setup, I use C++’s version of a static block.

#include <my_project.h>
#include <iostream>
#include <string>

struct ReplInit {
  ReplInit () {
    std::cout << "initializing some stuff" << std::endl;

static ReplInit repl_init;

Next the make rule.

  cling -std=c++11 -linit_repl.cpp -I./include -I./src -I./lib

After that you should just be able to run make repl and you’ll be dropped into a shell where you can dynamically explore you project. I’ve only been using it for a little while and I’m hooked. I look forward to the day where every project supports make && make repl.

C++: Inline Functions

Even though overuse of getter and setter functions can be frowned upon, they can help a lot if you’re looking to provide a intuitive api. However the overhead the additional function call introduces is undesirable. Thankfully, there’s the inline keyword. It tells the compiler to replace each invocation of the function with the body of the function.

struct Foo {
  int m_number = 123;

  inline int number () {
    return m_number;

int main () {
  Foo foo;

  // used like a regular function
  std::cout << foo.number() << std::endl;

  // compiled to almost identical assembly as this
  std::cout << foo.m_number << std::endl;

  return 0;

However the inline keyword isn’t a guarantee that the compiler will do this. It’s more of a hint to the compiler. So keep in mind that the compiler is free to ignore the fact that a function is declared inline and it can inline functions that haven’t been delcared as such. But in examples similar to the one above, you can assume it will behave as expected.

Another important piece of information is that the function definition needs to be available in every translation unit.

// foo.h
inline int foo ();
// foo.cpp
#include "foo.h"

int foo () {
  return 123;

If I try to use the foo function by including foo.h I’d get a warning telling me that the foo is not defined. This won’t prevent compilation, but the function will not get inlined. The compiler needs access to the function body to replace it with the call site. There’s a simple solution though. Just put the function definition in the header.

// foo.h
inline int foo () {
  return 123;

One finall note. Using inline too much can not only make your binary much bigger, but it can also slow it down due to the way things are cached during execution. So only use them on very small functions (1-3 lines) and you should be good.

Vim Marks

Marks are a feature that I’ve never really used enough. Hopefully writing about them will change that for the better.

Make a basic, file local, mark called a


Jump back to that mark


Now I try to be pragmatic. So use cases are what motivate me to learn new thing. I think that marks are a good replacement for a lot of the things I use visual line V mode for now.


Lets say a have some text


I want to remove lines 2-3.

Currently I’ll jump into visual line mode, select the lines and then d to delete them.


If I was going to do same thing with marks I’d set a mark on line 2 ma, go down a line j, go to the end of that line $, and then delete , go to the end of that line $, and then delete everything back to the mark d'a.


… not so great.

the best way would be 2dd to delete the 2 lines. I guess there’s no point trying to use marks for manipulating entire lines. They’re more usefull when you want to do more complicated motions where you’re not trying to grab the entire line. Or maybe when the content you are targetting is very large and visual mode would obscure the view. I’m lazy and don’t feel like coming up with examples for those situations. So next to another use case.


I think marks are more important in the case of navigation than in editing. Before I say anything else, you need to know that there are 2 different types of marks: Local abcde.... and Global ABCD.... Local marks are local to the file they are defined in. If a mark b exists in file1 and then you define mark b in file2, they can both exist oblivious to eachother. Global marks are shared across files.

A good usage would be when your trying to debug some C function and you’re always jumping between the usage, declaration, and definitions. You could just set global marks for those points.

Undo is a very awesome thing. But most of the time it’s only used for reverting changes made. What about movement? You know those times when you accidentally hit some key and your cursor jumps to a completely different part of the page? '' is your friend. It’s a special mark that denotes the last place you jumped from. It will keep jumping back and forth between the last 2 locations you were.

But say you did something really retarded and need to go back 3 jumps? In that case you need to bust out CTRL-O and his buddy CTRL-I. These will navigate forward and backward through the jump history.

CTRL-O and CTRL-I are the undo and redo when it comes to movement.


listing doesn’t really make sense as a heading when the other two are taken into account, but w.e. The way you list all the marks (global and local) is with the :marks command.

Last Mod

One last thing that you want to do is jump back to the last place you edited something. That’s what the . mark is for. .' will take you back to your last edit location.

Line or Char?

Ok so I left out a small tidbit of information, but it’s not that complicated. When you access a mark using ' then you will jump to the beginning of the line where the mark was defined. If you want to jump to the exact character where the mark was created, then you need to use `.

C++ Extending Classes via the Stream Operator


Looking for a way to create a class which behaved like one of the std::ostream classes.

MyClass obj;

obj << "foo" << 123 << some_string.c_str();


Implementing all those operator<< overloads would be redundant because something like std::stringstream already does it. However inheriting from std::stringstream is more complicated than it should be.

struct MyClass : public std::stringstream {
    /* not that simple ... */


You can use a simple template to achive the desired effect.

struct MyClass {

    std::stringstream m_ss;

    template <class T>
    MyClass & operator<< (T const& rhs) {
        m_ss << rhs;
        return *this;

This comes with the benefit being able to ‘hook’ into each invocation.

C++ Log4cxx vs Glog vs Boost.log vs Wrapper

It seems that logging in C++ isn’t a much discused topic when compared to a language like java. In a recent C++ project, I needed to add real logging support. Up till this point, the following was good enough (don’t judge).

#ifdef DEBUG
    std::cerr << "some error" << std::endl;

I started googling and the following to be the most popular and mature.



glog was my first choice because it’s the simplest one to set up and it has hardly any dependencies. The interface is also nice to use.

LOG(INFO) << "this is a test" << 123;

If you need simple and robust logging in a standalone application then glog is the way to go. However if you’re using it in a library and want to let your users configure logging options, it starts getting problematic. You can only initialze glog once, so having your library set its own default can get more complicated than it should be.



I didn’t get too far with this library. It’s simply overwhelming! If you want simple logging then it can do that.

BOOST_LOG_TRIVIAL(info) << "this is a test" << 123

But if you want anything more, get ready to read a LOT of documentation. Boost.Log is more a framework to build your own logging library as opposed to a logging library in an of itself.



I’m not a big fan of java and initially I wasn’t too thrilled about the idea of something that copies log4j. Another thing that turned me off was that it has some pretty heavy dependencies. I eventually decided to give it a try and it wasn’t all that bad.

log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(""));

LOG4CXX_INFO(logger, "this is a test" << 123);

The advantage here is that you can configure the system anywhere. All loggers inherit from the root logger log4cxx::Logger::getRootLogger(). In my example, bar is foo’s parent. So any setting given to bar will be inherited by foo.

custom wrapper

Soon after starting my search I came up with an awesome idea. Why not just build my own, back-end agnostic, wrapper. Then provide an abstract Logger interface which the user can extend with the underlying logging back end. This would be both flexible and let me make my own beautiful api.

log::error << "this is a test" << 123;

… just don’t do it. Doing it right is harder than it seems.


I ended up going with log4cxx. In my opinion, it strikes a nice balance between flexibility and simplicity.

Libpq: PQexec Timeout

1. Establish the connection

PGconn *pg_conn = PQconnect("info");

// error check
if (PQstatus(pg_conn) != CONNECTION_OK) throw "invalid connection";

2. Grab the socket file descriptor

int socket_fd = PQsocket(pg_conn);

// error check
if (socket_fd < 0) throw "invalid socket";

3. Set the timeout

// 5 second timeout
struct timeval timeout = { 5, 0 };

// recv timeout
int setopt_result_1 = setsockopt(
    (char *)&timeout,

// send timeout
int setopt_result_2 = setsockopt(
    (char *)&timeout,

// error check
if (setopt_result_1 < 0 || setopt_result_2 < 0) throw "failed to set timeout";

SWAPM: Code generation made easy.

I finally got around to reading the Pragmatic Programmer book. One thing that really interested me was the section on Code Generation. So in a recent C++ project I was interfacing with postgres and there was a LOT of code repetition. The sql query, class members, getters/setters, response parsing logic. They all contained the same information. Perfect I thought, here was the ideal chance to give code generation a shot. My first incarnation was a very ugly perl script (aren’t they all .. ?) which used mustache as the templating engine. It worked, But I had to copy and paste the generated code into my source every time it changed which was a pain.

Here’s what I really wanted:

  • have the generated code automatically be inserted into my source.
  • have an extemely simple templating language
  • solution for situations where simple templating wasn’t enough (computed properties).
  • separate my data from the templates
  • VERY easy to use.
  • VERY easy to integrate into existing projects.

I spent a decent amount of time googling but all I found was

I didn’t like them though. Cheetah is too complicated and cog is too limited.

So I set off to make my own. . I am using it in my projects with a very high level of satisfaction. I wrote it in javascript because node makes it portable, npm makes distribution painless, and I wanted support for having computed properties in my data.

Regarding the name, I’m not very creative and originally called it swap but that name was already taken on npm. So I renamed it to swapm pronounced “Swap-Em”.

** Note: ** It’s still very much a work in progress at the time of writing so use at your own risk of it eating your code. Github issues are always appreciated.

A week with Vim

During the past week I’ve been learning to use Vim (gVim). Day 1 and 2 weren’t fun to say the least. But now I’m completely hooked. I’m the type of person who will sit there for hours customizing my development environment until I think it’s perfect. I’ve been playing with almost every cool plugin i can find (and wasting a lot of time in the process).

vim cheatsheet

So Vim is, without a doubt, the best text editor I’ve ever used. However, that’s all it is. It’s just a text editor and I know a lot people don’t agree with me on this one, but IDE’s do help. They just make everything better. Therefore the ultimate combination would be an ide with vim as the text editor.

Netbeans jVi is the first thing I tried and it was far too limiting when you’re already used to Vim. I think this plugin would be good to someone who wished to add some Vim-like functionality to netbeans as opposed to making the netbeans text editor perfectly emulate vim7.

Vim (NerdTree, Sessions, OmniComplete w/ctags, etc..) is what I tried next. I wanted to see if I could turn vim into a sort of IDE like setup with plugins. Although I can’t give any specific reasons why, I didn’t like it…

EClim (Vim + Eclipse): I’m not a huge fan of eclipse because it’s just too slow. But after finding out about eclim I had to try it out. Basically you can either embed vim into eclipse, or have eclipse running as a daemon and vim connects to it. The results were very nice aside from one thing: it was slow which kind of defeats the purpose of vim.

So atm i’m still looking for the idea setup. One thing that I’ve really wanted to try was

  • Visual Studio 2010
  • Visual Assist X
  • ViEmu

Although ViEmu is just another emulator, the idea of using vim with visual assist x sounds incredible. However, this setup would have a serious implication …. switching to windows. I don’t feel comfortable developing on a virtual machine so a dual boot might be in order.

Ember.js with Brunch

I’ve recently discovered the brilliant Ember.js library and the first major issue I ran into was how to organize/modularize this thing!? At first I just opted into RequireJs because that’s what I know but I started hitting walls fast. I decided to try out the Brunch build system since I had heard good things about it before and this was a great opportunity to learn how to use it. Brunch uses skeletons which are essentially project templates to get rid of the boilerplate. Google search “ember brunch” and I found charlesjolley/ember-brunch perfect!

Unfortunately it hasn’t been kept up to date… Relevant Issue

If Charles wasn’t going to update it even after Paul (Brunch’s author) asked him to then it definitely wasn’t going to happen. So I was left with only one option, write my own icholy/ember-brunch
Paul was kind enough to include it on the homepage. Once ember 1.0 is finally released I’ll restructure the skeleton to use the new Ember.Router and Ember.States.

It Includes:

  • Template compiling
  • CoffeeScript version (coffee branch)
  • Twitter Bootstrap (not a big deal but nice)

CSS Compass Gradient Generator

This is a css gradient generator that i’ve been using for a while:

CSS Output

background: #1e5799; /* Old browsers */
background: -moz-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* IE10+ */
background: linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */

However I just noticed the switch to scss option!

SCSS Ouput

@include filter-gradient(#1e5799, #7db9e8, horizontal);
$experimental-support-for-svg: true;
@include background-image(
    linear-gradient(left, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%));

This makes implementing complex cross-browser css gradients painless.

VMware Workstation Ubuntu problems

I just tried starting up vmware workstation and was greeted with a message saying it needed to compile some modules and then went on to fail this step no matter what. This is an issue I’ve encountered before on Ubuntu 11.04 and now on 11.10.

This is a bug with all v7.x of workstation and can be fixed with a simple patch I found today at

How to use it:

mkdir ~/Downloads/patchv3
cd ~/Downloads/patchv3/
tar -xvf vmware2.6.39patchv3.tar.bz2
chmod +x
sudo ./

QML is Awesome

QML is Nokia’s recent addition to its well known Qt framework and comes part of the Qt Quick Suite

The way I describe it to people is:

it’s like html and css combined with the power of Qt in a extremely simple syntax.


I have used Swing, WinForms, and GTK in the past and never really liked anything to do with GUI work. QML is the first time I’m actually enjoying designing user interfaces and this results in a better end result. It feels a lot more like web development except without browser specific issues.


Speaking of browsers, WebView is a QML element which embeds QWebKit in your application and can be accessed within the markup itself with javascript! This is how you would embed a WebView

WebView { id: browser; url: ""; }

that’s it … you can access it in javascript through it’s id property.


Assuming everything doesn’t move to the web in the next few years, I think that QML is the future for GUI development. It’s simple, powerful and fun!

Qt Creator + Boost on Ubuntu 11.04

1. make a home for boost

sudo mkdir -p /code/include
sudo chown -R YOUR_USER_NAME /code
cd /code/include

2. download boost

sudo apt-get install subversion
svn co boost
cd boost

3. compile boost

sudo ./
sudo ./b2

note: this will take a while, go get some coffee.

4. Include in qt project

Add the following to your .pro file.

INCLUDEPATH += /code/include/
LIBS += -L/code/include/boost/bin.v2/libs/ -lboost_system -lboost_filesystem -lboost_asio

In this example i’m linking boost::filesystem and boost::asio. boost::system is required by other boost libraries but if you can compile without it, then trash it.

Compile CompassApp on Ubuntu 11.04

1. Install RVM

bash < <(curl -s;
echo 'if [[ -s "$HOME/.rvm/scripts/rvm" ]]  ; then source "$HOME/.rvm/scripts/rvm" ; fi' > ~/.bashrc
rvm install 1.9.2

2. Install jRuby

rvm install jruby
cd ~/.rvm/bin/jruby-1.6.4 -S gem install rawr

3. Get and Compile CompassApp

git clone
cd CompassApp

4. Run CompassApp

cd package/

Cloud9 IDE

I’ve always wanted to like web based IDE’s. However, there was one thing that always prevented it: they’ve always been terrible.

Until now that is. Cloud9 is epic. It’s built on node.js and has support for coffeescript and sass syntax highlighting and real time error checking. I can’t even find an desktop ide to do that right!

It gets better though. It’s 100% open source so you can install it on locally. I kinda used this as a general guide but didn’t need most of it

I’m using node 4.9 because express doesn’t support anything >= 5.x.x which is kinda shitty… You’re supposed to be able to install cloud9 through npm but it didn’t work for me so meh.

One thing that I ran into was compiling my scripts from the ide command line. It’s very restrictive and doesn’t allow you to freely execute commands. So I wrote a simple node.js script to compile my coffeescript and sass and it seems to do the job.

var exec = require('child_process').exec;

var run = function(cmd, max){
    var max = max != null ? max : 10000;
    var timeout;
    var p = exec(cmd, function (error, stdout, stderr){
        stdout != null && console.log(stdout);
        error != null && console.log(error);
        stderr != null && console.log(stderr);
        console.log('done: ' + cmd);

    timeout = setTimeout(function(){
        console.log('killing: ' + cmd);
run("coffee -c *.coffee",1000);
run("sass --update --scss sass:css");

Sass Compass Blueprint

So I just realized that I hadn’t actually written anything about compass. Now I feel a little dumb about the title of the Formalize post but w.e shit happens. Anyway I’ll be talking about css in this post. I started using these a while back so I don’t really know why I haven’t posted anything about it. Better late than never.

Let’s start with SASS. Syntactically Awesome Style Sheet

well actually I’ll be talking about SCSS which is sass syntax which is more like css. Well actually it’s exactly like regular css except you can add way more stuff. but regular css is still valid scss. I’m not going to try to explain so here’s an example.


$mycolor: blue;

@mixin blue-bg($color) {
    background-color: $color;

div#test {
    width: 100px;
    height: 100px;
    @include blue-bg($mycolor);
    a {
        color: black;'

Compiles into:

div#test {
    width: 100px;
    height: 100px;
    background-color: blue;
div#test a {
    color: black;

If you didn’t understand that then, well I don’t really care. The only reason I write these things is to procrastinate anyway. Actually I think I’ll cut off right here and continue later.

I said “Actually” too many times in this post. I wonder if I always do that … ? :S


I just spent the last 5 hours learning CoffeeScript and I feel like I have pretty much everything down. My brain is kinda dead right now, but at the same time I’m pretty excited to actually try it in a real project. In case you don’t know CoffeeScript is a python-esque language which ‘compiles’ into javascript. classes, list comprehension inheritance, ranges, semantic code etc…. dream come true.

One thing I was worried about was being able to use 3rd party libraries with it. It’s actually not different at all… Once you figure it all out, you realize that it’s still the exact same js you’re working with and you can do just as much. It’s just a lot less shitty. Yes, the learning curve is balls, but it’s definitely worth it (i hope).


cubes = (num * num for num in list)


var cubes, num;
cubes = (function() {
  var _i, _len, _results;
  _results = [];
  for (_i = 0, _len = list.length; _i < _len; _i++) {
    num = list[_i];
    _results.push(num * num);
  return _results;

Formalize [More Compass]

I think forms and all things related ( inputs, buttons, etc… ) are probably one of the more annoying things when building a website. They’re just not consistent and it takes a lot of effort to make them look decent. I spent some time looking for a tool to help me with this and I ended up with formalize which comes as a compass plugin and integrates with any web framework you’re using. It actually didn’t jump out at me the first time around when I checked out the site. It didn’t ‘dazzel’ me so I kept looking, but what I realized was that it shouldn’t stand out. It’s a form… You don’t want it to be shiny with crazy animations. So I went back and used it for the project I’m currently working on. It was perfect… enough said.

Reloader - multi browser live web preview

I recently started developing on linux and unfortunately stylizer 5 does not support linux. So I’m back to using kate. However, one thing that I really missed right away was the instant preview feature. Having to go and refresh multiple browsers every time you change a line of code blows. I searched around for a bit and found a few tools but none of them were any good. I needed something that would work in multiple browsers at the same time and I couldn’t find anything to my liking so I wrote my own.

Reloader: ( check wiki for basic tutorial )

Not the most inspired name, but it was free on google code so why not?

How It Works

Basically it’s a small http server written in python. The javascript in the browser polls the server via jsonp and when a file is modified in the target directory, either a “refresh-css” or “refresh-page” command is sent.

Multi Browser

The server uses cookies to distinguish between multiple browsers. This way it doesn’t send the same update command to the same browser twice.

Windows Support

I’m using the pyinotify python library to monitor the directory but it’s not cross platform. I used twisted-web to create the server so that’s completely portable. So i’m currently on the lookout for a pyinotify replacement.

JPProxy - tiny jsonp proxy

JPProxy is a very simple yet powerful JSONP script. It allows you to make ajax like requests to any page on a server that has the jpproxy.php script on it. I tried really hard to make it as simple and generic as possible so the source is tiny.

1. Client

A script tag is injected into the DOM and all the values are added to the url as GET parameters.

  • callback_id: this gets sent back in the generated javascript to execute the correct callback
  • page: the page to retrieve
  • data: request parameters in json
<script type='text/javascript' src='http://server/jpproxy.php?callback_id=1&page=somepage.php&data={"key":"value"}'>

2. Server

The $_GET["data"] key/value pairs are assigned to $_GET and $_POST variables. Then the requested page is included as a script so it can use the GET and POST paramters the way it normaly would. Finally javascript is generated which passes the callback_id and result data to the callback function

  echo "JPProxy.callback(" . $_GET["callback_id"] .",$result);";

3. Client

The generated javascript get’s executed and your callback function is called with the response data.


we have a page on and we want the page to grab

Drop jpproxy.php in the root directory ( )

Example Client Code:

//callback to handle the data once it arrives
function mycallback(data){

//POST and GET parameter passed to data.php
var parameters = {
    foo: "bar",
    bar: "poop",

//set the proxy location

//note: the page's path must be relative to jpproxy.php"path/data.php", parameters, mycallback);



var JPProxy = {
    request_id: 0,
    callbacks: [],
    scripts: [],
    proxy: null,
    setProxy: function(proxy){
        this.proxy = proxy;
    callback: function(id,data){
        delete this.callbacks[id];
        delete this.scripts[id];
    get: function(page,data,callback){
        this.callbacks[++this.request_id] = callback;
        var script = document.createElement('script');
        var src = this.proxy + '?page=' + encodeURIComponent(page) + '&callback_id=';
        src += this.request_id.toString() + '&data=' + encodeURIComponent(JSON.stringify(data));
        script.setAttribute('type', 'text/javascript');
        this.scripts[this.request_id] = script;


$data = json_decode($_GET["data"]);
$obj = "null";
if ($data && is_object($data) && is_file($_GET["page"])) {
    foreach ($data as $key => $value) { $_GET[$key] => $_POST[$key] = $value; }
    require $_GET["page"];
    $obj = json_encode(ob_get_clean());
echo "JPProxy.callback(" . $_GET["callback_id"] . ", $obj);";

Skybound Stylizer 5 - CSS Editor

Lets start with a little preface. Prior to finding Stylizer, I was completely happy using a regular text editor (gedit, notepad++) with firebug to do my css coding. I don’t really know how I found stylizer, or what motivated me to download it, but I am glad I did. Stylizer is, by far, the best css editor. I went on to try 10+ different editors in hopes of finding a free alternative and nothing even comes close. This is the first piece of software I bought a legitimate licence for and $80 is a lot for a broke ass student.

The feature that really stands out is the live preview in 8 browsers. The cool thing is that it has a built in file watch system. So if you modify a loaded file in an external editor, it will instantly get reloaded in stylizer. This keeps me from having to hit refresh after every edit and that’s awesome. There’s no point in me rambling on about this thing, just go and download the trial and watch the demo vidoes.

There are three things that I have against stylizer.

  1. The licence uses hwid to lock a key to a computer
  2. There is no linux version or wine support
  3. Bad things start happening when javascript gets involved.

nevertheless, it’s still sweet and you need to go try it right now.

Balsamiq Mockups - wireframing done right


You’re designing some type of user interface. Clients never know what they want (even when they think they do) so it’s usually a good idea to come prepared with a basic design to go off. You quickly whip together something in photoshop and think you’re good to go.

This is how the conversation goes:

Me: I threw together this mockup of a potential design. It’s very rough so just look at the basic layout and ignore details.

Them: hmm well I don’t like the colors and box A is not lined up properly with box B. Can you fix that?

Me: Yes, this is a very rough example to demonstrate very basic layout. Try not to get bogged down in the details and look at the big picture.

Them: Ok but I really don’t like these colors.

Me: -_-


So basically I need something that will prevent people from getting distracted by stupid details which always seems to happen. At the same time though, it still has to look appealing. Meet Balsamiq Mockups It’s an air application and they have a live demo on the site.

Not only does it help keep clients on track, it helps me focus too. I’m not sitting there for 5 minutes trying to find the right gradient for a button that I end up deleting anyway. The simplicity helps me to keep on track and pump out intuitive templates/mockups very quickly.

absoluteFudge - ie6 absolute positioning

I don’t know about you, but here is a snippet of css that I love.

div#selector {
   position: absolute;
   left: 10px;
   right: 10px;
   top: 10px;
   bottom: 10px;

assuming that the parent element has either relative or absolute positioning, the child div will fit inside with a 10px margin. This is a very powerful technique for creating liquid css layouts.


The problem is, that ie doesn’t support giving values to all sides (top,bottom,left,right) so you were forced to have a separate stylesheet for ie with a static layout.


Say hello to absoluteFudge backup: It’s sweet, just run it in ie6 and all absolute positioning problems are fixed.

I use jquery to detect the browser

    if($.browser.msie && $.browser.version=="6.0"){
        AbsoluteFudge.apply($('body')[0], true, true);

that’s it, problem solved.