Sunday, December 30, 2007

Will The U.S. Invade Pakistan?

Background

Pakistan acquires nuclear weapons in 1987, the result of a program started by Zulfiqar Ali Bhutto, grandfather of Benazir Bhutto.

In 1999 Military General Pervez Musharaff seizes power of Pakistan in a military coup d'etat, with active monetary and military aid from the United States. Reasonably, U.S. relations with Musharaff can be seen as a preventive safeguard, ensuring control over the nation's nuclear arsenal.

Recently

America's close relations with military dictator Musharaff has continuously been criticized,

By proxy, the international pressure has resulted in Musharaff removing his military uniform, effectively stripping himself (at least in theory) of his military executive power.

In exchange, he took up office as civil leader and president of Pakistan, and announces democratic election on January 8th of 2008.

Meanwhile, Benazir Butto, previous prime minister and a national hero of sorts, has returned from her self-imposed exile in order to run for presidency.

During a campaign rally on December 27th 2007 Benazir Butto is assassinated. The following days have seen much confusion, anger, violence and revelry on part of the Pakistani population.

Conspiracy theories flourish, and interviews from Pakistani streets portray a mixture of beliefs as for who bears the responsibility - anywhere from Al Qaida to Musharaff.

Discussions ensue whether elections should be held as planned or not, now that the oppositional party's primary leader is dead.

No one knows what will happen.

Next ?

Some scenarios:

  1. The people of Pakistan accept neither cancellation of elections nor Musharaff. Political instability ensues and in order to protect nuclear arsenals from militant Islamist groups in Pakistan, the U.S. invades Pakistan.

  2. Musharaff quells civil unrest, and his dictatorship commences and remains in place for the time being.

  3. The U.S. announces west/self-protective intentions and a detailed roadmap to when and how they will invade Pakistan, effectively imposing on their sovereign right.

And various nuances of the three. I would be interested in hearing what disagreements people may have with these - please comment.

Friday, December 28, 2007

Three small letters - big meaning

J for Just in time - you're caught by surprise every time.


U for Unexpected. Who the hell would've guessed? Certainly not I.

Y ou know what I'm talking about.

Saturday, December 22, 2007

Javascript DOM Event Handlers - The Right Way

What?
In his YUI theatre presentation An Inconvenient API, Douglas Crockford gives a great rundown of browser history, inner workings, and shortcomings. Among other things he gave a simple, cross-compatible way of doing javascript event handling in the browser.

Why?
Event handling is an excellent pattern, attested by its standardization and widespread use. However, due to browser incompatibilities it is not always obvious how to do it in javascript.

How?
First off, there are three ways of assigning event listeners to nodes: the old way, the IE way, and the W3C way. The type variable should always be an event name, e.g. 'click', 'mouseover', etc. See PPK's thorough listing of event names and compatibility notes at Quirksmode.


// IE way - non-standard
function ieEvent(node, type, handler) {
node.attachEvent('on'+type, handler);
}

// W3C way - long name and with a third, useless parameter that *must* be specified (undefined is not good enough)
function w3cEvent(node, type, handler) {
node.addEventListener(type, handler, false);
}

// Classic way - works in all A-grade browsers
function classicEvent(node, type, handler) {
node['on'+type] = handler;
}


Since the classicEvent way works in all Yahoo classified A-grade browsers Douglas recommends to simply use that way. How we process an event is still different across browsers however - in W3C our event handler gets passed an event object, while in IE we have to get the global event object. We deal with these incompatibilities as follows:


// A Cross browser event handler
function normalizedEventHandler(fn) {
// Get the event object - passed as argument in W3C, global object in IE.
e = e || event;
// Figure out what element the event happened to - again, disparate naming.
var target = e.target || e.srcElement;
// Now do your thing:
// ...
}


We now put it all together in a fail-safe, hopefully forwards-compatible event handling function:


/**
* Cross browser event handling function.
* @param {Element} node The dom node to attach the event handler to
* @param {String} type The type of event, e.g. 'mousedown', 'mousemove', 'resize'
* @param {Function} handler The function to be called when the event happens. It gets passed an event object e, as well as a target node.
*/
function addEvent(node, type, handler) {
// Create our normalized event handler
var normalizedHandler = function(e) {
// Get the event object - passed as argument in W3C, global object in IE.
e = e || event;
// Get the element the event happened to
var target = e.target || e.srcElement;
// Now call the handler with the normalized event object
handler(e, target);
}
// Assign the event handler in a way our browser understands
if (node.addEventListener) {
node.addEventListener(type, normalizedHandler, false);
} else if (node.attachEvent) {
node.attachEvent('on'+type, normalizedHandler);
} else if (node['on'+type]) {
node['on'+type] = normalizedHandler;
}
}
Finally, as a side note: wtf is the third parameter in W3C's addEventListener method? It has with event capturing and bubbling to do. An event gets called on a node, then its parent, then its parent, and so on until the event is canceled or the root node is reached. This is called bubbling.

Netscape implemented the reverse, called trickling down, which visits the parent first, and then goes down until the target node. This turns out to be simply wrong. What did W3C decide to do? Both, of course. This is it: the third parameter says whether you should do capturing the right way (i.e. bubbling, by setting it to false) or the wrong way (i.e. trickling, by setting it to true).

Bottom line is, if you don't know what capturing and event bubbling is, you will want it to be false. Always. To read more on event capture and bubbling, see this article.

Quickly, to cancel a bubbling cross-browser:

// Don't bubble up the event, i.e. "The event has been handled" or "Don't tell my parents"
function cancelBubble(e) {
// IE way
e.cancelBubble = true;
// Everyone else's way
if (e.stopPropagation) {
e.stopPropagation();
}
}
Many thanks, as always, to Douglas Crockford for the excellent information.

Object Oriented Programming with Javascript

What?
As Joseph Smarr at Plaxo said in his YUI theatre talk, Javascript is a malleable language and can be bent to do what you want it to. However, the best thing to do is simply let it be what it wants to be.

Object Oriented Programming has proved an accurate pattern, as far as it makes us architect our abstract information structures in humanly comprehendible manners. As javascript has arguably become the most used programming language and declared by many as the next big Language it becomes increasingly important for us to learn how to use it properly (which many of us do not - as Douglas Crockford [more on him later] points out, it is also the worlds most misunderstood language)

Why?
Hacks serve a purpose - they solve problems without project overhead - but any code that is to be built upon and maintained must be understandable. It would seem that much of software's strength comes from its hierarchical structurability (The work you did yesterday I can use as a foundation for my work today), but this requires intuitive usability (APIs).

How?
In javascript, each class has a prototype-object that all other objects of the class refer to. When an object wants to use a method this.doSomething(), it calls the prototype.doSomething() function.

To make this work, we have to get around two novelties: classes are declared as functions, and the methods of the class are declared outside of the class body.

/**
* Our MissManners application
*/
var MissManners = {
nextUniqueId : 0
};

/**
* 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++;
}

/**
* Generate and Html snippet to represent the guest.
*/
MissManners.Guest.prototype.toHtml = function() {
var result = '';
result += '<div class="missMannersGuest" id="'+this.color+'" style="background-color:'+this.color+'">';
result += '<ul>';
result += '<li>Name: '+this.name;
result += '<li>Gender: '+this.gender;
result += '<li>Interest: '+this.interest;
result += '</ul>';
result += '</div>';
}

/**
* The default values for a guest.
*/
MissManners.Guest.prototype.Default = {
name : 'Joan Doe',
gender : 'female',
interest : 'weather',
color : '#def'
}
We first initialize our MissManners object - this will contain our classes. Then we declare the Guest class, and at the same time define its initializer. This initializer defaults to return the this object.

Every function you create is given a prototype property, so that you can reference MissManners.Guest.prototype and build on it with the toHtml function.

We then go ahead and use our class:
function createGuest(divId) {
var guest = new MissManners.Guest({
name : 'Marcus Westin',
gender : 'Male',
interest : 'Flow',
color : '#cde'
});
document.getElementById(divId).innerHTML = guest.toHtml();
}
At this point, when we call guest.toHtml() it first checks to see if the newly created guest object has a function called toHtml(). If not, it then goes to its prototype, MissManners.Guest.prototype and checks if it has something called toHtml. If it does, it calls that function, and the this variable in toHtml gets bound to guest, such that this.name in toHtml is the same as guest.name in createGuest. If that prototype does not have the property or function, javascript goes to its prototype, and so on until it bottoms out in Object.prototype.

To view this code in action, as well as view the code in its entirety, see the demo. This entry builds on excerpt code of the Miss Manners demo app I wrote yesterday.

Wednesday, December 19, 2007

The computation beast awakens

More than a 100 years ago, Charles Babbage fathered the first abstract form of the computation beast into our world, in the shape of mathematics. This was the first modern day incantation of its primordial being.

. . .

Thirty years ago, you had to be able to count in hexadecimal (base 16) in order to make computers operate. Today, the everyday user has no idea these numbers provide the memory address to each and every little piece of data we use - your music, documents, programs and images.



Twenty years ago, you had to be able to use a teletype terminal to use a computer. Today we have personal computers with (sometimes) intuitive graphical interfaces, which we interacted with using a mouse or our fingers. Tomorrow we may do it by brain stimulus - already we have monkeys control robots and blind men seeing.


Ten years ago you had to know HTML in order to publish textual on the web. Today we blog, post videos, edit content and otherwise contribute with no technical knowledge beyond turning on a computer and using a web browser. Still, at the root of it all lie the hexadecimal representation of the binary, digital data that makes this all possible, from the transnational low of information to its pixelated display on your screen.


Today you have to spend years learning programming and various programming languages in order to create applications. At the root, however, programming is merely control and manipulation of information flow; tomorrow the technical threshold will be surmounted and programming will reduce to this (not less beastly) principle - complexity management through architectural and patterned structuring.

What I am saying is this: Computation is a beast of unimaginable capacity, and software its physical incarnation. Today, this beast is still in its early infancy, and we cannot predict or comprehend its mature form. Thus far, the technical threshold for participation in its development and nurture has been high enough to exclude all but the wiz and the nerd. However, technical literacy is on the rise, and with every human being a potential contributor to the most powerful tool of abstraction of human time we are in for exciting times.

Listen - you can hear it rumble...