TechMyWay – New Blog

Posted April 28, 2013 by TechMyWay
Categories: Uncategorized

TechMyWay – New Blog

Much has happened since I graduated and started working. Here is a link to my new blog, which I try my best to keep updated. Follow me up there for future posts 🙂


Git add remote branch

Posted September 27, 2012 by TechMyWay
Categories: Uncategorized

A quick post on git (might help some):

To create a branch: git checkout -b branchName
#this also switches you to the newly created branch

Now to upload it to your remote repository use:
git push origin branchName
# if the branch with that name already doesn’t exist then it would be updated (as tested on GitHub)

A major milestone : 5k views

Posted April 23, 2012 by TechMyWay
Categories: Uncategorized

Tags: ,

To all,

Thanks a lot for your love. My blog has crossed 5000 views. 🙂 🙂

Threading in Python

Posted April 15, 2012 by TechMyWay
Categories: Python

Tags: , ,

Recently in my effort to learn something new in Python, I thought of having a small introduction to threading in python.

The following modules are related to python that come in default installation in python:

From Python Docs:

The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0; however, you should consider using the high-level threading module instead.

Thus, it can be assumed that when developing scripts that may use threading, always use the threading module rather than thread.

To save myself some time, it would be better if you can read the basic concepts of threads from wiki itself.

Now, comes the first program.

#!/usr/bin/env python

import time
import thread

def myfunction(string, sleeptime, max_count, *args):

    counter = 0
    ## To manage I/O
    while counter < max_count:
        print "{}. {}".format(counter, string)
        counter += 1
        #sleep for a specified amount of time.

if __name__=="__main__":

    print "thread Started : {}".format(thread.start_new_thread(myfunction,("Thread No:1", 2, 10)))
##    thread.exit_thread
    ## this can be omitted
    while 1:


In the above script, a new thread is started using the function myfunction. The arguments to the function are passed to the start_new_thread() using a tuple (do remember to make a tuple from the arguments you want to pass). The start_new_thread() returns the thread identifier of the thread started (which has been printed here).
A very usual thing I noticed in threaded programs is the use of time.sleep(), it helps in synchronizing the input output on the terminal. In actual backend scripts, the sleep function would not prove useful (I may be wrong!)

The last example was just for introduction. To jump up the level, let’s calculate the Fibonacci series from a thread.


#Fibonacci threader

import time, thread, threading

def fib(n):
    a, b = 0, 1
    while a</pre>

The above script uses both <a title="Python Docs" href="">thread</a> and <a title="Python Docs" href="">threading</a> module. The thread module is used to create threads and threading module is used to get information on the current running threads in the process.

Here the function fib(n) is actually a <a title="Python Docs" href="">generator</a> and returning a iterator (returning a <a title="Python Docs" href="">generator iterator</a>). Thus we are able to iterate over the Fibonacci numbers using these generators. After the required number of Fibonacci numbers have been generated, <a title="Python Docs" href="">thread.exit_thread() </a>is called which exits the running thread silently.

After creating the thread the script prints the information of the running threads. (Execute to see)

In the end, I would be showing you the code for the (quite famous) <a title="Wikipedia" href="">Consumer-Producer problem</a> which would include the code for using locks.


#!/usr/bin/env python

import time
import thread

## Implementing consumer-producer problem using threads and locks

product = []

def producer(lock, produce_time, lim, *args):

    pr_val = 0

    while True:

        print "Producing.."
        print "Produced {}".format(pr_val)

        print "P: Lock ACK"
        print "Added product {}".format(pr_val)
        print "P: Release ACK"

        pr_val += 1

        if pr_val > lim:

def consumer(lock, consume_time, waiting_time, lim, *args):

    con_val = 0
    got_product = False

    while True:

        print "C: Lock ACK"

            con_val = product.pop()
            print "Retrieved value {}".format(con_val)
            got_product = True
        except IndexError:
            print "No produce!"
            got_product = False

        print "C: Release ACK"

        if got_product:
            print "Consuming.. {}".format(con_val)
            print "Waiting for produce"

        if con_val == lim:

if __name__=="__main__":

    max_produce = 3
    thread.start_new_thread(producer,(lock, 1, max_produce))
    thread.start_new_thread(consumer,(lock, 2, 1, max_produce))

    # Required for commandline output
    while 1:


The above code creates a lock to be used by the consumer and producer to acquire the produce-line. Then we define the units to be produced. When the threads are started, the consumer and producer are also told the consume-time and produce-time as arguments (these values are implemented in the program using the time.sleep() function).

The consumer thread starts with acquiring the lock on the produce-line and then taking the product from it. If there is no produce yet, it prints an error message. Else, the produce is picked and the lock released. The consumer then consumes the produce and go backs to the start of the loop.

The producer thread starts by producing an item. Then it acquires the lock on the produce-line and adds the produce to it. Then it releases the lock and starts reproducing.

What I have not covered: The threads can also be created and defined using classes. I could not cover that in this post. A good resource of it can be from IBM and devshed.

Github repository for it :

Also, python (CPython actually) is known to be not very good at threading because of GIL (Global Interpreter Lock) on all the data. Google for more information. 😛

My little hack on Pidgin

Posted February 16, 2012 by TechMyWay
Categories: Internet

Tags: , , , , ,

I hope you have had the good luck of using one of the best IM-client available named pidgin. You can find a whole lot of posts around telling about why it’s good and all so I am skipping it.

Now, this post is not aimed at dragging you to use pidgin. It’s actually about one good thing I stumbled upon when using it.

Usually when I am chatting with people, I find myself using terms they sometimes don’t know. So, the next usual thing to be done is to ask them to go and google it. (duh!) Now, wouldn’t it be better to just give them a link directly.!

I was thinking of making a plugin myself for this which would keep an eye on what I write and replace it with google links as and when required. But it required time.!

Luckily, I found another plugin by default in Pidgin which does the job for me. I am using Pidgin 2.7.9

  • Go to Tools->Plugins
  • Find a plugin named Text Replacement 2.7.9
  • Enable it by clicking on the little check-box by it’s side
  • Now click on the Configure Plugin just below the whole list of plugins.
  • Fill: You type -> !google
  • Fill: You type ->
  • Un-check  (remove the tick) Only replace whole words
  • Check (tick it) exact case match
  • Click on Add

Now you have got a kind of Bot which would create links for you.. 🙂

How to use it:

  • When chatting let your query be “techmyway”
  • Type in !googletechmyway
  • Press enter (and the link gets inserted) voila! 🙂

OR (this is what happens in my case)

  • whenever you write “!google” it is automatically replaced with the link

Now here is the catch: the queries can only be single-worded. The space is not recognized in urls. You would have to use %20 instead of space character. Also, remember not to try to replace every space with %20, your whole chat can get messed up.!

Share the info if you like.

Adding to each node the next inorder successor node in a binary tree

Posted February 3, 2012 by TechMyWay
Categories: C

Tags: , , ,

Lately I came to a question which stated that Given a Binary tree where each node has an extra field (node * next), write a function that puts the inorder successor of that node in the next pointer.

This can be petty easily done using the general Inorder traversal algorithm of binary trees, but in the code shown below, as you can see, I am using a global variable (which I don’t think is a good practice). If anyone turns up with a method that doesn’t use a global variable, please share the link.

I have added the necessary comments to my code so that even novices don’t have a problem in understanding it.

(Since wordpress has a bad habit of removing the spaces I put in my code x-( , you can have a better view at this gist )

// Global var to contain the inorder predecessor
node * prev;

void add_inorder(node * nd)
// Base case
if (nd == NULL)

// Recursive call for inorder processing

// The current node has a predecessor
if (prev != NULL)
// Set the next pointer
prev->next = nd;
prev = nd;

// This is the first node in the inorder processing
prev = nd;

// Recursive call for inorder processing

void mark_inorder(node * root)
/* assuming the structure to be:
typedef struct node{
int val;
struct node * next;
struct node * left;
struct node * right;
} */

// Initialising the global variable
prev = NULL;
// calling the function to add the values to pointers
// Complete the next pointers by adding to the next
// pointer of last node in inorder processing, NULL
prev->next = NULL;

K distance nodes in a Binary tree

Posted February 3, 2012 by TechMyWay
Categories: Uncategorized

Tags: , , , , ,

For a Given node of a binary tree, print the K distance nodes.

For the solution, you can also refer to stackoverflow. This also tells that only one ancestor can be at K distance from a given node.

Source code: (written in C)

void K_dist_children(node * nd, int K)
// Base case
// The Kth child found
printf("%d\n", nd->val);

// K distance node from nd are at
// K-1 distance from children of current node
K_dist_children(nd->left, K-1);
K_dist_children(nd->right, K-1);

int K_dist_ancestor(node * cur,    //curent node
node * search, //node being searched
int K)
// If the node is found, return back the result
if (cur == search)
return K-1;

int n1, n2;

// recursively search for the node in the tree
n1 = K_dist_ancestor(cur->left, search, K);
n2 = K_dist_ancestor(cur->right, search, K);

// PS: n1 & n2 can't be non-(-1) at the same time

// if node found in any of the sub trees
if((n1 == -1) && (n2 == -1))
return -1;

// node found in right subtree
if((n1 == -1))
// the current node is at distance K
if(n2 == 0)
printf("%d", cur->val);

// return back the distance
return (n2-1);

// node found in left subtree
if((n2 == -1))
// the current node is at distance K
if(n1 == 0)
printf("%d", cur->val);

// return back the distance
return (n1-1);

void print_K_distance_nodes(node * root, node * search, int K)
// The structure of node is:
// struct node{
// int val;
// node * left;
// node * right;
// }

// Print the ancestor at distance K
K_dist_ancestor(root, search, K);

// Print the children at distance K
K_dist_children(search, K);

%d bloggers like this: