Thursday, December 31, 2009

Identifying from where JavaScript libraries invoke your callback functions, with Firebug

There comes a time where one would need to dig beyond the abstractions to see what is really going on under the covers.

Say for example you wanted to see how a certain library computes parameters for your callback, how would you do it? Scanning the library and figuring out the logic step by step is one way you can do it, but that is very time consuming and with complex libraries such as jQuery, it's nearly impossible to exactly pinpoint from where your callback function is being invoked.

In this post we will see how we can use Firebug to pinpoint exactly from where your callback functions are called in the abstraction.

A simple library

Let's take an example with a very small hypothetical "library" example:

var alibrary = (function () {
    var callback, 
    privatefun = function (p) {
        callback(p);
    }; 

    return {
        setCallback: function (fn) {
            callback = fn;
        },
        doIt: function () {
            var params = ['some', 'parameters', 22 + 20];
            privatefun(params);
        }
   };
}());

This 'library' offers 2 public functions; setCallback, which takes a function and stores it into the callback parameter and the doIt function that invokes the function that was stored previously.

Here's how this library can be used:

alibrary.setCallback(function (p) {
    console.log(p);
});

alibrary.doIt();


When the doIt function is called, the callback function that was passed previously will be invoked, passing in some parameters from behind. The library is passing an array as a parameter and the third element of that array is a computation of 22 + 20.

Now, as users of the library, we want to check how that 42 is computed from our callback function; and we will do this with Mozilla Firefox's best friend, Firebug

Tracing the steps

Open your Firebug (F12) and head onto the Script tab and choose the script from where you are defining your callback function. Then find your function and put a breakpoint in the function:



To set a breakpoint, click next to the line number in the and a red dot will appear.

The next step is to perform the action that will invoke your callback, and in my case this 'action' is a page refresh.

So now after my page refresh, the library will invoke my callback and the breakpoint will be hit:



When the breakpoint is hit, the line will be highlighted in yellow.

Now comes the part where we trace the steps back to where the callback was invoked. If you look closely to the upper part of the Script tab, you will see the following:



From there, you can now trace the path to where the function was invoked! Now let's click on the first step, privatefun().




Upon clicking, Firebug takes you directly to that function, privatefun, and now from this function we can see how our callback function was invoked:



Now although we can see from there the function was invoked, we still don't know from where that 42 is coming from, and so we must check which function invoked privatefun and to do that, we move a step back through the invocation line, the doIt() step:





From here, we can now see how that 42 was being computed because we have finally arrived to the step we wanted to.



Now obviously this technique isn't that much useful for this example because the code of this 'library' is so small that it doesn't require backtracking of the function calls, but it can be used very effectively on much larger libraries to quickly identify how certain parameters are being computed and sent to your functions, amongst other uses.


Sunday, December 27, 2009

Trying out the examples from 'The Little Schemer' book

This delightful book leads you through the basic elements of programming in Scheme (a Lisp dialect) via a series of dialogues with well-chosen questions and exercises.


To try out the examples from The Little Schemer, you must first download1 PLT-Scheme. This will install DrScheme, which is the IDE you will use to type in the Scheme examples.

As a language, I chose Module in DrScheme and it seems to be suitable for trying out the examples.



Once the language is set, you need to start each file with the following line:

#lang scheme

The upper section of the screen is used to enter all the definitions and the lower part of the screen is used to execute those functions you defined in the upper part.



Minor Changes


Something you need to be careful about are the minor syntax changes. This is because there are slight changes from the examples in the book to the real Scheme.


One of changes is the way you call identifiers. Identifiers require an apostrophe (') in Scheme, but in the book the apostrophe is not used in the examples.

This is mentioned in page 3 of the book:

L, S: (quote atom) or 'atom


This means that, for example, to test the atom? function (or any function), you need to call it like such:
(atom? 'elem1)

Same goes for when the identifier is a list:

(atom? '(peanut butter jelly time))



The Apostrophe


The apostrophe is a shorthand notation of the (quote ...). Basically, you are saying the interpreter to not evaluate the name but only replace it with its value, verbatim.
Therefore, the following two lat? questions are the same thing:

(lat? (quote (peanut butter jelly)))

and

(lat? '(peanut butter jelly))

If you do not put the apostrophe, you are signaling the interpreter to use the variable. This can be clearly illustrated with the following example:

(let ((x 42))
  (display x) (newline)
  (display 'x) (newline))

The output of the above code is:
42
x



1 If you don't want to download PLT-Scheme, you can use an online interpreter. Two of which you can try are SISC and CodePad


Tuesday, December 22, 2009

jsLaTeX: A jQuery plugin to directly embed LaTeX into your website or blog



jsLaTeX is the latest plugin I developed for jQuery and I wrote it so that I could easily be able to embed LaTeX directly into my blog but anyone can use it for their site.

You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo

Here is a link to the jQuery plugin page, where you can find all the releases.

Usage Instructions


1. Download the jquery.jslatex.js file from one of the above-mentioned links and add it to your page along with jQuery (if it is not already added):

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.jslatex.js"></script>


2. The simplest way to invoke the script is by calling the plugin with no parameters:

<script>
$(function () {
    $(".latex").latex();
});
</script>
<div class="latex">
    \int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi
</div>

The above will render the following:


\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi


The plugin works by taking the inner HTML of the specified container obviously assuming that it is valid LaTeX, and displays the image using CodeCogs LaTeX engine. The rendered output replaces the equation inside the container.



The plugin also accepts 3 optional parameters:
  • format
  • url
  • callback

[format]
The format parameter is used to specify the format of the returned output. There are currently 3 supported formats:
  • gif
  • png
  • swf

[url]
The url parameter is used to change the engine of the LaTeX generator. Let's take an example with a different engine, and in this case I will be using SITMO's LaTeX engine.
The url SITMO's engine uses to render the output is as follows:

http://www.sitmo.com/gg/latex/latex2png.2.php?z=100&eq=equation


where equation is the the LaTeX equation you wish to render.

Now we must tell the plugin where to put the equation and we do this by using the {e} specifier. This is how it can be used:

$(".latex").latex({url: 'http://www.sitmo.com/gg/latex/latex2png.2.php?z=100&eq={e}'});

As you can see from the above example, we placed the {e} specifier where the equation should be and then the engine takes care of the rest.

Here is an example of using the new engine to render the output:


\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi


The plugin currently supports another specifier: {f} and this is used for those engines that allow you to specify a file-format output. The file-types that are currently supported are the ones mentioned in the [format] section.

If we take the 'original' engine url, we can turn into a url with specifiers like such:

http://latex.codecogs.com/{f}.latex?{e}


Here are examples of Engines you can use (ready with specifiers):


Engines
http://latex.codecogs.com/{f}.latex?{e}
http://www.sitmo.com/gg/latex/latex2png.2.php?z=100&eq={e}
http://www.forkosh.dreamhost.com/mathtex.cgi?{e}
http://chart.apis.google.com/chart?cht=tx&chl={e}


[callback]
The callback parameter allows you to pass a function that will be executed after the image has been retrieved. In your callback function, this will refer to the newly created element (as a jQuery object) that contains the rendered output.

The following example will set a border around your rendered output.

$(".latex").latex({
    callback : function() {
        this.css({ border: '1px solid black'});
    }                        
});

With the above callback, we can now render the following:


\int_{0}^{\pi}\frac{x^{4}\left(1-x\right)^{4}}{1+x^{2}}dx =\frac{22}{7}-\pi



Monday, December 21, 2009

Aligning a block of text in LaTeX

This is how you can indent and align a block of text in LaTeX:

\begin{tabbing}
Contact Address: \= 175, Ambjent\\
\> Francesco Buhagiar str.\\
\> Swieqi, SWQ 3230
\end{tabbing}

That will produce the following output:




Creating a signature line in LaTeX

To create a signature line in LaTeX, use the makebox command like such:

Signature\hspace{0.5cm} \makebox[1.5in]{\hrulefill}


This will produce the following:




Sunday, December 20, 2009

Centering a container on screen with JavaScript (jQuery plugin)

Recently I needed a way to center an image on screen for a 'Coming Soon' kind of page, and so I wrote this jQuery plugin that does in fact this.

You can download the normal, unpacked version for development or the packed version for production.

Click here to view a demo

The container needs to have a preset width and height for this to work


Here is the unpacked code:

/*
 * CenterScreen 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.centerScreen = function () {
        return this.each(function () {
            var $this = $(this),
                $window = $(window),
                center = function () {
                    var winWidth = $window.width(),
                        winHeight = $window.height();
                    $this.css({
                        position: 'absolute',
                        left: ((winWidth / 2) - ($this.outerWidth() / 2)),
                        top: ((winHeight / 2) - ($this.outerHeight() / 2))
                    });
                };
            $window.resize(center);
            center();
        });
    };
}(jQuery));

Saturday, December 19, 2009

Lexical Scoping in JavaScript

Take a look at the below code:

var f = function () {
    var n = 42;
    return function () {
        return n;
    };
}();

var result = f();
alert(result);

The function f is a self-invoking function that returns a function, that returns the variable n declared in the outer function.

The alert of the above code is, as you'd expect, 42

Now let's try rewriting the above code so that instead of returning a function that is declared internally, it now returns a function that was defined outside (but that does the same thing):

var f2 = function () {
    return n;
};

var f = function () {
    var n = 42;
    return f2;
}(); 

var result = f();
alert(result);

This should return the same result, no?

Actually, we are greeted with the following error:


n is not defined


This is because of JavaScript's static scoping, also known as lexical scoping, because matching a variable to its binding only requires analysis of the program text.

This means that the scope of the variable is determined at compile-time, and from the second code snippet we can see that during compile time variable n of function f2 has window (window.n) as it's scope; and since n doesn't exist in the global scope, it is undefined.


JavaScript's Function Scope

Those developers who are coming from a C background may find JavaScript's scoping rules a bit confusing.

Let's take a look at the following C code:

#include <stdio.h>

int main () {
    int n = 5;
    if (1) {
        int n = 2;
    }
    printf("n is %d", n);
}

The output of the above code is:

n is 5


Now let us implement the above code in JavaScript:

var scoping = function () {
    var n = 5;
    if (1) {  
        var n = 2;
    }
    alert('n is ' + n);
};

What do you think the above code alerts?

If you answered n is 5, then you are wrong


This is because, unlike C, JavaScript only supports Function Scope and not Block Scope.

What this means is that JavaScript creates a new scope only with a function:

var scoping = function () {
    var n = 5;
    var x = function () {  
        var n = 2;
    };
    alert('n is ' + n);
};

Now, n is 5 is alerted because a new scope has been created with the inner function and thus it's encapsulating the inner variable n.


Saturday, December 5, 2009

Updating your Twitter Status from C#

Today I needed a way to update my Twitter Status via C#, and for that I found this library: Yedda Twitter C# Library.

After I added a reference to the Yedda.Twitter.dll, I tried working with the following code:

namespace TestingAPIs
{
    using Yedda;

    class Program
    {
        static void Main(string[] args)
        {
            var t = new Twitter();
            t.Update(
                "myUsername",                          // Username
                "myPassword",                          // Password
                "From Visual Studio",                  // New Status
                Yedda.Twitter.OutputFormatType.JSON);  // Output Type
        }
    }
}

Simple eh?

Well, much to my amazement, that threw an exception -_- ...obviously, it wouldn't as much fun if it worked on the first try eh!

So, after some googling, I found some posts that detailed the problem:

This error is seemingly because Twitter servers have started rejecting Expect HTTP header with value "100-Continue".


So anyways, to fix this problem we need to modify a method from the Twitter.cs file of the Yedda library.

Open up the file and find the following method: ExecutePostCommand

At the start of the method, add the following line of code:

System.Net.ServicePointManager.Expect100Continue = false;

That will fix the above problem.

Here is the complete modified method:

protected string ExecutePostCommand(string url, string userName, string password, string data) {
 System.Net.ServicePointManager.Expect100Continue = false;
 WebRequest request = WebRequest.Create(url);
 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password)) {
  request.Credentials = new NetworkCredential(userName, password);
  request.ContentType = "application/x-www-form-urlencoded";
  request.Method = "POST";

  if (!string.IsNullOrEmpty(TwitterClient)) {
   request.Headers.Add("X-Twitter-Client", TwitterClient);
  }

  if (!string.IsNullOrEmpty(TwitterClientVersion)) {
   request.Headers.Add("X-Twitter-Version", TwitterClientVersion);
  }

  if (!string.IsNullOrEmpty(TwitterClientUrl)) {
   request.Headers.Add("X-Twitter-URL", TwitterClientUrl);
  }


  if (!string.IsNullOrEmpty(Source)) {
   data += "&source=" + HttpUtility.UrlEncode(Source);
  }

  byte[] bytes = Encoding.UTF8.GetBytes(data);

  request.ContentLength = bytes.Length;
  using (Stream requestStream = request.GetRequestStream()) {
   requestStream.Write(bytes, 0, bytes.Length);

   using (WebResponse response = request.GetResponse()) {
    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
     return reader.ReadToEnd();
    }
   }
  }
 }

 return null;
}