Archive for the ‘Programming’ Category

How many answers are there to a yes/no question?

Wednesday, May 21st, 2008

8.

How many answers are there to a yes/no question?

Along with an additional option, in case you just happen to know that you’ll be answering the exact same thing forever (which, assuming a uniform distribution of probability, will happen with a likelihood of 1 in about 90 billion…)

Thanks Signal vs Noise for the entertainment (not their design, only their picture).

Javascript optimization guidelines

Monday, May 19th, 2008

The Opera dev guys have put together a great list of JS optimization primers. Most of them I already follow, but a few of them were pleasant surprises.

The ones I already follow and which require little or no explanation or justification are:

  • Avoid using global variables
  • Avoid for-in in performance-critical functions
  • Pass functions, not strings, to setTimeout() and setInterval()
  • Isolate uses of eval and with
  • Don’t use try-catch-finally inside performance-critical functions
  • Avoid using with
  • Avoid using eval or the Function constructor
But these were the gems:
String Value to Object conversion when calling methods
The difference between 

var s1 = '0123456789';

and

var s2 = new String('0123456789');

is that s2 is an object with a bunch of associated methods, e.g. charAt and split, while s1 is just a value without these methods. When you call a string method on a string value, e.g. s1, the runtime engine has to convert that value into a temporary string object, call that method, return the value, and then discard the temporary object.
Who would have thought?
String concatenation
Similarly, the difference between

a1 += 'x' + 'y';

and

a2 += 'x';
a2 += 'y';

is that the concatenation of a1 requires a temporary variable to store ‘xy’ in before this gets appended to a1. That extra memory and garbage collection cycles is saved in the creation of a2.
Primitive operators can be faster than method calls
If you really need the very last ounce of performance, instead of writing

var min = Math.min(a,b);
A.push(v);

use the slightly less convenient but faster

var min = a < b ? a : b;
A[A.length] = v;

This one certainly makes sense - but as always: first get it right by using whatever means you feel most comfortable with. Then if you really need it, get primitive.

I’ve Got Code Running on Google

Monday, May 12th, 2008

Google App Engine is awesome.

Repeat. Google App Engine is awesome.

A quick tutorial video, 30 minutes of tinkering and playing around, and I’ve got database code running on Google’s BigTable(!). Go check it out - leave a shout.

Oh, and it turns out - Ruby to Python isn’t that bad after all.

Unobtrusive Javascrips with jQuery - Loading Spinner

Monday, May 12th, 2008

This is the first in an intended series of small snippets of unobtrusive javascript patterns.

What?

How to effortlessly and unobtrusively have a loading spinner appear on each ajax call with jQuery.
Ajax loading spinner

Why?

There are a number of reasons why, and they fall in a number of different categories

  • UI - You should always keep your user aware of what’s going on. In this case that something is loading.
  • Development - unobtrusive code degrades well by definition, and the effortless part explains itself.
How? Using jQuery
// Create closure
jQuery(function($){
	// Create img dom element and insert it into our document
	var loading = $('<img alt="loading" src="/images/loading.gif" />')
	.appendTo(document.body).hide();
	// Make the image appear during ajax calls
	$(window).ajaxStart(loading.show);
	$(window).ajaxStop(loading.hide);
});

Google I/O Registration - Comes with App Engine Invitation

Monday, May 12th, 2008

I finally registered for Google I/O, and was happy to see that it comes with an invitation to App Engine. Tonight I’m meeting up with a Python friend to show me the ropes.

I’m now intending to port ShareWithMe from rails to python and BigTable for its first, long overdue release.

Learning Javascript the Right Way

Tuesday, May 6th, 2008

What?

Marijn Haverbeke is the coder behind CodeMirror, the best in-browser code editor available on the web (I have considered MarkitUp, Helene, EditArea, and used others such as Heroku’s in-browser editor). As an exemplar of the open source spirit, it is widely available to use as you please (e.g. BSD, not GPL). 

I just stumbled upon his Elequent Javascript Tutorial, which is by far the best javascript coding tutorial I have come across (and I have searched far and wide!). In my mind it is the Javascript equivalent of Why’s (Poignant) Guide to Ruby

His tutorial is not only highly interactive, with examples that run right in your browser as you read, but also teaches excellent coding practices.

Anyone looking to learn how to program, or specifically are looking to learn javascript, should read this. Thank you Marijn!

Thoughts

Most source developers I know code because they are good at it, enjoy it, and feel they do something worthwhile with it. There is a definite reward.

It takes a completely different mentality to use your time (which is precious indeed at the level of design skill we see in Marijn’s work) and put in a significant effort into having others learn what you know.

Pretty Code on your (wp) Blog

Tuesday, May 6th, 2008

What? How to make your code look pretty on your blog with minimal effort. Meaning language appropriate highlighting without even specifying which programming language the code is in. Why? Because

/**
* A miss manners guest
* @constructor
* @param {Object} params The parameters object. All other parameters are named properties of this object
* @param {String} name The guest name
* @param {String} gender The guest gender. 'male' or 'female'
* @param {String} interest The guest interest. A single string. You should give guests interests so that some match up - this is what the rule engine bases their placemenet on.
* @param {String} color Hexadecimal value of the color to represent the guest with.
*/
MissManners.Guest = function(params) {
  this.name = params.name || this.Default.name;
  this.gender = params.gender ? params.gender.toLowerCase() : this.Default.gender;
  this.interest = params.interest ? params.interest.toLowerCase() : this.Default.interest;
  this.color = params.color || this.Default.color;
  this.id = 'MMGuest-' + MissManners.nextUniqueId++;
}

Looks infinitely better and is much more readable than

/**
* A miss manners guest
* @constructor
* @param {Object} params The parameters object. All other parameters are named properties of this object
* @param {String} name The guest name
* @param {String} gender The guest gender. 'male' or 'female'
* @param {String} interest The guest interest. A single string. You should give guests interests so that some match up - this is what the rule engine bases their placemenet on.
* @param {String} color Hexadecimal value of the color to represent the guest with.
*/
MissManners.Guest = function(params) {
this.name = params.name || this.Default.name;
this.gender = params.gender ? params.gender.toLowerCase() : this.Default.gender;
this.interest = params.interest ? params.interest.toLowerCase() : this.Default.interest;
this.color = params.color || this.Default.color;
this.id = 'MMGuest-' + MissManners.nextUniqueId++;
}

But this can be a pain to get right (you know if you’ve tried). There is an easy way, especially for all us WP bloggers. How? With wordpress, the easiest thing in the world. Just download Google Code Prettify for wordpress v1.1 to your wordpress wp-content/plugins directory with


curl -O http://www.deanlee.cn/downloads/google_code_prettify_v1.1.zip
unzip google_code_prettify_v1.1.zip

Then go to your wordpress plugins admin area at /wp-admin/plugins.php, and activate Google Code Prettify. The next time you write code, just wrap it in <pre class=”prettyprint”> /* your code here */ </pre> and the plugin takes care of the rest. Seriously - you don’t even have to specify the programming language your code is in. *Thank you!*

Running a Ruby Server has never been easier

Tuesday, May 6th, 2008

What?

Sinatra - the sleekest ruby server out there. Very appropriately named

Why?

I have a good friend who’s learning to program - we started with ruby, and are now venturing into the messy world of html/css/javascript.

One of the biggest challenges in getting started with this stuff is to *get started.* Installation of Apache is not necessarily difficult, but if you want more dynamic scripting (say ruby), things can get messy.

Sinatra makes it super easy. 

How?

Super easy. Just:

sudo gem install sinatra
echo "require 'rubygems'; require 'sinatra'" > sinatra-server.rb
ruby sinatra-server.rb
# == Sinatra has taken the stage on port 4567 for development

That’s it. now go enjoy sinatra at http://localhost:4567.

 

Default Sinatra web server index document

 

To handle a request, simply edit your sinatra-server.rb file:

require 'rubygems'
require 'sinatra' 

get "/:name" do
  "Hello #{params[:name]}!"
end

Find more details in this great Sinatra tutorial