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 TechMyWayCategories: 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 TechMyWayCategories: Uncategorized
Tags: 5k views, milestone
To all,
Thanks a lot for your love. My blog has crossed 5000 views. π π
Threading in Python
Posted April 15, 2012 by TechMyWayCategories: Python
Tags: code, python, thread
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:
Note
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
time.sleep(0.2)
while counter < max_count:
print "{}. {}".format(counter, string)
counter += 1
time.sleep(sleeptime)
#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:
pass
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.
Code:
#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="http://docs.python.org/library/thread.html">thread</a> andΒ <a title="Python Docs" href="http://docs.python.org/library/threading.html">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="http://wiki.python.org/moin/Generators">generator</a> and returning a iterator (returning a <a title="Python Docs" href="http://docs.python.org/release/2.5.2/ref/yield.html">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="http://docs.python.org/library/thread.html#thread.exit">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="http://en.wikipedia.org/wiki/Producer-consumer_problem">Consumer-Producer problem</a> which would include the code for using locks.
Code:
#!/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.."
time.sleep(produce_time)
print "Produced {}".format(pr_val)
lock.acquire_lock()
print "P: Lock ACK"
product.append(pr_val)
print "Added product {}".format(pr_val)
lock.release_lock()
print "P: Release ACK"
pr_val += 1
if pr_val > lim:
break
def consumer(lock, consume_time, waiting_time, lim, *args):
con_val = 0
got_product = False
while True:
lock.acquire_lock()
print "C: Lock ACK"
try:
con_val = product.pop()
print "Retrieved value {}".format(con_val)
got_product = True
except IndexError:
print "No produce!"
got_product = False
lock.release_lock()
print "C: Release ACK"
if got_product:
print "Consuming.. {}".format(con_val)
time.sleep(consume_time)
else:
print "Waiting for produce"
time.sleep(waiting_time)
if con_val == lim:
break
if __name__=="__main__":
lock=thread.allocate_lock()
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:
pass
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 : https://github.com/ayushgoel/PythonScripts/tree/master/learning_threading
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 TechMyWayCategories: Internet
Tags: google, link, pidgin, plugin, text replacement, www google com
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 -> http://www.google.com/search?q=
- 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 TechMyWayCategories: C
Tags: binary tree, inorder, successor, traversal
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)
return;
// Recursive call for inorder processing
add_inorder(nd->left);
// 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
else
{
prev = nd;
}
// Recursive call for inorder processing
add_inorder(nd->right);
}
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
add_inorder(root);
// 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 TechMyWayCategories: Uncategorized
Tags: binary tree, C, c sourcecode, interview, nodes, recursively search
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
if(K==0)
{
printf("%d\n", nd->val);
return;
}
// 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);
}
Python script to bring all files from subfolders to main folder
Posted January 3, 2012 by TechMyWayCategories: Python, Windows
Tags: file, module, move, os, python, shutil
A usual plight with me is bringing all photos I transfer from my phone to one folder. My phone transfer creates a subfolder for each date it has a pic for.
This was till I discovered the module shutil. (No, I knew about it for around _4 months, but I was too lazy to actually write the code π )
This code I have written is meant to be cross-platform. In case of any discrepancies, please do tell.
import shutil import os # copy all the files in the subfolders to main folder # The current working directory dest_dir = os.getcwd() # The generator that walks over the folder tree walker = os.walk(dest_dir) # the first walk would be the same main directory # which if processed, is # redundant # and raises shutil.Error # as the file already exists rem_dirs = walker.next()[1] for data in walker: for files in data[2]: try: shutil.move(data[0] + os.sep + files, dest_dir) except shutil.Error: # still to be on the safe side continue # clearing the directories # from whom we have just removed the files for dirs in rem_dirs: shutil.rmtree(dest_dir + os.sep + dirs)
Since the code is all documented, I would skip the explanation here.
Please comment, share or like the post. (Good for my writing spirit π )
N – QUEEN Backtracking problem solved
Posted November 9, 2011 by TechMyWayCategories: C++
Tags: backtracking, C, c++, N queen
This all started when I started doubting my coding and downloaded the code from geeksforgeeks for this N-Queen problem. I told one of my friends that I am gonna read it and understand. Then he told me that the problem is quite easy to code, just see the wiki (actually he and me were interested more in the animation on that page π
Anyhow the wiki pages : Eight Queen , Backtracking were not of much use as they were not giving good pseudo code. But this here, see it and try to think, what all can I need for the N – Queen problem..
Enough of waiting now, here is the C++ code for the problem I wrote.
#include<iostream>
using namespace std;
/** this is the size of chess board */
#define N 8
/** Given a completed board, this prints it to the stdout */
void print_solution(int state[N][N])
{
int i,j;
for(i=0; i<N; ++i)
{
for(j=0; j<N; ++j)
cout<<state[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
/** return true if placing a queen on [row][col] is acceptable
else return false */
bool accept(int state[N][N], int row, int col)
{
int i,j;
/* check the column */
for (i=0; i<N; ++i)
{
if (state[row][i])
return false;
}
/* check the row */
for (i=0; i<N; ++i)
{
if (state[i][col])
return false;
}
/* check the upper left diagnol */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (state[i][j])
return false;
}
/* check the lower left diagnol */
for (i = row, j = col; i < N && j >= 0; ++i, --j)
{
if (state[i][j])
return false;
}
/* check the upper right diagnol */
for (i = row, j = col; i >= 0 && j < N; i--, ++j)
{
if (state[i][j])
return false;
}
/* check the lower right diagnol */
for (i = row, j = col; i < N && j < N; ++i, ++j)
{
if (state[i][j])
return false;
}
/* return true if all tests passed */
return true;
}
void solve_state(int state[N][N], int row)
{
int i;
/* if all queens have been placed at non conflicting positions */
if (row == N)
{
print_solution(state);
return;
}
/* Place queens on all positions in a given row and
check if the state is acceptable
Continue the process till all possibilities found */
for(i=0; i<N; ++i)
{
if(accept(state, row, i))
{
state[row][i] = 1;
solve_state(state, row+1);
}
state[row][i] = 0;
}
}
int main()
{
/* initialise the board */
int state[N][N] = {0};
solve_state (state, 0);
return 0;
}
This code can be easily converted to C, just make amendments to bool values. Rest of the program deals with the board matrix, so C won’t have problems.
Result: Backtracking is pretty easy if you get the idea.