Playing with YUI3

Posted by – March 1, 2011

I have been playing with YUI3 for a while. Some one with a background in prototype.js and jQuery will find YUI3 bit complicated. To me YUI always sounded like JS toolkit developed by some c++/Java programmer who hated web developers to the core. Well YUI3 tries to be friendly. It took me just 15 minutes to write down the following code:

<html>
<head>
<title>YUI says Hello World!</title>
</head>
<body id="doc-body">
<div id="rgbvalues"> </div>
<script src="http://yui.yahooapis.com/3.3.0/build/yui/yui-min.js" charset="utf-8"></script>
<script type="text/javascript">
//use node and event modules
YUI().use("node", "event", function(Y){
    var handleClick = function(e) {
        var docBody = Y.one("#doc-body"); //equivalent to $(element) in prototype and jQuery(element)
        var winHeight = docBody.get('winHeight');//get "viewport" height
        var winWidth = docBody.get('winWidth');//get "viewport" width
        var red = parseInt (e.pageX * (255/winWidth));
        var green = parseInt(e.pageY * (255/winHeight));
        var blue = parseInt (red*green*0.004);
        var bgstyle = "rgb("+red+","+green+"," +blue+")";
        docBody.setStyle("background-color", bgstyle);//same as $(element).setStyle() from prototype and jQuery(element).css()
        Y.one("#rgbvalues").set("innerHTML", bgstyle);//set innerHTML
    };
    Y.on("mousemove", handleClick, "#doc-body");
});
</script>
</body>
</html>

Easy!
As I am not so good at maths I wasn’t able to write a formula or function that could translate mouse motion into color values, so I simply wrote down my stupid conversion :) .

Dynamic subdomains using .htaccess or mod_rewrite

Posted by – December 7, 2010

The man page documentation page for Apache mod_rewrite module says, “Welcome to mod_rewrite, the Swiss Army Knife of URL manipulation!”

Believe me, mod_rewrite lets you do cool things with URLs. You can have one script for every URI request. For uninformed a URI is simply a request for a page or a website like: http://www.kumarchetan.com/blog/all-about-lamp-web-development-blog/ or http://www.shameless-self-promotion.org/about/. In both cases, the websites run WordPress blogging platform and use mod_rewrite. mod_rewrite sends URIs like http://www.shameless-self-promotion.org/about/ or http://www.shameless-self-promotion.org/get los to one server side script or program which knows how to deal with good and bad requests.

But mod_rewrite also lets you play with your domain name and you can have sub-domains on the fly. So you can, without messing up your DNS entries, create sub-domains automagically.  Look at the following mod_rewrite which was added to a .htaccess.

Options +FollowSymLinks
#Turn on the engine
RewriteEngine On
RewriteCond %{HTTP_HOST} ([^.]+)\.domain\.com
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ /%1/$1

Event Delegation: Save thou webpage

Posted by – October 3, 2010

To make a web page interactive web developers rely on Events on the page. Event handling could be as easy as reloading the page on click of a button or as complex as following mouse pointer and responding to it. The usual way to do this is onEvent do some thing.

<button name="aButton" id="aButton" onclick="alert('Hello World!')">Cliché</button>

Easy.

There are so many ways to handle events and then do something. Inline, shown above, unobtrusive, shown below.

<button name="anotherButton" id="anotherButton">Another Cliché</button>
<script>
document.getElementById('anotherButton').addEventListener('click', function(){alert('Hello World!')}, false);
</script>

One can add as many as event listeners required for an event occurring for an element. Well, not really a wise idea. Think of Gmail inbox set to display 100 emails in a row. Does that mean100 addEventListener? Not a good idea. Here comes a very simple technique called Event Delegation. Example

<ol id="olElem">
 <li id="li1">One</li>
 <li id="li2">Two</li>
 <li id="li3">Three</li>
 <li id="li4">Four</li>
 <li id="li5">Five</li>
 <li id="li6">Six</li>
 <li id="li7">Seven</li>
 <li id="li8">Eight</li>
 <li id="li9">Nine</li>
 <li id="lin">n</li>
</ol>
<script>
document.getElementById('olElem').onclick = function(e){
 e = e || window.event;
 var target = e.target || e.srcElement;
 var textClicked = document.getElementById(target.id).innerHTML;
 alert('You clicked ' + textClicked);
}
</script>

This is all due to Event Bubbling which simply means that an event bubbles up to document root. So, when I click on “Nine”, the element li9 tells its parent that it got clicked, which in turn informs its parent and so on.

Method chaining

Posted by – October 2, 2010

I love the way CodeIgniter explains method chaining by saying.

Method chaining allows you to simplify your syntax by connecting multiple functions.

As explained above it simply lets you do things like

FileObject->OpenFile('FileName')->AppendLine('Hello World!')->CloseFile()

Its neat. But in PHP, you have to have PHP5.x. This wonderful thing is also available in JavaScript. From jQuery home page

$("p.neat").addClass("ohmy").show("slow");

How to do method chaining?
To have an object chain methods every method in that object must return a reference to itself. Easy. Example?

<?php
class MethodChainingExample{
	public function methodOne(){
		echo __METHOD__." \n";
		return $this;
	}
	public function anotherMethod(){
		echo __METHOD__." \n";
		return $this;
	}
	public function oneMoreMethod(){
		echo __METHOD__." \n";
		return $this;
	}
}
$example =  new MethodChainingExample;
$example->methodOne()->anotherMethod()->oneMoreMethod();

PyGTK Hello World or: How I learned to write my first GUI application on Ubuntu?

Posted by – September 21, 2010

There are so many things I like about Ubuntu and I can write in extent about all those. My focus is in this post is Python. Python is easy to learn. So easy that one can write GUI apps in just 2 minutes. The title for the post has also indicated this(and is somewhat similar to Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb ). I am a learn by doing person and this post is for same kind of persons. So first the code, with very little or no explanation, shows a hello world widow:

Hello World using Python & PyGTK

Hello World using Python & PyGTK

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Hello world!")
		self.label = gtk.Label("H3ll0 W0rld!")
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then how I tweaked it

#!/usr/bin/python

import pygtk
pygtk.require('2.0')
import gtk
import os
import commands

class Whc:
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title("Your \"fortune\"")
		self.window.set_default_size(200,100);
		f=commands.getoutput("fortune")
		self.label = gtk.Label(f)
		self.window.add(self.label)
		self.label.show()
		self.window.show()

	def destroy(self, widget, data=None):
		gtk.main_quit()

	def main(self):
		gtk.main()

if __name__ == "__main__":
	base = Whc()
	base.main()

…and then output

Displays a random fortune cookied in GUI

Displays a random fortune cookied in GUI

…and now the analysis. :-)

The code given above uses PyGTK, GTK bindings for Python, GTK, OS and Command module. The OS and Command module is just to fetch the output of fortune command. fortune is a Linux command, more can be found here and may have to be installed, the package is fortune-mod. The Python code is plain English, create a TOPLEVEL window, see for more. In the first code listing another GTK widget Label has been added. The Label contains a snippet of readonly text rendered on Window and in first snippet the text string is legendary, “H3ll0 W0rld!” in L33T. The string in 2nd code snippet is replaced by output of fortune command for which I utilised command and os modules. Easy!!!

This post was lying in drafts for more than 15 months.