December 21, 2011

Converting a space delimited sentence into a sequence of null terminated strings

The title says it all, you are given a string which consists of words separated by spaces, here is a snippet of code for converting the same into a sequence of null terminated strings and then later printing them. Returning the indices in the original string where the words begin is the key here :

Printing the strings is pretty trivial as :

Quick code, picked up the hack from a certain shell command parsing code in Xinu.

December 20, 2011

Intents and Activities in Android

The android UI is built around the concept of Activities. Each screen you see when you use an android app is an activity. And as usual, each activity has a layout that in programming methodology can only be accessed by the thread which set/created the layout. Android however has better method for creating activities and getting back information from them than purely language oriented methods (like global variables, shared objects etc). Android defines the notion of an intent, which can be used to give some information to an Activity and also get back information from an activity as an intent. The general code flow looks like the following :

create an intent and start the activity :

 final int result = 1;
Intent intent = new Intent(VoipChat.this, UserSettings.class);
startActivityForResult(intent, result);

Add code in the event handler when an activity returns ( you need to check for the specific return code which is the same as result)

   public void onActivityResult(int requestCode, int resultCode, Intent data) {
                 if (resultCode == Activity.RESULT_OK && requestCode == 1) {
                                    //Do some work here

In the activity class which is started, make sure you put the necessary data in a new intent before calling the finish() method. The code in for example would look something like :

   Bundle bundle = new Bundle();
Log.d("USERSETTINGS", "Returning : "+userName.getText().toString());
bundle.putString("UserName", userName.getText().toString());
this.setResult(RESULT_OK, data);

Accordingly the code inside the if block above would look something like :
   String result = data.getExtras().getString("UserName");

note that data is the intent variable in the arguments for the onActivityResult() method.

NOTE : This blog post contains very specific information about the android sdk and included libraries. Unlike most of the other posts on this blog, it may not be of interest to the general readers.

December 06, 2011

Disabling auto indentation for code pasting in vim

If you are a vim user and have automatic indentation enabled, then you have sure been through the trouble of trying to paste indented code and messing up the indentation completely. There is however a fix for this , you can temporarily disable code indentation when you are pasting text. Add the following to your vim configuration file (mostly ~/.vimrc) :

set pastetoggle=<key sequence>

You can set whatever key sequence you want and if you do not have any other mapping for that key sequence, you just need to hit the key sequence and then "i" for insert and paste the text. Insert will generally show you the mode, for example if you have paste mode enabled, you will see

-- INSERT (paste) --

You can disable the paste mode using the same sequence as above. On my machine I have the sequence  set to <leader><C-p>, (my leader key is bound to the default ",")

set pastetoggle=<leader><C-p>

So hitting, "," and then Ctrl-p toggles the mode on vim on my machine.

October 03, 2011

Per host username configuration for ssh

Using ssh to access many remote servers is a common scenario and more often the user names on these servers might be different from the one on the local machine and/or different among themselves. Ssh allows one to set the default username to use per host. You need to edit either the user specific configuration file (~/.ssh/config) or the system wide configuration file (/etc/ssh/ssh_config) and add the following :

1     Host <hostname>
2          User <username>

You can add as many entries as you want like above and the next time you can just do

$ ssh <hostname>

and ssh will try to log you in with the default username specified for that host in the configuration file.
More information on ssh can be found on the ssh man page (man ssh) and more information about the ssh configuration options can be found on the ssh_config man page(man ssh_config). (BTW, setting up passphrase-less ssh authentication is suggested if you connect to the remote servers very often and if security is not of high priority).

August 21, 2011

Letting it go ...

No system is efficient, there are memory leaks, there are application freezes, and some never work at all, you cannot keep a system up for ever, even the most resilient of servers have to be rebooted once in a while.
It so happens in life too, you need to let it go, to forget all the things that you have seen, heard and been through so far, this is not a foolish blog post with the constant onslaught of 'a' someone's thoughts in the hindsight of the mind. It is rather a realization, once in a while, you need to let it go, discard all the burden that has come as part of the memories that so form the foundation of our (everyone's) existence. The multitude of neurons in the head will take a few days if not weeks to flush the changes through to the deepest reaches of the synapses, but you have to start it somewhere and let it go, start afresh. I feel that need now more than ever, but this of all things in the world is something you cannot verify, still you just have to go with the feeling that your heart asked your mind to let it go and the grey blob paid heed, you will however never know for sure that it did or not until another day when all the melancholy is triggered [again] by that one memory you have tried to let go time and over  !

July 27, 2011

Converting paths on a linux filesystem to WINE relative paths

Wine is a windows software emulator for Linux. Wine generally installs itself to ~/.wine and the C:\ Drive for the corresponding emulated windows environment is ~/.wine/drive_c/ . Wine sees the actually filesystem as mounted under a emulated Z:\ drive, so for example /mnt on the linux filesystem becomes Z:\mnt. To automatically run windows programs which require files from the linux filesystem, it is nifty if the linux filesystem path for a file can be converted to the emulated version starting with Z:\ , here is a small snippet of code which does that for the current working directory :

$ echo Z:`pwd` | sed 's/\//\\/g'

It gets the absolute path for the current working directory and converts all forward slashes ('/') to backward slashes ('\') and prepends the drive letter (Z:) to it. Now adapting the above snippet to get the wine path for a normal file is quite easy, and is left for those who are interested

Setting up password less authentication between two linux machines

Setting up password less authentication between two machines is a common requirement for many distributed software to work, some examples being hadoop, MPI etc ... however it is sometimes also handy if you are a system administrator and frequently login to a remote machine. Now the ssh-copy-id utility already exists to copy the ssh public key from the current machine to the remote machine. But if you have to copy the key from the remote machine to the local machine you have to first login to the remote machine, and then use ssh-copy-id (or some other method) from there. Here is a handy bash script to do the same.

set -x
if [ $# -eq 0 ]; then
echo "Usage : setup_ssh <local_interface> <remote_ip> [<remote_user>]"
echo "Example : setup_ssh wlan0"
exit 1
my_ip=$(ifconfig $interface | grep "inet addr" | sed 's/inet addr://g' | awk '{print $1}')
if [ $? -ne 0 ]; then
echo "Could not get the current machines ip"
exit 1
if [ $# -eq 3 ];then 
if [ "$user" = "root" ]; then
echo "Checking for remote copy program .."
which scp
if [ $? -eq 0 ]; then
which rsync
if [ $? -eq 0 ]; then
echo "Could not find a remote copy program, quitting !"
exit 1
which ssh-copy-id
if [ $? -ne 0 ]; then
echo "Could not find ssh-copy-id "
exit 1
if ! [ -f ~/.ssh/ ]; then
echo "Could not find the default public key : ~/.ssh/"
exit 1
echo "ssh-copy-id $user@$remote_ip"
ssh-copy-id $user@$remote_ip
$remote_copy $user@$remote_ip:$remote_home/*.pub ./
cat *.pub >> ~/.ssh/authorized_keys
rm -rf *.pub
if [ $? -ne 0 ];then
echo "Copying the public keys failed ... quitting "
exit 1
echo "Successfull"
exit 0

Note that the script only works in one of the following two formats :

$ ssh-setup interface remote_ip remote_user 
$ ssh-setup interface remote_ip 

The remote ip need not only be an ip address, as you would have already understood from the script, it can also be a hostname or some handle which can be resolved to an ip address.

A sample execution would look like  :

$ ssh-setup wlan0 root

Note : This script has only been tested on a linux machine (Fedora 14 ) and I do not assure you of its functionality, use at your own risk.

July 15, 2011

Modifying SWT widgets from outside the event thread / Using a single display with SWT on linux

Like most GUI frameworks , SWT ( which itself is a wrapper over the native windowing system) has an event loop, more over it has other restrictions on the way the widgets/elements within the GUI can be modified. The main item of importance in a SWT based GUI is the display, created like :

Display display = new Display()

now, on linux (x64 at least to the extent I have tested), SWT does not support multiple displays. So you have to use one display entity to drive all your GUI components, this can especially get really troublesome if your GUI has multiple components and windows. Logically making the code modular (splitting the code for each window into may be different classes imposes its own issues) will result in problems.
This is because, SWT allows the GUI widgets to be accessed/modified only from the thread in which the display was created. If you try to access it from outside this thread, you will end up with a SWTException : Invalid thread access.  Here are the possible fixes for this :

  • Declare the display as a static variable so that you have access to it based on the class name
  • Now whenever you need to change something in the GUI, assume you have a function changeWidgetStyle( Params ) which changes the widget style, then you can call the function as : 
                                 <Class Name>.display.asyncExec(new Runnable(){ 
                                                    public void run(){
                                                                  changeWidgetStyle( Params );

  • Now the code inside the changeWidgetStyle function can access and modify any components of the GUI. I guess SWT imposes this restriction to make the event thread as responsive as possible.
  • Use the display.syncExec() method with exactly the same syntax if you want to wait for the execution of the function to complete.
I will try to post a code example soon ( as I find some more time). !

Configuring java using the alternatives system (on Fedora/Centos/Redhat)

On most red-hat based systems, alternative versions of the same software (from say different vendors) are managed using the "alternatives" system. Here is an example :

$ which java | xargs file
/usr/bin/java: symbolic link to `/etc/alternatives/java'
$ file /etc/alternatives/java
/etc/alternatives/java: symbolic link to `/usr/lib/jvm/jre-1.6.0-openjdk.x86_64/bin/java'

Here in this case we are looking at the java pointing to the one bundled by openjdk. Say if you have installed the Sun (or Oracle rather :|) JDK and if the path to that is /opt/java/bin , then you can add the sun version of java to the alternatives system using : 

$ alternatives --install /usr/bin/java java /opt/java/bin/java 100000 

The last number there is a priority, set it high so that any priority based overrides are ineffective. Now by doing : 

$ alternatives --config java 

you should be able to switch between the alternative versions of java !

July 13, 2011

The number of f**ks and sh**ts in the linux kernel source !

I was getting bored with my work and started trying to write out a fast parser in C which given a directory prints out the number of occurrences of fu*cks and sh**ts in files inside that directory. The program is here . I ran this program on the current stable linux kernel Here are the interesting results ( I wrapped up the results from the C program to convert them to links to the source on the web using a simple python script, so that anyone interested can verify the count for themselves). It took the program a little more than 6 seconds (~ 6.3 secs) to complete parsing the entire kernel source.

Found a shit in;a=blob;f=drivers/mmc/host/sdhci.c
Found a fuck in;a=blob;f=drivers/media/video/bt819.c
Found 9 shits in;a=blob;f=drivers/media/video/zoran/zr36050.c
Found 9 shits in;a=blob;f=drivers/media/video/zoran/zr36060.c
Found a shit in;a=blob;f=drivers/media/video/zoran/zr36016.c
Found a shit in;a=blob;f=drivers/scsi/qlogicpti.c
Found a fuck in;a=blob;f=drivers/scsi/qlogicpti.h
Found a shit in;a=blob;f=drivers/block/ub.c
Found a fuck in;a=blob;f=drivers/mtd/mtd_blkdevs.c
Found a shit in;a=blob;f=drivers/net/declance.c
Found 2 shits in;a=blob;f=drivers/net/niu.h
Found 2 fucks in;a=blob;f=drivers/net/sunhme.c
Found a shit in;a=blob;f=drivers/net/sunhme.c
Found a shit in;a=blob;f=drivers/net/wan/z85230.c
Found a shit in;a=blob;f=drivers/net/wireless/iwlegacy/iwl3945-base.c
Found a shit in;a=blob;f=drivers/net/sunlance.c
Found a shit in;a=blob;f=drivers/video/aty/radeon_pm.c
Found 2 shits in;a=blob;f=drivers/video/sis/sis_main.c
Found a shit in;a=blob;f=drivers/macintosh/adb.c
Found 2 shits in;a=blob;f=drivers/staging/slicoss/slicoss.c
Found a shit in;a=blob;f=drivers/ata/sata_via.c
Found a fuck in;a=blob;f=drivers/ide/cmd640.c
Found a shit in;a=blob;f=sound/oss/uart6850.c
Found a shit in;a=blob;f=sound/pci/cs46xx/dsp_spos_scb_lib.c
Found a shit in;a=blob;f=sound/pci/ac97/ac97_patch.c
Found a shit in;a=blob;f=Documentation/ManagementStyle
Found a fuck in;a=blob;f=Documentation/DocBook/kernel-locking.tmpl
Found a shit in;a=blob;f=Documentation/DocBook/kernel-hacking.tmpl
Found a shit in;a=blob;f=include/linux/fb.h
Found a fuck in;a=blob;f=lib/vsprintf.c
Found a shit in;a=blob;f=net/ipv4/tcp_input.c
Found a fuck in;a=blob;f=net/ipv4/netfilter/nf_nat_snmp_basic.c
Found a fuck in;a=blob;f=net/core/skbuff.c
Found a fuck in;a=blob;f=fs/notify/inotify/inotify_user.c
Found a shit in;a=blob;f=fs/jffs2/dir.c
Found a shit in;a=blob;f=fs/isofs/inode.c
Found 2 fucks in;a=blob;f=fs/xfs/xfs_btree.h
Found 24 fucks in;a=blob;f=arch/mips/pci/ops-bridge.c
Found a shit in;a=blob;f=arch/mips/kernel/genex.S
Found a shit in;a=blob;f=arch/mips/include/asm/mipsprom.h
Found a fuck in;a=blob;f=arch/mips/sgi-ip22/ip22-setup.c
Found a fuck in;a=blob;f=arch/m68k/include/asm/sun3ints.h
Found a fuck in;a=blob;f=arch/x86/kernel/cpu/cpufreq/powernow-k7.c
Found a shit in;a=blob;f=arch/x86/platform/visws/visws_quirks.c
Found a shit in;a=blob;f=arch/sparc/mm/ultra.S
Found a shit in;a=blob;f=arch/sparc/mm/srmmu.c
Found a fuck in;a=blob;f=arch/sparc/kernel/head_32.S
Found a shit in;a=blob;f=arch/sparc/kernel/traps_64.c
Found a shit in;a=blob;f=arch/sparc/kernel/pcic.c
Found a shit in;a=blob;f=arch/sparc/lib/checksum_32.S
Found a fuck in;a=blob;f=arch/parisc/kernel/sys_parisc.c
Found 42 f words and 53 s words !

Note : Don't go by the run time of the program, my machine has a i7 and is pretty fast !

EDIT : Considering the attention this post has been getting, the words matched are : *fuck* and *shit~[a-z], the program is of course not case sensitive, and as is obvious , it is not a perfect matching program, it was just a half an hour worth coding experiment !

June 15, 2011

rcat - Concatenate to a remote file

I have recently had the need to do something like "cat file1 >> file2", but where file2 sits on a remote machine. Most users can also think of the most common use case for this, when you have to concatenate your (public key) to the authorized_keys list on another machine. I came up with a small hack to do the same which uses rsync behind the scenes, here is how it looks :

#script to remotely concatenate files.
#args -> rcat file1 file2 
#concatenates file1 to remote file file2
username=`echo $2 | sed 's/:/\t/g' | awk '{print $1}' | sed 's/@/\t/g' | awk '{print $1}'`
remote_host=`echo $2 | sed 's/:/\t/g' | awk '{print $1}' | sed 's/@/\t/g' | awk '{print $2}'`
remote_file=`echo $2 | sed 's/:/\t/g' | awk '{print $2}'`
file_name=`echo $local_file  | sed 's/\// /g' | awk '{print $NF}'`
if [ -d $local_file ] ;
echo "Cannot cat a directory"
echo "Qutting"
rsync $local_file $username@$remote_host:$temp_folder/
ssh $username@$remote_host "cat $temp_folder/$file_name >> $remote_file && rm -rf $temp_folder/"
echo "done"
echo "rcat $local_file $username@$remote_host:$remote_file"

the bad thing about the script right now is that it will ask for authentication twice. But the good thing is that you need not manually sync the files and then concatenate them. The syntax for the remote file is similar to rsync, scp etc. 
rcat [local_file] [username]@[remote_host]:[remote_file]

There is a utility "ssh-copy-id" to copy the public keys across systems.

June 03, 2011

adding the Power Off option to the statusMenu in gnome-shell

The status menu, which is the dropdown menu to the right most corner on the top panel in gnome 3 contains the Suspend option. This is an alternating option, if you focus on the Suspend option and hit the "Alt" key, you will also see the "Power Off" option.

But I wanted the "Power Off" option to be shown in all cases along with the Suspend option. Here is how I dissected the issue (for the facts, this is the first time I am even looking at gnome 3 code).

1) Located the gnome-shell repository at, searched for "Suspend" , and landed at the commit,

2) Going through the above commit, figured out that the corresponding UI stuff is in

3) Cloned the gnome-shell repository. Edited the file gnome-shell/src/js/ui/statusMenu.js and made the following changes :
--> Made the Suspend option a non-alternating Menu item and display it only if we have suspend support.
--> Added the Power Off option as a new menu item and added a function which would be called when the option is activated.

Voila , I now have the Power Off option as a separate option. Here are the before and after screenshots.

The patch to the latest trunk of the gnome-shell repository which does this is here.

For compiling the gnome-shell code once you have made the changes, follow the usual, "configure", "make" steps and then run "gnome-shell/src/gnome-shell --replace" to use the newly compiled gnome-shell instead of your existing gnome-shell.

This post is more aimed at providing a general flow for fixing issues, not really much in here.

merging commits into a single patch with git-rebase

It is often the scenario that you have cloned a git repository and you have made some changes, now you cannot push to the repository and need to go through a reviewer, so you basically have to submit all your commits to the code as a single patch. Here is how :

We are going to use the repository http:// all through the process as the remote repository. It only has a single file, README, and has just one commit with the default branch.

1) Clone the repository :

$ git clone [email protected]:eerpini/git_demo.git

and then change into the directory git_demo.

2) Add a new file :

$ touch new_file
$ echo "Entering something into the new file" >> new_file

3) Since the new file is untracked, "git status" should show something like :

# On branch master
# Untracked files:
# (use "git add ..." to include in what will be committed)
# new_file
nothing added to commit but untracked files present (use "git add" to track)

4) Add the file and commit :

$ git add new_file
$ git commit -a -m "Adding a new file to the repository"

Note you can now get the change as a patch by doing "git format-patch -1 HEAD". But that is not our goal.

5) Just like above lets commit some more changes(add another file for simplicity).

$ touch new_file_2
$ echo "Entering something into the second new file" >> new_file_2
$ git add new_file_2
$ git commit -a -m "Added the second file to the repository, this should be the second commit"

6) Now we have two commits and "git status" should show you this :

# On branch master
# Your branch is ahead of 'origin/master' by 2 commits.
nothing to commit (working directory clean)

7)Now if you want to submit all the changes you have made so far as a single patch, you need to first rebase the two commits into a single one. This is how you do it :

$ git rebase -i origin/master

This will show you the following text in your editor :

pick d5d924c Adding a new file to the repository
pick c0883ac Added the second file to the repository, this should be the second commit

# Rebase 879598c..c0883ac onto 879598c
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.

Edit the above text, basically changing the keywords from pick to something else. If you want only the commit message from one of them, change all the others to fixup or squash. I used squash (edit as follows) :

pick d5d924c Adding a new file to the repository
squash c0883ac Added the second file to the repository, this should be the second commit

Now you can see that both the commits have been combined into a single commit. You can check either using "git log" or "git show HEAD". You can convert these changes into a single patch now using :

$ git format-patch -1 HEAD

In my case, this ended up being :

From 11d19a54021cccdf75e5f16d46eeff89c275be39 Mon Sep 17 00:00:00 2001
From: eerpini
Date: Fri, 3 Jun 2011 01:39:45 -0700
Subject: [PATCH] Adding a new file to the repository

Added the second file to the repository, this should be the second commit
new_file | 1 +
new_file_2 | 1 +
2 files changed, 2 insertions(+), 0 deletions(-)
create mode 100644 new_file
create mode 100644 new_file_2

diff --git a/new_file b/new_file
new file mode 100644
index 0000000..e3c484b
--- /dev/null
+++ b/new_file
@@ -0,0 +1 @@
+Entering something into the new file
diff --git a/new_file_2 b/new_file_2
new file mode 100644
index 0000000..b4a1e8e
--- /dev/null
+++ b/new_file_2
@@ -0,0 +1 @@
+Entering something into the second new file

May 24, 2011

Change ... and not letting it happen

I have not written here for a long time, and I sure did not want to begin again with a non-technical post, but here this post is. The title is a little deceiving. It should have been "Change ... and not letting it happen in an overwhelming place like the US". The subject is simple, I know many people, both relatives and not, who have been here for some time and yet I can name no one who has not changed a bit after coming here. That both surprises and scares me, frankly I do not want to change anything within me, but it looks like it happens automatically, almost an year later, I see that happening to me. I only realize it when I talk to a friend back at home.
It is this place, overwhelming in every aspect, larger than life - life. I guess it indeed is tough to hold on to what you were ....

January 25, 2011

Visualizing directories and files as a graph

The Information Retrieval class I have been taking this spring has been inspiring me to try quite a few things, the first of them was to try and analyse text to extract the semantic information in the words. Well that has not reached anywhere near perfection but the present code for a naive method of drawing a graph containing the words can be found here. While trying to draw the graph for the words, I did however read through the NetworkX library documentation extensively. I really like this library, creating simple graphs is very easy and at the same time there are so many features if you want to do a lot more with the graph. While I was searching for some interesting problem which I could visualize as a graph (just to flex my python skills and to get more fluent with NetworkX), the idea of trying to see a directory as a graph with files and sub-directories as nodes colored by the file type struck, especially I wanted to try this out on the directory where I store all my work related files, and here is the result :

well , the above code is simple directory traversal in python with the code for drawing the graph added. (the script works only on *nix systems and ignores hidden files and directories by default, this is so that I could ignore the nasty version control related metadata directories like .git or .svn which are quite common in my folders).
The graph without the file names produced by the script looks like this :

The other files and graphs can be found here.

January 03, 2011

Websites that load fast, why it is subjective !

I am a pretty active (if not aggressive) user of facebook, and the one thing that I observe every time I pop up a new tab with facebook on google chrome is that it is almost instantaneous. This set me thinking about how the time a website takes to load affects the user's experience. My speculation is that it is completely subjective. It majorly depends on two important factors (or rather categories of factors) :
  1. What the user is using : the website + browser
  2. What is the user's mood 
Most benchmarks deal with the first set of factors, the ones which deal with the software, but this is not a perfect measurement of the affects on the users interaction with the website. I performed a simple task to measure the difference and took into consideration the second set of factors such as the user's mood etc which affect how the user perceives the speed : 

Open a new tab in a browser you prefer, wait till the page completely loads, now open another tab of the same website and try to close the earlier opened tab, see if you can close the old tab before the new tab opens. Repeat this for various browsers and various websites while you are in different moods. 

This simple test also brings into play a certain factor that we often forget, most benchmarks deal with the time taken for a site to load from scratch (a fresh tab) which is often not the case, most of the time an individual spends on the internet, he/she is not going to open a new website every time, most websites are closed and opened again and again. Again, the whole point of the post is not to provide solid results on which websites are faster or which browser is the best, rather, to focus on some subjective issues we forget in user interactivity !

Power notifications on a laptop (quick and simple)

First you would need to install packages appropriate for your distribution providing "acpitool", then you could use watch to get updated information on the battery at fixed intervals, for example to update the information every one second you could run the following on a terminal :

watch -n 1 "acpitool | grep charging"