Wednesday, November 23, 2011

A short perl code to find union of 2 arrays in perl

Using slices on hash variable :)

sub array_union {
    my ($arrRef1, $arrRef2) = @_;
    my %hash;
    @hash{@$arrRef1} = undef;
    @hash{@$arrRef2} = undef;
    return keys %hash;
}

Wednesday, October 12, 2011

Upgrading CM7 on LG O2X

If you are planning to upgrade CM7 on your LG O2X, please make sure you have done the following!
Upgrade clockworkmod to a version >= 5. (You can do this from 'ROM Manager' itself)

Monday, September 5, 2011

ARFF file-reader in C++

Long time ago I had written a C++ library to parse ARFF files for one of my Machine-Learning projects. Today, I'm making the code open-source! Here's the link to the code hosted on github: https://github.com/teju85/ARFF. This also comes with doxygen documentation for the API exposed by this library and also has unit-tests (written using google-test) for CYA.

Sunday, August 28, 2011

Iterator for templated STL containers in C++

I realized this today! The following code almost always will give compilation error.
std::vector::const_iterator itr;

And the compilation error (with g++ version 3.4.6) will be as vague as:
error: expected `;' before "itr"

The solution is to just do the following:
typename std::vector::const_iterator itr;

Sunday, July 31, 2011

Getting (approx?) memory usage information on linux

Here's the code for doing so: (Tested on Ubuntu 10.10)

#include <unistd.h>
#include <stdio.h>
int processMemUsage() {
    int vm = 0;
    FILE* fp = fopen("/proc/self/stat", "r");
    if(fp == NULL) {
        return vm;
    }
    int dummy;
    char cmd[128], state[8];
    fscanf(fp, "%d%s%s%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
           &dummy, cmd, state, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy, &dummy, &dummy, &dummy,
           &dummy, &dummy, &dummy);
    unsigned long vmSize;
    fscanf(fp, "%lu", &vmSize);
    fclose(fp);
    vm = (int) (vmSize >> 10);
    return vm;
}

Hope this helps!

Thursday, July 28, 2011

How to request 'super user' permission from your app?

NOTE: This blog assumes that you have installed Superuser application installed on your device! Also, I'm not responsible for any bricked devices!

Process p;
try {
    p = Runtime.getRuntime().exec("su");
}
catch(IOException e) {
    e.printStackTrace();
}

This will pop up a window from 'Superuser' application which will ask user to whether allow your app to be given 'su' permissions or not. Users can either 'Allow' or 'Deny' and also set 'Remember this option' on this window.

Hope this helps!

AdbCommandRejectedException!

Sometimes, adb goes crazy on my Win7. If I open 'ddms' (to view logcat messages), I wont see any messages at all! If I look into the 'Command Window', I see the above exception being raised in it. Apparently, the work-around this is to do the following:
  1. Un-plug the USB cable.
  2. Kill the adb-server (adb kill-server)
  3. Start the adb-server (adb start-server)
  4. Plug in the USB
 Hope this helps!

Sunday, July 24, 2011

Camera shutter sound on CM7!

Due to legal issues in some countries (see this issue) cyanogenmod doesn't support any settings for enabling/disabling camera shutter sound (It is enabled by default!). However, there's a system property which one can set in order to turn off the shutter sound. But, unfortuantely for this you need to install android SDK on your system and plug USB cable to your phone and connect it to your PC. (Also, do not forget to 'enable USB debugging'!!).
  adb shell setprop persist.camera.shutter.disable 1

NOTE:
 I'm not responsible for any damages/law-suites caused (whatsoever), by disabling the shutter sound of your phone's camera!

Tuesday, July 19, 2011

Measuring read/write BW of sdcard(s) on your android phones

I needed a quantitative way to measure the performance of the sd-card on my LG Optimus 2X. Hence I wrote the tool 'sd-speed'. Currently, this tool is supported only on linux and windows platforms. The project is hosted on github at the following location: 'git@github.com:teju85/sd-speed.git'. I have released it with the WTFPL (do What The Fuck you want to Public License).

Here are the results of running my program on my 'external sd-card', 'internal sd-card' and on 'phone memory' respectively: (Phone: LG O2X, CM7)

External sd-card
$ ./sdCardSpeedTest.sh /mnt/sdcard
NOTE: Test might take about 5-10 min depending on your sd-card speed!
      Please be patient during this time...

Evaluating write-BW...
100000000 bytes transferred in 26.371 secs (3792044 bytes/sec)
100000000 bytes transferred in 19.656 secs (5087505 bytes/sec)
100000000 bytes transferred in 20.697 secs (4831618 bytes/sec)
100000000 bytes transferred in 20.086 secs (4978592 bytes/sec)
100000000 bytes transferred in 53.975 secs (1852709 bytes/sec)
100000000 bytes transferred in 28.934 secs (3456141 bytes/sec)
Write BandWidth: 3.81448 MBps

Evaluating read-BW...
100000000 bytes transferred in 18.844 secs (5306728 bytes/sec)
100000000 bytes transferred in 17.818 secs (5612302 bytes/sec)
100000000 bytes transferred in 17.331 secs (5770007 bytes/sec)
100000000 bytes transferred in 17.301 secs (5780012 bytes/sec)
100000000 bytes transferred in 17.306 secs (5778342 bytes/sec)
100000000 bytes transferred in 17.310 secs (5777007 bytes/sec)
Read BandWidth: 5.40803 MBps

Cleaning up all the temporary files...


Internal sd-card
$ ./sdCardSpeedTest.sh /mnt/emmc
NOTE: Test might take about 5-10 min depending on your sd-card speed!
      Please be patient during this time...

Evaluating write-BW...
100000000 bytes transferred in 9.372 secs (10670081 bytes/sec)
100000000 bytes transferred in 6.579 secs (15199878 bytes/sec)
100000000 bytes transferred in 6.252 secs (15994881 bytes/sec)
100000000 bytes transferred in 6.321 secs (15820281 bytes/sec)
100000000 bytes transferred in 6.532 secs (15309246 bytes/sec)
100000000 bytes transferred in 6.516 secs (15346838 bytes/sec)
Write BandWidth: 14.0415 MBps

Evaluating read-BW...
100000000 bytes transferred in 5.168 secs (19349845 bytes/sec)
100000000 bytes transferred in 5.038 secs (19849146 bytes/sec)
100000000 bytes transferred in 4.661 secs (21454623 bytes/sec)
100000000 bytes transferred in 4.671 secs (21408691 bytes/sec)
100000000 bytes transferred in 4.694 secs (21303792 bytes/sec)
100000000 bytes transferred in 4.693 secs (21308331 bytes/sec)
Read BandWidth: 19.8165 MBps

Cleaning up all the temporary files...


Phone memory
$ ./sdCardSpeedTest.sh /data/local
NOTE: Test might take about 5-10 min depending on your sd-card speed!
      Please be patient during this time...

Evaluating write-BW...
100000000 bytes transferred in 6.876 secs (14543339 bytes/sec)
100000000 bytes transferred in 8.566 secs (11674060 bytes/sec)
100000000 bytes transferred in 8.565 secs (11675423 bytes/sec)
100000000 bytes transferred in 6.783 secs (14742739 bytes/sec)
100000000 bytes transferred in 7.617 secs (13128528 bytes/sec)
100000000 bytes transferred in 8.168 secs (12242899 bytes/sec)
Write BandWidth: 12.3989 MBps

Evaluating read-BW...
100000000 bytes transferred in 5.537 secs (18060321 bytes/sec)
100000000 bytes transferred in 5.641 secs (17727353 bytes/sec)
100000000 bytes transferred in 5.274 secs (18960940 bytes/sec)
100000000 bytes transferred in 5.275 secs (18957345 bytes/sec)
100000000 bytes transferred in 5.268 secs (18982536 bytes/sec)
100000000 bytes transferred in 5.273 secs (18964536 bytes/sec)
Read BandWidth: 17.7468 MBps

Cleaning up all the temporary files...

I have compiled these results in a tabular format for quick comparison.
Location Write BW (MBps) Read BW (MBps)
External sd-card 3.81 5.41
Internal sd-card 14.04 19.82
Phone Memory 12.40 17.75
If you find any issues with this tool, do drop-in a comment here!

Friday, July 15, 2011

How did I 'almost' brick my phone (and recovered from it)?

I use CM7 (nightly-74). When I heard that LG had released 0622 baseband version I couldn't resist to go back to stock ROM and try it out. :) And I did exactly that... However, somehow, during the update using the LG PCsuite, it said 'failed to communicate with phone' and asked me to remove battery, restart and plug in USB and start over again. When I tried that, after the LG boot-splash, I got this screen. :( And that's when I knew, I had screwed up my phone!

Then I went to modaco-forums to find that Paul had given a nice tutorial on how to flash your phone to the stock ROM (using nvflash). I successfully flashed the stock ROM. But little did I knew that worse was waiting when I would boot the phone. My baseband firmware was no more! Meaning my phone had become a wifi-tablet :(( Luckily, I found this thread in modaco-forums on how to flash baseband-firmware (using smartflash). Instructions were pretty simple and using this, at the end, I was able to get back my baseband to 0622 version :D (phewww!!)

Now, I just had to manually install CWM (ClockWorkrecovery Mod) version 4.0.0.5 and restore my CM7 (nightly-64) from the nandroid backups. Now I'm enjoying the nightly-74 on CM7 with the latest baseband firmware!

Wednesday, July 13, 2011

Manually installing clockworkmod (CWM) recovery on LG O2X

Strange as it seems, on my phone, 'ROM Manager' does not allow an upgrade to the CWM after 3.0.2.8. :( So, I wanted to install it manually. The steps I followed were from the one given by our very own Paul on modaco forums. However, I wanted to understand what exactly those 'install-clockworkmod-windows.bat' kind of scripts did. Here it is... (I used the windows batch file in order to install CWM)


# copy over the psneuter binary to your phone
> adb-windows push psneuter /data/local/psneuter

# give this binary on your phone, the executable permission> adb-windows shell chmod 4755 /data/local/psneuter

# run this exe, (psneuter exploit to gain root access)
# you wouldn't need it if your phone is already rooted(?)
> adb-windows shell /data/local/psneuter

# wait the device to come online (as the above exploit would have killed the adbd)
> adb-windows wait-for-device

# copy the CWM image over to your phone> adb-windows push clockworkmod.img /data/local/
 
# place this image over to the appropriate location?
> adb-windows shell dd if=/data/local/clockworkmod.img of=/dev/block/mmcblk0p7

Clockworkrecoverymod v3.0.2.8 bug! :(

Seems like this version does not properly restore the nandroid backups. I tried to restore using this version and the restore succeeded. However, during the bootup, (LG O2X) it used to hang on the second LG screen! The solution is to upgrade it to later version (latest verion 4.0.0.5) seems to work properly. I'll write a blog on how to manually upgrade CWM sooner...

Saturday, June 25, 2011

Android adb “Unable to open sync connection!”

This happens sometimes on eclipse (or you can also experience with working on adb commandline). Unfortunately, the best known solution so far is to:
  1. Unplug the USB cable.
  2. Disable the USB debugging mode on the phone, and re-enable it.
  3. Then re-plug the USB cable!

Courtesy: StackOverflow.

Friday, June 24, 2011

Using LG Optimus 2X under USB debugging mode on Ubuntu

If you want to develop/debug applications or even connect ddms/adb to your LG-O2X, you need to setup udev rules, in order for it to be detected by the OS. I'm assuming here that you have already installed android SDK for this purpose, if not please do so (google it!) before proceeding.

In order to do this, at first you need to open a terminal Applications->Accessories->Terminal. Then type in the following commands into your terminal. As soon as you enter the command below, you might be prompted for your password. Enter it to proceed with privileged access.
    gksudo gedit /etc/udev/rules.d/90-android.rules

In the text editor which opens, enter the following line:
BUS=="usb", SYSFS{idVendor}=="1004", OWNER="<userName>", GROUP="<groupName>"
Where: 
1. <userName> is your user name on this machine. Yes! this means that this setting only works you alone! 
2. <groupName> is the name of the group you belong to on this machine. 
3. 1004 is the vendor ID of LG (Courtesy: theandroidphone) 
4. (Google on how to get your username and groupname if you don't know!)

Save and close this file. Then type the following command on your terminal:
    gksudo service udev restart

After this is done, plug-in the USB cable of your phone (if it's already plugged in, remove and re-plug) and in your phone enable USB debugging by: Settings->Applications->Development->USB debugging.

Then type the following command to make sure your phone is getting detected:
    adb devices
You should see something like below in the terminal:
List of devices attached
XXXXXXXXXXXXXXXX    device

PS: All this information is from my PC running Ubuntu-10.10 (the Maverick Meerkat).

Tuesday, June 21, 2011

Installing Cyanogenmod7 (Gingerbread build) on LG Optimus 2X

Even though the guidelines to do so are described nicely in the CyanogenMod wiki, there are small things this wiki forgets to mention, which caused me a lot of pain when I followed the steps mentioned in them. This blog is an attempt to make the process of installing cyanogenmod as smooth as possible. These were the steps I followed on my O2X (LG Optimus 2X) to successfully install Cyanogenmod ROM.


Step0. Terminology:
If you are new to the world of android-hacking or new to android, in general, make sure that you are familiar the terminologies mentioned in this wiki.


Step1. Pre-requisites:
Do make sure that you satisfy all these before proceeding!
  1. Make sure that you have atleast 50% (to be on safer side, 75% :D) of battery charge remaining. This is highly important! If a low battery shuts down the installation process, then there's a very high chance that you are going to brick your phone!
  2.  The Recovery Mode somehow doesn't mount the internal sd-card of your phone. So, you have to make sure that you have another external sd-card plugged-in of atleast 2GB in size (on a safer side).
  3. If you have data like contacts, sms, call-log and such other stuffs, now's the time to get a backup of them (onto sd-card). Titanium Backup is a nice app for this purpose. Basically, all of the data on phone will be wiped-clean during this process. So, backup all those things on your phone, which you feel is important to you.
  4. You need to download/install all of these tools/files on your PC, before proceeding further: (This tutorial assumes that you are working on a PC with Windows-OS running on it)
    1. Install ADB. There's a very nice tutorial on how to install this tool. I recommend you to go through this link for more details. (Please do NOT perform the step4 mentioned the above tutorial link).
    2. Download busybox: Download this zip and extract its contents.
    3. Download psneuter: Download this zip and extract its contents.
    4. Download Superuser apk: Download this apk file onto your PC.
    5. LG USB drivers (v3.2.1): Download this exe and install it to your PC.
    6. It will be handy if you can extract the contents of all the zip files above into a single directory.
  5. Install ROM Manager on your phone: This is a very useful tool in booting to recovery mode and then installing ROM's of your choice.
  6. CyanogenMod ROM: Go to this link and download the latest nightly OR if you want to play safe, you can download the nightly numbered 53, because that's the one I downloaded and it works fine for me :). Download it to your pc and then transfer to over to your phone's sdcard. DO remember to store this zip file in the root of your external-sdcard and name it as update.zip!
  7. Google Apps: Default cyanogenmod ROMs do not have any google apps installed on them, so you would have to install them by yourself. You can download the zip file from here and then transfer it to the root of your external-sdcard and let's say that you name it as google.zip.
One small thing before you proceed, as soon as you boot into recovery mode, your phone goes into an eternal vibration mode. Don't panic. It's a bug in recovery mode and it will not affect the installation process.

Step2. Rooting:
You need to root the phone prior to installing cyanogenmod. Here are the steps you need to follow for this: (In step4, the commands appearing the first indentation level are the ones you will be typing on the command prompt and the ones in the second indentation level are the ones you will type inside the shell opened by 'adb'.)
  1. In your phone, enable 'USB Debugging': Settings->Applications->Development->USB Debugging.
  2. Connect your phone to this PC via USB cable.
  3. On your PC, open command prompt and 'cd' into the directory where you had extracted all the files from the zip files downloaded.
  4. In the command prompt type the the following commands:
    1. adb push busybox /data/local/
    2. adb push psneuter /data/local/
    3. adb push su /data/local/
    4. adb shell chmod 777 /data/local/busybox
    5. adb shell chmod 777 /data/local/psneuter
    6. adb shell
      1. /data/local/psneuter
    7. adb shell
      1. mount -o remount,rw -t ext3 /dev/block/mmcblk0p25 /system
      2. mkdir /system/xbin
      3. /data/local/busybox cp /data/local/su /system/xbin/su
      4. chown 0:0 /system/xbin/su
      5. chmod 6755 /system/xbin/su
      6. ln -s /system/xbin/su /system/bin/su
      7. exit
    8. adb push Superuser.apk /system/app/Superuser.apk
  5. Reboot.
  6. Your phone has been rooted.

Step3. Installing Cyanogenmod:
Note that when you are in recovery mode, you should use the volume up/down buttons to navigate the options on the screen. In order to select an option, press the power button.
  1. Open the 'ROM Manager' application on your phone.
  2. Tap on 'Flash ClockworkMod Recovery'.
  3. Select LG Optimus 2X in the menu that pops up.
  4. You will get a 'Superuser Request' prompt. Select 'Remember' and then 'Allow'.
  5. As soon as the flash is complete, you'll see a 'Successfully flashed ClockworkMod Recovery!' dialog box. Tap OK.
  6. ClockworkMod Recovery should be installed on your phone.
  7. Tap on 'Backup Current ROM' in order to backup your current ROM (which is, in most cases, the manufacturer supplied, stock ROM).
  8. 'Reboot into Recovery'.
  9. Select the option 'Wipe data/factory reset'.
  10. Select the option 'Wipe cache partition'.
  11. Select the option 'install zip from sdcard' and then select 'apply /sdcard/update.zip'.
  12. Select the option 'reboot system now'. 
  13. Now, your phone should boot into the Cyanogenmod ROM!
After this, if, you need to install the google-apps using google.zip:
  1. Open the 'ROM Manager' and select 'Reboot into Recovery'.
  2. Select the option 'install zip from sdcard' and then select 'choose zip from sdcard'.
  3. Select the 'google.zip'.
  4. Now, after your phone boots up, you'll be taken through series of asking you to confirm what are all the apps you want to be installed. Select the ones you need and you're done!

Lemme know how the info in this blog worked for you! Feedback on whether this content was useful to you would also help. : )

Happy modding!

Java API for Bitly webservice

I wrote a Java API for Bitly webservice (details about this webservice can be found here). It provides a easy interface to the output of the webservice, by parsing the JSON format and storing the values in the corresponding variables inside an appropriate 'BitlyResponse' object. This could be a very useful API for accessing url-shortening services from inside java apps (could be for android as well!). You can find the jar file and the relevant code at the following github repo: git@github.com:teju85/BitlyAPI.git

PS: There's no restriction on the using this library, provided you acknowledge the use of this API in your application. :)

Friday, June 17, 2011

CorrDim: a fast correlation dimension evaluator

After going through this blog written by Bill Maier, I thought why not I give a shot in writing a C++ program to find the correlation dimension and figure out its performance. 'CorrDim' is the result of this. This has some of the most common maps already available within the project folder viz: Logistic map, Tent map and Henon map. Also, adding a map of your choice is a piece of cake, thanks to virtual inheritance. Go through the 'README' file available in the source code to know more on how build and extend this to include more maps. This program supports 2 modes of correlation dimension evaluation:
  1. Fast but huge memory: In this mode, the distance matrix will be evaluated apriori so that the subsequent lookups are faster. However, this requires huge memory, especially if the number of elements considered is huge.
  2. 'Relatively' fast but consumes little memory: In this mode, the distance matrix will be evaluated on-the-fly, during the evaluation of the correlation dimension, thus requiring very little memory.
The choice of the mode depends on: If you absolutely cannot sacrifice even a little performance, then you should use the normal version. But for all practical purposes, it is recommended that you use the low-memory version.

Profiling:
Here are the results from profiling this program [Results are on a Dell-Latitude E6400, with Ubuntu 10.10 installed and on LogisticMap.]...

Memory Profiling:

Run-time profiling:

As you can see, the LowMemory version of this program gives a significant reduction in memory footprint compared to its counterpart. At the same time, the performance loss is also not that noticeable.

I have hosted this project (open-source'd with GPL) on github at: git@github.com:teju85/CorrDim.git.

Wednesday, June 8, 2011

Replacing tabs with spaces in eclipse

Tabs are evil! They are interpreted differently by different editors. So, it is always better to setup your editor to replace tabs with a constant number of spaces. IMO, 4 spaces will be visually appealing. While working with eclipse, here's how to set this property: (assuming eclipse version "Helios Service Release 2")
Window -> Preferences -> Java -> Code Style -> Formatter -> New
Give your profile a name, something like 'Eclipse [only-spaces]' and inherit all the basic settings from the 'Eclipse [built-in]' profile. (You can choose to inherit from whichever other profile of your interest or you can directly edit one of your favorite profiles. For me, the built-in profile was sufficient). Also make sure that 'Open the edit dialog now' is checked in and then press 'Ok'.
In the dialog box which opens, select Indentation -> Tab policy -> Spaces only.
Set the 'Indentation size' and 'Tab size' to 4. (meaning 4 spaces, as I mentioned in the beginning).
Press Apply to save all your settings and from here onwards, eclipse will put spaces instead of tabs for the indentation!

The reason I created a new profile is because one can keep re-using this in all your future projects and also has the ability to export your profiles when you want to use this profile on some other machine!

Monday, June 6, 2011

Neat trick to replace spaces with any other character in Makefile

Sometimes, you would want to replace spaces in a string with another character (for this post let's assume that this character is a colon ':'. You can replace it with whatever replacement string you desire). The following makefile trick serves this purpose:
null      :=
SPACE     := $(null) $(null)
WITHSPACE := A string with spaces
REPLACED  := $(subst $(SPACE),:,$(WITHSPACE))
default:
 @echo WITHSPACE = $(WITHSPACE)
 @echo REPLACED = $(REPLACED)
And here's the output:
$ make
WITHSPACE = A string with spaces
REPLACED = A:string:with:spaces

Sunday, June 5, 2011

Accessing linux ext file-systems on win7

If you want to access only 'ext2' file systems:
'ext2ifs' is a very cool program to access the linux ext2 file-systems from windows. However, this works only on winXP or Vista, but not on Win7. No problem! win7 supports a compatibility mode where one can the programs on XP or Vista. To do so, right click on the exe of your interest (which you want to run under compatibility mode) -> Properties -> Compatibility. Check the box 'Run this program in compatibility mode for:' and select the windows version. After this, click 'Apply' to save your changes and you are done! The next time you run this exe, it'll automatically run under the mode for the appropriate windows version you selected above.

If you want to access an 'ext3/4' file systems: (read-only access)
There's a nice utility called linux-reader. This can provide read-only access to ext2/3/4, HFS and RaiserFS file systems! But, as mentioned above, it provided read-only access.

If you want to access an 'ext3' file system (both read/write access)
Utility called 'ext2fsd' is a solution for this case. However you have to install this exe and run it as administrator. To do so: right click on the exe to run -> 'Run as administrator'. This is an awesome utility and a plus point about it is that it doesn't require it's own explorer unlike the 'linux-reader' utility! Once you have assigned a drive letter to the volume of your interest, you can directly access them using the windows native explorer!

Monday, May 9, 2011

Sudoku checker

Time for another home assignment! :P
Given a solved sudoku board, the aim is to check whether it is a valid solution or not. The program pasted below will do the same. In fact, it prints out ALL the offending rows, columns and blocks (if the solution is not valid). The idea is simple, if a row/column/block has all its elements to be unique, then the sum of all it's elements will be (N*(N+1))/2, where NxN is the size of the sudoku board.

#include <stdio.h>
void isCorrect(int** grid, int N, int sqrootN) {
    int sum = (N * (N + 1)) >> 1;
    // all rows
    for(int i=0;i<N;i++) {
        int actual = 0;
        for(int j=0;j<N;j++) {
            actual += grid[i][j];
        }
        if(actual != sum) {
            printf("Row '%d' is incorrect!\n", i+1);
        }
    }
    // all columns
    for(int i=0;i<N;i++) {
        int actual = 0;
        for(int j=0;j<N;j++) {
            actual += grid[j][i];
        }
        if(actual != sum) {
            printf("Column '%d' is incorrect!\n", i+1);
        }
    }
    // all blocks
    for(int i=0;i<N;i+=sqrootN) {
        for(int j=0;j<N;j+=sqrootN) {
            int actual = 0;
            for(int a=0;a<sqrootN;a++) {
                for(int b=0;b<sqrootN;b++) {
                    actual += grid[i+a][j+b];
                }
            }
            if(actual != sum) {
                printf("Block starting at '%d,%d' is incorrect!\n", i+1,j+1);
            }
        }
    }
}

int main(int argc, char** argv) {
    if(argc == 2) {
        FILE* fp = fopen(argv[1], "r");
        if(fp == NULL) {
            fprintf(stderr, "Failed to open '%s' for reading!\n", argv[1]);
            return 1;
        }
        int N, sqrootN;
        int** grid;
        fscanf(fp, "%d", &N);
        fscanf(fp, "%d", &sqrootN);
        grid = new int* [N];
        for(int i=0;i<N;i++) {
            grid[i] = new int [N];
            for(int j=0;j<N;j++) {
                fscanf(fp, "%d", &(grid[i][j]));
            }
        }
        isCorrect(grid, N, sqrootN);
        for(int i=0;i<N;i++) {
            delete grid[i];
        }
        delete grid;
        fclose(fp);
    }
    else {
        fprintf(stderr, "USAGE: %s <file>\n", argv[0]);
        return 1;
    }
    return 0;
}

How to compile?
(Assuming the above program is saved in the file sudokuChecker.cpp)
g++ -o checker sudokuChecker.cpp

How to run?
./checker <file>
<file> = the file containing the sudoku board

Format of the <file>?
<BoardSize> <squareRootOfBoardSize>
Each of the elements in the board in row-major order.

Complexity?
Obviously, the above program has a time complexity of O(N^2).

Saturday, May 7, 2011

Finding (and printing) cycles in a directed graph

I know... this seems some kind of under-grad assignments. But I was feeling boring last night and hence decided to write this code to kill time. I spent about 20-30 minutes in coming up with this program. The program is available at git://github.com/teju85/Cycles.git. This code takes a file as input (containing the adjacency matrix for the graph of interest) and prints all the elementary cycles in the directed graph.

PS: However, I haven't tested this code rigorously, yet! So, if you find any issues with this code, just drop in a comment here and I'll take a look into it.

Friday, April 29, 2011

How to find the size of a file in C++?

We need to use the combination of fseek and ftell functions. Here's one such implementation. This implementation will return a '-1' in case it'll not be able to open the file, else returns the size of the file (in B).

#include <stdio.h>
/**
 * @brief Finds the size of the file (in B)
 * @param file name of the file
 * @return if file-open fails, returns a value of -1; else size of the file.
 */
int sizeOfFile(const char *file) {
    FILE* fp = fopen(file, "rb");
    if(fp == NULL) { return -1; }
    fseek(fp, 0, SEEK_END);
    int i = ftell(fp);
    fclose(fp);
    return i;
}

I tried to verify the performance of the above function, using the piece of code below:
int main(int argc, char** argv) {
    if(argc != 2) {
        fprintf(stderr, "USAGE: %s <fileToBeRead>\n", argv[0]);
        return 1;
    }
    for(int i=0;i<10000;i++) {
        sizeOfFile(argv[1]);
    }
    return 0;
}

I copied above 2 pieces of code into a file named 'test_perf.cpp'. Then, I compiled using the command: 'g++ -o perf test_perf.cpp' in cygwin version 1.7. Here's my result: [System: Dell Latitude E6400, Win7, 32b]
$ time ./perf.exe perf.exe
real    0m2.677s
user    0m0.342s
sys     0m1.887s
$ stat perf.exe
  File: `perf.exe'
  Size: 19596           Blocks: 20         IO Block: 65536  regular file
 .... some more outputs hidden for privacy reasons ....

Monday, April 18, 2011

cutop: GPU version of 'top'

Here's a tool I wrote today for for mimicking the functionality of the famous unix tool 'top'. The idea is to give the user the capability to monitor how the resource usage is going on in the GPU's. Currently, this tool does not do much, but only monitors the memory usage of the GPU's. In the future releases of this tool, I'm planning to add more functionalities. Ofcourse, assuming that I get hold of the NVML API as soon as possible! (fingers crossed). 

But till then, I've hosted the project over github and you can access the source code from here: (read-only) 'git://github.com/teju85/cutop.git'.

Wednesday, April 6, 2011

Minimum resolution of the C 'clock' function

Here is the C program to find out the minimum resolution of the 'clock' function on your system.

#include <time.h>
#include <stdio.h>

int main(int argc, char** argv) {
    clock_t a, b;
    a = b = clock();
    while(a == b) {
        b = clock();
    }
    printf("Minimum resolution by 'clock()' = %lf s\n",
           ((double) (b - a))/CLOCKS_PER_SEC);
    return 0;
}

How to compile? (assuming that you have stored this program in a file named 'minRes.c')
gcc -o minRes minRes.c

How to run?
minRes

On my system (Dell Latitude E6400, running Win7), I got this to be about 15ms, on an average.
What about you?

Wednesday, March 23, 2011

How to compose an 'attrs.xml' in android?

There are a lot of blogs which describe how to create custom attributes [3-5]. But I couldn't find anyone which describes the syntax and possible xml attributes for each of the elements inside it. Also, there aren't any documentations available for this as well!

In order to figure out this syntax, I had dig into some internal android code! I know that android is open-source. I like open-source and it's cool. But one shouldn't have to dig into the code in order to understand this simple information, which could have been documented.

Thus this blog is an attempt from my side to document this feature, so as to keep others from wasting their time in doing the same!

declare-styleable
List of possible xml-attributes for this element:
  1. name: name of this styleable.
  2. parent: name of the styleable from which to inherit the attributes.
List of possible children:
  1. attr: the attribute which needs to be defined inside this styleable.

attr
This element can either be found as a tag outside the 'declare-styleable' tag or as an child inside it. List of possible xml-attributes for this element:
  1. name: name of this attribute.
  2. format: data-type represented by this attribute. (This is optional)
List of possible children:
  1. enum: If the current 'attr' is of type 'enum', then you have to define possible enumerations for this attribute.
  2. flag: If the current 'attr' is of type 'flag', then you have to declare this.

enum
List of possible xml-attributes for this element:
  1. name: name of the enum element.
  2. value: the value to be used for this element.

flag
I'm still unable to figure out the syntax for this element. Whenever I'll find out, I'll update this section. So, please do check-back here for more info on this!

format
One small catch here! I just said that this is an optional attribute to 'attr' element. However, from the code [1] it seems that an 'attr' with not 'format' will be silently ignored! Hence, I would recommend putting one of the values below for this attribute. Possible values for 'format' attribute of 'attr' are: [2]
  • reference
  • string
  • color
  • dimension
  • boolean
  • integer
  • float
  • fraction
  • enum
  • flag

That said, an example should clarify much of the stuffs here. Given below is an example 'attrs.xml' which contains all the above elements/attributes. Go through this carefully in order to understand the syntax.

An example 'attrs.xml':
<resources>
    <attr name="global1" format="float"/>
    <declare-styleable name="parent-attr">
        <attr name="attr1" format="integer" />
        <attr name="global1" />
    </declare-styleable>
    <declare-styleable name="myattr" parent="parent-attr">
        <attr name="attr2" format="integer" />
        <attr name="attr3" format="enum">
            <enum name="name1" value="value1" />
            <enum name="name2" value="value2" />
        </attr>
    </declare-styleable>
    <declare-styleable>
        <attr name="global1" />
        <attr name="attr4" format="boolean"/>
    </declare-styleable>
</resources>


NOTE:
  1. All the 'attr' elements in the current xml file will be parsed into a single 'Map'. So, you have to make sure that all 'attr' elements have unique names! [1]
  2. However, if there is an 'attr' element which needs to be shared between 2 styleables, then make it global. (But make sure that you specify a 'format' for this!) Now inside the 'declare-styleable's where you want to define this 'attr', just put this without the 'format'. There is an example of this in the sample xml above. [1]


REFERENCES:

Saturday, March 19, 2011

Proguard.cfg missing in eclipse?

This happened to me after I updated my eclipse today. Basically, whenever I was trying to create a new project, I used to get this error message. The reason for this error is due to mismatch between the versions of your ADT, sdk-tools and eclipse. The best thing to do is to upgrade all of them to their latest versions.

Upgrading ADT: From inside eclipse, Help -> Check for Updates and then follow the instructions.
Upgrading sdk-tools: From inside eclipse, Window -> Android SDK and AVD manager and then follow the instructions.

After you are done, just restart the eclipse and you'll be back on track!

Tuesday, February 1, 2011

Small class to quickly print out application information in HTML

Wrote a class, which queries the package manager in order to fetch the package name, version code/name and permissions for a given app. There's also a method which returns a html formatted string which could be used to display your app's info (probably in a TextView or an AlertDialog). This will help avoid creating a separate 'about' HTML for your app. Go through this link for more information on this class. (The source file has been released under APACHE LICENSE2)

Monday, January 24, 2011

Setting up LG-Optimus One for development

I have been writing android-apps for over more than 8 months now. Finally, I got hold of my first android smart-phone, LG-Optimus One (Model name P500). The following were the steps I had to perform in order to get this phone ready for Android development.

Installing USB driver:
By default, this phone will not be detected over USB, as windows (Win7 32b) failed to find the USB driver for this device. Google search suggested that P500 USB driver needs to be manually installed. To do that, just go to the following link: http://www.lgforum.com/resources/ and select the 'LGAndroidDriver_Ver_1.0_All.exe' executable (about 9.4MB). Then run this exe in order to install the USB driver. Wallah! You're done!

Enabling USB debugging:
Again, by default, USB debugging will be disabled on this phone. (Makes perfect sense as this feature is for development only) In order to enable just select the Settings -> Applications -> Development -> USB debugging check-box. Now connect the USB cable. After this, open a command-prompt and then type adb devices. You'll see something like this:
> adb devices
List of devices attached
******************      device
 You're done! Now, you should be able to run an application (assuming android:debuggable is set true in the app's AndroidManifest.xml) and see the log messages through 'ddms'.

Happy coding!

Thursday, January 20, 2011

traceview fails to find the trace file (on windows)

You have the trace file 'my-trace.trace' present in the current working directory. However, when you type traceview my-trace, you would get the error message: "trace file 'my-trace' not found". Even if you append the trace file with the '.trace' extension, you would get the same error message.
Somehow, the traceview cannot recognize relative paths. So, the solution is to pass the absolute path of the trace file as input to the traceview.
EG: traceview C:\path\to\file\my-trace

(PS: It's been assumed here that the android-tools folder is in your PATH env-variable.)

Sunday, January 2, 2011

Kaprekar-Numbers

Kaprekar-numbers are interesting. For eg.: 703 is a kaprekar-number. Reason: 7032 = 494209 and 494 + 209 = 703. It's also been proven that one can get all the Kaprekar-numbers by prime factorization of 10n-1. However, I wanted to list all the Kaprekar-numbers by solving it in its pure form! A number 'k' (in base 10) is called as Kaprekar-number if it can be expressed in the form:
k = q + r   and   k2 = q * 10n + r
Where, q >= 1, 0 < r < 10n
I've hosted this program on github at the following location (read-only): git://github.com/teju85/Kaprekar-Numbers.git. If you are interested in this, please download the program and follow the instructions inside the 'README'.
I profiled this program and here are the results:
$ make profile
printCpuInfo.sh
Processor Information:
processor       : 0
vendor_id       : GenuineIntel
model name      : Intel(R) Xeon(R) CPU           X5355  @ 2.66GHz

kaprekarnumber -nooutput -profile -limit 10000
Found 17 kaprekar-numbers among first '10000' integers.
Took 0.001309 seconds to search for self-numbers among these integers.

kaprekarnumber -nooutput -profile -limit 100000
Found 24 kaprekar-numbers among first '100000' integers.
Took 0.014230 seconds to search for self-numbers among these integers.

kaprekarnumber -nooutput -profile -limit 1000000
Found 54 kaprekar-numbers among first '1000000' integers.
Took 0.188414 seconds to search for self-numbers among these integers.

kaprekarnumber -nooutput -profile -limit 10000000
Found 62 kaprekar-numbers among first '10000000' integers.
Took 1.616492 seconds to search for self-numbers among these integers.

Not sure whether the timings are 'optimal' or not. Still looking for possible optimizations...

Saturday, January 1, 2011

Removing password from pdf files

We frequently come across a lot of password-protected pdf's in our daily lives, be it our internet/credit-card bills. Problems come when we want to share these kind of files with others. We obviously don't want to share the password as well! There are a lot of (commercial!?) tools out there which claim to remove password from pdf files. However, we all know that ghostscript already provides an option of reading password-protected pdf files and then storing them back to hard-disk. So, wrote a wrapper-tool for myself in order to do this process for me. I've created a repo for this tool and is publicly available (for free, ofcourse!). If you want to use this tool, please download all the files from this repo: git://github.com/teju85/No-Pass.git.

Happy new year fellas!