JavaScript Notes – 4 (Best Practices)

Posted: February 10th, 2012 | Author: | Filed under: technical | Tags: | Comments Off

In this blog article I want to discuss on few of the JavaScript best practices that I have gleaned from various people, talks, videos, books. For the sources, see here.

VAR, WHERE?

To start with declaration of variables. The best way to do it is

var oneVariable,
    anotherVariable,
    oneArray = [],
    oneObject = {};
// do your thing

Points to notes -
- Good formatting
- Initialization of arrays and object literals without using new is much cheaper (as scope resolution is not required).
- Do not forget the commas after each of the variables

Staying on the topic of variables, there is a useful-to-know concept of hoisting . The following code segment will elucidate the idea-

var foo = 1;
function bar() {
	if (!foo) {
		var foo = 10;
	}
	alert(foo);
}
bar();

Can you guess the output? Click show source below for answer and explanation.

/* the code above re-written to explain 
 * how the interpreter sees it
 */
var foo = 1;
function bar(){
    var foo; // the declaration of foo is hoisted to the top of the scope and undefined
    if(!foo){ // foo is undefined now, this foo not the global variable 
        foo = 10; // set the value of the local variable foo
    }
    alert(foo); // alert foo, the local foo 
}
bar(); // alerts 10

So that is the idea of hoisting explained simplistically. The lesson is to have all your var statements together at the top of the function to avoid such issues. There is something similar that happens with functions too, you can read more about it in Ben Cherry’s article. Long story short, you would want to define your functions before using them.

Do remember that JavaScript has function-level scope, not block level scope . You can create block level scope using anonymous, immediately-executing functions. I will do a more detailed blog post on JavaScript scoping and chaining later.

ARRAYS, LOOPS, YEAH TOGETHER

var a = [];
console.log(typeof a); // "object" Arrays are objects, not arrays. 
console.lo(a.length); // 0

a[10] = "nadu";
console.log(a.length); //11 

a["another_element"] = "another nadu";
console.log(a.another_element); // another_nadu
console.log(a.length); // 11 (still)

This means that arrays are slow, because they are effectively represented as objects. So, the easiest way to improve performance is to NOT do this

var i,
    elements = document.getElementsByTagName("div"); // a huge array
for(i=0; i<elements.length; i++){
    //add a class to the div
    // do something else
}

What is wrong? Well, in each iteration, the length of the elements array is calculated instead just cache the length in a variable and compare it with the loop variable. No big shakes at all right? Well do remember to do this for big arrays!

var i,
    elements = document.getElementsByTagName("div"), // a huge array
    l = elements.length;
for(i=0; i<l; i++){ 
    //add a class to the div
    // do something else
}

DOOM DOM

Few rules for manipulation of the DOM gleaned from this talk.

USE FRAGMENTS TO APPEND NEW ELEMENTS

Assume, you have a container div element and you want to create the child div elements after getting some JSON data from an external server. For appending the child elements,

var i,
    cDiv = document.getElementsById("container-div"), 
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div");
    newChild.innerHTML = jsonResponse[i];
    cDiv.appendChild(newChild);    
}

The problem here is that if there are 100 children divs that are going to be created, then the live DOM will be modified 100 times for appending each child div and the performance takes a hit. Instead, the better method is to create a document fragment, append your nodes to the fragment and then attach the fragment to the live DOM.

var i,
    cDiv = document.getElementsById("container-div"), 
    frag = document.createDocumentFragment(),
    l = jsonResponse.length ;
for(i=0; i<l; i++){ 
    var newChild = document.createElement("div"); 
    newChild.innerHTML = jsonResponse[i]; 
    frag.appendChild(newChild);    
}
cDiv.appendChild(frag); // hurray only once do you touch the live DOM

Useful JavaScript Fact – Did you know that you do not need to convert your object keys to strings unless they are a keyword in JavaScript –

var obj = {
    "name" : "Nadu",
    "is_human": true
    "class": "Less Awesome"
}
// instead write 
var obj = {
    name : "Nadu"
    is_human: true
    "class" : "More Awesome"
}


Next planned article on jQuery and its goodness.

Credits

Ben Cherry’s (a Twitter Engineer) blog – http://www.adequatelygood.com
Paul Irish’s talk here


JavaScript Notes – 3 (Pub/Sub)

Posted: January 20th, 2012 | Author: | Filed under: technical | Tags: , | Comments Off

In this blog post I cover the implementation of Publisher-Subscriber (a.k.a Observer) Design Pattern in JavaScript. As the name suggests, the Pub-Sub model is a way by which an entity can publish events/messages and multiple entities can subscribe to those events/messages and subsequently take action. Browser event are examples of this pattern where the browser publishes events like keypress, mouseclick etc. and event handlers in JavaScript can have act when those events occur.
The example explained below can be seen live here. They are from the book JavaScript Patterns
The publisher, say paper which publishes a daily and a monthly magazine and a reader say, joe will be notified when that happens. A publisher object would need the following members for implementing the functionality

subscribers = [] //- an array (list) of all subscribers
subscribe = function(){} //- a method to add to the list of subscribers
unsubscribe = function(){}  //- a method to remove from the list
publish = function(){} //a method to notify all subscribers by calling the methods they provided when they signed up
//All the 3 methods above will need a type parameter as there can be many different type of events

Since these methods are generic to any publisher, it is better to implement this as a separate object. Then we can copy these properties over to any object and convert any object to a publisher (we will see this in a bit).
The code snippet below defines each of the methods and the subscribers array mentioned above.

var publisher = {
    subscribers: {
        any: [] // event type: subscribers
    }, // an object with different event types

    subscribe: function (fn, type) {
        type = type || 'any';
        if (typeof this.subscribers[type] === undefined) {
            this.subscribers[type] = [];
        }
        this.subscribers[type].push(fn);
    },
    unsubscribe: function (fn, type) {
        this.visitSubscribers('unsubscribe', fn, type);
    },
    publish: function (publication, type) {
        this.visitSubscribers('publish', publication, type);
    },
    visitSubscribers: function (action, arg, type) {
        var pubtype = type || 'any',
            subscribers = this.subscribers[pubtype],
            i,
            max = subscribers.length;
            
        for (i = 0; i < max; i += 1) {
            if (action === 'publish') {
                subscribers[i](arg);
            } else {
                if (subscribers[i] === arg) {
                    subscribers.splice(i, 1);
                }
            }
        }
    }
};

Now we have a generic publisher using which we can convert any object to a publisher. The way we do it is that we copy the function properties of the generic publisher to the object. Sweet?

function makePublisher(o) {
    var i;
    for (i in publisher) {
        if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {
            o[i] = publisher[i];
        }
    }
    o.subscribers = {any: []};
}

Now say we have the paper object which publishes daily and monthly (2 events). So you can have the object as

var paper = {
    daily : function(){
           this.publish("Daily news publication - Breaking News Today");
    }
    monthly : function(){
           this.publish("30 Days of News!", "Monthly Type");
    }
}
// use the makePublisher method to convert this to a publisher object
makePublisher(paper);

Let’s define our subscriber object, joe

var joe = {
    drinkCoffee = function(paper){
               console.log("Reading paper" +paper);
    }
    readMonthlyDigest = function(monthly){
               console.log("Reading monthly digest"+ monthly);                  
    }
}

// Joe subscribers to the paper
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.readMonthlyDigest, "Monthly Type");

So effectively the joe object has bound those 2 methods to those 2 events of the paper object. So whenever the paper publishes (monthly or daily), joe’s methods are called since it had subscribed to them.

// Now paper publishes
paper.daily(); // logs Reading paper Daily news publication - Breaking News Today
paper.daily();
paper.daily();
paper.monthly(); // logs Reading monthly digest 30 Days of News!

So, the joe object does not hardcode the paper object or vice-versa. The objects are loosely coupled and one can be changed without impacting the other (adding new subscribers or new publications- weekly)

The beauty of this loosely coupled pattern emerges now when we can turn joe into a publisher and the paper object into a subscriber.

makePublisher(joe);
joe.tweet = function(msg){
    this.publish(msg);
}

paper.readTweets = function(tweet){
    console.log("Someone tweeted on our blog - " + tweet);
}

joe.subscribe(paper.readTweets);
// so joe can say 
joe.tweet("The news was really boring today");

The above was an example of the Pub/Sub model in JavaScript, useful for loosely coupled objects and when you have time to architect your JavaScript solutions before jumping into code directly.


Thoughts translated in pictures

Posted: November 27th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

Lone Bright Spot - However much life sucks, there is always, yes always, a bright spot in your life that will lead us to the non-sucky part of life. Love and nurture that bright spot, that might be the reason for one’s existence in this world.





Fields of Moods - Like magnetic fields, our moods have fields, and they affect the people coming in contact with that field. A bright and good mood has a bigger field of impact, whereas dark and gloomy mood has a smaller but more intense field of impact. In our worst moods, we hurt the ones closest to us. In the best of our moods we will be kind and spreading our radiant energy to total strangers.




Perspectives - Every living thing in this world has a point of view, a perspective. These brush strokes represent these diverse perspectives in the world about any given thing. Remember, at the end of the day, you too have a perspective on life, and how you should lead it. Follow that. Believe.


Open-Captions

Posted: October 23rd, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

What is Open-Captions?

According to research, over 90% of deaf children have hearing parents who “frequently do not have fully effective means of communicating with them”. The American Sign Language (ASL) is a difficult language to learn, especially as a second language.

Open-Captions makes it easy for parents and children to learn and practice American Sign Language together while watching their favorite videos on YouTube. People can find closed captioned videos on any topic with the Open-Captions search engine. The viewer is able to select individual words in the video’s caption stream and see the American Sign Language representation of the word.

Open Captions Example Screenshot

Closed captions on various television shows have been around for quite some time. They are useful for hearing impaired people and also to people whose first language is not English.
Captions have always been a steady stream of white text on black background, located either at the top or bottom of the screen. Video sites like YouTube and Hulu , have adopted the same style from television.
Open-Captions, changes the way users watch videos by making the captions more interactive.

  • The viewer can pause the video, select a word and watch an ASL representation.
  • The viewer can review earlier captions with the “Previous Caption” button.

The American Sign Language representations are shown from the SmartSign dictionary maintained by Georgia Institute of Technology’s Center for Accessible Technology in Sign (CATS).

How did Open-Captions come about?

My interest in building Assistive Technologies has been one of the main motivating forces behind getting a graduate degree in Computer Science.

I built a web based widget platform for Interactive TV as a graduate student researcher at GeorgiaTech. In the process I worked on developing functionality that would allow widget developers to access the closed captions associated with the currently playing content.
Harley Hamilton, a researcher at CATS, was interested in leveraging this ability of accessing closed captions and we ended up building a rough prototype. Subsequently, I learnt more about hearing impaired children from Harley and wrote a small tool using which one can select any word on a webpage and see the American Sign Language representation of the word. This would be very useful for parents who want to learn ASL.
In September this year, I signed up for the HackdayTV weekend hackathon and ended up building the first version of Open-Captions, which is the mashup of the earlier ideas I had worked on related to ASL.

What happens behind the scenes in Open-Captions?

Disclaimer: Technical content ahead ;)
The entire source code for the project can be found on GitHub
YouTube has extensive documentation on how to use their APIs for search, embedding and controlling videos on your site. The search and results page are based on the PHP library of the YouTube search API. The page on which the video plays is the one that gets interesting. There are 2 parts to it -

  • Getting the closed captions of the video and synchronizing it to show correctly
  • Handling the mouse clicks on the individual words to show the ASL representation

I used Firebug to see what requests YouTube sends whenever you click on the “Interactive Transcript” icon under the video. I removed parameters that were not mandatory (i.e. I would still get the same result if I removed them) and made a PHP curl request for the trimmed URL to get the captions formatted as XML. For this YouTube video the URL for the captions would be


http://www.youtube.com/api/timedtext?lang=en&format=1&v=<VIDEO_ID>&type=track&kind=&hl=en

and the result will be of the form

<transcript>
<text start="0.734" dur="4.299">[Sesame Street theme music]</text>
<text start="5.033" dur="1">Elmo: You okay, Chris?</text>
<text start="6.033" dur="1">Chris: I&#39;m good, I&#39;m good.</text>
<text start="7.033" dur="1">Elmo: You ready?</text>
<text start="8.033" dur="1.067">Chris: Yeah, I&#39;m ready. Oh, hey!</text>
<text start="9.1" dur="1.467">Red light&#39;s on. Hey, hi, everybody.</text>
<text start="10.567" dur="1.034">I&#39;m Chris.</text>
<text start="11.601" dur="1">Elmo: Oh, and Elmo&#39;s Elmo.</text>
<text start="12.601" dur="1.367">Chris: Mm-hmm, he sure is.</text>
<text start="13.968" dur="3.199">
I work at Hooper&#39;s Store right here on Sesame Street.
..
..
</transcript>

As far as I understood, not all YouTube videos with captions could be accessed with the above API call because their caption files had names. Then, I came across this user script which is useful if you want to download the captions file. The author had a snippet of code for retrieving the name of the captions file –


http://video.google.com/timedtext?hl=en&v=<VIDEO_ID>&type=list

this returned an XML with the name of the captions file. I used that to extend my API call to


http://www.youtube.com/api/timedtext?lang=en&format=1&v&<VIDEO_ID>&type=track&kind=&hl=en&name=<CAPTION_FILE_NAME></strong>

Then using JavaScript setTimeout function and the values of the start and duration of the captions, I do the synchronization of the captions and the video.

function showAppropriateCaptions(){
   var i,
     len = global_full_captions.length,
     currTime;
   //my_ytPlayer is the handle of the YouTube player
   if(my_ytPlayer.getPlayerState() == -1){
      return;
   }
   if(my_ytPlayer.getPlayerState() == 1){
      // State = 1 => playing video - so get the time and show appropriate captions
      // this will get triggered automatically when the video starts for the very first time
      currTime = my_ytPlayer.getCurrentTime();

      // to-do: a better way to handle hide show instead of doing at every iteration
      $('.myCaptionSpan').show();// the container having the captions
      $('#previous').show(); // the previous button 
      
      for(i=0;i<len;i++){
        if(currTime < global_full_captions[0].startTime){ 
          // if the captions has not started, call just before the first caption is scheduled
          setTimeout(showAppropriateCaptions, (global_full_captions[0].startTime - currTime )*1000);
          return;
        }
        if(currTime > global_full_captions[len-1].startTime + global_full_captions[len-1].duration){
          // it has ended, no more captions to show
          $('.myCaptionSpan').hide();
          $("#previous").removeClass('enabled');
          $("#previous").attr("disabled",true);
        }
        if((global_full_captions[len-1].startTime <= currTime && ((global_full_captions[len-1].startTime + global_full_captions[i].duration) > currTime))){
          // ugly workaround for showing the last caption
          if(!$('#previous').hasClass('enabled')){
            $("#previous").addClass('enabled');
            $("#previous").attr("disabled",false);
          }
          createBeautifulCaptions(global_full_captions[len-1].captions);
          setTimeout(showAppropriateCaptions,global_full_captions[len-1].duration*1000);
          return;
        }

        if((global_full_captions[i].startTime <= currTime && (global_full_captions[i+1].startTime > currTime))){
          // found the appropriate caption
          if(!$('#previous').hasClass('enabled')){
            $("#previous").addClass('enabled');
            $("#previous").attr("disabled",false);
          }
          createBeautifulCaptions(global_full_captions[i].captions);
          // now call the same function before the start of the next caption
          setTimeout(showAppropriateCaptions,
                     Math.abs(global_full_captions[i+1].startTime - global_full_captions[i].startTime)*1000);
          return;
        }
   }

}

Now, for every word in that particular line of the caption, I broke it up into span elements and attached click handlers to each. The span elements look like this

<p class="mycaption" >
<span id="beautifulCaptions0">to</span>
<span id="beautifulCaptions1">spend</span>
<span id="beautifulCaptions2">some</span>
<span id="beautifulCaptions3">good</span>
<span id="beautifulCaptions4">time</span>
<span id="beautifulCaptions5">with</span>
<span id="beautifulCaptions6">my</span>
<span id="beautifulCaptions7">good</span>
<span id="beautifulCaptions8">buddy</span>
<span id="beautifulCaptions9">Elmo</span>
<span id="beautifulCaptions10">over</span>
<span id="beautifulCaptions11">here.</span>
</p>

When a word is clicked on the captions, the showASL method gets called and the word string is passed as a parameter. After stripping the words of extraneous characters like !, &, ], [, ; etc and converting the word to lowercase, the method inserts an iframe on the right hand top corner whose URL points to

http://cats.gatech.edu/cats/MySignLink/dictionary/html/pages/<THE SELECTED WORD>.htm

The pages showing the ASL have flash videos embedded, so I have styled the iframe so that the flash video is at the center of the box. Some of the pages have just images and some may have both. Hence, I added the “Full Page View” button under the ASL box, so that viewers could see the entire page if they wanted to.

The SmartSign website covers around 25000 words and hence there will be words in the captions for which the ASL representation do not exist. For such cases, I get an image from Bing to substitute for the ASL.
The source code is undergoing constant refactoring, and would love to get more ideas on how to design a better solution.

What lies ahead for Open-Captions?

Currently, I am gathering feedback from hearing impaired users about Open-Captions and also getting thoughts on what additional features they would like. Harley, the researcher at CATS, is excited about this project too and reaching out to more people for feedback.
Another idea is to build Open-Captions as the “Khan Academy” of ASL, by having videos that enable different levels of learning of ASL.


JavaScript Notes – 2

Posted: October 21st, 2011 | Author: | Filed under: technical | Tags: | 1 Comment »

In this blog post, I am introducing Custom Constructor functions, a method for “Classical Inheritance” in JavaScript and Prototypal inheritance in JavaScript. The knowledge in this post is condensed from Stoyan Stefanov’s book JavaScript Patterns.
While trying to understand Prototypal inheritance in JavaScript, I realized that I needed to grasp the above concepts strongly. So hence this post touches upon a breadth of topics.

Custom Constructor Functions

3 ways of creating objects in JS –

var myObject1 = {}; // literal notation
var myObject2 = new Object();
var myObject3 = new MyConstructor(); // custom constructor

The third way is what we are interested in currently. So, it looks the same as we would do in Java to create a new object of a class MyConstructor. Below is one way that the function MyConstructor can be defined. (Do remember that MyConstructor is a function at the end of the day. The capitalized first letter is a coding practice to differentiate custom constructors from functions)

var MyConstructor = function(name){ 
    this.name = name;
    this.hello = function () {return "Hello "+this.name;};
}
var obj = new MyConstructor("nadu");

When we call MyConstructor with new, 3 things happen inside the function

  • An empty object is created and referenced by this variable, inheriting the prototype of the function.
  • Properties and methods are added to the object referenced by this.
  • The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).

In the above example, the hello was added to this. So each time new MyConstructor gets called, a new function hello is created in memory. Since the method hello does not change from one instance to another, we can add that to the prototype of MyConstructor.

MyConstructor.prototype.hello = function(){
    return "Hello "+ this.name;
}

A prototype is an object and every function you create automatically gets a prototype property that points to a new blank object. You can add functions to the prototype and they will be accessible to all the objects created using new MyConstructor()

There are 2 different ways inheritance (code-reuse) can be done in JavaScript. One is to create classes to emulate the typical (class-ical) inheritance and the other is using the prototypal nature of the language.

Classical Inheritance

This can be implemented in JavaScript based on custom constructors. Below is just one pattern (simplest) of implementing classical inheritance. Refer to the book for different implementations.

// parent constructor
function Parent(name){
   this.name = name || "Adam";
}
// add functionality to the prototype
Parent.prototype.say= function(){
    return "Hello "+ this.name;
}

The hidden link __proto__ points to the prototype property of the constructor function that created that object.

//child constructor
function Child(){}

//inherit - C will have access to P's properties
inherit(Child,Parent);

var kid = new Child();
console.log(kid.name);//"Adam"
console.log(kid.say()); 

// here is how inherit is defined
function inherit(C,P){
    C.prototype = new P();
}

Working Example on JS Fiddle

Prototypal Inheritance

In Prototypal inheritance, objects inherit from objects. You have an object that you would like to reuse and you want to create a second object that gets functionality from the first one.

var parent = {
    name:"Parent"
};

// the new object which inherits parent
var child = object(parent); 

console.log(child.name); // Parent
console.log(child.prototype);
console.log(child.__proto__);


// here is how object is defined
function object(o){
    function F(){};
    F.prototype = o;
    return new F();
}

An important thing to understand is that the child.__proto__ points to the parent object. The __proto__ link points to the prototype property of its parent constructor which was the temporary function F. The __proto__ link is what makes the interpreter check for the property name in its parent.

The console output showing the values of child.name, child.prototype, child.__proto__


Rest in Peace Steve Jobs

Posted: October 6th, 2011 | Author: | Filed under: technical | Comments Off

The man who was and always will be an inspiration to everyone. Rest in Peace.

Steve Jobs

Image Credit: Diana Walker


I am guilty of screen scraping

Posted: October 2nd, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

I love data visualization. I am inspired by the fact that India has a wealth of data that can lead to wonderful visualizations that can help Government officials, politicians, journalists, social workers do their daily jobs better. Even the average citizen should be able to see the visualization and understand what’s going on and maybe get inspired to be a more responsible citizen.
I am on the constant lookout for Government data that is openly accessible and see if I can do something interesting with it. That led me to build this visual guide of elected representatives of India and this blog entry comparing corruption at the higher levels and by average citizens
There are a lot of websites (usually run by NGOs) that have data about Indian politicians and their details (education, criminal records, attendance in the parliament, participation in the parliament etc). This website has data on criminal records that made me interested. I emailed them asking (hoping) if they have any APIs that can be used to access the data, but I guess that is not high on their priority list. However, what they had was data arranged in HTML tables and lots of pages numbered serially. So I got into screen scraping mode and scraped out information of around 7800 candidates who stood in the elections in the Indian General Elections in 2009. Now, I have their educational qualifications, criminal records, total assets and liabilities (some have really obscene numbers) in my database.
The goal is now 2 fold.

  1. Create a simple visualization on the map of India to show educational qualifications, assets information and criminal cases of these candidates. Give the ability to filter by party, state. So viewers can see which areas had more educated candidates, which had more criminal candidates and where did the richest candidates come from.
  2. While creating the above goal, ensure that the API to access data is well written so that it can be exposed to other developers interested in building more cool visualizations.

This should be fun.


Open Captions

Posted: September 11th, 2011 | Author: | Filed under: technical | Tags: , , , , | 12 Comments »

[Updated with the latest status of Open Captions project]

I started building Open Captions for the Hackday TV hackathon at General Assembly.

Open Captions gives the viewers, the ability to search and view closed captioned YouTube videos. While watching the video, the viewer can select individual words of the closed captions and then see an American Sign Language Representation of the word on the screen. The viewer can also jump back to the previous caption showed on the screen. Whenever, a word is selected, the video automatically pauses when the ASL is showed on the page. The working prototype can be seen on Open Captions

Currently the project is a work in progress, and is susceptible to fail at a few places. Please feel free to email feedback, ideas, suggestions about Open Captions.

The ASL representation is just one of the use cases of Open Captions. This can be linked with Google Translate to find out words in other languages (very useful for people for whom English is not the first language). This can also be linked with say Wikipedia and children can learn about a word or a place spoken about on TV.

This idea of selecting words from closed captions also works for videos from Universal Subtitles, an initiative which helps create closed captions for videos on the Internet. Open Captions example with Universal Subtitles

Reference
The ASL representations are being scraped from www.cats.gatech.edu, which has around 25000 words shown in ASL in 25000 web pages.


My new friend Marvin

Posted: September 6th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

Given my anti-social tendencies (read not logging on to Facebook for 3 months at a stretch), I decided that I needed a new friend.

My Friend Marvin

My Friend Marvin

Marvin (the paranoid android) is built out of waste thermocol (that came with the packing of my monitor). It has a small red breadboard attached as it’s heart. The light on the heart glows green if there are more tweets with positive sentiment going around in the (All izz well) and glows red if there are more tweets with negative sentiments going around in the virtual world. (I took about a handful of words like “environment”, “plastic”, “global warming” etc. as the baseline hashtags to be analyzed for sentiments) More on the implementation of the Arduino controlling the LEDs can be found in the Project Cycles post here

My last Labor Day weekend project was drawing this, I am happy that the trend of doing something I love during the long weekend has continued.


JavaScript Notes – 1

Posted: August 19th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

My notes on JavaScript Patterns. This is just a part of the patterns covered by Addy Osmani and those covered by Stoyan Stefanov

**Disclaimer**: The code examples below are modified examples from JavaScript Patterns

Namespaces
Using global variables and functions in JavaScript can lead to smashing of variables as the code base grows. So a simple way of handling namespaces is

var NxJ = {};
NxJ.property1 = "Name is Nadu";
NxJ.method1 = function(){console.log("name is bond, james bond");}

// if you want to add modules
NxJ.modules.module1 = {};
NxJ.modules.module1.data = {"a":1,"b":2};

var moduleToBeUsed = NxJ.namespace("NxJ.module1.module2.module_n");

The variable names keep getting larger and larger. A way to handle this is to create a function called namespace, that can parse the module name and return only that module with all the methods. Useful when you are using big libraries like YUI (they have different modules for DOM, Events etc)

Private properties, Module and Revealing Module
By default everything is public

var myObj = {
	myName : “Nadu”;
	getName = function(){
		return myName;
	}
};
console.log(myObj.myName); // accessible

So a way of fixing this is

myObj = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	return: // yes return an object
	{
            getName = function(){
               return myName;
            }
	};
}());

console.log(myObj.myName); // inaccessible now
console.log(myObj.getName()); // this is the right way to get it

Points to note -

  • Immediate function call – so what value does myObj get?
  • var before myName makes it private because of closure
  • getName is a privileged function

Lets add namespaces now,

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;

	return:
	{
              getName = function(){
		   return myName;
	      },
	      setName = function(n){
			myName = n;
              }
	};
}());

So that’s the Module pattern!
Since we have reached alive till here, we will jump to the Revealing module pattern, which is nothing but a simple extension of the Module pattern.
In the Revealing module pattern, you define all the properties as private in the object and then return only those that you want to be made public

var NxJ = {};
NxJ.coolModule  = ( function(){
	// a var before myName - makes it private
	var myName = “Nadu, the Private”;
	var yourName = “Someone else”;
        var getName = function(){return(myName);};
	var setName = function(n){ myName = n;}

	return:
	{
		getName: getName,
		getTheAwesomeName: getName // sort of an alias!
	};
}());
console.log(NxJ.coolModule.getName());
console.log(NxJ.coolModule.getAwesomeName()); // this works too

There are 2 advantages of this pattern, one is that it’s a little more cleaner than the Module pattern and two you can have these aliases. One can create a JavaScript API and then just return all that is public.

Be careful!

var NxJ = {};
NxJ.coolModule  = ( function(){
    // a var before myName - makes it private 
    var student = {"name":"Nadu", "age":"18-till-i-die"};
    var getStudent = function(){ return student; }    
    
    return    {
        getStudent: getStudent
    };
}());
var stud = NxJ.coolModule.getStudent();
console.log(NxJ.coolModule.student); // not possible
console.log(stud.name); // says Nadu
stud.name = "Narayanan Ramakrishnan"; // trying to modify it
var stud2 = NxJ.coolModule.getStudent();
console.log(stud2.name); // prints Narayanan Ramakrishnan - Hey WTF ?

This is because for arrays and objects, JavaScript returns the reference, so its accessible to anyone who has the reference. So one way of handling this is to return a new object that has properties that the caller is interested in. Called the Principle of Least Authority which states that you should never give more than intended. One way of doing this in the example above is, instead of giving the caller everything, you can break it down into functions getName(), getAge(). There is another approach using a general purpose cloning function, but that will be covered later.

More notes to follow in another post.
Further reading
A beautiful explanation of Module Pattern by Twitter engineer Ben Cherry
Signing off treat – www.jsfiddle.net


Project Cycles

Posted: August 13th, 2011 | Author: | Filed under: technical | Tags: , | Comments Off

The weekend of August 5th -7th 2011 was one of the most memorable weekends in recent times. I was participating at the Art Hack weekend organized by the Creators Project at Eyebeam. It was a  two-day, open-source hackathon (hacking+marathon) that celebrates new artistic experiences.

The goal: We were to design, code and prototype projects that re-imagine the way people create, consume, and interact with media.

tl;dr – Jump to straight to video
The participants (around 75 in number) met up on Friday at Eyebeam to socialize and form teams. Each of us introduced ourselves and talked about our skill sets (what we brought to the table) and also mentioned any ideas they had in mind for the weekend. It was very exciting for me as it was the first time I was participating in a hackathon that involved people other than just developers. It was a wonderful way to understand and see things from a different perspective. After the round of introductions we were “left loose” to mingle around and talk to people with whom we wanted to collaborate for the weekend. I had no particular idea in mind, but my criteria was 4-fold.

  • Work on something interesting for the weekend
  • Get out of my comfort zone
  • Work on something that would increase social awareness and make people think
  • Have :awesome: fun

One of the participants, Mark Stafford, a fine artist by profession, said that he wanted to work on an art installation made up of waste material. That triggered a bell for me as I am interested in waste management, recycling and all that good stuff. Soon, Mark, Meredith and me were sitting and threshing out our idea for the weekend. It took us to about 5-10 minutes to decide that the idea was something all of us wanted to invest our time and energies in.

So here is the idea and what we wanted to build -

We as a race are progressing at pretty good speed on the technology front. We keep building more and more devices, connect more and more in the virtual world, get more and more impacted by the technology around us. All this progress does leave something behind. Project Cycles, is an attempt to describe the life cycle of our digital, virtual and physical environments.The installation – a dying rabbit, signifying the flip side of technological progress, would be a living, breathing form that conveys this message. It carries the burden of the ill-affects of technological progress. We wanted to create an interactive art installation that would react to the environment around it as well as well to the virtual world beyond it. When people would come near it, it would start breathing heavily. The ears of the rabbit would twitch based on the sentiments of the tweets going around the virtual world about things like #recycling, #electronic waste, #environment.  The legs would move involuntarily would be depending on how the leading technology companies are doing on the stock market that day. The eyes would play a flashback of the dying rabbit’s life, when it used to live in a more greener and cleaner planet.

We started sketching some of our ideas on Friday night itself and Saturday morning we had started to put the pieces together. Mark and Saaid (he joined us on Satuday) started building the exoskeleton of the model. Meredith and me were handling the movements of the rabbit based on its sensing of the environment.

If the details below get too technical for you, you can jump to the end here.

The “technical” parts of building the model consisted of mainly 4 things -

- Getting the sentiment analysis of the tweets on relevant topics like environment, recycling etc., pushing those values to an Arduino controlled motors so as to make the ears twitch.

- Using a sonar sensor to sense proximity of the people around it. If someone is very close by, the rabbit would start breathing heavily.

- Connecting a 2nd generation iPod to show the “flashback” of the dying bunny’s life. The iPod would be playing scenes from Animal planet.

- Getting the live stock market feeds of leading technology companies and control the movement of the legs based on their fluctuations.

We were able to implement the first 2 ideas above in the given timeframe of 24 hours and left the other 2 for version 2.0. I was in charge of the getting the sentiments of the tweets and passing to an Arduino and this is how I built it -

Googling for “twitter sentiment analysis” gives out a lot of results and the one that I used was this. What this does is take the last 100 tweets and run a supervised learning algorithm on them to analyze the tweets. The tweets are marked as “positive”, “negative” or “neutral” and then the final sentiment index is calculated based on them.
They have a super simple API call and all I had to do was write a php script to call their API with the parameters. It returns a JSON object which has the analysis of the individual tweets:

{
    "sentiment_index": 22,
    "results": [
        {
            "created_at": "Mon, 15 Aug 2011 00:26:55 +0000",
            "from_user_id_str": "360406363",
            "profile_image_url": "imgUrl"
            "from_user": "alissawehingec",
            "id_str": "102899029364588544",
            "sentiment": -1,
            "metadata": {
                "result_type": "recent"
            },
            "text": "Rain gardens: A practical solution for water pollution"
            "to_user_id": null,
            "id": 102899029364588540,
            "from_user_id": 360406363,
            "geo": null,
            "iso_language_code": "fr",
            "source": "http://twitter.com",
            "to_user_id_str": null
        },...
        //99 more such elements
        "positive": 16,
        "negative": 72,
        "neutral": 12,
        "tweets_analyzed": 100

This is what my php script to make the call looked like

		$topics = array("recycle","plastic","ewaste", "environment","planet","global%20warming","prakriti", "risaikuru", "earth");
		$max = count($topics)-1;
		$index =  rand(0 , $max );
		$url = "http://data.tweetsentiments.com:8080/api/search.json?topic=".$topics[$index];
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url );
		curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
		$result = curl_exec( $curl );
		curl_close($curl);
		$result = utf8_encode($result);
		$data = json_decode($result, true);
                // to get the actual values of the sentiments
                $sentiment_index = intval($data["sentiment_index"]);
		$negative = intval($data["negative"]);
		$positive = intval($data["positive"]);
		$neutral =  intval($data["neutral"]);

Once I had the values, I needed to push these values to the Arduino over the Serial port. I was able to use the guide here (I am running Ubuntu) to connect the Arduino and send data over serial using php.
It took me a long time to get this running. All I needed to do was to send 4 key value pairs (index,value). Finally the way I got it to work was to send data encoded in ASCII format (well now it sounds so obvious!). The Serial.read() command of Arduino reads the values that it gets as ASCII values. So for example, the character ‘a’ sent over serial would be read as 97 by Serial.read(). So I had to send numbers (the values) which I encoded in ASCII and sent. So if the value was 62, I sent the value as if it was the character ‘>’ (using the chr() method of php). Here is the code -

                // the protocol followed was s/p/g/n preceded the values
                // the characters s,p,g,n acted as flags
		$serial->sendMessage('s');
		$serial->sendMessage(chr($sentiment_index));
		$serial->sendMessage('p');
		$serial->sendMessage(chr($positive));
		$serial->sendMessage('g');
		$serial->sendMessage(chr($negative));
		$serial->sendMessage('n');
		$serial->sendMessage(chr($neutral));

Final php file can be downloaded here and the Serial class can be found here.
On the Arduino side, this code below reads the bytes sent over the Serial port and if it gets an ‘s’, it reads the next byte which is the value of the sentiment index, if it gets a ‘p’, then reads the next byte which is the value of the positive tweets,.. so and so forth


int neutral, positive, negative, sentiment;
void loop() {
   if(Serial.available() > 0) {
    number_in = Serial.read();
    if(number_in == 112){ //p
      // its the positive number of tweets
      positive = Serial.read();
      Serial.println(positive, DEC);
    }
    if(number_in == 115){ //s
      // its the sentiment index of tweets
      sentiment = Serial.read();
      Serial.println(sentiment, DEC);
    }
    if(number_in == 110){ //neutral - m
      // its the neutral number of tweets
      neutral = Serial.read();
      Serial.println(neutral);
    }
    if(number_in == 103){ // negative - g
      // its the negative number of tweets
      negative = Serial.read();
      Serial.println(negative);
    }
  }
  else{
      Serial.println("Still waiting for serial");
  }
    delay(300);
    number_in = 0;
}

The final Arduino file
Now that I have the values on the Arduino side, I can manipulate the rotation of the servo motors that control the movement of the ears.All we wanted to achieve was to move the left ear slowly (harmoniously) and the right ear violently. Due to lack of time I did not do any great mathematical manipulation, so it was just random servo movements in a loop.
PS -The final php and arduino files can be downloaded here. I wrote a similar version for sending data over serial in python (but it runs only once)
Meredith handled the part of the proximity sensing and making the dying rabbit breathe faster. Mark and Saaid were instrumental in building the model. It was fantastic work in limited amount of time. In the end, the 4 of us were happy to have been a part of it!

Here is the final video of Project Cycles that we presented

Yes, it was indeed one of the best weekends ever! I happened to meet a whole variety of people – artists, designers, developers and actually spent time building something tangible. There was this sense of elation even though we did not win. These were the other projects in the Art Hack.


ASL Dictionary Greasemonkey script v0.1

Posted: April 15th, 2011 | Author: | Filed under: technical | Tags: , | 1 Comment »

Research says that around 90% of hearing impaired children are born to hearing parents. So if parents do not know Sign Language then it is difficult for the child to learn ASL quickly. Wouldn’t it be great if people could learn sign language on the fly when they are reading articles on the web? Maybe they are reading stories to their children from a website and they can have ready assistance to translate words in written language to Sign Language. So, I thought of creating a simple Greasemonkey script that would show the ASL equivalent of a selected word.
Center for Accessible Technology in Sign at GeorgiaTech has a huge database of words and their American Sign Language equivalent. I used their web pages that they had created for around 25000 words. Whenever a word is selected, I load the ASL equivalent in an iframe on the right top corner of the page.

To Install

Here are the steps to try it on Firefox

  1. Open Firefox (version 3.0 – 4.0.*)
  2. Install Greasemonkey if you are using Firefox
  3. Click on this link to download the script
  4. Let Greasemonkey install the user script.
  5. Now open any webpage say – Wikipedia entry on ASL
  6. Now select any word (not phrases/sentences) – for example – Sign, Language, also, common, English or languages

You will see the American Sign Language representation of the word on the top right.
If a word that does not exist in the database is selected then, it shows “Sorry word could not be found”.

Here are the steps to try it on Chrome

  1. Open Chrome
  2. Click on this link to download the script
  3. Let Chrome install the user script.
  4. Now open any webpage say – Wikipedia entry on ASL
  5. Now select any word (not phrases/sentences) – for example – Sign, Language, also, common, English or languages

You will see the American Sign Language representation of the word on the top right.
If a word that does not exist in the database is selected then, it shows an error message.

An example, with the word Languages highlighted

Another example, with the word Sign highlighted

The representation automatically hides after 5 seconds. (So if you click on another word before 5 seconds, the results may be buggy)
Update

To Uninstall
To uninstall on Firefox, click on the Greasemonkey icon and disable the ASL Dictionary.
To uninstall, open chrome://extensions/ and disable the ASL Dictionary.

For future versions
1) If you select a phrase, it shows the sequence of signs
2) Fix “Word not found” error in Chrome
3) Ability to select the word, right click and have the option to play the video or the cartoon


ns2.34 setup on Ubuntu Lucid Lynx 10.04

Posted: September 17th, 2010 | Author: | Filed under: technical, Uncategorized | Comments Off

Setting up ns2 on Ubuntu (Lucid Lynx 10.04),

$ sudo apt-get update
$ sudo apt-get install build-essential autoconf automake libxmu-dev libxt-dev libxt6 libsm-dev libsm6 libice-dev libice6 vim

Download ns-allinone.2.34.tar.gz – http://sourceforge.net/projects/nsnam/files/allinone/ns-allinone-2.34/

$ tar -xvzf ns-allinone.2.34.tar.gz
$ cd ns-allinone.2.34/
$ ./install

You might hit the error
otcl-1.13 make failed! Exiting

Solution
in otcl-1.13/configure file -
replace

Linux*)
SHLIB_CFLAGS="-fpic"
SHLIB_LD="ld -shared"
SHLIB_SUFFIX=".so"
DL_LIBS="-ldl"
SHLD_FLAGS=""
;;

with

Linux*)
SHLIB_CFLAGS="-fpic"
SHLIB_LD="gcc -shared"
SHLIB_SUFFIX=".so"
DL_LIBS="-ldl"
SHLD_FLAGS=""
;;

This should work now.
Note for this to work the CC value in Makefile.in inside otcl folder should be @CC@. It did not work when I changed it to gcc 4.3
Hope this helps