Pages

Friday, 28 December 2012

Maemo: ldconfig not found on PATH

Partial upgrades to core system libraries like libc6 can sometimes lead to "ldconfig not found on PATH" error. To fix this, first try to find if ldconfig is present somewhere in the system.
find / -name ldconfig
The above command returns the path of ldconfig if found. I got the path as /var/cache/ldconfig.
Now copy the ldconfig to /usr/bin or similar directory which are added to the PATH variable.
sudo cp -r /var/cache/ldconfig /usr/bin/
Now we remove (downgrade) the library that caused this problem. In my case it was libc6_2.11.3-4 which caused the problem. So removing the current one will downgrade to the previous installed version, which is libc6_2.5.1-1eglibc27+0m5.

Monday, 3 December 2012

Delete Colour Schemes in NetBeans

To delete colour schemes in NetBeans 7.2.1, remove the colour scheme from Tools -> Options -> Fonts & Colors -> Profile and delete all the folders in the directory C:\Documents and Settings\<username>\Application Data\NetBeans\7.2\config\Editors except Preferences.

Tuesday, 27 November 2012

My Unused Yahoo Account Got Compromised

My unused Yahoo account got compromised yesterday (Sun, Nov 25, 2012 at 2:22 PM). Someone logged in from Vietnam. Or most likely that someone relayed through a server located in Vietnam with the IP address 123.22.191.25. pfft..
I got notified to my another email account that the Yahoo account's password got changed. Well there was two emails, one at 2:22 PM and the other at 2:23 PM. When I entered the password, Yahoo mail asked the security question, but I opted for verification code to be sent to my another email account.
Anyway, I got hold of the account, but who needs a Yahoo account anyway. I just initialized account termination.
Relayed login IP address screenshot | Relayed login Country Info screenshot

Monday, 19 November 2012

Open Links In Background Tab

A snippet to open links in a background tab. The idea is to trigger a mouse click event with control key pressed set as true, to open the clicked link in a background tab.
<!-- html -->
<div>class="bgLink" href="http://www.qlambda.com">qlambda​</div>
<div>class="bgLink" href="http://www.google.com">Google​</div>
//js
window.onload = function () {
    //event listeners
    var a = document.querySelectorAll(".bgLink");
    if (a != null) {
        var len = a.length, i=0;
        if (len > 0) {
            for (i = 0; i < len; i++) {
                a[i].addEventListener("click", openNewBackgroundTab, false);
            }
        }
    }

    // event handlers
    // open links in background tabs
    function openNewBackgroundTab(e){
        var a = document.createElement("a"), evt;
        a.href = this.getAttribute('href');
        evt = document.createEvent("MouseEvents");    
        evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, false, 0, null);
        a.dispatchEvent(evt);
        e.preventDefault();
    }
};
Reference: initMouseEvent
Update: Stopped working with Google Chrome dev release 41.0.2224.0 after 2014-11-20.

Sunday, 18 November 2012

Install Java SDK in Nokia N900

Nokia N900 with Maemo Operating System is one true computer rather than a smartphone or an internet tablet. One of the judging criteria is whether we can develop applications right on the phone. With Nokia N900, we surely can.

Java platform is an amazing environment. We have the JRE with the JVM and the libraries, and of course with Java and a whole bunch of JVM languages like Clojure, Groovy, Scala etc. To develop applications in Java we need the Java Standard Development Kit (JDK) which contains the compiler and the supporting files. The cool thing about Maemo is that we can install JDK compiled for the ARM architecture.

The easiest way is to install the IceTea6 version of the OpenJDK preset at the maemo repository.

To manually install, follow the steps below.
1. Get OpenJDK for ARM. Cambridge Software Labs (link down) provides optimized version of OpenJDK for ARM. Download OpenJDK v1.6.0_0. (Mirror).
2. Copy the archive to /opt directory of the phone. Say you have downloaded or copied the file to MyDocs/tmp, then run the below command to copy it to /opt. We need to be root to preform the following operations. Install rootsh from the maemo-extras repository to get root privilege, if not done already.
cd  #home dir
sudo cp MyDocs/tmp/OpenJDK-camswl.tar.gz /opt  #copy file
3. Extract the archive.
cd /opt
sudo tar zxvf OpenJDK-camswl.tar.gz #extract the archive
sudo rm OpenJDK-camswl.tar.gz #delete the archive
4. Add /opt/OpenJDK-camswl/bin to PATH.
cd /etc
sudo vim profile  #open the file
Add the line to the file after the already present export path statement, save and exit vim (:wq). The file will look like:
# ...
export PATH="/usr/bin:/bin"
#JDK
export PATH=$PATH:/opt/OpenJDK-camswl/bin
# ...
5. Exit and relaunch the terminal.
6. Test the installation by typing in the following commands.
java -version  #prints java version "1.6.0_0"
javac -version  #prints javac 1.6.0_0
javap java.util.Date  #lists all methods in Date class
Happy hacking !

Friday, 9 November 2012

BeanShell: The Java Interpreter (JSR-274)

BeanShell is a pure Java interpreter. BeanShell uses BeanShell Scripting Language which is a Java syntax compatible scripting language for the Java platform (JSR-274). BeanShell supports dynamic execution of the full Java grammar and semantics with transparent access to Java objects and APIs. It also provides additional scripting features which is a strict superset of the Java language syntax.

Setting up BeanShell
1. Download latest BeanShell jar file. The current one is bsh-2.0b4.jar.
2. Place the jar file in a directory say D:\env\javaLibs\.
3. Set CLASSPATH environment variable pointing to BeanShell jar file. It will look like .;D:\env\javaLibs\bsh-2.0b4.jar; under Windows. The . is to look for classes in the current directory. If the variable is already present, append the path at the end separating the paths with a semi-colon.
4. Open command prompt and run java bsh.Interpreter (assuming that JDK or JRE is present in the path).

Now we have a fully working Java interpreter which we can use to quickly prototype ideas. The interpreter is similar to what we see in other dynamic languages like Python or Groovy.

Friday, 2 November 2012

Get HTML5 Canvas Click Co-ordinates

Click co-ordinates for HTML5 canvas element can be obtained using both layerX, layerY property or offsetX, offsetY of the click event.
Firefox does not support offsetX, offsetY so we have to use layerX, layerY amd opera does not support layerX, layerY, so we have to use offsetX, offsetY.
<html>
<head>
    <meta charset="utf-8">
    <script src="script.js"></script>
</head>
<body>
    <canvas id="myCanvas"></canvas>
</body>
</html>
//script.js
window.onload = function () {
    var canvas = document.querySelector('#myCanvas'),
        ctx = canvas.getContext("2d");

    //draw something
    ctx.fillStyle = "#000000";
    ctx.strokeStyle = "#000000";

    ctx.beginPath();
    ctx.rect(100, 100, 300, 100);    //x, y, width, height
    ctx.fill();
    ctx.stroke();
    ctx.closePath();
    
    //listen for click event
    canvas.addEventListener("click", function (e) {
        var cX,    //will contain clicked x co-ordinate
            cY;    //will contain clicked y y co-ordinate
        if (e.offsetX == null) { //in case of Firefox
            cX = e.layerX;
            cY = e.layerY;
        } else { //in case of Opera layerX does not work, use offsetX instead
            cX = e.offsetX;
            cY = e.offsetY;
        }
        console.log("clicked at: " + cX + " " + cY);
    }, true);
}

Tuesday, 30 October 2012

Smoothly Scroll Element Inside div With Scrollbar Into View

We can scroll to an element which is inside a div which has scrollbar using jQuery.animate() and for scrollTop pass in $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top

The scrollTop() method sets or returns the vertical position of the scrollbar for the selected elements.
The offset() method allows us to retrieve the current position of an element relative to the document.

The idea is add the current offset of the scrollbar with the current offset of the element, and subtract the top offset of the parent element, i.e., the area which is fixed below which the scroll area beings. Offset on an element relative to the document can be positive or negative, depending on whether the element is yet to be scrolled or the element has passed the scrolling.

Sample code:
<!-- html -->
<html>
<head></head>
<style>
    .content {
        height: 300px;
        overflow-y: scroll;
    }
</style>
<body>
    <header></header>
    <nav>
        <!-- link to navigation to sections -->
    </nav>
    <article class="content">
        <section>
            <div></div>
            <p></p>
        </section>
        <!-- more sections here -->
    </article>
</body>
</html>
// js
$('.content').animate({
    scrollTop: $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top
}, {
    duration: 1000,
    specialEasing: {
        width: 'linear',
        height: 'easeOutBounce'
    },
    complete: function (e) {
        console.log("animation completed");
    }
});
Live Demo | View Source

Unable to find Mach task port for process-id


When we try to build and run any project under Xcode and if we get an error like "Unable to find Mach task port for process-id 274: (os/kern) failure (0x5)", then it is mainly due to some issues in validating cryptographic certificates. As written in the Building GDB for Darwin article the Darwin kernel refuses to allow GDB to debug another process if the user don't have special rights. Kernel allows a root user to debug. The latest method to allow GDB to control another process is to sign it with any system-trusted code signing authority. I got this error because of wrong system date. If system date is wrong, then verifying cryptographic signature fails.

Monday, 29 October 2012

PDCurses for Windows

ncurses is a C API that helps us in creating text based user interfaces in a terminal-independent manner. It is a free software emulation of curses in System V.
PDCurses is a public domain implementation of the curses library for DOS, Win32, OS/2, X11 platforms. Installation procedure is given below.
1. Install latest GCC (>=v4.7.2). Download it from equation.com and follow the installation instructions. Let's say GCC is installed into D:\gcc4.7.2 directory.
2. Download pdc34dllw.zip or newer from sourceforge.net. For direct link click here.
3. Extract pdcurses.dll to "D:\gcc4.7.2\libexec\gcc\i686-pc-mingw32\4.7.2" directory.
4. Extract pdcurses.lib to "D:\gcc4.7.2\i686-pc-mingw32\lib" directory.
5. Extract curses.h and panel.h to "D:\gcc4.7.2\i686-pc-mingw32\include" directory.
6. Ensure that proper environment variables and path variables are set. The path must be added to the front of the other path variables so that it takes precedence.
EQ_LIBRARY_PATH
d:\gcc4.7.2\i686-pc-mingw32\lib
PATH
d:\gcc4.7.2\bin;
d:\gcc4.7.2\libexec\gcc\i686-pc-mingw32\4.7.2;
7. Run the sample program to see if it prints "Hello World from PDCurses!" in the command prompt.
//hello.c
#include <curses.h>

int main() { 
    initscr(); // Start curses mode
    printw("Hello World from PDCurses!");  // Print Hello World
    refresh(); // Print it on to the real screen
    getch(); // Wait for user input
    endwin(); // End curses mode
    return 0;
}
/* ---------------------------------------
> gcc -Wall -g -lpdcurses -o hello hello.c
> hello.exe
-----------------------------------------*/
8. To run the executable the pdcurses.dll library is required. So if we are to bundle the app, ensure that the pdcurses.dll file is also included along with the executable.
9. Awesome! Now we have a working curses library.

To know more about ncurses see ncurses programming howto, Programmer's Guide to NCurses by Dan Gookin.

getchar() not waiting for input

When scanf() is used to get input from stdin and then using getchar() will mostly make the program exit without waiting for the input from stdin. The reason is that scanf() reads the input till new line from stdin which is a buffered stream. So the new line is still present in the buffered input stream. So getchar() sees the buffer as non-empty and reads from it which is the new line and returns. Instead, we can use fgets() to get the input as string and if we are looking for an integer input, then use strtol() to get the integer (long) value from the string.
// read_integer_input_before_getchar.c
// Monday 29 October 2012

#include <stdio.h>
#include <stdlib.h>

enum {
    MAX_RANGE = 4    //maximum number of input characters, max two digit with '\n' and '\0'
};

int main(int argc, char **argv) {
    long num;        //input value
    char *in;        //input buffer
    char *end_ptr;   //used by strtol, a result param, used for checking error conditions
    int base = 10;   //used by strtol to determine set of recognized digits
    int c;           //will contain a character
    
    puts("Enter a number");
    in = malloc(MAX_RANGE);
    if (in == NULL) {
        fprintf(stderr, "\nError allocating memory");
        exit(1);
    }
    fgets(in, MAX_RANGE, stdin);
    // @link: http://www.kernel.org/doc/man-pages/online/pages/man3/strtol.3.html
    num = strtol(in, &end_ptr, base);
    // handle strtol error conditions
    if (end_ptr == in) {
        fprintf(stderr, "\nNo digits found");
        exit(1);
    }
    free(in);       //free the allocated memory
    in = NULL;
    printf("Entered number is %ld\n", num);
    
    puts("\nEnter a single character");
    c = getchar();
    printf("\nEntered character is %c", (char) c);
    return 0;
}

/* ------------------------
// input - output

$> Enter a number
1
$ Entered number is 1

$ Enter a single character
a

$ Entered character is a
------------------------ */

Sunday, 28 October 2012

Git for Beginners

Common commands in the day-to-day usage of git.

Configure global email
git config --global user.email "user@example.com"
Configure global name
git config --global user.name "username"
Generate SSH key
ssh-keygen -t rsa -C "user@example.com"
View SSH key fingerprint
ssh-keygen -l -f ~/.ssh/id_rsa.pub
Add a remote repository
git remote add origin repo_url_here
Remove a remote repository
git remote rm origin
Push 'master' branch to remote repository
git push origin master
Rename a local branch
git branch -m old_branch_name new_branch_name
Delete remote branch
git push origin :old_branch
Exclude files but include a specific file in .gitignore
*.rar  #excludes all files ending in .rar
!myfile.rar #includes myfile.rar if present
Tagging a commit (give the first 7 chars of the commit)
git tag v1.0.0 dee70ed
git push origin --tags

Monday, 24 September 2012

Quick Setup CherryPy in Python 3

CherryPy is a minimalist, pythonic, object-oriented HTTP framework.
For Windows,
1. Download and install the latest version of python 3.
2. Download and install the latest version of CherryPy with wsgiserver3 support.
3. Test the installation by running an example program (say hello.py) like below.
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())
4. Navigate to the directory and run python hello.py to start the server.
5. Now goto 127.0.0.1:8080 and we will get a "Hello World!" from the server.

Thursday, 20 September 2012

Generete Ant build.xml for an Android Project

If we have an Android project which does not have a build.xml, then we can generate a build script by running the below command.
1. Navigate the android project root directory
2. Update the project to generate the build file
android update -p .

Thursday, 13 September 2012

Common Regular Expressions

Match letters, space, comma, ampersand, hyphen, forward slash, parentheses with length 1..12.
^[a-zA-Z0-9\s,&-/\(\)]{1,12}$
Match 2, 3 digit numbers with 0 to 2 decimal places.
[1-9]{2,3}(\.\d{1,2})?
Matches everything including control characters with length 5..255.
^[\w\d\s\W]{5,255}$
Postal code with min length 3, max length 10. Upper case alphabets, digits and spaces.
^[A-Z0-9\s]{3,10}$
Mobile number with length 10..15 with an optional plus '+' symbol in front.
^\+?[0-9]{10,15}$
Number with minimum 2 digit with first digit not zero and max 3 digit number, with optional decimal upto 2 place.
^[1-9]{1}\d{1,2}(\.\d{1,2})?$

Sunday, 9 September 2012

Install GCC in Nokia N900

The GNU Compiler Collection (GCC) can be installed in Maemo on Nokia N900, which allows on device development! To install them, first add the Maemo SDK repository to the application catalogs. Do *not* run upgrade (apt-get upgrade) after enabling the SDK repository. After the installation of the build tools, disable the SDK repository. Once the repo is disabled we can run apt-get upgrade command safely.
Catalog name: maemo sdk
Web address: http://repository.maemo.org
Distribution: fremantle/sdk
Components: free non-free
After reloading, close the application manager.
In the terminal, run the following.
root
apt-get update
apt-get install build-essential #installs the necessary packages
exit
Open the application manager and disable the SDK repository. After that run update.
apt-get update

Thursday, 6 September 2012

Writing Bash Shell Logs With Date & Time

Bash shell scripts can be used to do a variety of things. It is very easy to schedule the script to run under crontab. It would be helpful if we log the steps with date time and a message. It can be done as follows.
echo '['`date +%F\ %T`'] Downloading file abc'
#outputs: [2012-09-06 23:20:16] Downloading file abc
NB: The date command is enclosed in back tick, not single quote.

Wednesday, 22 August 2012

Load External Scripts in PhoneGap for iPhone

To load external script files or to make calls to external hosts in a PhoneGap (Cordova) web application running on iOS devices, add a new property say Item 0 to the ExternalHosts with value * in the Phonegap.plist file.

Sunday, 19 August 2012

Closing Other Scratchbox Sessions

We can switch session in a scratchbox. If we get a message saying "You must close your other scratchbox sessions first", we can issue a killAll command to close the programs running on scratchbox.
sb-conf killall --signal=9 #9 or any other number
After that switch the session.

Install Maemo 5 SDK in Ubuntu

To develop native applications using C/C++ and GTK+ for Maemo, we need to install the Maemo 5 SDK and the development environment which include scratchbox, which is used for cross-compilation. The host environment here is Ubuntu 12.04 LTS 64bit. Scratchbox now supports 64bit platform.
1. First, we need to install scratchbox. For that add the scratchbox apt source url
deb http://scratchbox.org/debian/ hathor main
to /etc/apt/sources.list. We can use vim to do it or the following command.
sudo add-apt-repository "deb http://scratchbox.org/debian/ hathor main"
The above command will add deb-src link as well, which can be removed.
2. Update package list
sudo apt-get update
3. Install scratchbox and dependencies
sudo apt-get install scratchbox-core scratchbox-devkit-apt-https scratchbox-devkit-autotools-legacy scratchbox-devkit-debian-squeeze scratchbox-devkit-doctools scratchbox-devkit-git scratchbox-devkit-perl scratchbox-devkit-python-legacy scratchbox-devkit-qemu scratchbox-devkit-svn scratchbox-libs scratchbox-toolchain-cs2007q3-glibc2.5-arm7 scratchbox-toolchain-cs2007q3-glibc2.5-i486 scratchbox-toolchain-host-gcc
If dependency errors were encountered during installation, run the below command to auto resolve them
sudo apt-get install -f
4. Once scratchbox installation completes successfully, add the user to scratchbox.
sudo /scratchbox/sbin/sbox_adduser <yourUserName>
Logout and login. Now we will have a working scratchbox environment. We can test it by logging into scratchbox.
5. Download SDK setup script:
wget http://repository.maemo.org/stable/5.0/maemo-sdk-install_5.0.sh
6. Since Hathor is based on Debian Squeeze, modify the install script to replace etch with squeeze.
sed -i -e 's/etch/squeeze/g' maemo-sdk-install_5.0.sh
7. Make the script executable and run it (as a normal user, outside scratchbox env).
chmod +x maemo-sdk-install_5.0.sh
./maemo-sdk-install_5.0.sh
8. In 'Package Selection' screen, choose "Runtime Environment + All Dev and Dbg packages" option. In 'Selection Summary' screen we will get
Installed Component: maemo-sdk-debug
x86 target name: FREMANTLE_X86
Armel target name: FREMANTLE_ARMEL
Overwrite existing targets: no
Proxy Server:
Alternative sources.list:
9. The SDK installation is not complete yet. After the successful completion of the above steps, we need to install Nokia-closed binaries for the target platform. To install Nokia binaries, we need to accept the EULA at the Nokia website.
10. Once we accept the EULA, we will get a token code and a source url with the token code to access the closed components of the SDK. The website says to not distribute or share the token code we get, and it is for personal use only.
The url will be of the format
deb http://repository.maemo.org/ fremantle/<theTokenCodeHere> nokia-binaries
11. Login to scratchbox.
/scratchbox/login
12. Select target platform and install the closed binaries. First we will select ARM and then x86.
sb-conf select FREMANTLE_ARMEL
13. Add the source url obtained in step 10 to /etc/apt/sources.list in the scratchbox armel environment.
vim /etc/apt/sources.list  #and add the source url to the nokia binaries
14. Update the package's list.
apt-get update
15. Install the Nokia binaries.
fakeroot apt-get install nokia-binaries nokia-apps
16. Once the above installation completes, choose change the target env to x86 and install the binaries of the x86 platform as well.
sb-conf select FREMANTLE_X86
To install the binaries, repeat the above steps from 13 to 15. After installation logout of the scratchbox env.
logout
With this the Maemo 5 SDK installation is complete and ready for development.
Happy Hacking!

Friday, 17 August 2012

Err: Dust.js - p.substr [undefined]

In android mobile browser, compiling a dust.js template caused the error "p.substr [undefined]". It worked fine in desktop browsers. The reason for the error was the closing of <input class="xyz" /> tag elements. Same in the case of img tag as well.
So writing the element like
<input type="hidden" name="someName" value="123">
<img src="pic.png" >
works fine.

Thursday, 9 August 2012

JQM: 'pageinit' & 'pagechange' Events

jQuery Mobile has many events associated with a page. Here we will discuss about the difference between 'pageinit' and 'pagechange' events. When a page is displayed for the first time 'pageinit' event will be fired. 'pagechange' event also fires here and for every page change. When we move from say page1 to page2 where page2 was not displayed before, 'pageinit' event will be fired. 'pagechange' event will also get fired since we changed the page from page1 to page2.

When we move from page2 to page1, where page1 was displayed previously, only 'pagechange' will be fired.

Friday, 20 July 2012

Center Align an Image

The easiest way to centre align an image in html is to wrap the <img> tag inside a <div> tag and text-align to center.
<!-- html elems -->
<div class="wrapper-img">
    <img src="images/pic.png">
</div>
/* css */
.wrapper-img {
    text-align: center;
}
Example of a centre aligned image using the above snippets:



Tuesday, 17 July 2012

JQM: Fix PhoneGap Android textarea Jumping Around

Android 2.3 browser is buggy when it comes to CSS3 properties. Recently we got this
weird bug when user types something in a textarea component. The page jumps around with
each character we typed.
We can fix that by not using any CSS3 3D properties like -webkit-transform: translate3d(0, 0, 0);.
Also, in the AndroidManifest.xml file add windowSoftInputMode="adjustPan" in the activity tag.
Modified activity tag will look like:
<activity
    android:name=".ProjectNameActivity"
    android:configChanges="orientation|keyboardHidden"
    android:windowSoftInputMode="adjustPan"
    android:label="@string/app_name">

Tuesday, 3 July 2012

Make STS Faster with STS.ini & Java Opts Settings

If you have a system with 3 GB RAM you can use the following settings to make your STS faster than the default.

STS.ini settings
-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
com.springsource.sts.ide
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
384M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=256m
-XX:MaxPermSize=512m
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=50
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:+UserParallelGC
JAVA_OPTS environment variable value:
-Xms512m -Xmx1g

Sunday, 24 June 2012

Nokia N900: Validating Facebook Sharing - Network Error

Recently I got the error message, "No network connection available, operation cancelled", when I try to add a facebook sharing account. The problem is with the curl library. We need to update it the to latest version. Add extras-devel, extras-testing repository if you cannot find the library in the stable channel.
Open terminal (Ctrl + Shift + X) and give the following commands:
root #change to root user
apt-get install libcurl3
Now re-validate your facebook account from the sharing accounts.

Thursday, 14 June 2012

JQM: Refresh jQuery Mobile Select Menu

Suppose you are adding select menu to the page dynamically using JavaScript, jQuery mobile will not style the select menu. So have to refresh the select menu.
$('.mySelectMenu').selectmenu('refresh', true);
Sometime we might get an error like: "Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'". To resolve it by first initialize the select menu and then refreshing it.
$('.mySelectMenu').selectmenu();
$('.mySelectMenu').selectmenu('refresh', true);
20 Nov 2012: Update with JQM 1.2.0 code explanation given below.
Make sure that the selector returns items which are all select nodes. Otherwise JQM will throw the above mentioned error. See the below JQM code.
// jQM v1.2.0: line 516
// ...
if ( isMethodCall ) {
    this.each(function() {
        var methodValue,
            instance = $.data( this, fullName );
        if ( !instance ) {
            return $.error( "cannot call methods on " + name + " prior to initialization; " +
                "attempted to call method '" + options + "'" );
        }
        // ...
    });
}
// ...
The code at line 6 checks for mobileSelectmenu property in the current element and assigns to the instance variable. If the current item is not select then the instance is null and we get the error.

Wednesday, 23 May 2012

Project Level Extra Properties in Gradle Script

We can have project level 'extra' properties in gradle. These properties are accessible throughout the script.
To set some properties, we can do it as
project.ext {
  myVar = "A variable"
  isProcessStarted = null
}
Some examples of using these properties are given below.
/** Task which starts some process */
task startProcess() << {
  project.isProcessStarted = true
}
/** Task which stops a process */
task stopProcess() << {
  project.isProcessStarted = false
}
/* Stop the process only if the process was started */
stopProcess.onlyIf { project.isProcessStarted == true }

Add Host Entries in Android Emulator

You can add host entries in the android emulator using the following commands.
1. You need to mount the android emulator's file system in read write mode.
2. Then upload the modified host entry to /system/etc/
adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock0 /system #mount as rw
adb push hosts /system/etc/ #where hosts file contain our modified host entries
However the changes does not seem to persist. So we need run this script every time we start the emulator.

Monday, 21 May 2012

JQM: Accordian - Change Right Plus & Minus Icon to Arrow Icons

The recommended way to change the plus and minus icons of the collapsible sets (accordian) in jQuery Mobile is to specify data-expanded-icon and data-collapsed-icon attribute to the div. But sometimes it does not change the icons. In such cases we can change it manually by overriding the .ui-icon-plus and .ui-icon-minus classes giving the background-position for the down and up arrows. Add a class eg-accordion to the div with data-role="collapsible-set" and see the below CSS overrides.
eg:
.eg-accordion .ui-icon-plus {
    background-position: -216px 50%; /*override the '+' with down arrow*/
}
.eg-accordion .ui-icon-minus {
    background-position: -180px 50%; /*override the '-' with up arrow*/
}

Sunday, 13 May 2012

jQuery: Show or Hide an Element on Click

To show or hide an element when use click on a button, you can use jQuery's .toggle() method. It toggles the display of that node. It adds a style display: none; and display: block alternatively, with each click.
//js
//listen for the button click event
$('.myElemBtn').on('click', function (e) {
    $('.myElem').toggle();  // toggle visibility
}

jQuery: Get the Closest Node From the Current Node

Say that you are in an event handler function and you want to get the closest element that matches certain conditions from the current event's target node. You can use .closest() method provided by jQuery.
<!-- html -->
<div class="topElem" data-id="1" >
    <div>First child elem of first div</div>
    <img class="imgElem" src="pic.png">/>
</div>
<div class="topElem" data-id="2" >
    <div">First child elem of second div</div>
    <img class="imgElem" src="pic.png">/>
</div>
Here we want to get the value from the data-id attribute of the parent div (containing class topElem) when the user clicks on the image.
//js
// event listener
$('.imgElem').on('click', function (e) {
    $(e.target).closest("div.topElem");  // will give you the parent div with the class 'topElem'
    $(e.target).closest("div.topElem").data('id'); //will give you the value of the data-id attribute
});
.closest() returns only one element matching your selection criteria where as .parents() returns all the matched elements. Also there is significant difference in the way that both these methods work. .parents() travels all the way up to the DOM's root element and then filters the collection. .closest() travels the hierarchy until it finds the matched element and then returns. So if you want to get only one element, then .closest() is more efficient.

Using .parents() the above code would be
// js
// event listener
$('.imgElem').on('click', function (e) {
    $(e.target).parents("div.topElem");  // will give you the parent div with the class 'topElem'
    $(e.target).parents("div.topElem").data('id'); //will give you the value of the data-id attribute
});

Thursday, 12 April 2012

Unit Test Grails Domain Class having a Relational Mapping

Let's say that we have two domain classes Book.groovy and Library.groovy.
//Book.groovy
package com.example.book

class Book {
    static constraint = {
        name blank: false, size: 2..255, unique: true
    }
    static belongsTo = [lib: Library]
    String name
}

//Library.groovy
package com.example.library

class Library {
    static hasMany = [book: Book, branch: Branch]
    static constraints = {
        name blank: false
        place blank: false
    }
    String name
    String place
}

To unit test Book class you need to create an object of Library class since Book 'belongsTo' library with a back reference.

So our unit test will be:
//BookUnitTests.groovy
package com.example.book

import grails.test.*
import com.example.library.*

class BookUnitTests extends GrailsUnitTestCase {
    
    def b    //book
    def lib  //library

    protected void setUp() {
        super.setUp()
        lib = new Library(name: "My Library", place: "XYZ Ave")
        mockForConstraintsTests(Book)
    }

    protected void tearDown() {
        super.tearDown()
    }

    void testPass() {
        b = new Book(name: "MyBook", lib: lib)    //pass the Library object to which the book belongs to.
        assert b.validate()
    }
}

Uninstall Subclipse from STS

Subversive plugin for STS is much better than subclipse svn plugin. Install subversive, and then uninstall subclipse by going to STS Help->'About SpringSource Tool Suite'->'Installation Details'->'Installed Software' and remove the ones with 'id' containing org.tigris.
Next navigate to STS plugin directory from the command line and run the following commands:
$ ls |grep org.tigris.subversion|xargs rm -rf
01 May 2012 Update: After working with this plugin for around three weeks, I find it difficult to make directory changes. I find it difficult to use STS with subversive plugin. I agree that it has got more options than subclipse, but when it comes to daily operations like commit, rename, delete directories, branching, it is a big mess (at least for me). So I am back to subclipse.

Sunday, 19 February 2012

Configure Japanese Locale in Debian

I'm using CrunchBang (#!) and I find Japanese fonts missing. To configure Japanese locale in Debian do the following.
1. Install the following:
sudo apt-get install ttf-kochi-gothic ttf-kochi-mincho ttf-sazanami-mincho xfonts-intl-japanese
2. Now you need to reconfigure the locale.
sudo dpkg-reconfigure locales
In the 'locales to be generated' dialog box, choose "ja_JP.UTF-8 UTF-8". If you use English, choose "en_GB.UTF-8 UTF-8" or "en_US.UTF-8 UTF-8", which ever is appropriate and click Ok. Next choose you default locale.
3. Reboot (or logout session, which ever works).

Tuesday, 7 February 2012

Pyramid - ImportError: No module named config

'ImportError: No module named config' error occurs due to the naming conflict. If you named your test file as pyramid.py, then you are most like to get this error when you try out the pyramid web framework examples. Simply use a different name for your file.

Monday, 30 January 2012

ghc error: libgmp.so.3 cannot open shared object file

When trying to configure the latest binary of ghc (7.0.4) under Kubuntu 11.10, you might most probably get an error like: "libgmp.so.3: cannot open shared object file". You need libgmp3c2 installed before trying to configure ghc.
sudo apt-get install libgmp-dev libgmp3-dev libgmp3c2
Now you can do a ./configure.

Monday, 23 January 2012

Compile and Install BigInt as a Shared Library in Kubuntu

BigInt is an awesome library that allow us to write C/C++ programs that use arbitrary precision arithmetic. Here we'll go through on how to setup the library as a shared object under GNU/Linux (Kubuntu).
#Download the library
wget https://mattmccutchen.net/bigint/bigint-2010.04.30.tar.bz2 --no-check-certificate
#Extract it
tar -xvf bigint-2010.04.30.tar.bz2
#Rename it to bigint
mv bigint-2010.04.30 bigint
#copy it to the include dir
sudo mkdir -p /usr/local/include/bigint/
sudo cp bigint/* /usr/local/include/bigint/
#creating shared library
#create object files
g++ -fpic -c BigInteger.cc BigIntegerAlgorithms.cc BigIntegerUtils.cc BigUnsigned.cc BigUnsignedInABase.cc
#create shared library called libbigint.so which can be invoked using -lbigint
g++ -shared -o libbigint.so BigInteger.o BigIntegerAlgorithms.o BigIntegerUtils.o BigUnsigned.o BigUnsignedInABase.o
#copy it into the local lib dir
sudo cp libbigint.so /usr/local/lib/
#configure ldconfig (dynamic linker runtime bindings) to rebuild the shared library cache
#note that ldconfig should contain the path where you copied the libbigint.so file
#/usr/local/lib is already added. You can add additional paths in /etc/ld.so.conf.d/
sudo /sbin/ldconfig -v /usr/local/lib
-fpic or -fPIC means position independent code.
Now that the library & the environment is ready, let's write a small program and verify it.
// big.cpp
#include <iostream>
#include <bigint/BigIntegerLibrary.hh>

using namespace std;

int main()
{
    BigInteger a = 31415926535;
    cout << a * a * a * a * a * a * a * a << endl;
    return 0;
}
Compile & run
g++ big.cpp -o big -lbigint
./big
#output
948853101390095872711467085400133633064593764027907283066796117781702198979687890625

Sunday, 22 January 2012

Kubuntu 11.10 Installer Crashed

I got this weird bug that tells that the Kubuntu installer has crashed. I tried to install three times and the same thing happened. Later I changed the file format for the root partition and everthing got sorted out. The problem was that I was using btrfs as the file format for the root partition, which lead to the error. Now that I have changed to ext4 for root, Kubuntu installs fine. You can use btrfs for other partitions like /home and not for root at the moment.

Sunday, 8 January 2012

Change URL of blog posts in blogger

Sometimes, after editing your post, the URL for the blog post might end up like _02.html. So to edit the url, there are two ways. If you don't have any comments, then you can create another post with the desired title, so that the url follows the title, and paste the contents of the post. Then you can schedule the post to be somewhere near the original post's date and time, and then publish the new post. After that you can delete the old post.
If you seriously messed up the urls, then export the blog & it's template. Then rename the current blog to a random address, and create a new blog with the original blog's address. Import the posts and template to the newly created blog and delete the old blog.

Saturday, 7 January 2012

Tooltip on Hovering Links

We can use CSS alone to display tooltip when we hover on links. The idea is that we'll add a span tag to the anchor text and hide them initially using display: none; for the span tag. Only when we hover, we'll display the span tag by changing display to block.
Say I need to show tooltip "..lost in silence" when I hover on a link with text 'kadaj'. Then the anchor tag will be
<a id="t1" href="">kadaj<span>..lost in silence</span></a>
and the CSS for that is
/* hide span tag in the anchor tag (which is our tooltip) */
#t1 span {
display: none;
}

/* on hover show the span tag (tooltip) */
#t1:hover span {
display: block;
position: absolute;
top: 11em;  /* depends on the position of the link */
left: 6em;  /* depends on the position of the link */
border-radius: 3px;
text-align: center;
font: 10px Verdana, sans-serif;
padding: 0 .5em 1.5em .5em;
margin: .5em;
width: 13em;
z-index: 100;  /* to show on top of other elements */
border:1px solid darkcyan;
background-color: lightcyan;
opacity: .9;
color: black;
}

/* styling tooltip image */
#t1:hover span img {
position: relative;
top: .7em;
left: .2em;
z-index: 100;
}
The only thing that changes is the top and left value depending on where the tooltip should appear when you hover on the link. However, there is a drawback when using this method. It will work only if the position of the link is fixed. Here we are using absolute position for the tooltip, so if the position of the link changes, the position of the tooltip won't change, unless you use javascript and change it accordingly. It is good for pages with fixed layout. Not ideal for blog posts, where the position of the post changes when new posts appear.
Demo

Friday, 6 January 2012

Detect if the current page is running in an iframe

This is a code snippet to detect if the current page is running in a frame or not.
if (top === self) {
//not in an iframe
} else {
//in an iframe
}

Page Navigation for AJAX driven websites using Html5 History API

Html5 History API provides a way to maintain history of the current session. This information can be used for page navigations. It will really come handy when you are using AJAX to load pages and want to have browser navigation (back/forward) active. Using Html5 History API, we will maintain the history and use it for navigating back and forth using browser's navigation button. We will use 'hashchange' event and hashtags for urls.
To navigate using the browser's default navigation buttons, i.e, by using the back and forward buttons, there must be a change in the URL. The navigation buttons get active only if the URL of the current window (page) changes. When we use AJAX (JSON), the URL of the current window doesn't change. So we won't have any active navigation, which implies, no history as well.
To add hash to the URL without causing the page navigation, we'll use
window.history.pushState(null, "", "#hashtag") method. We need to be concerned mainly about the third parameter, which is the hashtag string. After that we'll trigger a 'hashchange' event $(this).trigger("hashchange");.

These are some of the notable functions in the history API.

window.history.pushState(data, title, url)
@param data
data is generally something that is specific to the context of the particular page.
Say in the first page you retreive data in JSON format. Say our data is:
{
page: '1',
title: "Tutorial",
category: "Html5",
desc: "intro"
}
So when we want to navigate to another page we can save that data so that, the next time when we revisit, popstate will fire and you can retreive the data through event.originalEvent.state object.

@param title
The second parameter can be any string.

@param url
Can be hashtag or a string. Note that you can't change the baseURI,
or it will throw SECURITY_ERR exception. Otherwise it will be easy for URL spoofing. This value will be appended to the baseURI without loading the appended URL. This will activate the browser history, so that we'll have active back and forward button.

The 'popstate' event
When you navigate in history, popstate will be fired, and the data corresponding to the state will be popped. Theses data objects are kept in a stack using the pushState function explained above.

window.location.hash
This variable will contain the current hashtag of the window

The 'hashchange' event
'hashchange' event is will be fired whenever there is a change in navigation, i.e if you travel back and forth in history, each time the hashchange event will be fired. So we can listen for the hashchange event and depending on the hash, which we can obtain from window.location.hash, we can take the necessary action. Since we already listen for the hashchange event, we'll trigger the event when the user clicks the page's anchor link to go to that particular page. Otherwise, we can write a separate way to deal with clicking anchor links as opposed to clicking back/forward buttons, which isn't really necessary. So that's the reason we trigger 'hashchange' event manually.

window.history.replaceState(data, title, url)
This function is same as that of push state. But instead of pushing a new state to the stack, it will replace the top state (from the stack) with the one specified in this function.

Live Demo | View Source

Tuesday, 3 January 2012

Add script tags to DOM dynamically using javascript

Here is a little snippet for adding <script> tags dynamically to your html file using javascript and DOM api.
// Add scripts to DOM by creating a script tag dynamically.
// @param {String=} url Url of a js file
// @param {String=} src Script source code to add the source directly.
// NB: At least one of the parameters must be specified.
var hookScripts = function(url, src) {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = url || null;
    s.innerHTML = src || null;
    document.getElementsByTagName("head")[0].appendChild(s);
};
// usage eg:
hookScripts('url/path/to/myscript.js');  //url
hookScripts(null, 'alert("hello");');  //giving the source code directly
We use the native DOM API instead of jQuery for this particular case because of the way jQuery treats <script> tags. jQuery inserts script to DOM, then evaluates the script separately and then it removes the tag from the DOM. So you won't see the script tag, but the script will get executed.

Add stylesheets to DOM dynamically using jquery

This is a code snippet to add stylesheets to DOM dynamically using javascript.
// Add stylesheets to DOM by creating a link tag dynamically.
// @param {String} url The stylesheet url.
var hookLinks = function(url) {
    var link = $('');
    link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: url
    });
    $('head').append(link);
};
//usage eg:
hookLinks('url/to/stylesheet.css');

Import emails from Thunderbird to Windows Live Mail Client

Windows Live Mail client looks better than Thunderbird. If you want to migrate to Windows Live Mail client from Thunderbird, then do as follows:
1. First, you need to backup the Thunderbird folder under the C:\Documents and Settings\<your-user-name>\Application Data folder and any local folders if any.
2. Install ImportExportTools add-on and restart thunderbird.
3. Right-click on the folder which contain the mails you want to export. Say Inbox, Sent Mail etc, and choose Import/Export -> Export all messages in the folder to EML Format from the context menu. Choose a location to save the exports, say C:\mails\eml-format\Inbox for inbox and C:\mails\eml-format\Sent Mails for sent mails.
4. Open Windows Live Mail client and from the File menu choose Import -> Messages -> Live Mail. Choose the directory from the previous step where we saved the mails. So at first we will import mails from Inbox folder, so we'll choose C:\mails\eml-format\Inbox folder. Click Next and choose All folders, and complete the import wizard. Similarly for the other folders.
5. If you have successfully imported the emails, then it will be shown under the Storage Folders -> Imported Folders section on the left pane. Now you can select all the emails under that folder and drag-and-drop to Inbox or any other folder, and organize them accordingly.
5. Voila! Enjoy new Windows Live Mail client.

Generating diff files

To generate diff between two files the command is:
diff -ru originalfile modifiedfile >patch.diff
#eg:
diff -ru script.orig.js script.js >bugfix-1234.diff
If you are using IDEs like Eclipse with SVN plugins, then to generate a diff file, right-click on the file and choose Team -> Create Patch -> Save in File System (browse to the directory of your choice and give the file a name, say patch.diff) and click next. Choose Selection and click Finish.

Monday, 2 January 2012

Install HDBC-sqlite3 in windows

HDBC-sqlite3 is a package that provides support for sqlite db interaction for Haskell. To install it in Windows you need to have sqlite source.
1. Download the sqlite source code and extract to any directory, let's say 'C:\sqlite'.
2. Run
cabal update
cabal install HDBC-sqlite3 --extra-lib-dirs=C:\sqlite --extra-include-dirs=C:\sqlite