Sunday, November 29, 2009

Detecting Firebug with JavaScript

Need to implement some debugging methods for your library with Firebug's console as your Output Window?

Here's a quick way to check if Firebug is enabled:

if (window.console && window.console.firebug) {
    //Firebug is enabled
}

Obviously, this is not a fool-proof method because anyone can overwrite the console object, but I think that it's the best you're gonna get.


Thursday, November 26, 2009

Custom-sorting arrays in JavaScript

To sort an array in JavaScript, we use the array.sort() method.

Let's take a look at the following code:

var words   = ["andreas", "john", "grech", "janica", "buhagiar"];
var numbers = [5, 2, 8, 666, 42, 13];

console.log(words.sort());
console.log(numbers.sort());

The results of the above are:

["andreas", "buhagiar", "grech", "janica", "john"]

[13, 2, 42, 5, 666, 8]

As you can see, the strings are sorted correctly, but what happened to the numbers? 13 is obviously greater than 2, so why is it before?

Sorting lexicographically

The problem with the array.sort function is that it sorts lexicographically, meaning it sorts 'alphabetically'; in dictionary order; and thus the sort function just assumes that the elements that need to be sorted are strings. And if they aren't strings, it converts them to strings and then compares them.

Fortunately, sort takes also a single parameter; a function that will be used to sort the array with.

Let's take an example of how we can sort numbers:

var numbers = [5, 2, 8, 666, 42, 13];
var ascNumSort = function (a, b) {
    return a - b;
};
var ns = numbers.sort(ascNumSort);
console.log(ns);

Now we created a function called ascNumSort and passed it to the sort method, and as you can see the numbers are now correctly sorted in ascending order.

What kind of function ?

The function that you pass as a parameter to the sort method needs to abide with the following rules:
  1. It must accept two formal arguments
  2. Return a 0 if the two elements are equal
  3. Return a positive number if the second parameter should come before the first parameter
  4. Return a negative number if the first parameter should come before the second parameter
With these rules, we can now build our custom sorting functions.

Let's say that we have an array of objects representing people and we want to sort these people according to their height, in descending order:

var people = [
    {name: "Andreas", height: 5.4},
    {name: "Janica",  height: 4.3},
    {name: "Cameron", height: 5.8},
    {name: "Richard", height: 5.4},
    {name: "Ryan",    height: 4.5}
];

var sortedPeople = people.sort(function (p1, p2) {
    return p2.height - p1.height;
});

console.log(sortedPeople);
/*Result:
[
 Object name=Cameron height=5.8, 
 Object name=Andreas height=5.4, 
 Object name=Richard height=5.4, 
 Object name=Ryan    height=4.5, 
 Object name=Janica  height=4.3
]
*/

Sorting on multiple keys

By implementing what we did above, but in a more general way, we can come up with a function that will allow us to sort an array of objects, given a key (or multiple keys) [taken from Douglas Crockford's The Good Parts]:

//Function by takes a member name string and an
//optional minor comparison function and returns
//a comparison function that can be used to sort an
//array of objects that contain that member.  The
//minor comparison function is used to break ties
//when the o[name] and p[name] are equal 

var by = function (name, minor) {
    return function (o, p) {
        var a, b;
        if (typeof o === 'object' && typeof p === 'object' && o && p) {
            a = o[name];
            b = p[name];
            if (a === b) {
                return typeof minor === 'function' ? minor(o, p) : o;
            }
            if (typeof a === typeof b) {
                return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
        } else {
            throw {
                name: 'Error',
                message: 'Expected an object when sorting by ' + name
            };
        }
    }
};      

Now let's take a look of an example of how we can use the above by function:

var people = [
    {name: "Andreas", height: 5.4},
    {name: "Janica",  height: 4.3},
    {name: "Tony",    height: 5.8},
    {name: "Richard", height: 5.4},
    {name: "Ryan",    height: 4.5},
    {name: "Cameron", height: 5.8}
];

console.log(people.sort(by('height')));
/*Result:
[
 Object name=Janica height=4.3,  Object name=Ryan height=4.5, 
 Object name=Andreas height=5.4, Object name=Richard height=5.4, 
 Object name=Tony height=5.8,    Object name=Cameron height=5.8
]
*/

console.log(people.sort(by('height', by('name'))));
/*Result:
[
 Object name=Janica height=4.3,  Object name=Ryan height=4.5, 
 Object name=Andreas height=5.4, Object name=Richard height=5.4, 
 Object name=Cameron height=5.8, Object name=Tony height=5.8
]
*/


Check if your CPU is either 32-bit of 64-bit in Windows Vista

Today or tomorrow I will be upgrading from my current Vista to Windows 7 and I needed to check which version of the OS the install.

To check whether my CPU was 32-bit or 64-bit, here's what I did (in Vista):

 First open up the System Information tools from Accessories > System Tools




Then from the System Information, look for the System Type Row, and there you will have your answer:




  • x86-based PC: 32-Bit Computer
  • x64-based PC: 64-Bit Computer


Wednesday, November 25, 2009

JavaScript's Evil Equality Twins (Equality vs Identity)

In JavaScript, there exists two sets of equality operators:

=== and !==

and, as Douglas Crockford likes to call them, their corresponding evil twins :

== and !=

What's the difference?

The first set of operators, called Identity Operators ( === and !== ), produce true (or false) whenever the given operands are both of the same type and have the same value.

On the other hand, the evil twins, formally known as Equality Operators ( == and != ), do type-coercion whenever the operands are of a different type before checking for value equality.

Type-Coercion?

First of all, don't get thrown off by the word coercion; it's just another word for conversion.
In Computer Science, there are two forms of type conversions, implicit and explicit.  The term used for implicit type conversion is coercion and the term used for explicit type conversion is casting.

In most languages, explicit casting is done via the parenthesis:

int main () {
    float fl = 7.2;
    int n = (int) fl;   // (int) makes an explicit cast
    //n is now 7
}

But JavaScript, being a loosely typed language, never casts.

Implicit casting, coercion, is the automatic type conversion that is done internally by the compiler.  For example, we can rewrite the above C code as such:

int main () {
    float fl = 7.2;
    int n = fl;   //now the C compiler is internally coercing the operator to an integer 
    //n is now 7
}

This time, the compiler is implicitly casting fl to an integer.

What's wrong with type-coercion ?

Earlier on I said that the evil twins do type-coercion before checking for type-equality, and unfortunately the rules by which they coerce the values are complicated and unmemorable.

Here are two cases of comparing the values with both sets:

//Using the equality operator (==)

true == 1; //true, because the boolean value true is converted to 1 and then compared
"2"  == 2  //true, because 2 is converted to "2" and then compared


//Using the identity operator (===)

true === 1  //false
"2"  === 2  // false

Here is a list of other "interesting" cases:

'' == '0'          //false
0  == ''           //true
0  == '0'          //true

false == 'false'   //true
false == '0'       //true

false == undefined //false
false == null      //false
null  == undefined //true

' \t\r\n ' == 0    //true

All of the comparisons shown above produce false with the === operator.

Therefore in my opinion, you should never use the Equality operators, but only use the Identity operators, === and !==

Simple enough?

Well, not really...because as usual, there has to be a caveat. Take a look at the following example:

var x = new String('hello');
var y = 'hello';

console.log(x === y); //shows false
console.log(x == y);  //shows true

As you can see, a false is returned when we used the Identity operator! This is because:

console.log(typeof x); // 'object'
console.log(typeof y); // 'string'

When we used the Identity operator ===, it returned false because x and y are not of the same type! This is due to the fact we used the constructor to initialize a string (new String()), the primitive value was boxed into an Object.

The moral of this is to Always use literals to initialize values and this goes for all the primitive types. I will leave further explanation of this for another post.


3D Rotating Tag Cloud for Blogger (Cumulus Cloud)

Today I implemented a rotating 3D tag cloud, called a Blogumus.  Such a script was initially written as a plugin for WordPress, called WP-Cumulus.

But Amanda from BloggerBuster has ported a version of the WordPress plugin to Blogger; and it's now called Blogumus.

Here's an example of the Blogumus in action:





Implementing the Blogumus for your Blogger blog is very easy:

  1. Find the side-bar section in your layout's html. The sidebar section starts with the following tag:


    <b:section class="sidebar" id="sidebar" preferred="yes">

  2. In your side-bar section (ie in the tag mentioned above), paste the following code:


    <b:widget id='Label99' locked='false' title='Labels' type='Label'>
    <b:includable id='main'>
    <b:if cond='data:title'>
    <h2><data:title/></h2>
    </b:if>
    <div class='widget-content'>
    <script src='http://halotemplates.s3.amazonaws.com/wp-cumulus-example/swfobject.js' type='text/javascript'/>
    <div id='flashcontent'>Blogumulus by <a href='http://www.roytanck.com/'>Roy Tanck</a> and <a href='http://www.bloggerbuster.com'>Amanda Fazani</a></div>
    <script type='text/javascript'>
    var so = new SWFObject("http://halotemplates.s3.amazonaws.com/wp-cumulus-example/tagcloud.swf", "tagcloud", "240", "300", "7", "#ffffff");
    // uncomment next line to enable transparency
    //so.addParam("wmode", "transparent");
    so.addVariable("tcolor", "0x333333");
    so.addVariable("mode", "tags");
    so.addVariable("distr", "true");
    so.addVariable("tspeed", "100");
    so.addVariable("tagcloud", "<tags><b:loop values='data:labels' var='label'><a expr:href='data:label.url' style='12'><data:label.name/></a></b:loop></tags>");
    so.addParam("allowScriptAccess", "always");
    so.write("flashcontent");
    </script>
    <b:include name='quickedit'/>
    </div>
    </b:includable>
    </b:widget>
    



To customize the dimensions and background-color, modify the following line from the code above:

var so = new SWFObject("http://halotemplates.s3.amazonaws.com/wp-cumulus-example/tagcloud.swf", "tagcloud", "240", "300", "7", "#ffffff");

The default values are:
  • Width: 240
  • Height: 300
  • Background Colour: #ffffff

To change the color of the font, modify it from the following line:

so.addVariable("tcolor", "0x333333");

The default color is #333333

This tutorial was adopted from Amanda's Tutorial.


Tuesday, November 24, 2009

Code Beautifiers

Don't you hate it when you want to follow some code that's virtually unreadable because of it's horrific formatting?  Believe me, you're not alone.

That's why in this post I am going to compile a list of Code Beautifiers.



JavaScript









CSS






HTML




'What I was listening to' box in my posts

I recently implemented a 'system' in where I show one or more songs I was listening to whilst writing a blog post, in this form:



To do that, I wrote a small script:

var blogmusic = function () {
    var lastContainerDone = 0;
    return function (music) {
        var musiccount = music.length,
            blogmusic = $(".blogmusic").eq(lastContainerDone++),
            header = $("<div/>").addClass("header");
        header.append("<center>What I was listening to</center>");
        var musiclist = $("<div/>").addClass("musiclist");
        for (var i = 0; i & lt; musiccount; i += 1) {
            var song = music[i];
            var listing = $("<div/>").addClass("listing");
            var songname = $("<span/>").addClass("songname").html('<a href="' + (song.link || '#') + '" target="_blank">"' + song.name + '"</a>');
            var artist = $("<span/>").addClass("artist").html('- ' + song.artist);
            listing.append(songname);
            listing.append(artist);
            musiclist.append(listing);
        }
        blogmusic.html(header);
        blogmusic.append(musiclist);
    };
} ();

And I invoke the script in my blog posts like such:

<div class="blogmusic">
<script>
blogmusic([
{ 
    artist : 'Jerry Lee Lewis',
    name : 'Whole Lotta Shakin\'',
    link : 'http://listen.grooveshark.com/#/song/Whole_Lotta_Shakin/6325468'
}
]);
</script>
</div>

The correct way to delete an element from an array in JavaScript

In JavaScript, there exists an operator called delete.  This operator is used to remove properties from objects, and since arrays in JavaScript are really objects, it can be used to remove elements:

var arr = ['a','b','c','d','e'];
delete arr[2];

//arr is now ['a', 'b', undefined, 'd', 'e']

As you can see from the above code, the element is removed but this leaves a hole in the array because the element was replaced with undefined.

Therefore, the correct way to remove an element an array from an element is by using the splice method.



Arrays in JavaScript have a method called splice.  To remove an element from array, we will use it is like such:

var arr = ['a','b','c','d','e'];
arr.splice(2, 1);

//arr is now ['a', 'b', 'd', 'e']

The first argument is an index (ordinal) in the array from where to start deleting and the second element is the number of elements to delete. Thus, with 2 and 1 as parameters, we are starting at index 2 and removing 1 element. (Additional parameters get inserted into the array).

One thing to note is that with splice, the property with the value 'd' has it's key changed from 4 to 3 and because every property after the deleted property will be removed and reinserted with a new key, this might take a while for large arrays.


Sunday, November 22, 2009

Passing a pointer to a function with parameters in JavaScript (Partial Function Application)

In JavaScript, you can easily add a direct reference to a function with no parameters like such:

var f = function () {  };

var pf = f; // passing a direct reference to the function f

pf(); //invoking the function f

But how can you pass a reference to a function with parameters?

Say I have the following function:

var f = function (arg1, arg2) {  };

var pf = f(4, 5); // you can't do that, because that invoke f and put 
                  // it's result into pf, instead of a reference to f

pf();

One alternative is by invoking that function within an anonymous function:

var f = function (pars) {  };

var pf = function (pars) {
    f(pars);
};

pf(200);

What I am doing in the above example is wrapping the function invocation of f with an anonymous function, and passing a reference of that anonymous function to pf.

That will then allow me to invoke pf with parameters, which will in turn invoke f with the parameters passed to pf.

But in the above example, although it works, I am not passing a direct reference to function f, but rather a reference to a function that invokes f.

Fortunately enough, there is a way we can pass a direct reference to a function including its arguments, and this is called Partial Function Application.



Take a look at the following function:

var partial = function (func /*, 0..n args */) {
    var args = Array.prototype.slice.call(arguments, 1);
    return function () {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(this, allArguments);
    };
};

With the partial function, I can now do:

var f = function (pars) {  };

var pf = partial(f, 200);

pf(/* you can add more arguments */); //invokes f with the previously 
                                      //added arguments (in this case, 200);

Let's go through the partial function step-by-step:

First of all, as you can see from the function signature, I declared only one formal argument for the partial function: func; yet when I am invoking the function, I passed in more than one parameter: 

partial(f, 200);

This is because every function in JavaScript has a property named arguments (JavaScript is a functional objected-oriented language, and thus functions can have both methods and properties), which is an array-like object that allows you to access all the actual arguments in the function (I will leave further explanation of the arguments object arguments for another post).


Now in the first line of the function we are taking a copy of the arguments array, excluding the first argument (which will be the pointer to a function), func, and storing it into a variable. The reason we are doing this will be clear later on.

But how exactly am I taking a copy of this arguments object ?

To make a copy of an array in JavaScript, one should use the array's inbuilt method slice.  The slice method returns a part ( a slice) of the array it is invoked on.  But if you remember earlier on I told you that arguments is an 'array-like' object. This is because it has the length property, but lacks all the methods that are available to normal arrays; thus we cannot call slice directly from arguments (i.e. we cannot do arguments.slice

Therefore, we are calling the slice method directly from the Array.prototype, passing in arguments as the first parameter and 1 as the second parameter.  That will return a copy of the arguments 'array' excluding the first element; the first element being the function that is passed into the partial function, func.

The next line of the function is returning an anonymous function.  This means that we are declaring a closure.  The explanation of closures is beyond this post, but I will just explain it lightly.

In JavaScript, whenever a function declares an inner function and returns it, it is creating a closure.  This is because the function that is being returned (inner) will still have access to the local variables of the function that is returning it (outer), even after the outer function has returned!  In C terms, this could mean that instead of the variables in the main function being allocated in the stack-frame, they are malloc-ed!

Now back to the partial function.

The first line of the inner function is making a copy of the arguments object (of the inner function) and concatenating it with the copy of the arguments object that we copied in the outer function, args.  And that is the reason why we took a copy of the arguments object when we first entered the outer function, so now we could access it and concatenate it with the new arguments (of the inner function).

The final line is then invoking the function func that was passed as an argument (from the outer function) with the current function as it's context (this) and with an array of all the arguments we built earlier on.
This is because the apply method takes 2 arguments; the first one is the object that will be bound to this and the second an optional array arguments.


Saturday, November 21, 2009

Function pointers in JavaScript

What do you think the following code alerts ?

var f = function () {
    alert('Function 1');
};

var pf = f;

f = function () {
    alert('Function 2');
};

pf();

If you answered 'Function 2', then you are wrong



First, a function f was created which now occupies a block of memory. Internally, the only reference the function has is the assigned location in the JavaScript's Heap.

When you a pass a function (var pf = f;), you are only passing a pointer to a function. This means that you are passing a reference to the memory location of the function, not the function name!

In the above code, pf is a pointer to the function f created beforehand. When we later on change to original function f to point to a different function, pf still retains its pointer to the original allocated function.

The only difference now is that the variable f is now pointing to a different memory address of the Heap (because it is now pointing to a new function)


No one should extend the Object.prototype in JavaScript!

In an earlier post, I wrote:


But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO


But why exactly should no one extend the Object.prototype?

What is the prototype?


Every object in JavaScript has a property (an object) called prototype (Introduced in JavaScript 1.1) that allows you to add custom properties and functions to every instance of that object.

Let's take an example.  First we'll add properties to objects without using the prototype:

var square = function () {  };

var box = new square();
box.height = 55;  //Adding a custom property to the box instance

In the above example, we created a new function called square and other one called box. The box is then initialized as an instance of square.
We then added a custom property to box called height and assigned a value to it.

If we now check the value of box.height, we get 55.

But if we now create another instance of a square, that new instance will not have the height property:

var anotherBox = new square();
alert(anotherBox.height) ; //alerts 'undefined' (not 0)

The reason undefined is displayed is because anotherBox does not have a property called height.

So the best thing to do is to add the height property to the square object, instead of the instantiated objects, via the prototype:

var square = function () {  };
square.prototype.height = 0;

//Now, every instance of square will have a height object

var box = new square();
box.height = 55;

var anotherBox = new square();
alert(anotherBox.height) //alerts 0

anotherBox.height alerts 0 because this time round, the anotherBox object has a property named height and it's set to 0.

I'll soon explain why it's a bad idea to extend the Object.prototype.


In JavaScript, every object inherits from an object called (not surprisingly) Object. Now, earlier on I described how when you attach a property to the prototype, it will exist in all instances of that object...so basically, since every object inherits from Object, when you extend the Object's prototype, every object from then on will have that property that was added to the Object.prototype.

Let's take an example:

Object.prototype.myCustomProperty = 200;

var square = function () {  };
alert(square.myCustomProperty); // 200 is alerted

As you can see from the above example, square now has a property called myCustomProperty!

But now you may think that this won't cause problems because you will only call the properties you know exist in the object you create; and well, that may be true but the real problem occurs when you use the for...in statement.

In JavaScript, there exists a construct that lets you iterate over all the properties of an object, the for...in statement:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    props += p + "\n";
}
alert(props);

In the above code I am iterating over every property of the box object and appending the name of that property to a string called props.

The output of the above alert is :



So you see, myCustomProperty now appears as part of the box object! And when you iterate over properties of an object, you will want the properties of only that object and not properties that are up the inheritance chain!

Fortunately enough, there is a workaround for this. This workaround involves using the hasOwnProperty function:

Object.prototype.myCustomProperty = 200;

var box = { width: 200, height: 500 };

var props = "";
for (var p in box) {
    if (box.hasOwnProperty(p)) {
        props += p + "\n";
    }
}
alert(props);

Now the alert displays:


This is because the hasOwnProperty returns true only if the property in the current iteration is directly linked to the object you are using in the loop; and thus, it returned false for the myCustomProperty property.

So make sure that when iterating over properties in JavaScript, you use the for...in construct! ...or else bad things may happen if someone (probably some JavaScript framework) extends the Object.prototype!

Friday, November 20, 2009

Arduino with a 3x4 Keypad

The following is something I made a while back with an Arduino, a speaker I ripped off from an old toy and two LEDs:



To make use of the keypad, I used Arduino's keypad library.

I connected the keypad to the Arduino as follows:

Keypad Pin
Arduino Pin
1
7
2
5
3
8
4
2
5
6
6
3
7
4

The above keypad numberings map as follows:




To use in your code, make sure you include it:

#include <Keypad.h>

You also need to map out the keys like such:

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
  {
    '1','2','3'    }
  ,
  {
    '4','5','6'    }
  ,
  {
    '7','8','9'    }
  ,
  {
    '*','0','#'    }
};

//The below numbers correspond to the Arduino Pins
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6};    //connect to the column pinouts of the keypad

Afterwards, instantiate the Keypad:

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

Then to get the key pressed, it's just as simple as this:

char key = keypad.getKey();

Thursday, November 19, 2009

Stackoverflow's reverse-engineered WYSIWYM editor

If you want a lightweight, yet advanced (especially if you want it for a website for developers) online wysiwym editor, I suggest you take a look at Stackoverflow's reverse-engineered WMD Editor.

To download it, visit their development folder at github: http://github.com/derobins/wmd



Note that in the demo, I used the wmd along with a modified Stackoverflow css file.




Konami Code in JavaScript

Yesterday I came to know about this thing called a Konami Code and about how many websites use it as an easter egg!

So I decided to write up my own JavaScript version of this Konami Code.  You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo


To use the code, following these instructions:

1. Download the konami.js file from one of the above-mentioned links and add it to your page:

<script src="konami.js"></script>

This will create a konamiCode object in your website, which can be used in multiple ways. The konamiCode object takes 2 parameters: combination (an array of keyCodes) and a callback function.

The combination parameter can be skipped and if it is skipped, the default combination will be the Konami Code (UP, UP, DOWN, DOWN, LEFT, RIGHT, LEFT, RIGHT, B, A)

2. The simplest way to enable the Konami Code for your website, is like such:

konamiCode(function () {
    alert('You entered the code!');
}).start();

This will start the Konami code listener.

3. To stop listening for code input, store the konamiCode in a variable and call it's stop method:

var konami = konamiCode(function () {
                 alert('You entered the code!');
             }).start();

//...

konami.stop(); // <== stop listening

4. To use a different combination, enter an array as the first parameter of the konamiCode function:

konamiCode([38, 40, 37, 39, 52, 53], function () {
    alert('You entered the code!');
}).start();

The combination listed above is UP, DOWN, LEFT, RIGHT, 4, 2
As you can see, the elements of the array are the Key Codes of the keys, not the letters themselves. Use this website to convert from a key-press to a Key Code



Here is the unpacked code:

/*
 * Konami Code in Javascript
 * Andreas Grech
 * http://blog.dreasgrech.com
 *  v 1.1 (20091119)

 Keycodes for the Konami Code
 UP    : 38
 DOWN  : 40
 LEFT  : 37
 RIGHT : 39
 B     : 66
 A     : 65
*/

var konamiCode = function(combination, callback) {
 var lastCorrectInput = - 1,
 isActive = 0,
 o = {};
 if (typeof combination === "function") {
  callback = combination;
 }
 if (Object.prototype.toString.call(combination) !== "[object Array]") {
  combination = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
 }
 o.start = function() {
  if (isActive) {
   return;
  }
  isActive = 1;
  document.onkeyup = function(e) {
   var code;
   if (!isActive) {
    return;
   }
   code = window.event ? window.event.keyCode: e.which;
   if (combination[++lastCorrectInput] === code) {
    if (lastCorrectInput === combination.length - 1) {
     if (callback && typeof(callback) === "function") {
      callback();
     }
    }
    return;
   }
   lastCorrectInput = - 1;
  };
  return o;
 };
 o.stop = function() {
  isActive = 0;
  return o;
 };
 return o;
};

Testing if an element is an array, in Javascript

Up till now, I have always used this function (taken from Crockford's The Good Parts) to check for array validity in JavaScript:

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

But recently I came to know that a guy from Google (Mark Miller) used the following condition (by carefully reading the ECMAScript Standard):

var is_array = function (value) {
    return Object.prototype.toString.call(value) === '[object Array]';
};

Although mind you, the above isn't perfect either, because it can easily be broken by extending the Object prototype :

// native prototype overloaded, some js libraries extends them
Object.prototype.toString= function(){
  return  '[object Array]';
}

function isArray ( obj ) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

var a = {};
alert(isArray(a)); // returns true, expecting false;

But everyone should keep in mind that extending the Object prototype in JavaScript is a big NO-NO . So, as of the moment, the most robust and concise way you can use to check for array validity in JavaScript is by using Miller's method.

Tuesday, November 17, 2009

Passing a pointer by reference in C

Today I needed a way to pass a pointer to an int to a function, modify the location of that pointer (via malloc) in that function, and then access the modified pointer from outside the function (from the caller).

I tried to code it like such (incorrectly):

int f(int *arr, int n) {
    int i;
    arr = malloc( n * sizeof (*arr));
    for (i = 0; i < n; ++i, ++arr) {
        *arr = i;
    }
    arr -= i;
    printf("Second element (from function) : %d\n", *(arr + 1));
    return 0;
}

int main()
{
    int *arr;
    f(arr, 5);
    printf("Second element (from caller) : %d", *(arr + 1));
    free(arr);
    return 0;
}
This is the output:

Second element (from function) : 1
Second element (from caller) : 1032044593

As you can see from the above output, the correct element is displayed when accessing the array from the function, but when I try to access the array from outside of the function (after it has been malloced and data was added), the value displayed seemed like a value from an unmalloced address!

What was I doing wrong?

The problem with the above code is that I am passing the pointer to an int by value to the function; ie a copy of the pointer.  That is why when I changed its address, the change was only visible from inside the function.

The Correct Way

The correct way to do it is to pass a pointer to the pointer to int (int **arr) to the function, like such:

int f(int **arr, int n) { //arr is now a pointer to a pointer to int
    int i;
    int *temp = malloc(n * sizeof **arr); //declare and malloc temporary space
    for (i = 0; i < n; ++i, ++temp) {
        *temp = i;
    }
    temp -= i;

    *arr = temp;  //Assign the value of the inputted location to the temporary one created earlier on

    printf("Second element (from function) : %d\n", *(temp + 1));
    return 0;
}

int main()
{
    int *arr;
    f(&arr, 5);  //The address of the pointer is now passed, not the pointer itself
    printf("Second element (from caller) : %d", *(arr + 1));
    free(arr);
    return;
}
Now the output from the above function is correct:

Second element (from function) : 1
Second element (from caller) : 1


Monday, November 16, 2009

Number of elements in an array in C

Take the following piece of code:
int main()
{
    int nums[] = {1,2,3,4,5};
    printf("Outside: %d\n",sizeof(nums) / sizeof(*nums));
    f(nums);
    return 0;
}

int f(int nums[]) {
    printf("Inside: %d\n",sizeof(nums) / sizeof(*nums));
}

Here is the output of the above code:
Outside: 5
Inside: 1
As you can see from the above output, when the calculation is done in the scope where the array was initialized, the correct output is displayed; but when it is passed to a function, the calculation fails!
This is because the formal argument int nums[]  does not contain any information about the array whereas the declaration of the array in the main function contains an implicit size  (determined by the number of items in the value), so as long as you use the variable in the main function (ie where it was declared), the compiler knows the size of the array.

When you send the array as a parameter to the f function, there is no information about the size sent along, it's just a pointer to an array of unknown size. The f function could be called from anywhere, so the compiler can't use the information about the variable in the main function.
If you want to know the size of the array in the f function, you have to send that along with the array as another parameter.


Sunday, November 15, 2009

ShowSlow - A jQuery plugin for displaying elements in order, one by one with a delay

Recently I needed the functionality for displaying some hidden divs, in order, one by one, and with a timed-delay between each one.

Thus I wrote this jQuery plugin that does infact this (demo):

/*
 * ShowSlow v1.1 - jQuery plugin
 * 
 *  Copyright (c) 2009-2010 Andreas Grech
 *
 *  Dual licensed under the MIT and GPL licenses:
 *    http://www.opensource.org/licenses/mit-license.php
 *    http://www.gnu.org/licenses/gpl.html
 *
 * http://blog.dreasgrech.com
 */

(function($) {
    $.fn.showSlow = function(options) {
        var opts = $.extend({}, $.fn.showSlow.defaults, options),
        elementCounter = 0,
        $elements = this,
        isStopped = 0,
        isPaused = 0,
        callbackExecuted = 0,
        executeCallback = function(val) {
            if (typeof opts.callback == "function") {
                callbackExecuted = 1;
                opts.callback(getValues());
            }
        },
        getValues = function() {
            return {
                elementsDone: elementCounter
            };
        },
        showNextDiv = function($element) {
            if (isPaused || isStopped) {
                return;
            }
            if (!$element.length) {
                executeCallback();
                return;
            }
            $element.slideDown(opts.slideTime, function() {
                setTimeout(function() {
                    showNextDiv($elements.eq(elementCounter++));
                },
                opts.displayTime);
            });
        };

        return {
            start: function() {
                if (isStopped || elementCounter < $elements.length) {
                    $elements.css("display", "none");
                    elementCounter = 0;
                } else if (isPaused) {
                    elementCounter -= 1;
                }
                isStopped = 0;
                isPaused = 0;
                callbackExecuted = 0;
                showNextDiv($elements.eq(elementCounter++));
            },
            stop: function() {
                isStopped = 1;
                if (!callbackExecuted) {
                    executeCallback();
                }
                return elementCounter; //return the number of elements displayed before stopped
            },
            pause: function() {
                isPaused = 1;
            }
        };
    };

    $.fn.showSlow.defaults = {
        slideTime: 1000,
        displayTime: 500
    };
})(jQuery);

Saturday, November 14, 2009

Vim is like your average text editor...on steroids!

So recently I started using vim after a friend suggested it, and man I have to say, it's like your average text-editor on steroids!

vi was actually written in the 70s (1976), but I just started using recently.  Actually, what I started  I had read a lot about it on Stackoverflow, and last time my friend told me he uses vi when working with C (I, instead, had been using the Code::Blocks IDE); and so I decided to give vim (which is actually an extended version of the vi editor) a go during a *boring* Entrepreneurship lesson at school...and I was impressed and got so immersed in it that I even forgot I was still in a lesson at school.

What really impressed me with vim is the amount of work I can do with fewer keystrokes as possible.

Here is a list of couple of basic commands (from this answer over at stackoverflow) :


y(ank) - copy
d(elete) - delete
c(hange) - change
p(aste) - put from buffer after cursor
o(pen) - start a new line
i(nsert) - insert before current character
a(fter) - insert after current character
w(ord) - moves to beginning of next word
b(ack) - moves to beginning of current word or prior word
e(end) - moves to end of current word or next word
f(ind) - moves to a character on the current line
movement keys you just need to learn: h,j,k,l

^ - beginning of text on a line
$ - end of text on a line
0 - first position on line

most commands can be prefaced with numeric modifiers.
2w - means move 2 words
5h - means move 5 charcters to the left
3k - means move 3 lines up
3fs - means move to the 3rd letter s folling the cursor

modification commands (d,c,y) need to know how much to work on.
dd - delete a line into memory
yy - yank a line into memory
cc - change the whole line
c$ - change from current position to the end
c2w - change the text spanning the next 2 words
3dd - delete 3 lines
d2f. - delete to the second period.

. - means redo the last modification command.
/ - searches for text, and then n(ext) will go the next found occurance. N will go prior.
? - searches backwards through the document.

This is the book I used to start learning vim with: http://modular.math.washington.edu/home/agc/lit/vim/vim_tutorial.pdf

Once I complete the above book, I'll have a go at O'Reilly's Learning the vi and Vim Editors

Greatest Common Divisor and Least Common Multiple functions in Haskell

Recently, I wrote a post about finding the gcd and lcm with C: http://knowledge-aholic.blogspot.com/2009/11/greatest-common-divisor-and-least.html

Since then, I have started Haskell and here is how implemented the "same" functions with Haskell (note that with Haskell, I have to use recursion to find the gcd) :


mygcd :: Int -> Int -> Int
mygcd n m
 | m == 0 = n
 | otherwise = mygcd m (mod n m)
 
mylcm :: Int -> Int -> Int
mylcm n m = div (n * m) (mygcd n m) 

Greatest Common Divisor and Least Common Multiple functions in C

Below are two functions (with a sample application) that calculate the Greatest Common Divisor and Least Common Multiple of two numbers; a,b

#include <stdio.h>

int gcd(int x, int y);
int lcm(int x, int y);

int main()
{
    int x = 156;
    int y = 156;

    int g = gcd(x,y);
    int l = lcm(x,y);

    printf("GCD (%d, %d) : %d\n", x,y,g);
    printf("LCM (%d, %d) : %d\n", x,y,l);
}

int gcd(int x, int y) {
    /*;
        a = qb + r,  0 <= r < b

        a => dividend, q => quotient, b => divisor, r => remainder
    */
    if (x == y) {
        return x /*or y*/;
    }

    int dividend = x, divisor = y, remainder = 0, quotient = 0;

    do {
        remainder = dividend % divisor;
        quotient = dividend / divisor;

        if(remainder) {
            dividend = divisor;
            divisor = remainder;
        }
    }
    while(remainder);

    return divisor;
}

int lcm(int x, int y) {
    /*
        lcm(x,y) = (x * y) / gcd(x,y)
    */
    return x == y ? x /*or y*/ : (x * y) / gcd(x,y);
}

Wednesday, November 11, 2009

An elegant Fibonacci solution with Haskell

Here's a very elegant Fibonacci solution I found in Simon Thompson's book, The Craft of Functional Programming:

--Given a tuple with a fibonacci pair, this function returns another tuple with
--the next two numbers in the sequence
fibStep :: (Int, Int) -> (Int, Int)
fibStep (u,v) = (v, u + v)

--The Definition for the Fibonacci pair
fibPair :: Int -> (Int, Int)
fibPair n
| n == 0 = (0,1)
| otherwise = fibStep (fibPair (n - 1))

--Pass the output of the fibPair function to Haskell's fst function,
--which returns the first item in the given tuple
fastFib :: Int -> Int
fastFib = fst . fibPair

Thursday, November 5, 2009

Cleaning out \Windows\Installer folder correctly in Vista

If you are on Vista, you may have noticed that the %SYSTEMDRIVE%\Windows\Installer folder might get quite huge and take up quite a lot of hard disk space.


Anyway, that folder is used as a cache for installation files and patches and removing those will cause you to not being able to repair or uninstall applications, and in some cases not removing patches or applying new patches to software.


To remove the contents of this folder correctly, download Windows Installer Cleanup Utility and once installed, run the following command with it:

msizap.exe G!

Reference: http://www.theexperienceblog.com/2009/05/16/how-to-clean-out-windowsinstaller-folder-correctly/