Sunday, December 30, 2012

Backup and Restore using MySQL Workbench


Not so recently, I installed MySQL Workbench on my local system for a personal project. I had installed it a long time ago and it seems that after Oracle's acquisition of MySQL, they have made quite a few changes to the setup. Especially the bundle that you can install now contains examples and MySQL server and the MySQL workbench.

One nice feature about this new bundle is that you don't need to install additional software if you already have MySQL workbench installed. Earlier, you had to install MySQL admin to do a backup and restore of your system. Now its a bit more simplified since everything is accessible from within MySQL workbench itself.

In this post, I am just going to show the steps involved in using the new MySQL workbench (the one that I have is MySQL Workbench 4.2.44 CE) to take a backup of your database in a simple text file and then later use the same text file to restore your database to a prior state.

My MySQL database is on my local system, uses the standard port 3306 and is at its default install state at the moment. The screenshot of the homepage looks like this.



In order to take a backup of your database, you need to focus on the Server Administration section of Workbench and select your MySQL server from the list of servers displayed.

Once you do that, you are taken to a page where it shows you details about the health of the server and the different operations that you can perform on the this instance of your MySQL server.



Since you want to take a backup, you need to select the option that is circled in red that lets you import and export data.

Lets first export our data. Its pretty easy, select the database and then the tables from that database of which you want to take a backup.



For small projects, its convenient to take a backup in a single file. This file will contain all the sql statements that can be used to backup all the data and structure of you schema. Most of the times, you might want to take a backup of only the data, but not the schema. If you are taking a backup of the schema, it just means that when you use the file to restore, it will try to recreate the tables if the they don't already exist. However, if you don't want this extra detail to be present in your backup file, and only want backup of the data, an option in the advanced tab lets you do that.



Once  you are done mixing and matching all the options, click on the Export progress tab and then click on Start Export.



That's as easy as it gets to take a backup of your MySQL database.

Restoration is an equally easy process. Just select the file that you want to use as the restoration file and click on start import. And you are good to go.



Pretty neat, although I do believe a few more changes to the interface could make some things more obvious.

Hope this helps!


Happy Programming :)
Signing Off 

Ryan

Thursday, December 20, 2012

Git : Editing A Previous Commit

When you work with Git, making branches is a very common task and when you are flooded with ideas, you  may be in a hurry and sometimes make mistakes. The most common example of making mistakes when committing in git is - the commit message. Sometimes, just after committing, you would realize that you forgot to mention something crucial.

Sometimes, it may also happen that when you create your commit, you might accidentally forget to add a particular file to the commit. Even this is a likely scenario since git does not automatically add new directories under version control when you add them through your local file system. So if you did a git add . during your first commit and then created lots of subdirectories and files, they will not be added automatically just because you had done an initial "git add .".

Well, there is one small source of relief - and that is - you can easily amend the last commit in git and fix these tiny issues. For example, let us say that you just committed with a very nonsensical and convoluted message. like this

git commit -m "I was so drunk when I wrote this shit".

And then, the next morning when you wake up, you do a git log and you see this message pop up on your screen and jump out of your seat. Well, if you have not pushed your changes upstream, i.e. the commit still resides only on your local repository, it would really serve a noble purpose if you actually make the message more sensible. Here's how you can do that.

git commit --amend -m "This commit has all the equations that prove the String Theory"

The above command will simply edit the commit message of the latest commit.

However, if you have done something more grave, like missed out on files that were supposed to be added in the previous commit, then you can simply add them using the git add . command then use the git commit with the --amend option in the same way as shown above. Basically what you did was that you rebuilt the tree that represents the files of this commit, discarded the previous commit and created a new one in its place. You can say so because when you amend a commit, it results in a new commit checksum.

Hope this helps!

Signing Off
Ryan

Wednesday, December 19, 2012

Timer Chaining in JavaScript

Only recently, I was working on a project where I had to implement a feature that is usually implemented using gif. What I had to do was to cause 4 images -  lets say 1, A, B, C overlayed on each other to display sequentially. And then, after the first set of 4 images have been displayed, have a similar sequence repeat, but with only the first image changed, i.e. 2, A, B, C. And then the third set - 3, A, B, C.

Now, since the sample that I had to replicate was made in gif, I presume that creating such an image using an image editing software is pretty easy. My task was to replicate this effect using pure javascript. Moreover, since it was only in the development phase, I had to design for flexibility, since requirements can change at any moment of time. Thankfully, for me, designing for flexibility is a huge turn on. Albeit inititally difficulty, the immense amout of satisfaction that you gain out of it when you see the requirements change and be able to tell your clients that you can implement the changes in like 10 seconds is totally worth the time and energy that you put in during the initial development phases.

For my experiment, the flexibility that I had to incorporate was to be able to change the duration for which each of the 4 images can be displayed if the requirements changed. Had it been a gif file, it wold have been an easy task, just change the time in the application and then it would be ready. Show the client, and if its not what he/she wants, then redo the same.

I wanted to achieve something similar in JavasScript. However instead of a tool I wanted to create a system wherein you can programmatically configure the time duration for each image and then automatically have the effect ripple throughout all the sequences of images.

Also, instead of restricting the system to that of 4 images, I wanted it to be extensible such that it would be able to incorporate any number of images that could be overlaid on top of each other. Also, I wanted the system to behave in a way that incorporates a slightly different functionality - not be restricted to images being overlaid.

So, ultimately, after thinking about all the flexibility that I wanted to incorporate into the system, it turned out that what I wanted to create was a system of timers such that each timer could be chained to each other yet they would be oblivious to characteristics of the next timer. Also, these timers would have a feature that would let them bind the timer ending function for the next timer without knowing what the function does. And the beauty would be that each of these functions can be chained to an infinite level.
So, how did i proceed to make such a system.

First things first.
I designed the system as a phase based system. Since I had 4 images in my sequence, I created a object that saved the properties of 4 phases and references to the functions that would be invoked on the terimination of each function. I called this object a phasedTimeout object, which is essentially nothing but a nested object.

The first thing that I did was - created an object that contains all the values for which i want each of the phases to execute.

var settings = {
  duration1:2000, //Millisecond duration for the first timer
  duration2:300, //Millisecond duration for the second timer.
  duration3:300, //Millisecond duration for the third timer.
  duration4:300, //Millisecond duration for the fourth timer.
 };


In the next part, I define the different phases, and the functions that can be executed at the end of each phase.

var phaseTimeouts =  {
  'phase1':
   {
    duration:settings.duration1,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase2':
   {
    duration:settings.duration2,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase3':
   {
    duration:settings.duration3,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase4':
   {
    duration:settings.duration4,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
 }


And then, finally on window loading, ( because it was part of my requirement to do all of this only after the images on the page have loaded), i created a function that chains together the different phases.

var timeOutSetter = function(){
  
   //Call the terminating function of the previous phase
   phaseTimeouts['phase'+currentPhaseId].end(currentPhaseId);
   
   //If there is anything left in phaseTimeouts array
   //create a new timer and update the new timerId
   var nextPhaseKey = 'phase'+(currentPhaseId+1);
   if(phaseTimeouts[nextPhaseKey]){
    currentPhaseId++;
    console.log('Entering Next Phase : ' + nextPhaseKey);
    currentTimerId = setTimeout(timeOutSetter,phaseTimeouts[nextPhaseKey].duration);
   }
  };


The above function does nothing but chains the different timers together by using the settings from the phaseTimeouts object. The variable phaseTimeouts is a misnomer since it captures more than just the timeout, and can perhaps be used to bind extra functionality.

For my experiment, I toggled the visibility of different images inside the 'end' function of each of the phases. But the fact that  you can have any number of phases and that each phase has a different function that handles the phase end that is independent of each other makes it all the more useful.

Below is the piece of code in its entirety


$(function(){

 var settings = {
  duration1:2000, //Millisecond duration for the first timer
  duration2:300, //Millisecond duration for the second timer.
  duration3:300, //Millisecond duration for the third timer.
  duration4:300, //Millisecond duration for the fourth timer.
 };
 
 var phaseTimeouts =  {
  'phase1':
   {
    duration:settings.duration1,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase2':
   {
    duration:settings.duration2,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase3':
   {
    duration:settings.duration3,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
  ,
  'phase4':
   {
    duration:settings.duration4,
    end : function(currentPhaseId){
     console.log('Ending phase : '+ currentPhaseId);
    }
   }
 }
 
 //Once all the contents of the window finishes loading, start the slideshow
 $(window).load(function(){
  
  var currentPhaseId = 1;
  var currentTimerId = 0;
  
  var timeOutSetter = function(){
  
   //Call the terminating function of the previous phase
   phaseTimeouts['phase'+currentPhaseId].end(currentPhaseId);
   
   //If there is anything left in phaseTimeouts array
   //create a new timer and update the new timerId
   var nextPhaseKey = 'phase'+(currentPhaseId+1);
   if(phaseTimeouts[nextPhaseKey]){
    currentPhaseId++;
    console.log('Entering Next Phase : ' + nextPhaseKey);
    currentTimerId = setTimeout(timeOutSetter,phaseTimeouts[nextPhaseKey].duration);
   }
  };
  
  var currentTimerId = setTimeout(timeOutSetter,phaseTimeouts['phase1'].duration);
  
 });
 
});


Decoupled designs can be so addictive, is'int it?

Signing Off
Ryan


Thursday, December 13, 2012

Git : Status Of Working And Staged Files

I just came to know about this very neat feature of the git status command.

Basically, the status command gives you the the names of the files which you are tracking but have certain changes in them relative to your last commit.

Now, Git has 3 places in which it keeps the code - the commit area, the stage area/index and the working directory.

Lets take a few scenarios to explain the usefulness of this command




Scenario 1
Lets say that you have a file called Sample_File.txt in the working directory to which you made a few changes. But you have not staged it yet. So, the state of the file in the three repositories can be described as  (latest commit == staged)  != (working).

To know which files have been modified in the working directory, in a very shorthand form, use git status with the -s option. Here's what I got when I ran it on my system.








Notice that the M is in Red, and there is a little bit space to its left, which means, that the file is modified in your working directory. (The extra space is explained in scenario 2)
The status code M stands for 'Modified'. There are many other one letter status codes that you can take a peek at over here.



Scenario 2
Lets say that you have a file in your working directory, that has some changes but you staged it after making these changes.
In this case the state of the file in the three repositories can be described as  (latest commit)! = (staged  == working )

Now if you run git status -s, this is what you get







Notice that the M is in Green, but this time there no space to its left, which means, that the file is in a modified state in your staged directory. You can however notice that there is some extra space between the M and the file name this time. (Will be clarified in Scenario 3)



Scenario 3
Lets say that your made changes to your file, staged it and then edited it again. 

In this case the state of the file in the three repositories can be described as  (latest commit ! = staged  != working )





Now you can see clearly that you have 2 M's. One in red indicating the state of your file in the staged area and one in green indicating the state of your file in the working directory.



Its quite common that throughout your workflow, you would find yourself moving between the above scenarios sequentially. (Scenario 1 -> Scenario 2 -> Scenario 3) . The above set of commands should be able to help you keep track of what files were changed where.




References
The git manual reference

Signing Off 
Ryan

Wednesday, December 12, 2012

Using Google Drive As A Web Host

Okey, another one of my experiments. I came to know a few days ago that Google officially announced how you can now use your Google Drive account as a web host.

So, I decided to make use of this awesome new feature and tried to create and host my profile on Google Drive itself. In this post, I am simply going to tell you what you need to do to get up and running with Google Drive as your web host in its simplest form.

Things that you need to do to setup Google Drive as your web host


  1. Go to Google Drive
    Of course, you gotta have a Google account to begin in the first place and then just type in drive.google.com

  2. Create a public folder
    This is important. If you want to use Google Drive as a web host, you need to keep your files in a public directory. Create a new folder and then simply choose the 'share' button and give it public access. Lets assume my folder is called 'ryan'

  3. Dumping your static files
    Lets say that your site has a lot of html pages, css stylesheets, jQuery, javascript, images - the usual stuff. Just add all your files in the same directory structure in which they are present in your local system to the public folder that you just created. So, all my files are dumped into the public folder called 'ryan' in my google drive.

  4. Naming convention
    Ensure that at least one file in the public folder is named as index.html. This will act as the landing page for your site.

  5. What to publish
    Now comes an important step. In order to share your site, you need to share a link to the public folder. Initially I thought that you would need to share the link to the index.html but that did not work as expected.
    So what you need to do is,  note the google drive file-id of your public folder. To do that, just open your public folder in google drive. By default it lists all the files in that folder. In the url at the top, you will see that it contains a long string of garbled aphanumeric characters after the last slash. That is your folder id. Copy it.

  6. Creating a url to publish
    Now all you need is a url that points to your folder. To create your url, simply append the file id to the following string - http://googledrive.com/host/

    For eg. The raw link to my profile on google drive is http://googledrive.com/host/0B87xZT3F0rDcZlVONVRVY3QtZFE



And that pretty much does it. Clicking on the above URL serves the index.html page of your public folder. 


Other Tips

  1. If you want to use a neat little name instead of the long string of garbled alphanumeric characters that appear at the end of the url, go to Gdriv.es and convert your folder id custom name. That's what I did for my profile, and now it looks like this - http://gdriv.es/ryansukale. Much more neat i'd say.
  2. Sometimes its just easier to download Google Drive for the desktop, edit your files right in your local machine and then watch them automatically get uploaded.
  3. When multiple pages are interlinked, I have observed that the url in the address bar remains the same. So, I guess bookmarking will be an issue in this case.


Signing Off 

Ryan

Monday, December 10, 2012

Handling Page Unload Using JavaScript

Recently for one of my projects, I was working on trying to implement some functionality wherein if the user tried to leave web page by any other means other than submitting a form, (s)he would be prompted for confirmation. It was part of one of the research experiment surveys that I was designing. So, if the user left the page, we would simply discard the user's responses as invalid because partial responses are of no use to do any meaningful analysis.

Apparently, there are plenty of ways in which a user can close a webpage - the back button, the close button, or maybe some other gestures that I might be unaware of that are present in some of the newer web-browsing applications/devices.

What I found interesting was that there is a very simple and convenient way to check when a page is being 'unloaded' from a browser window. Javascript lets you bind a neat little handler to the 'window.onbeforeunload' property which tells the runtime that a web page is going to be unloaded.

Being a jQuery fanatic, I usually tend to use jQuery for all such stuff, since it makes maintenance a far easier task than writing pure JavaScript. So, my jQuery instincts told me to use the new on method to bind an event handler to the event. And it did work pretty good. All I did was this -

window.onbeforeunload = function(){ return "Are you sure 
you want to leave the page?"; };

Oh, I am sure that message looks familiar on many marketing sites. You can be assured that I am not creating one more such website. In fact, even the message that I displayed was  something completely different. This is just meant to be a sample.

Easy peasy, and that works. Now, the issue comes when the user actually submits the form. The issue is that this function fires if the user leaves the page in any way, which does make a lot of sense, because after all, the user is leaving the page.

However, what I did not want was for the function to fire when the user submitted the form. So, what did I do? I just created a submit handler for my form and then tried to unbind the event handler using the off function of jQuery.

Neat as it may sound, that did not work. I am still not sure why. However after going through a couple of posts wondering what I had done wrong, it dawned on me that a better way to handle this feature was to both bind and unbind an event handler for this function directly using pure JavaScript.

So, this is what i eventually ended up doing
 //For binding
 window.onbeforeunload = confirmExit;
 function confirmExit()
 {
  return "Are you sure you want to leave this page?";
 }
 
 //For unbinding
 $('#myForm').submit(function(event){
  window.onbeforeunload = null;
 });

And that's pretty much all it took to create a page that warns the user before (s)he accidentally (or intentionally) attempts to leave a web page.

Also, after completing my piece of code, i stumbled across this jQuery unload function, that I beieve pretty much does the same thing.

Signing Off
Ryan

Change Image Resolution in Powerpoint

Recently for one of my projects a teammate had created a simple Powerpoint presentation , the slides of which we later decided to use as a mockup for a website.

We wanted to make a video using these slides emulating the user interaction with the pages. I believe that the video authoring tool that was being used required images in order to create a video. Now, I haven't worked on any video authoring tool before, but then, of course I am supposed to be knowing a lot more about tech than I actually do now.

So, I said that I would try to export the slides as images and that they could be used by my teammate who was making the video.

I was making use of Microsoft Powerpoint 2010, which is a very good piece of software. Hopefully many of you would agree if you are using it. Well, if you don't agree, I am never in a mood to argue about Microsoft software.

One neat feature that Powerpoint has is that it lets you save your slides in the form of jpeg images. Just go to File->Save as->, and select the file type to be jpeg images.

The interesting thing is that the images exported are not of such a high quality. So, when my teammate added them into the video, most of the text got blurred.

Well, there is a crazy way to increase the resolution of the images when you are saving a Powerpoint presentation as a set of images. I could  not find any options from the UI, but it can be done by adding a registry entry.

  1. Simply type in regedit in the command prompt or in the run manager or in your start menu.
  2. Expand the registry to HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\PowerPoint\Options
  3. Add a new registry key from Edit->New DWORD Value
  4. Name the new key ExportBitmapResolution and set its (Decimal) value to anything among these - 50, 96, 100, 150, 200, 250, 300. Maybe you can try other values and see if tha works out well for you.
  5. Open Powerpoint again, and then try to save your file as a set of jpeg images. This time your pictures will be of a different resolution depending upon what decimal value you provided for the new registry key.


I am not registry expert but if you have some other version of Microsoft Windows or having some other issues, check out the official documentation at their site here and figure them out.

Signing Off 
Ryan

Friday, November 30, 2012

Github : File Changes and Commit History

Most of the times, when working with Github, you will want to see the differences between the current local copy of a file and the previous commits. One of the easiest ways to see it visually would be to make use of the gitk command and give the file name as the argument. e.g.

gitk  filename

Thats all. This command would open up a neat little window and show you all the changes that were made to this file across different commit and lets you compare it with the version in your current working directory. Oh, and do remember to include the relative path before the filename. Standard convention.

Signing Off 
Ryan

Wednesday, October 24, 2012

Keyboard Shortcuts For Gmail


The more you work, the less you want to move your hands away from the keyboard. And most of us spend shitload of time browsing through emails. The last thing that you want to do is have to use your mouse when you want to do bulk actions using email such as deleting, archiving or moving emails to specific labels.

If by any chance you are gmail user, you have a lot of options to improve your productivity - at least during email time.

So, lets cut the crap and get to the point.




Things to get you started with using keyboard shortcuts in gmail

  1. Setup your gmail to make use of keyboard shortcuts.
  2. Know where to look for help when you start learning or when you forget a shortcut.
  3. Memorize the common shortcuts that are relevant to YOU.




1) Setup your gmail to make use of keyboard shortcuts

  1. Go to the cog icon in the new gmail interface (new as of this writing in Oct 2012)
  2. Go to 'Settings'
  3. Look for the keyboard shortcuts option and enable it.





2) Know where to look for help when you start learning or when you forget a shortcut.
There are 2 ways you can do this

  1. Instant help : Press ? anywhere in your gmail (while you not typing, of course). You get a list of available shorcuts.
  2. Official google documentation - List of all the shortcuts with their explanation




3) Frequenty Used ones you might LOVE to have at your finger tips

  • Select conversation - x (One of the most basic ones, You definitely would want to learn this one to  combine it with others)
  • Next conversation - j
  • Prev conversation - k
  • Delete conversation - # (This is just so important!)
  • Move to label - First select using x , and then press v (Definitely learn this one)
  • Go to inbox - g then i
  • Compose - c
  • Search - /
  • Reply - r
  • Reply All - Shift + a
  • Mark as read - Shift + i
  • Mark as unread - Shift + u
  • Move to chat search - q




Happy Programming :)
Signing Off

Ryan

Wednesday, July 4, 2012

Useful Google Chrome Extensions

Over a period of time, I came across a couple of good Google chrome extensions that have helped me quite a bit in getting things done.

This post is nothing but just a short list of some really useful google chrome extensions that you might find useful if you are a developer or if you spend most of your time online working on Google Chrome and like to organize your stuff right from your browser window.


As a good practice, I mostly keep the extensions disabled and only enable the ones I need when i need them such as Awesome Screenshot or the Alarm clock. If you keep too many of these active, Chrome takes extra time to startup, which is something that none of us want.

Sometimes its just better to use different extensions in different chrome profiles and you can use each profile for a different purpose.


Here's the stuff that I use. Click on the titles to go to the extension in the chrome extension gallery. If you are aware of better alternatives to some of these, I would love to try them out, so don't hesitate to share the goodies!


Springpad is a free application that makes it quick and easy to take notes and save anything you want to remember - from tasks and lists to products, places, movies, recipes and more. Everything you save is automatically organized and enhanced with useful information for instant access on the web and on your phone



Download youtube videos in different formats. Such extensions keep on failing whenever there is a new update to youtube, so I am not sure if this one is still working at the time that you are reading this post. Remember to check the user comments before installing this extension.



Capture the whole page or any portion, annotate it with rectangles, circles, arrows, lines and text, blur sensitive info, one-click…



Add the current page to your Instapaper List
Similar to pocket. A single click on the icon will save the current page to your Instapaper unread list. A double click will take you to the Instapaper unread list.



Todo.ly is an intuitive and easy to use online Todo list, and Task Manager. It helps you to get organized, and to get things done.



Easy to use world clock. Find time for global meetings easily. Do time zone conversions among cities intuitively.



Receive notifications and quickly access everything you love about Facebook with Facebook Lite for Chrome.




+1 and share a web page, anywhere you go on the web.




Easily check Google Calendar and add new events from websites you visit.



View definitions easily as you browse the web.
With this extension, you can:

  1. Double-click any word to view its definition in a small pop-up bubble.
  2. View the complete definition of any word or phrase using the toolbar dictionary.




Quickly send email from the address bar using GMail™!
OmniMail helps you send emails faster! Easily start new emails from the address bar/omnibox.




Pocket Extension for Google Chrome – The best way to save articles, videos and more
When you find something on the web that you want to view later, put it in Pocket. It automatically syncs to your phone, tablet or computer so you can view it at any time, even without an internet connection.



Allows you to upload a pdf version of the current page to your Google Docs using the pdfcrowd service.
This extension's purpose is to make it easy to save a web page to your Google Docs.



A clock with two configurable alarms that will play a sound and speak a phrase of your choice.
This extension gives you a handy and fun alarm clock that's at your fingertips whenever you're running Chrome!
Two separate alarms, with handy controls to adjust by 5-minute intervals - or type any exact time with 1-minute precision.



Runs Windows Live Messenger in Google Chrome.Connect with friends and family with Windows Live Messenger (MSN Messenger). Sign in with Windows Live ID and chat with your friends. This one has a good sound alert



YAGBE - Displays Google Bookmarks in a tree. Supports nested labels, searching, sorting, creating, and managing Google Bookmarks.



Quick and easy notes for Chrome : Sticky Notes is a Chrome app that locally stores all your notes in a single tab. It auto saves on every letter, so you don't have to worry about losing something because your computer crashed and you didn't click Save - it's already done for you!


Checker Plus for Gmail
Displays new emails and the sender's contact photo, get desktop notifications or even listen, read or delete them without opening a tab.


Happy Programming :)
Signing Off

Ryan

Monday, June 25, 2012

jQuery makeArray And Array Lengths

Today I just came to know about a pretty cool thing when i was going through the documentation of the jQuery.map function. Now, the jQuery makeArray function is pretty useful because it can convert objects into arrays. But there is one restriction, your objects need to be array like objects. And what are array like objects? Array like objects are objects that have a length property. And I think that it would be safe to presume that he most common array like object known to mankind is the arguments object that is available in javascript functions.

Well, arrays in JavaScript are pretty cool because you can just remove elements from the end of an array by doing a very simple thing. Modifying the length property of the array. For example, lets say that you have an array

var myArray = [1,2,3,4,0,0,0];


Now you want to keep only the first four elements. What do you do? You simply change the lenght of the array to 4. And voila you're done. While that's cool, I was hoping that if you want to delete elements from the beginning of the array, you could set the length to a negative value. But sadly, that does not work :(. Well, you could always resolve to the good ol technique of using the shift() function. Or you could choose to reverse() and then pop(). Depends on your requirement.

But the interesting thing was that when using the makeArray function, if the length property is not set to a proper value, you will end up with an incorrect array. Taking this example right from the jQuery documentation page for the map function


// The following object masquerades as an array.
var fakeArray = {"length": 1, 0: "Addy", 1: "Subtracty"};

// Therefore, convert it to a real array
var realArray = $.makeArray( fakeArray )

// Now it can be used reliably with $.map()
$.map( realArray, function(val, i) {
  // do something 
});


As you see the fakeArray has a lenght property set to 1. When you invoke makeArray, you get an array containing only 1 element - [Addy]. What just happened to the second element??? It seems that the makeAray function converts the object into an array only for 'length' number of elements. Hence, when using this function, just beware of this behaviour and make sure that the lenght property is equal to the number of properties in your object (not counting the lenght property itself), or you might just be in for a little surprise! 

Signing Off
Ryan Sukale

Thursday, June 7, 2012

Naked Javascript - Prototypes and Inheritance

In part 9 of this series Naked Javascript, I am going to talk discuss inheritance in Javascript. In order to understand the concept of inheritance, it definitely hepls to understand the concept behind functions and closures in Javascript. You can check out the previous article on closures and this article on functions to brush up on the basics of these concepts.

Inheritance in Javascript is a bit different from inheritance in other programming languages like Java. The difference lies not only in terms of the syntax but even the implementation is so staggeringly different that it may sometimes not be an easy task to grasp without knowing a few other concepts in javascript.

Lets start from the root of the problem.



Functions

As I have mentioned multiple times throughout the series, functions are first class objects in Javascript. The underlying reason is simple. In Javascript, everything is an instance of the class Object. This is somethign that is taken from Java. The Object class provides a default implementation of several commonly used functions, for example the 'toString' function. Now, to think about it, since all javascript objects need this functionality, they must somehow inherit this function from the object class.

There are 2 important things that you need to remember when dealing with inheritance in JavaScript.
1) Since JavaScript does not have classes, inheritance in JavaScript is achieved by The
2) The mechanism by which two objects are connected in an inheritance hierarch is via the 'prototype' property of objects.

Lets talk about 'prototype'.
When you create any Function in javascript, javascript implicitly defines a new property on that object called 'prototype'. The prototype property is no ordinary property.

Lets see it with a simple example

//Here I have defined a simple constructor function
function Employee(name){
 this.name=name;
}

//Set the default age
Employee.prototype.age = 16;

var emp1 = new Employee('xyz');
console.log(emp1.age);

This is the simplest example that demonstrates the use of the prototype property.

In the first few lines, I defined an ordiary function constructor that would let me create Employee objects. We know that functions are objects. And as I stated earlier, every object gets its own prototype property. Therefore we were able to define a variable called 'age' on the prototype property of the employee class and set its value to 16.

In the last few lines, notice that although we did not declare any property called 'age' on the Employee instance inside the Employee constructor function, we did not get an 'undefined' when we printed the value of the 'age' property on the console. The reason this happened is because we defined a property called 'age' on the prototype property of the Employee function.

What happend here is that when an attempt was made to access a property that is not present on the 'empl' object, the prototype of the constructor function was searched for the property of the same name. So in this case, when we accessed emp1.age, since the JavaScript engine was unable to find the property on the object itself, it tried to lookup a property called 'age' on the Employee.prototype object. This leads us to the conclusion that prototypes are a good place to declare defaults.

Now lets see what happens when we attempt to modify a property on an object that was defined only on the prototype.

function Employee(name){
 this.name=name;
}

//Set the default age
Employee.prototype.age = 16;

var emp1 = new Employee('xyz');
var emp2 = new Employee('abc');
console.log(emp1.age);
emp1.age++;
console.log(emp2.age);
console.log(emp1.age);


When you check the console, you will notice that once you modify the property on the object, that was initially defined only on the prototype, the object will then begin to own a local copy of the property. In our case, when we wrote emp1.age++, this is what we would normally expect the program to do : -

emp1.age = emp1.age + 1;


But, this is what the js engine executed

emp1.age = Employee.prototype.age + 1;


Thats because, before adding doing the addition, emp1.age does not exist. And thats the reason why, on the RHS of the equals operator, emp1.age becomes Employee.prototype.age

The direct implication of this feature is that the prototype property of Functions becomes the most suitable candidate for declaring constants and other properties that will not be modified by instances created by that funcion but which are required for every instace of the class.

function Employee(name){
 this.name=name;
}

Employee.prototype.getName=function(){
 return this.name;
}


This solved the problem of creating a single place to define functions that can be reused by all instances.

However, what if you want a function or a property to be available for all functions?
The answer is pretty simple. Define the property/function on the Function.prototype. For example.

Function.prototype.PI=3.14;

var dummyFunction = function (){};

console.log(dummyFunction.PI);



Note the syntax that we used to access the property PI. We directly made use of the function name. Reiterating myself, this is possible because every function is an object in itself whose constructor is the Function method.


Inheritance

Inheritance is a little bit twisted in Javascript as compared to Java and other similar languages. Thats because in Javascript, objects inherit from objects. The prototype property plays a key role in implementing inheritance. However, it can also be a bit misleading at times. Consider the following example.

In this example, we want to create a Class whose objects inherit certain protperties from another Object. The simplest example to represent this form of inheritance would be

//The doom object is the parent object
//You want to inherit its functions and properties in all
//instances of the MyClass class
var doom = {name:'doom',
   baseMethod:function(){
    console.log('defined on doom');}
   };

//Your class whose instances you want to create
function MyClass(){
 //Some properties
}

//Set the prototype property to the 'doom' object
MyClass.prototype=doom;

//The following invocation wont work because the function is defined on
//the prototype of MyClass. Therefore, MyClass itself
//cannot access the variables of doom directly without
//the prototype property
//MyClass.baseMethod();

//This works because instances of the class
//can access the variables defined in the
//prototype directly.
var mc = new MyClass();
mc.baseMethod();


The secret to the functionality of the prototype is intuitivley simple. Every object in javascript has a hidden property called __proto__. Observe the 2 underscores before and after the word proto. When you create an object in javascript, even if it is an empty object, the value of the '__proto__' property is set to a default object - the Object object, that contains a number of useful methods like toString. Type the following lines in your browser console to verify this

var obj = {};
console.dir(obj.__proto__);


You find that the __proto__ references a default object with a set of functions.

Following our previous example, type the following in your browser console

console.dir(mc.__proto__);


You will find that it points to the doom object. The underlying principle is very simple. When you created an object of type MyClass, something similar to this would have executed under the hood.

mc.__proto__=Myclass.prototype;


And since you have already set MyClass.prototype to reference the doom object, you are all set to inherit the properties of the doom object.


So, whenever you create an object, imagine an invisible link from the '__proto__' of the object to the 'prototype' property of its constructor. For ordinary objects the constructor is the Object class and for your own custom classes, the constructor is the constructor function of your classes. You might want to take a look at this article to learn more about using functions as constructors. 

Another implication of this feature is that, if at any point of time, you want that all objects of your class should inherit a different set of properties, you can simply change the 'prototype' variable in the function name to a different object. That would be equivalent to dynamically swapping the a parent class at runtime, thereby enriching all the existing objects with a new set of functions, which is something is something absolutely cool because thats not something that you can do in languages like Java. What's more is that if you want to change the parent class of only one single object, you can change the '__proto__' property of that object to refer to a different object. Simple, sweet and sexy. 

Thats probably all that I had to say in this post. I hope that you folks loved it. 

Signing Off!
Ryan

Tuesday, May 29, 2012

Naked JavaScript - Defining Classes and Function Instances

In part 8 of the series Naked Javascript, we are going to explore the mystical land of classes in Javascript. Now, coming from a backround with extensive programming in OOPS using Java, the absence of straightforward classes was quite a shocker to me at the start. The syntax, representation and implementation was a complete deviation from conventional methods.

As we learnt in the previous articles, functions are the building blocks of numerous things in javascript. Classes are one of them. In fact, when you define a constructor function, what you are actually doing is creating a function that can be used to construct objects. Lets check out what I mean by looking at an example.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientNewJoinee = new Employee('xyz',99);


If you take a look at this function, there are a number of things that you will note about it.

  1. We make use of the constructor naming convention. 
  2. We make use of the 'this' keyword when assigning property values. The 'this' keyword in javascript is one of those features that may sometimes lead you to lose all your hair if you dont know what you are dealing with(Personal advice : 'this' is highly recommended for hairy women!). I tried to talk about it in intricate details in a previous article. (Make note, hairy women!) 
  3. We passed in two arguments and assigned them as properties on the 'this' object.

Now, this might sound simple at first. Isi'nt it what we always do in other languages like Java?? This is 'suppposed' to be simple right??

Hell no, its not.

Or maybe it is. Lets see what happens.





Case 1 : Doing it the wrong way

You invoke the Employee function as if its just another function, instead of a constructor function. There is nobody who is ever going to stop you from doing such a hideous thing, right? So, lets do it and observe what happens.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

Employee('blah',90);


So what does this do? It works. It executes normally. Really cool, awesome. But what happend to the name and age property that I had passed as arguments? Whos kid did i rename?

Turns out, that you did something totally horrible. What you did was, you created two new properties on the window object.

Now, you should recollect from the previous articles that when you dont specify the context during a function invocation, the function is invoked using the context of the window object which takes the form is nothing but the 'this' keyword inside the function. So, when you invoke the function by directly using the above syntax, you end up creating unnecessary properties on the window object. But thats not something that we want.





Case 2 : Doing it the right way

You invoke the employee function by using the new operator.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientEmp = new Employee('xyz',99);

When you create an object in this way, you are actually creating a new function object, whose constructor is of type 'Employee', and it is this newly created function object that is then used as the context inside the constructor. So, when you are creating properties on the 'this' variable, you are creating properties on your newly created function object. Since you have not explicitly specified any return value, the Employee constructor function returns the value of 'this' variable from the function, which is nothing but the newly created function instance.

Now that solves the mystery of creating classes. But there is much more to this scheme than meets the eye. How do you protect members. Like other programming languages, is there not a way to create private members that cannot be accessed from the outer world? There is a way, but it is not as obvious as it seems.

In the example that we saw, we created two properties on the Employee instance. Both of these properties have public access. i.e. you can directly modify the values of these properties using the object access notation.

function Employee(name, age){
 console.log('');
 this.name = name;
 this.age=age;
}

var ancientEmp = new Employee('xyz',99);

ancientEmp.age=5;

Oh no, now our ancient emp is younger than the kid next door. And child labor is a crime. We dont wana get into a mess with the authorities, do we? Well, at least not me. So, what do I do that enables me to access the properties on the object but still restrict me from modifying them to incorrect values.

The solution is simple. If you remember, in the previous article, we spoke about closures and scoping in JavaScript. Scoping is a very powerful concept and this is one of the places where scoping is used to mimic the behaviour of private variables in classes.

The JavaBean standard is quite common in the Java world. We can apply the same principle to solve the problem of private variables using getters and setters for our variables and instead of accessing the properties directly.

function Employee(name, age){
 console.log('');
 this.getName = function (){
  return name;
 };
 this.getAge=function(){
  return age;
 };
 this.setName = function (newName){
  name=(newName==true)?newName:name;
 };
 this.setAge=function(newAge){
  age=newAge>14?newAge:age;
 };
}

var ancientEmp = new Employee('xyz',99);

ancientEmp.setName('');
ancientEmp.setAge(5);

console.log(ancientEmp.getName());
console.log(ancientEmp.getAge());

The variables that are declared as function parameters are nothing but local variables in the function and behave like instance variables within the function scope. Due to javascript's scoping rules, they remain available to the function instance as long as the instance exists or are explicitly deleted from the object via some method. Creating getters and setters like this improves decoupling between the various code components.

Now there is a minor issue with creating classes in this way. What happens is that whenever you create a function on an object you are creating a function ONLY for that object. Okey, lets think about it once more. In the first article of the series, I mentioned that when we create properties on objects, the properties are specific only to that object. Now look at our constructor function. What exactly is happening when we are trying to assign getters and setters on the 'this' object? The getters and setters are created exclusively for the current function instance, i.e. the 'this'. This implies that if you are creating a large number of objects, you will end up with each object having its own independent copy of each method and property.





Although, it is highly desirable for each object of a class to be able to save the state of its properties independently, you really don't want to create multiple copies of the same function for each object because that will set your browser on fire and send your users screaming out of their houses. What you want to do is to define a function only once and let all the object point to that function. There are a couple of ways in which you can do that.





1) Use an external function

function calculateSalary(){
 //Sorry for being so random!
 return Math.random();
}

function Employee(name, age){
 //Your stuff
 //
 //End of your stuff
 
 this.calculateSalary=calculateSalary();
}


This is a convenient and perhaps the simplest way that you can enable the reuse of the function. In this way, the calculateSalary property of all the function instances will refer to the same externally defined calculateSalary function. Its simple, its nice. However, there lies scope of improvement. This brings to the point where we have to talk about perhaps the best and the coolest concept in javascript - prototypes (But that's just my opinion. So no bashing please!). I will be discussing javascript prototypes in the next article in absolute details. But until then, we need to learn just a bit to get this example working.





2) Using prototypes

What is a prototype?
A prototype is nothing but a property on an object that is visible to all instances of the object.

Lets demonstrate it in our class example. But before that, I want to reiterate a few points.

  • Functions are objects themselves.
  • Functions can be instantiated to create special objects called function instances, by invoking them using the 'new' keyword.
  • Function objects are also objects, but they have a special property called 'constructor' that identifies the function that was resposible to instantiate this object.
  • Objects can have properties.
  • All objects have a property called 'prototype'.


The prototype property is pretty awesome. When you declare a property on the prototype property, it automatically becomes available to all the instances of that object/function/classs. This means that the prototype is the optimal place to declare a function that needs to be reused by all the objects of a class.

function Employee(name, age){

 this.name=name;
 //Other variables
}

Employee.prototype.getName=function(){
 return this.name;
}

Employee.prototype.setName=function(newName){
 name=(newName==true)?newName:name;
}
Employee.prototype.calculateSalary=function(){
 //Whoops!
 return Math.random();
}

var emp1 = new Employee('xyz');

console.log(emp1.getName());

I simplified the class just for the sake of the example. But if you have noticed, although we eliminated the issue of all the objects having a local vaiable pointing to the getter or setter, we are back to the problem where the property is defined on 'this' itself. So, although this technique is useful for defining the calculateSalary function which does not make use of any properties, it somehow manages to breaks the principle of encapsulation because once again, all the properties will have to be publilcly visible for them to be accessible via the prototype method.




That covers the basics of classes in Javascript. In the upcoming article, I plan to talk the most amazing prototype property and perhaps talk a bit about implementing inheritance in JavaScript. So, until then, stay tuned!

Signing Off!
Ryan Sukale

Saturday, May 19, 2012

Naked JavaScript - Function Scopes, Hoisting And Other Quirks

In this part 7 of the series Naked Javascript, I am going to cover a few interesting quirks about functions and scoping in JavaScript and also talk about a strange feature called hoisting.

The first thing that one needs to know is that in JavaScript, we dont have block level scopes. Instead, in JavaScript, functions are responsible for creating new blocks of scope. Let me elaborate. In other programming languages like java, if you write a block of code like this

public void someMethod(){
for(int i=i;i<10,i++){
 //Some usage of variable i
}
//Compiler error
System.out.println(i);
}


When you attempt to complie this program in Java, you are presented with an error at the line where you attempt to print the value of the variable 'i'. Thats because, once you are outside the for loop, you cannot access the variable 'i'. The scope of the variable 'i' lies only within the code block in which it was declared in Java. Cominng to JavaScript, you need to understand that although javascript makes use of code blocks in the same way that Java does, the scope of a variable lies throughout the function in which it was declared. This means that the following code will successfully print 10 when executed in JavaScript.

public void someMethod(){
for(int i=i;i<10,i++){
 //Some usage of variable i
}
//Prints 10
console.log(i);
}


In the above code, although we printed the value of the variable after it was declared and initialized ,but outside the curly braces, it worked perfectly fine. Now lets take another example.

var n = 1;

function someRandomFunction() {
    console.log(n); // This prints 1.
}


In this function, we declared a variable outside the function. And were were easily able to print its value inside the function, due to closures. Now consider the following piece of code.

var n = 1;

function someRandomFunction() {
    console.log(n); // This prints undefined.
    var n = 100;
    console.log(n); // This prints 100
}


Strange as it may seem, the first console ouput prints undefined. But why? Why is it not able to see the declaration of the variable 'n' that was part of the closure like the earlier example? The reason behind this odd behavior is a feature called 'hoisting'. Hoisting can be explained in a very simple way. For any variable declared within a scope, JavaScript separates the variable declaration and the variable initialization and hoists the declaration to the first line of the scope and initializes the variables at the appropriate lines at which they were initialized by the programmer.

Based upon the above explanation, this is what JavaScript saw when it ran our program.

var n = 1;

function someRandomFunction() {
 var n; //The variable declaration hides under harry potter's cloak. So you cant see it.
    console.log(n); // Now you know why its undefined here
    n = 100; //Now the variable gets initialized.
    console.log(n); // And prints out 100 here.
}


As you see in the code above, the variable was undefined because it was shadowed by the local declaration of the variable in the function. (At least they got that part right!). But then, enter functions! And you have some more nasty code to deal with.

Check out the following piece of code wherein we declare a variable, a function using the conventional function declaration and a second function using the variable style declaration.

function hoistingContainer(){
 console.log(n);
 
 innerOne();
 innerTwo(); //Throws an exception
 
 var n = 100;
 
 function innerOne(){
  console.log('innerOne');
 }
 
 var innerTwo = function innerTwo(){
  console.log('innerTwo');
 }
 
 //This will execute but the code never
 //reaches here because of the previous exception
 innerTwo();
    
}


In the above example, make a note of the different ways in which we declared the two functions. If you run the above code, you would find that the first invocation of the function innnerTwo() leads to an exception whereas the invocation for the function innerOne executes normally. The only difference between these two functions was the way in which they were initialized. Perhaps it can be concluded that when functions are explicitly declared using a variable instead of the conventional notation, the initialization is not hoisted. However, using the conventional function declaration notation, even the function body gets hoisted along with the function declaration.

This implies that if you define functions using the standard notation instead of the variable notation, you can create functions anywhere within a scope and use them at any point within the same scope irrespective of their point of declaration.

The next interesting thing that I want to discuss about is what could happen if you accidentally forget to use the 'var' keyword when declaring a variable inside a scope. Usually, when you declare local variables inside a function, you would use the var keyword. Only the variables that are declared using the var keyword become function local. However, if you accidentally forget the var keyword, javascript will not complain, instead it simply creates a property of the same name in the global scope i.e. on the 'window' object. And as we are already aware, this can have disasterous consequences.

Take a look at the follwing code.

window.constant = 10;

//prints 10, the constant from the global
//window object, 
console.log(constant);

function outerFunction(){

 var name = 'xyz';
 
 //Missing var keyword
 constant = 20;
}

//Invoke the function
outerFunction();

//Prints undefined since name was 
//locally scoped in the function
console.log(name);

//Prints 20, because its value was
//reassigned inside the function
console.log(constant);


Moral of the story, dont forget to use the 'var' keyword when declaring local variables inside a scope.



Scopes and closures.


Closures take extensive advantage of the scoping feature of JavaScript. When a function is declared within the scope of another function, the inner function maintains 'hidden references' to the varibles in the scope in which it was declared. You may also think of it as if functions have their own scope memory. Functions are behaviour. But Javascript functions can not only contain behaviour but also act as a data store. You may like to read another article of mine in which I have elaborated on closures with a couple of examples.



Semicolon insertion.

This is a really strange feature in javascript. The JavaScript processing engine tries to act smart and detect if a semicolon is missing where it should have been put. If it is found to be missing, it simply inserts the missing semicolon and executes the code without any warning. The simplest example, as demonstrated by many other is the problem of semicolon insertion with the return statement. The follwing code returns undefined.

function badStyle(){
 return
 {
  name:'value'
 };
}


function goodStyle(){
 return {
  name:'value'
 };
}

//Runs as expected
console.log(goodStyle());

//Prints undefined
console.log(badStyle());


The second line prints undefined because, since javascript expected that return statement be terminated by a semicolon, it inserted one when it did not see any in the badStyle function. In the goodStyle function, it did not insert one because before the line termination, it encountered a symbol for object literal declaration.

Most of the problems that arise due to the above discussed quirks of the language can be avoided by writing simple yet decently formatted code. Variable declarations at the top, function declarations before using them, and proper opening and closing of curly braces and always adding a semi colon when you are terminating your statements wont only avoid these issues but also make your code readable and understandable. Who knows, just spendinng just a couple of minutes restructuring your code may later save you hours of debugging. 

Stay tuned. There's more to come!

Signing Off!
Ryan