Monday, June 29, 2009
Building Boost Lib 1.35 with VC++ 2008
Below are the steps I followed to have everything working on Win 7.
If not already done, install the following development tools (in the prescribed order, please):
Visual C++ 2008 Express Edition
Microsoft Windows SDK
Microsoft Compute Cluster Pack SDK
The last one will only be needed if you plan to compile the Boost.MPI library.
Download and install Python. Download Boost 1.35 and the latest Boost Jam binary (3.1.17 at the time of this writing). Copy the bjam executable to the Boost root directory. Next, disable the automatic linking features of the Microsoft Visual C++ compiler by enabling the BOOST_ALL_NO_LIB macro on the file user.hpp (boost/config/user.hpp). We’re ready to go (type all the commands inside the Visual Studio 2008 Command Prompt):
“bjam stage”
Boost Jam auto detects the Visual C++ 2008 compiler!
If you want to compile the Boost.MPI library a couple of additional steps must be followed. Boost Jam is your friend as it prints it nicely for you:
warning: skipping optional Message Passing Interface (MPI) library.
note: to enable MPI support, add “using mpi ;” to user-config.jam.
note: to suppress this message, pass “–without-mpi” to bjam.
note: otherwise, you can safely ignore this message.
Follow the instructions. The user-config.jam is to be created in your “current” directory ($BOOST_ROOT_DIR\tools\build\v2).
Now build the Boost.MPI library by issuing:
“bjam –with-mpi stage”
The Microsoft MPI library is auto detected!
That is it! Happy Hacking :)
Sunday, June 28, 2009
Anbe Vaa - Vijay TV's New serial
Oru paarvai paarkirai..
pudhidhai nan pookiren..
Idhayam idam maarudhe..
Idhu kaadhala...
Nilavodu theigiren..
Ninaivale karaigiren..
sugamana vedhanai..
Idhu kaadala...
Engeyo.. engeyo..
ennule engeyo..
vinmeengal sidharudhe
yaenadi..
Anbe vaa..
Anbe vaa..
Anbe vaa
Anbe vaa.. a...
Ah...
(Female)
Kannukule kannukule.. kaadhal vandhu nenjai thotu povathen..
(Male)
Enna idhu enna idhu.. vaanavillil vanam rendu koodudhe..
(Female)
Theendinal.. vaanile..
megamai alaigiren
(male)
neenginal dhoorathil..
pulliyai tholaigiren..
Nillarendral nillaamal
yenendru kelaamal
edhedho seigirai..
yaenadi..
Anbe vaa..
Anbe vaa..
Anbe vaa
Anbe vaa.. a...
(F)Enna solli enna solli kaadhal adhai unnidathil kaatuven..
(m)Sathamindri sathamindri mounamai nenjukulle pootuven..
(F)kavithaigal ezhudhida vaarthaigal thedinen..
(M)un peyar ezhudhinaal kavidhayai paadinen..
Enn ulle en ulle..
un kannin minsaram..
edhedho seiyudhe..
Yaenadi..
Anbe vaa..
Anbe vaa..
Anbe vaa
Anbe vaa.. a...
Thursday, June 25, 2009
Secrets of std::map
Below is the snippet of similar case.
#include "stdafx.h"
#include < iostream >
#include < map >
int main()
{
// 1. define the map
typedef std::mapMap;
// 2. Create the object for it
Map myMap;
for (int i=0; i<10; ++i)
{
/****************************
3. Whats going on here ???.
We just created the object.
Could this be a buggy code ??
Nope. When we reference an item in map
and if the item is not available,
it creates the object. Great :)
I personally seen/used the creation
of map on the left side,
something like myMap[2] = 20
But the below is of something which
I am seeing new today :)
**********************************************/
int &ref = myMap[i];
ref = i;
}
for (int i=0; i<10; ++i)
{
std::cout << myMap[i] << " ";
}
std::cout << std::endl;
return 0;
}
Happy Hacking :)
Monday, June 22, 2009
C++ forward declaration error
I am trying to declare and use a class B inside of a class A and define B outside A.I know for a fact that this is possible because Bjarne Stroustrup uses this in his book "The C++ programming language" (page 293,for example the String and Srep classes). So this is my minimal piece of code that causes problems.
class A
{
struct B; // forward declaration
B* c; A()
{
c->i;
}
};
struct A::B
{
/** we define struct B like this
** becuase it was first declared
** in the namespace A */
int i;
};
int main()
{
}
Error:
This code gives the following compilation errors in g++ : tst.cpp: In constructor ‘A::A()’: tst.cpp:5: error: invalid use of undefined type ‘struct A::B’ tst.cpp:3: error: forward declaration of ‘struct A::B’
Solution:
Define the constructor for A AFTER the definition of struct B.
Sunday, June 14, 2009
Step 1:
Put Onions, Tomato, Chilly, Coriander leaf, 1 Spn of Turmeric Cumin powder (from Amma) in a pressure cooker and keep 3 Whistle.
Step 2:
Put all the needed vegetables in the same pressure cooker and add 1/5 Spn of chilly power, salt to taste. Keep for one more whistle.
Sambhar is ready ;)
Thursday, February 26, 2009
How to get the elapsed time in millisecs
My Approach:
You can use gettimeofday at the start and end of your method and then the difference the two will give the elapsed time .. You'll get a structure like the one below:
struct timeval {
time_t tv_sec; /* in secs */
suseconds_t tv_usec; /* in Microseconds */
};
Code snippet:
#include
#include
#include
int main()
{
struct timeval start, end;
long mtime, seconds, useconds;
// Get the start time
gettimeofday(&start, NULL);
// Here you go with your method call
usleep(2000);
// note the end time
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
printf("Elapsed time: %ld milliseconds\n", mtime);
return 0;
}
Wednesday, February 25, 2009
Python: Human readable time span given total secs
Function takes an amount of time in seconds and returns a human readable time span.
Input: 14723 (in secs)
Output : 4h 5m 23s
Suffixes used:
y - year
w - week
d - days
h - hours
m - min
s - sec
Code:
#!/usr/bin/env python
def elapsed_time (seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)
# - the first piece in each tuple is the suffix (d, h, w)
# - the second piece is the length in seconds (a day is 60s * 60m * 24h)
parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
(suffixes[1], 60 * 60 * 24 * 7),
(suffixes[2], 60 * 60 * 24),
(suffixes[3], 60 * 60),
(suffixes[4], 60),
(suffixes[5], 1)]
# for each time piece, grab the value and remaining seconds, and add it to
# the time string
for suffix, length in parts:
value = seconds / length
if value > 0:
seconds = seconds % length
time.append('%s%s' % (str(value),
(suffix, (suffix, suffix + 's')[value > 1])[add_s]))
if seconds < 1:
break
return separator.join(time)
if __name__ == '__main__':
# 2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
# 2y 1w 6d 2h 59m 23s
seconds = (60 * 60 * 24 * 7 * 52 * 2) + (60 * 60 * 24 * 7 * 1) + (60 * 60 * 24 * 6) + (60 * 60 * 2) + (60 * 59) + (1 * 23)
print elapsed_time(seconds)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'])
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True)
print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True, separator=', ')
Output:
[10:13:34 gmuniyan@lnl43a-3102] /home/gmuniyan/python>./elapsedTime.py
2y 1w 6d 2h 59m 23s
2 year 1 week 6 day 2 hour 59 minute 23 second
2 years 1 week 6 days 2 hours 59 minutes 23 seconds
2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
Honor: Original Post
Tuesday, February 24, 2009
Running a cmd from bash script
There are many situations in which you may want to run different command in your shell script depending on requirements and circumstances.
There are two approaches we can take from here on.
Approach #1:
Use either case statement or if..elif..else For example:
#!/bin/bash
if [ this -eq that ];then
command1
else
command2
fi
Approach #2:
BASH allows you to assign/store a command in a built-in variable called CMD. Build your command in this variable and execute $CMD.
#!/bin/bash
[ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date";
eval $CMD;
This is a very simple example and this approach is very much generic if you want to have a generic function to execute all the commands. For example:
#!/bin/bash
execute() {
# $1 holds the arg to this function
CMD="$1";
eval $CMD;
}
## Here is your main function
if [ this -eq that]
then
execute "/bin/ls | wc -l";
else
execute "/bin/ls";
fi
NOTE: eval is required when you use "|" or redirection of cmd output.
Happy hacking :) !!
Monday, February 23, 2009
Python: Processing cmd line args
Method #1: Using sys:
#! /usr/bin/python
import sys;
if __name__ == "__main__":
for args in sys.argv:
print args;
Output:
# cmdLine.py 1 2 3 4
cmdLine.py
1
2
3
4
Python: Hello World
Python way of saying "Hello world" :)
#!/usr/bin/env python
## In Python each module will have a name associated with it
## And here is the main module
if __name__ == "__main__":
print "Hello World";
Sunday, February 01, 2009
Show that 2^n is O(n!)
This is an interview question from MS.
Answer:
n! = 2*3*...*n >= 2*2*...*2 = 2^(n-1)
Since 2^n <= 2*n! for all n, we have that 2^n = O(n!).
Thursday, January 15, 2009
Monday, January 05, 2009
Arrange 0's & 1's
-------------------
An array of size n among which there are n/2 0s and n/2 1s arranged in random order.
Arrange all the 1s to left and all 0s to right but it needs to be
stable i.e., the order of 1s and 0s in the i/p array should be maintained.
Expected Complexity:
--------------------------------
O(N) with constant space.
Pseudocode:
--------------------
1. Have two counters, count1 = 0 and count2 = (n/2)+1
2. Traverse thru the array, if(arr[ i ] == 1) { arr[ i ] = count1++;} else { arr[ i ] = count2++ };
3. At the end of the traversal, you have array filled with numbers 0 to n-1
Now the problem reduces to sorting and array of n numbers which has elements from 0 to
n-1 occuring only once which can be done in O(n).
for(j = 0; j <= 1; j++)
{
for(i = 0; i<n; i++)
{
if(arr[ i ] != i)
{
swap(arr[ i ], arr[ arr[ i ] ]);
}
}
}
</pre>
Note: j loop runs only twice irrespective on 'n' and has constant complexity. The order of this whole loop is 2*n = O(n).
4. After the array is sorted, Again traverse thru the array and make elements arr[0] to
arr[n/2] to '1' and arr[(n/2)+1] to arr[n] as '0'.
Space complexity is constant and time complexity is O(step2) + O(step3) + O(step4) = n + 2n +n = 4*n = O(n).
Solution #1 (Stable):
------------------------
<pre name='code' class='cpp'>
#include<iostream.h>
int a[] = { 1,0,0,0,1,1,1,0,0,1};
#define _SIZE sizeof(a)/sizeof(a[0])
/* Helper Function */
void printArray()
{
for(int i=0;i<_SIZE; ++i)
cout<<a[i]<<" ";
cout<<endl;
}
int main()
{
int countOne = 0;
int countZero = (_SIZE)/2;
int i = 0;
/* Fill the array with numbers from 1 to N */
for(i=0; i < _SIZE; ++i)
{
if(a[i] == 1)
{
a[i] = countOne;
countOne++;
}
else
{
a[i] = countZero;
countZero++;
}
}
printArray();
/* Swap the number and make it a sorted one */
for(int j = 0; j< 2; ++j)
{
for(i=0; i < _SIZE; ++i)
{
if(a[i] != i)
{
int temp = a[i];
a[i] = a[a[i]];
a[temp] = temp;
}
}
}
printArray();
/* Fill the 1st N/2 elements with 1 */
for(i=0; i<_SIZE/2; ++i)
a[i] = 1;
/* Fill the last N/2 elements with 1 */
for(i=_SIZE/2; i<_SIZE; i++)
a[i] = 0;
printArray();
return 0;
}
</pre>
Solution #2 (UnStable):
-----------------------------------
Here is a small variation of the quick sort to solve the same problem but this solution is not stable. So I prefer #1.
<pre name='code' class='cpp'>
#include<iostream.h>
using namespace std;
#define _SIZE sizeof(a)/sizeof(a[0])
void swap(int *a, int l, int r)
{
cout<<"Swaping "<<l<<" "<<r<<endl;
if(a[l] != a[r])
a[l] ^= a[r] ^= a[l] ^= a[r];
return;
}
bool compare_1_upper(int *a, int u, int p)
{
return (a[u] == p);
}
bool compare_1_lower(int *a, int l, int p)
{
return (a[l] < p);
}
bool compare_0_upper(int *a, int u, int p)
{
return (a[u] > p);
}
bool compare_0_lower(int *a, int u, int p)
{
return (a[u] == p);
}
bool (*funcPtr_upper)(int *, int, int) = 0;
bool (*funcPtr_lower)(int *, int, int) = 0;
void qPartition(int *a, int low, int upper)
{
int pivot = a[low];
int l = low - 1;
int u = upper + 1;
if(a[low])
{
funcPtr_upper = compare_1_upper;
funcPtr_lower = compare_1_lower;
}
else
{
funcPtr_upper = compare_0_upper;
funcPtr_lower = compare_0_lower;
}
while(1)
{
while(funcPtr_upper(a, --u, pivot));
while(funcPtr_lower(a, ++l, pivot));
if(l<u)
swap(a, l, u);
else
return;
}
return;
}
int a[] = { 1,1,1,1,1,0,0,1};
void print()
{
for(int i=0; i< _SIZE; ++i)
cout<<a[i]<<" ";
cout<<"\n";
}
int main()
{
print();
qPartition(a, 0, _SIZE - 1);
print();
return 0;
}
Monday, December 29, 2008
XOR Linkedlist
Implement a doubly linked list with a single pointer.
Solution:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/* pray that a long is the size of a struct link* */
typedef unsigned long pointer;
struct link
{
pointer next_prev;
int payload;
};
typedef struct link link;
link* add_data(int payload, struct link* list)
{
struct link * new_link = (struct link*)malloc(sizeof(link));
assert(new_link);
new_link->next_prev = (pointer)list;
new_link->payload = payload;
if (list != NULL)
{
list->next_prev = (pointer) list->next_prev ^ (pointer)new_link;
}
return new_link;
}
void walk_list(link *list)
{
struct link* prev = 0;
while (list != NULL)
{
pointer next = ((pointer)prev) ^ list->next_prev;
printf("%d ", list->payload);
prev = (struct link*)list;
list = (link*)next;
}
printf("\n");
}
int main(void)
{
link *l1 = add_data(1, NULL);
link *l2 = add_data(2, l1);
/* add something to the front ... */
/* add something to the back ... */
link *l3 = add_data(3, l2);
link *l4 = add_data(4, l3);
link *l5 = add_data(5, l4);
/* walk from front to back */
walk_list(l1);
/* walk from back to front */
walk_list(l5);
return 0;
}
Dutch Nation Flag Problem
Given an array of red, green and blue balls arrange them in groups of all red together, greens together and blue together. Do in a single scan of the array.
This is same as You have an array containing only '0's, '1's and '2's. Club same items together in single scan.
Solution:
<br />#include<iostream.h><br />#define _SIZE sizeof(a)/sizeof(a[0])<br />using namespace std;<br />void printArray(int *array, int size)<br />{<br /> for(int i=0; i<size; ++i)=""><br /> cout<<array[i]<<" ";<br /> cout<<endl;<br /> return;<br />}<br />void swap(int *a, int left, int right)<br />{<br /> if(a[left] != a[right])<br /> {<br /> a[left] ^= a[right] ^= a[left] ^= a[right];<br /> }<br />}<br />void reArrange(int *a, int length)<br />{<br /> int low, mid, high = length -1;<br /> low =0; mid = 0;<br /> while(mid <= high)<br /> {<br /> switch(a[mid])<br /> {<br /> case 0 :<br /> swap(a, low, mid);<br /> low++;<br /> mid++;<br /> break;<br /> case 1 :<br /> mid++;<br /> break;<br /> case 2 :<br /> swap(a, mid, high);<br /> high--;<br /> break;<br /> default:<br /> cout<<">>> Error \n";<br /> }<br /> }<br />}<br />int main()<br />{<br /> int a [ ] = { 1,1,1,0,1,2,2,1,0,2,1,2,0 };<br /> printArray(a, _SIZE);<br /> reArrange(a, _SIZE);<br /> printArray(a, _SIZE);<br /> return 0;<br />}<br /><br />Saturday, December 27, 2008
Create encrypted tar file
$ tar -zcvf - stuff|openssl des3 -salt -k secretpassword | dd of=stuff.des3
This will create stuff.des3...don't forget the password you
put in place of secretpassword. This can be done interactive as
well.
$ dd if=stuff.des3 |openssl des3 -d -k secretpassword|tar zxf -
NOTE: above there is a "-" at the end... this will
extract everything.
Friday, December 26, 2008
Mount error in Ubuntu
Error Message:

Solution:
1. sudo apt-get install ntfsprogs
2. sudo ntfsfix /dev/sda2
mganesh@bluegene:~$ sudo ntfsfix /dev/sda3
Mounting volume... FAILED
Attempting to correct errors...
Processing $MFT and $MFTMirr...
Reading $MFT... OK
Reading $MFTMirr... OK
Comparing $MFTMirr to $MFT... OK
Processing of $MFT and $MFTMirr completed successfully.
Setting required flags on partition... OK
Going to empty the journal ($LogFile)... OK
NTFS volume version is 3.1.
NTFS partition /dev/sda3 was processed successfully.
mganesh@bluegene:~$ sudo ntfsfix /dev/sda2
Mounting volume... FAILED
Attempting to correct errors...
Processing $MFT and $MFTMirr...
Reading $MFT... OK
Reading $MFTMirr... OK
Comparing $MFTMirr to $MFT... OK
Processing of $MFT and $MFTMirr completed successfully.
Setting required flags on partition... OK
Going to empty the journal ($LogFile)... OK
NTFS volume version is 3.1.
NTFS partition /dev/sda2 was processed successfully.
Happy Ubuntu :) !! .. This solves the problem
Wednesday, December 24, 2008
Search in the Matrix
We a Matrix where every ROW and COL are sorted something like the below:
1 4 5 6
2 5 7 9
3 6 8 10
Problem: give a number, you need to search whether it is there in the Matrix or not.
Solution:
The below solution's complexity is O(m+n) where m - ROW, n - COL
<br />#include<iostream><br />using namespace std;<br />#define ROW 4<br />#define COL 5<br /><br />int Matrix[ROW][COL] = {<br /> { 1, 3, 5, 7, 9},<br /> { 2, 4, 6, 8, 10},<br /> {11,13,15,17, 19},<br /> {20,40,60,80,100}<br />};<br />bool isValid(int row, int col)<br />{<br /> if(row >= 0 && col < COL)<br /> {<br /> return true;<br /> }<br /> return false;<br />}<br />int main()<br />{<br /> int i = ROW-1;<br /> int j = 0; // Zeroth Column<br /> int searchItem = 0;<br /><br /> cout<<"enter the number to be searched: ";<br /> cin >> searchItem;<br /><br /> while(isValid(i, j))<br /> {<br /> if(Matrix[i][j]== searchItem)<br /> {<br /> cout<<"Item found @ ("<< i<<","<< j << ") :"<< searchItem<< endl;<br /> return 0;<br /> }<br /> else if (Matrix[i][j] > searchItem)<br /> {<br /> //go up, which means reduce the row<br /> i--;<br /> }<br /> else<br /> {<br /> // itea is lesser than the index, go right<br /> j++;<br /> }<br /> }<br /> cout<<"Item not found :("<< endl;<br /> return 0;<br />}<br />Tuesday, December 23, 2008
Palindrome Number
#include<iostream>
using namespace std;
bool isPanlindrome(int n)
{
int rev = 0;
int num = n;
while(n)
{
rev = rev * 10 + (n%10);
n = n /10;
}
if(num && num == rev)
return true;
return false;
}
int main()
{
int number = 0;
cout<<"Enter the number: ";
cin>>number;
cout<<number<<" is Panlindrome ?."<< (isPanlindrome(number)? "Yes !!": "No :(!!");
cout<<endl;
return 0;
}
Monday, December 22, 2008
String Manipulation
Encode it to : ab3c2d4e3
#include<iostream>
#include <strstream>
#include<stdlib.h>
#include<string.h>
using namespace std;
void convert(char *input)
{
char *start = input;
char *s1 = input;
char *s2 = input + 1;
int len = strlen(input);
int count = 0;
char *end = start;
while(--len && *s1 && *s2 )
{
while(*s1 && *s2 && len && *s1 == *s2)
{
++count;
s2++;
--len;
}
if(count)
{
ostrstream str;
str<<(count+1);
*start = *s1;
*++start = *(str.str());
start = start + strlen(str.str()) - 1;
count = 0;
}
else
*start = *s1;
start++;
s1 = s2;
s2++;
}
if(*s1 != *(s1-1))
*start++ = *s1;
*start = *s2;
cout<<"Magic: "<<end<<endl;
return;
}
int main()
{
char input[100];
memset(input, 0, 100);
cout<<"Enter the string: ";
scanf("%s", input);
cout<<"You entered: "<<input<<"!!\n";
convert(input);
return 0;
}