How to get a Croatian visa (if you need one ..)

I am getting pretty bored waiting for my connecting flight at DFW and thought I might put my time to good use by writing about my experience of getting a Croatian Visa.

So we decided to travel to Croatia in June, the first order of business was to get our visas. Since we are not citizens of countries with Golden passports we needed to get a Croatian visa. It is not required if you are a US / Canadian citizen or if you have a valid Schengen visa (highly recommend getting one if you can)

Since we do not have a Schengen visa and are not traveling to Schengen country as part of our visit, we decided to get a Croatian visa. The process on the face of it seems pretty simple but there are a lot of things that one needs to take care of.

First off, you need a travel insurance, there are plenty of websites that provide travel insurance. I think you need around $50,000 insurance. We got travel insurance for around 15 days for $60, I think that was pretty ok. Next you need to reserve a hotel (or accommodation ) beware they will call up the hotel and make sure you have a valid reservation. Then go online and fill up a straightforward application form, at the end, take a printout and either mail it or take it to your nearest consulate. You also need to provide a proof of travel e.g. plane tickets. The application fee for me was about $120 (changes)

The folks at the consulate are very helpful, I would suggest calling them up before hand if you got any questions they are super nice. The process is pretty painless, just walk in, give your travel documents and supporting documents and you should be done. For me it took about 2 weeks to get my visa. A word of advice try going to the “Croatia Consulate General” rather then “Croatia Consulate”, Croatia Consulate General is much much faster.

The only weird thing was the validity and the duration of the visa. I had provided proof for 8 days of stay and I got a visa for 8 days and the validity was only one month, what the hell ! I am still a bit mad about it though.

Anyways looking forward to my travel to the “mediterranean as it once was”.

P.S. These are my personal experiences and rants, for detailed requirements checkout

Set max value without a lock (using CAS)

tl;dr : I was looking for a way to set the maximum value of a variable but without using locks (because locks suck) this is my rant about it using CAS (compare-and-set operation).

We deal a lot with multi-threading and performance is something which we cannot part with. We needed a way to record the maximum latency for the application. The throughput is about 15-20K requests/second  and we needed to monitor and set the maximum latency value (since the start of the application) amongst other things, without affecting the performance.

There were a bunch of solutions that I found online that used locks, but locks although conceptually simple are performance bottleneck. Naturally, I turned to the Java concurrency package for reference and realized that Doug Lea had this algorithm which he used for AtomicLong.getAndIncrement() which used CAS operations. I used the same algorithm to set the max value and so far it appears to work.

Following is the code I used, with comments, hope it helps !

	 * Try to update the max value without using a lock.
	 * This method is thread safe.
	 * @param val the values to be updated to, if greater than given atomic.
	 * @param atomic the {@link AtomicLong} to be checked
	 * @return true if updated, false if not updated.
	public static boolean setMax(final long val, final AtomicLong atomic)
		while (true)
			final long currentMax = atomic.get();
			if (currentMax >= diff)
				/* if the current value is greater than diff we break */
				return false;
			 * Here we check whether other thread has already modified the
			 * currentMax value, if yes setSuccess=false or else setSuccess=true
			 * in which case we the following operation will update the
			 * maxLatency value to the diff.
			final boolean setSuccess = atomic.compareAndSet(currentMax, diff);
			if (setSuccess)
				 * we managed to update the max value, no other thread changed
				 * it, we are don here.
				return true;
			/* some other thread got in the way, go back and do the drill again. */



OpenVPN for RaspberryPi (Static Key)

You all must be familiar with the amazing things that your RaspberryPi can do ! One of the things that I wanted to get on RaspberryPi was OpenVPN so that I could securely browse the internet while on free WiFi networks like Starbucks. Without the fear of being snooped on.

Before beginning, please note that this is an OpenVPN static key setup and following are the advantages and disadvantages of this setup.


  • Simple setup.
  • No X509 PKI (Public Key Infrastructure) to maintain.


  • Limited Scalibility.
  • If the static key is compromised then all the previous sessions can be disclosed.
  • Secret Key must exist in plaintext form on each VPN peer.
  • Secret Key must be exchanged using pre-existing secure channel.

For me, I am ready to live with the disadvantages (for now).
Following are the steps to get and configure OpenVPN Server on your RaspberryPi. Assuming that you have debian, I don’t expect it to be much different for other linux distributions.

Get OpenVPN:
$ sudo apt-get install openvpn

Get bridge-utils ?? (can be skipped)
$ sudo apt-get install bridge-utils

Generate the Static Key
$ openvpn --genkey --secret static.key

Please, make sure that static.key is not compromised.

Create Server Configuration File:
create a file called server.conf with the following contents:

dev tun
secret static.key

Start the OpenVPN server:
start OpenVPN server with the following command:
$ sudo openvpn --config (path to server.conf)/server.conf --log (path to save the log)/server.log

Configure the client:

  • Copy the static.key to client and server over a secure channel.
  • create a file on the client machine client.conf with following contents:
remote myremote.mydomain
dev tun
secret static.key

On the client you can use the OpenVPN client (for Mac/Win/Linux) (download from here) and all it needs is the client.conf file and the static.key.

VPN Speed Test Results

Without VPN:   Download: 2.90 Mb/s      Upload: 2.69 Mb/s      Latency: 25 ms
With VPN:        Download: 2.71 Mb/s      Upload: 2.03 Mb/s      Latency: 27 ms

Breaking Linear Congruential Generator

Recently I came across Linear Congruential Generators (LCG) while taking an online course in Cryptography. Initially it looked like a cute little method to generate pseudo random numbers (PRN), which was simple and elegant but as it turns out it has been broken, pretty badly broken. The class did not go into the details of how it was broken and left it as a mental exercise for students. I will (hopefully) try to demonstrate a way to break it. There could be many other ways to do it; this is using George Marsaglia’s way. He was the one to expose the “Crystalline” nature of multiplicative generators. For curious readers name of the paper is “RANDOM NUMBERS FALL MAINLY IN THE PLANES“. A lot (almost all) of what I will be talking here is borrowed from this paper and other references noted at the end of the post.

So, what is an LCG ?
LCG can be defined as:

X(n-1) = (aX(n) + c) mod p

X(n) is a sequence of pseudo random values.
p is modulo defined as 0 < p
a is the multiplier defined as 0 < a < p
c is the increment 0 <= c < p ( if c = 0 the LCG is called Multiplicative Congruential Generator)

LCG is seeded by the ‘initial value’ or ‘start value’ X(0) where 0 <= X(0) < p

As you can see from the above definition, the current state is used to determine the next state of the LCG.

Due to the “Crystalline” (see animation) nature of these generators we can successfully predict the next sequence of random number and calculate the values a,c and p in the above defined equation by just observing few pseudo random values generated by the generator, let’s see how we can achieve this.

In this example, I am using the LCG used in one of the programming assignments by Stanford Cryptography online course[4] by Prof. Dan Boneh[5].

import random
# Linear Congruential Generator
P = 295075153L
class WeakPrng(object):
    def __init__(self, p):   # generate seed with 56 bits of entropy
        self.p = p
        self.x = random.randint(0, p)
    def next(self):
        self.x = (2*self.x + 5) % self.p
        return self.x  
prng = WeakPrng(P)
for i in range(1, 10):
  print "output #%d: %d" % (i,

The LCG in the following program is

x = (2*x +5) mod (295075153) …. (I)

a = 2
c = 5 and
p = 295075153

Let’s assume we have no knowledge of a,c and p and initial seed for x was chosen randomly (ah, right !). What we do have is the following output sequence generated by the above LCG equation(I).

LCG output:
output #1: 54294923
output #2: 108589851
output #3: 217179707
output #4: 139284266
output #5: 278568537
output #6: 262061926
output #7: 229048704
output #8: 163022260
output #9: 30969372

The task here is to find out a,c and p values which would help us predict the next output for this sequence.

The way I was able to get this to work was using a determinant of a 2×2 matrix, a 3×3 matrix would also work but I haven’t tried it.
Let’s create a 2×2 matrix of above output such as:

| output(i)-output(1)    output(i+1)-output(2) |
| output (j)-output(1)   output(j+1)-output(2) |

The absolute value of the determinant of the above matrix is the volume of a parallelepiped determined by the three output points in the plane (remember the crystalline structure).

The code below will take space separated pseudo random values and calculate the determinant
e.g. for 7 values generated by the above LCG x(1), x(2), x(3), x(4), x(5), x(6), x(7)

input = 54294923 108589851 217179707 139284266 278568537 262061926 229048704

The program calculates determinants:
d(2,3), d(3,4), d(4,5), d(5,6)
[note: no error checking done in the program, if you get ‘IndexError: list index out of range’ enter one more pseudo random number]

d(2,3) = 16021084186723984
d(3,4) = 25078243389094479
d(4,5) = 25078243389094479
d(5,6) = 4870690766336483

import sys
def calc_det(i,j,X):
	""" Calculate the values for the matrix[lattice] """
	a1 = X[i] - X[0]
	b1 = X[i+1] - X[1]
	a2 = X[j] - X[0]
	b2 = X[j+1] - X[1]
	""" Calculate the determinant """
	det = a1*b2 - a2*b1
	return abs(det)
def main():
	print "Calculate determinant 2X2"
	print "Enter the random number list whose determinant you want (space seperated) "
	s = raw_input()
	X = [long(i) for i in s.split(' ')]
	""" calculate determinant for d(1,2) """
	print calc_det(1,2,X)
	""" calculate determinant for d(1,2) """
	print calc_det(2,3,X)
	""" calculate determinant for d(1,2) """
	print calc_det(3,4,X)
	""" calculate determinant for d(1,2) """
	print calc_det(4,5,X)
if __name__ == "__main__":

Because the points lie on the lattice of the structure, the volume must be multiple of unit-cell volume, which is

m^(n-1) in n dimensions.

So, the modulus of the generator is the GCD of all the possible d(a,b) values. We need not find all the d(a,b) values only few would suffice.

p = GCD(d(2,3),d(3,4),d(4,5), d(5,6) )

Following, is the python script to find GCD of multiple numbers.

import sys
import math
def GCD(a,b):
	""" Euclidean Algo"""
	a = abs(a)
	b = abs(b)
	while a:
			a,b = long(b%a),a
	return b
def main():
	print 'Enter the numbers whose factors you want seperated by spaces'
	s = raw_input()
	list = [long(i) for i in s.split(' ')]
	#list = [8, 24, 12]
	soln =  reduce(GCD, list)
	print soln
if __name__ == "__main__":

Feeding the above d(2,3), d(3,4), d(4,5),d(5,6) values to the program we get
p = 295075153

Which turns out to be the p that we started with !
Once we have p, and the initial sequence, it is not at all difficult to find a and c by using equation (I) which is left as an exercise for the reader.



* Some of you might frown on my inefficient Python coding skills. My apologies, this is the first time I have written a python code (an awesome learning experience) and this post is about LCG and not intended to demonstrate my Python skills.

Android on Nook Color – Quick, easy and always works !

Android CM7 on Nook Color

So, if you are having problems installing Cyanogenmod 7 for Nook Color on a MicroSD card you are not alone. I was in the same boat, the MicroSD card I used was Transcend 32 GB Class 4, as it turns out make of the card does matter. Fortunately though I had a 2 GB Sandisk SD card laying around gathering dust, so I decided to put it to use.

I followed these instructions to install Android on a Micro SD card for my Nook Color, it worked for Sandisk but not for my Transcend Micro SD card. I got a whole bunch of IO errors with Transcend while installing. The problem is with the SD card, and as it turns out  not all SD cards are the same and some are evil.

For all of you, those who want an easy and workable solution, you can download the gunziped image file here (~250 MB) that I created. MD5 checksum is 7b2c46113f4e9baa73c61b1f5d98a78b (if you care).

Extract it (type tar -zxvf file.tar.gz) and burn it to your new SD card. Following are the things you need.

  1. A 2 GB MicroSD card (or greater)
  2. A program to burn the image to your MicroSD card, like Win32DiskImager or ‘dd’ for Mac and Linux.
  3. If your MicroSD  card is more than 2 GB then you will need a utility program like GParted (Ubuntu) to expand the 1 GB Nook SD card partition space to the unallocated space (sorry if it sounds complicated but its really simple I promise !).

I will describing the steps for Mac, for Windows it should be easy using Win32DiskImager, if you have any trouble just ask me in the comments and I will try to address it.

  1. Plug in the MicroSD card in your Mac.
  2. In the terminal ( type ‘diskutil list’
    this will list all the mounted drives on your machine, identify your SD card using the storage space and/or the file system. This step is critical, make sure you know the correct path to your MicroSD card.
  3. Unmount the MicroSD card using the following command ‘diskutil unmount /dev/disk#’ where # is the number of your Micro SD card volume.
  4. Run the command
    dd if='complete_path_to_Image.img' of='/dev/disk#' conv=noerror

After the command is done running (which can take a while !) you will see two volumes mounted on your machine:

  • boot and
  • SD Card

You are all set, if you have a SD card more than 2 GB you can use GParted (Ubuntu utility program) to accomodate the unallocated space into the SD Card space.
Hint: if the new partition exceeds 4GB use fat 32 ! by default the partitions are fat 16.

Have fun with your new Nook Color Tablet

Pooling framework for Memcached

Since a long time I wanted a pooling framework for Memcached API, so I decided to build one. Its fairly straight forward to use and modify, you can get the source code from my Git repository.

Following are the steps to get it up and running.

  1. Import the project in Eclipse
  2. Add the following jars to the project as they are needed for the project to compile
    1. commons-logging.jar  (
    2. commons-pool-1.5.6.jar   (
    3. junit.jar     (
    4. memcached-2.5.jar   (
  3. I have included JUnit test, just in case !
  4. The settings to connect to the Membase/Memcache server are in the file (memcached.server)
  5. Pool size can be set in the same file (memcached.poolObjects)
  6. API currently implements SET,GET and DELETE methods, feel free to extend it and let me know, I will be more than happy to update the code.


private CachingBroker cb = new CachingBroker();
	cb.set("key" ,TTL, "value");   // set
	cb.get("key");                     // get
	cb.delete("key");	        // delete


Also, don’t forget  to leave a comment if you like it or even criticize it if you don’t.

Happy Coding

Setting up SSH on Mac OSX

Well, it’s been a long time I wanted to set up a SSH service on my Mac. Every time I did it I got slammed by robots trying to brute-force my password. Not that I have a week password but it ate a lot of my bandwidth and not to mention the processing power. So, I decided to make a series of changes to make my box more secure.

Change the default SSH port to something other than 22 :

From a security point of view defaults are a big no-no. So, here are the steps to change the default SSH port from 22 to something else. Now, for some reason its not as easy as changing /etc/sshd_config file as it is with Linux. Anonymous, has written a nice article on this, I will duplicate some of it here.

1) Using Terminal go to the file /etc/services

2) Find the line where SSH port value is defined, by default it should be 22 (for TCP and UDP)

3) Modify the number from 22 to any number between 1024-65535.

4) Restart the machine for the changes to take effect.

One small thing to remember about ports is that values 1-1024 are privileged ports and avoid using those values. Any value between 1024-65535 should be acceptable but larger values are invalid.


Disable Password Logins and enable Publickey Authentication:

I would rather disable password logins on my internet facing box. Its Game Over for me if my password is compromised or gets brute-forced.

To disable password logins follow the following steps:

1) Using terminal go to the file /etc/sshd_config

2) Open the file with your favorite editor (vim in this case)

sudo vim /etc/sshd_config

3) Uncomment (remove #) the line which says ‘#ChallengeResponseAuthentication yes’ and change it to following

ChallengeResponseAuthentication no

4) To enable publickey login, uncomment the lines

PubkeyAuthentication yes

AuthorizedKeysFile      .ssh/authorized_keys

Publickey on

This will enable you to login using publickey which is a nice and secure way to log in from outside your network.

5) If you want to turn on Tunneling then you can change the line ‘#PermitTunnel no’  to ‘PermitTunnel yes’

6) Once you are comfortable with all the changes type ‘Esc:wq’ which means Write the file and Quit.

We don’t need to restart the SSH server on mac OS X as services are started and stopped dynamically by launchd. Configuration changes are immediate.

Creating SSH Public-Private Key:

To be able to login from outside the network we need to set up public private key pair. The private part remains with you all the time ( never ever share it !) and the public part goes to whatever server you want to be able to be log in from.

Here you will be creating public-private key pair on the client machine (e.g. iPhone or PC) from which you want to access your SSH server securely. In my case I want to access it from iPhone using iSSH. So I will be creating the keys on my SSH server itself and copy the private part to my iPhone and public part to my server.

Following are the steps to create public-private key pair:

1) Fire up the terminal and type ‘ssh-keygen’

2) Select the default location and hit enter.

3) Select a strong passphrase and hit enter.

4) Confirm the passphrase and hit enter.

5) Your key should be ready now.

6) Login into the server as a user you want to login using SSH. Create a folder .ssh under the home directory (if  it dos not exist)

mkdir ~/.ssh

7) Copy the public part of the key ( to that .ssh folder

cp ~/Desktop/ ~/.ssh/

8 ) Rename file to ‘authorized_keys’ (this is an important step !)

mv ~/.ssh/ ~/.ssh/authorized_keys

9 ) Change the permissions on the public file so that its read only for the user

chmod 400 ~/.ssh/

10) Copy the private part of the key (id_rsa) to the machine from where you want to be able to login (client).

11) Try log in from the client machine.


Awesome, you got yourself a secure SSH server ! make sure you do not share the private key with anyone and make sure you protect it.

For some reason if things do not go your way check the output of

ssh -vvv

and see what you get. If you are still having issues try repeating above steps, if that does not help post a comment may be I can be of some help.

There is a very nice post describing above steps and Kerbros authentication for SSH here.


SVN Repository Visualization Tool


Snapshot of Repository

I love graphs and charts ( not the ones used by the MBA people) and was looking for a tool which could give me a snapshot or a timeline of the events for our repository we use at my work. My search ended when I stumbled upon a tool called Gource while browsing
Let me admit one thing this tool is the coolest I every played with and its awesomeness brought me on my knees. Basically Gource is a open source software version control visualization tool for linux, Mac and Windows. It works best with Git but then there are some cool folks (Bitshifter)
who have written python script to make Gource work with SVN.
following are the steps to use Gource with SVN on windows, I am documenting them so that I don’t forget them:
You need

  1. Gource download
  2. Python (2.5 or later) download

Unzip and install Gource and Python.
Go to your SVN trunk (or branch) – my-svn-project.

cd my-svn-project

Get SVN log

svn log –verbose –xml > my-project.log

Run the python script to convert svn logs to Gource friendly log

python –filter-dirs my-project.log > my-project-gource.log

Display the results

gource –log-format custom my-project-gource.log

By default the display speed is 10 seconds per day, you can speed it up by using the option -s (e.g 0.1 is faster, 100 is slower)


gource -s 0.1 –log-format custom my-project-gource.log

Calculating distance between 2 points on the Earth

Out of curiosity I had built myself a GPS Datalogger, I was able to get the raw NMEA data out of it but it only provided information regarding my position and time. I wanted to calculate the velocity of a vehicle at a given location and plot a graph of distance Vs velocity. I used the following calculations to calculate the distance between the two coordinates on the Earth’s surface. By dividing that distance with time I was able to calculate the velocity in KMPH at a given location.

To calculate the distance between two Latitude and Longitude coordinates, I am using the ‘Havesine’ formula. Haversine formaula calculates the great-circle distance between the two points i.e. the shortest distance given between the two points on the earth’s surface. It calculates the “as-the-crow-flies” distance between the points ignoring any terrain.

Here’s the formula (angles are assumed to be in Radians)

R = Earth’s radius = 6,371 Km
Dlat = latitude2 – latitude1
Dlong = longitude2 – longitude1
a = sin²(Dlat/2) + cos(latitude1)*cos(latitude2)*sin²(Dlong/2)
c = 2.atan2(√a, √(1−a))
d = R*c

Haversine formula (Mathematical explanation)

haversin (d/R) = haversin(θ2 – θ1) + cos(θ1)cos(θ2)havesin(Δλ)

havesine(θ) = sin²(θ/2) = (1−cos(θ))/2
d is the distance between two points on a sphere
R is the radius of the sphere
θ1 is the latitude at point 1
θ2 is the latitude at point 2
Δλ is the longitude seperation

The arguments to the haversine function are assumed to be in Radians.
so, to calculate the distance we have

d = R haversine(inverse)(h) = 2Rarcsin(√h)

Where h = haversin (d/R)

My implementation of the above formula is in Java, I be publishing the code as soon as I get some free time.
I can email the code if anybody wants it urgently.



DIY GPS Datalogger

GPS Datalogger


Since a long time I wanted a GPS Datalogger, I do have a Garmin GPS, which to my dismay does not provide me with all the data that I need. I wanted the NMEA data from my GPS device, but as it turns out I cannot have it. So, I decided to build myself one, so that I can track my travel pattern and do some fun stuff. Before going down this path, I checked online for some cheap dataloggers but they were all in the range of $100 to $199, too much for my tiny hobby.

Following are the steps to build your own cheap GPS datalogger, I wrote these steps as a future reference to me and also for someone who would like to walk this path. A detailed component list is attached at the end of the article.

Step 1) Getting a cheap GPS Module:

There are lots of GPS modules available in the market ranging from $50 to $200 which can do lots of fancy things, but do you need all those things ? for me the answer was no. So I went to eBay and brought a cheap GPS module based on SiRF 2 chip-set, it can track up to 12 GPS satellites as compared to 20 with other high-end GPS modules, but then you only need 4-5 GPS satellites at a given point in time to correctly identify your position. Here’s the GPS module that I brought for $14 and the eBay link for it.


GPS Module

GPS Module

Step 2) RS232 to TTL conversion

Some GPS modules output TTL (Transistor Transistor Logic) signals and some output RS232 signals (mine used RS232), if you are planning to use the GPS module with a PC then RS232 is great, but in my case I wanted it to be used with Arduino and with a data logging circuit which logs raw data to a Micro SD card.

So, I had to build a circuit to convert RS232 signal to TTL signal. I used a well known IC, MAX 232A for conversion. To complete the circuit you need five 0.1 µF capacitors. Following is the pin layout of  MAX 232A and a circuit diagram that I used to convert RS232 signal to TTL signal.

This is how the conversion circuit looks after hooking up all the components and IC.

RS 232 toTTL

RS 232 toTTL

Step 3) Designing a Voltage Regulator to use a 9V battery to power the circuitry

I am planning to use a 9V battery to power the entire unit. The GPS receiver needs 5V, so I needed to design a voltage regulator circuit with 5V constant output voltage. I used the  LM7805 voltage regulator, it was cheap and easy. I used a 0.1 µF Capacitor at the output to prevent any spikes, but it’s optional to use and only LM7805 will do the job.

The circuit diagram for the Voltage regulator, in case you need, here .

Step 4) Serial Data Logging Circuitry.

For logging the serial data output from the GPS, I used Open Log from Sparkfun . It logs serial data to a micro SD card, the baud rates can be adjusted. I had to adjust the baud rate to 4800 so as to match the GPS Data baud rate. It’s simple and extremely easy to use, I got it for $25.

Voltage Regulator Using LM7805

Voltage Regulator Using LM7805

Step 5) Assembly

Get everything soldered and make sure you do not have any open ends. I am not very good at soldering and suck in PCB optimization. Anyhow, I got my prototype working, its not the preetiest thing in the world but hey it works !

GPS Datalogger

GPS Datalogger

Since I was indoors I could not get a proper fix on the satellites. But, I did get valid GPS sentences logged.

$Baud rate: 4800  System clock: 12.277MHz
$HW Type: S2AM
$Asic Version: 0x23
$Clock Source: GPSCLK
$Internal Beacon: None

I used Google Maps to plot the graph of Altitude Vs Distance using a KML file, I am in a process of optimizing the code, currently I am a bit tied down and will upload the code once I get some free time.

The following graph shows Velocity Vs Distance, height of the graph is the velocity of my car, notice how the height of the graph decreases at the turns and at the stop lights. I had to do some math to calculate the distance between two consecutive coordinates to get the velocity, I will post the formula and the Java code that I used to calculate the velocity once I get some time.  If you want to know more about calculating the distance refer to this post Calculating distance between 2 points on the Earth.


Component List:

1) A GPS Module

2) Serial Data Logger (like Open Log from Sparkfun)

3) MAX 232A IC

4) Five 0.1 µF Capacitors

5) LM7805 Voltage Regulator

6) 9V Battery