<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Ashish Yadav&#039;s Weblog</title>
	<atom:link href="http://42bits.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://42bits.wordpress.com</link>
	<description>Curious tidbits on code, geekery, tech and life - In that order</description>
	<lastBuildDate>Sun, 18 Dec 2011 11:24:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='42bits.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Ashish Yadav&#039;s Weblog</title>
		<link>http://42bits.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://42bits.wordpress.com/osd.xml" title="Ashish Yadav&#039;s Weblog" />
	<atom:link rel='hub' href='http://42bits.wordpress.com/?pushpress=hub'/>
		<item>
		<title>PDB style function backtrace in python using Inspect module.</title>
		<link>http://42bits.wordpress.com/2011/01/23/pdb-style-function-backtrace-for-python-using-inspect-module/</link>
		<comments>http://42bits.wordpress.com/2011/01/23/pdb-style-function-backtrace-for-python-using-inspect-module/#comments</comments>
		<pubDate>Sun, 23 Jan 2011 08:55:15 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[backtrace]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[frames]]></category>
		<category><![CDATA[gdb]]></category>
		<category><![CDATA[inspect]]></category>
		<category><![CDATA[pdb]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[stack]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=300</guid>
		<description><![CDATA[A while back I had a conversation with a friend of mine, which went something like this(with some paraphrasing). Friend : Hey, is there a way in python to display the function calls which end up calling a certain function, &#8230; <a href="http://42bits.wordpress.com/2011/01/23/pdb-style-function-backtrace-for-python-using-inspect-module/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=300&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A while back I had a conversation with a friend of mine, which went something like this(with some paraphrasing).</p>
<blockquote><p><strong>Friend</strong> : Hey, is there a way in python to display the function calls which end up calling a certain function, kind of like a function call flow but displaying only the ones which call a certain function.<br />
                   <strong>Me</strong>   :   Have you tried a python debugger like PDB? Check out the backtrace command.<br />
                   <strong>Friend</strong> : Oh, I Don&#8217;t have any idea about PDB, and there are only few such functions, I don&#8217;t need any other debugger functionality, Debugger may be bit of a overkill here.<br />
                   <strong>Me</strong>   :    Oh Ok, Let me see what I can do!!.
 </p></blockquote>
<p>I found it to be the perfect excuse to play with <a href="http://docs.python.org/library/inspect.html">Inspect Module</a>, which provides several useful functions to help get information about live objects in a running program.<br />
About 5 minutes later, I had the working code. (Isn&#8217;t python <em>Freakin Awesome</em>!!)<br />
<pre class="brush: python; light: true;">
import inspect
def getBackTrace():
    for idx, frame in enumerate(inspect.stack()[1:-1]):
        print '#%d  %s at %s'%(idx, frame[3], frame[1])
</pre><br />
Suffice it to say, that his problem was solved. Now he can just invoke <em>getBackTrace()</em> to get the list of functions in outer frames from within a function. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>On my way back home that day, I thought that this could be a good utility for someone who <a href="http://www.skorks.com/2010/05/why-i-love-reading-other-peoples-code-and-you-should-too/">loves to read other people code</a>, but considers a full debugging session a overkill to get a better understanding of the unfamiliar code.You can also think of it as a addition to the old school <em>Printf Debugging</em>.FWIW, If it&#8217;s well written code in python, most of the times you will <em> just get </em> what the code is trying to do. Python code is really just executable pseudo-code. </p>
<p>My friend suggested that I should add this code to my collection of <a href="https://gist.github.com/ashish0x90">Gists@github</a>. I asked him if he can think of some other features I should be adding to this code. After some talking, we narrowed down to the following two nice-to-have features.</p>
<ul>
<li>Add some more context, by printing function arguments, source code line number for each of the frames.</li>
<li>The ability to log this information to a external log file, defaulting to the standard outstream.</li>
</ul>
<p>It took me some more time to do the code/testing, but it was worth the effort. Overall what&#8217;s really great about this utility function is that tracing a function call is as easy as putting <i>@getBackTrace()</i> decorator before the function definition and just run the code. The other (<em> rather tedious</em>) way is to start a pdb debugger session, setting the function breakpoint, running the code and then inspecting the stack once breakpoint is reached. So choose the way you like <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . Here is the code. <strong> (Tip: Looks a lot better <a href="https://gist.github.com/790155">@Github</a>)</strong><br />
<pre class="brush: python; highlight: [35,42,61]; wrap-lines: false;">
import sys, inspect
def getBackTrace(printArgs=None , logger=sys.stdout.write):
    '''
    This decorator method can be used to get GDB style backtrace (Stack trace) of 
    currently active stack frames during the execution of a program, 
    optionally printing positional/variable/keyword arguments for the 
    functions in the outer frames.
    It can be used to easily trace the function call flow in a running application, 
    without having to use a external debugger like pdb.
    
    @Input
      printArgs - This is a boolean value which is true/false depending on 
                  whether function arguments need to be displayed.
      logger    - This can be a python logger instance to log information to a log file.
                  By default information is printed on stdout.
    @Output
      Output is similar to GNU Debugger Stack traces, the difference being 
      in the way arguments are displayed.
      More info on GDB backtrace command here - 
      http://inside.mines.edu/fs_home/lwiencke/elab/gdb/gdb_42.html

    Note: AFAIK, Once a function is called with the respective arguments, 
    these arguments become part of locals() function scope in python, and they can be 
    mutated by function code. So, the argument values may be **DIFFERENT**
    than what the function initially may have got and I am only displaying 
    values the variables had at the time stack trace was done.
    
    '''
    log = logger or logger.debug
    log('*'*50 + ' BackTrace START ' + '*'*50+'\n')
    def wrap(f):
        log(&quot;#0   %s at %s\n&quot;%(f.__name__, f.__module__))
        def wrapped_f(*args, **kwargs):
            outerFrames = inspect.stack()[1:-1]
            for frame_idx, frame in enumerate(outerFrames):
                functionName = frame[3]
                moduleName = inspect.getmodulename(frame[1]) or frame[1]
                traceStr = &quot;#%d   %s at %s:%s\n&quot;%(frame_idx+1, functionName, 
                                                  moduleName, frame[2])
                if printArgs:
                    argObj = inspect.getargvalues(frame[0])
                    posArgs = sorted([ [arg, argObj.locals.get(arg)] for \
                                       arg in argObj.args or []])
                    varArgs = sorted(argObj.locals.get(argObj.varargs,{}))
                    keywordArgs = sorted(argObj.locals.get(argObj.keywords,{}).items())

                    prettyArgsString = ', '.join('%s=%s'%(str(item[0]), 
                                                          str(item[1])) for item in posArgs)
                    prettyVarArgsString = ', '.join('%s'%(str(item)) for item in varArgs)
                    prettyKeywordArgsString = ', '.join('%s=%s'%(str(item[0]), 
                                                                 str(item[1])) for item in keywordArgs)

                    traceStr+=&quot;%-10sPositional Arguments : %s\n&quot;%('',prettyArgsString)
                    traceStr+=&quot;%-10s*Variable Aruguments : %s\n&quot;%('',prettyVarArgsString)
                    traceStr+=&quot;%-10s**Keyword Arguments  : %s\n&quot;%('',prettyKeywordArgsString)
                    traceStr+= '\n'
                log(traceStr)
            log('\n')
            log('*'*50 + ' BackTrace END ' + '*'*50+'\n\n')
            f(*args, **kwargs) #Call the function
        return wrapped_f
    return wrap



#################################
## Example Usage
## Output
&quot;&quot;&quot;
#0   func3 at __main__
#1   func2 at getBackTrace:67
          Positional Arguments : i=10000
          *Variable Aruguments : 1230, 12345
          **Keyword Arguments  : oi=20

#2   func1 at getBackTrace:64
          Positional Arguments : i=100
          *Variable Aruguments : 
          **Keyword Arguments  : 


&quot;&quot;&quot;
def func1(i):
    func2(i**2, 1230, 12345, oi=20)

def func2(i, *args, **kwargs):
    func3(i**2)

#@getBackTrace()
@getBackTrace(printArgs=True)
def func3(i, **kwargs):
    pass

if __name__ == '__main__':
    func1(100)
</pre><br />
If you are thinking of some other Nice-to-have features, The code is just <a href="http://help.github.com/forking/">one Fork away</a>, or give me a shoutout in the comments below.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/300/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=300&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2011/01/23/pdb-style-function-backtrace-for-python-using-inspect-module/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>notify.sh: Get notified when shell scripts go wrong.</title>
		<link>http://42bits.wordpress.com/2010/12/05/notify-sh/</link>
		<comments>http://42bits.wordpress.com/2010/12/05/notify-sh/#comments</comments>
		<pubDate>Sun, 05 Dec 2010 09:51:26 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[error handling]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[named pipe]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[shell script]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=219</guid>
		<description><![CDATA[TLDR: Project Summary: Can be used to automatically suspend execution of a shell script if runtime error occurs, followed by notifying the user who started the script. The suspended script can be easily resumed later by the user. This is &#8230; <a href="http://42bits.wordpress.com/2010/12/05/notify-sh/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=219&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>TLDR:</p>
<blockquote><p><strong>Project Summary</strong>: Can be used to automatically suspend execution of a shell script if runtime error occurs, followed by notifying the user who started the script. The suspended script can be easily resumed later by the user. This is particularly helpful in a scenario where you are running a script which does lot of work and you don&#8217;t want to do the cleanup and start the script again in case a runtime error occurs. In such cases script suspend/resume functionality can save you a lot of time.<br />
                   <strong>Project Page</strong>: <a href="https://github.com/ashish0x90/notify.sh">Notify.sh</a>
</p></blockquote>
<p>I got the idea for this project a few weeks back, while running a large-scale DB migration on production servers at my day job, on how to handle the process errors better. Though I had tested migration process multiple times on all the possible things that could wrong, I couldn&#8217;t just ignore Mr. Murphy completely.</p>
<p>I also had few other rather obvious things to take care of like, website downtime required if any must be least possible, and I also was given relatively short time for process to be completed. This means if a problem occurs after the process has started I probably won&#8217;t be able to <strong>re-run the process from scratch</strong>, and would have to wait for next time window to schedule the migration process.</p>
<p><strong>But there was a catch, if I could just suspend the process if/when the error occurs, then I could see what caused the error and <em>I can just resume the process , instead of having to restart the process from scratch.</em>.</strong><br />
The task consisted mostly of &#8211; <strong>executing SQL and shell scripts in a Linux environment.</strong></p>
<p>The main script(run.sh) had the following format -</p>
<blockquote><p>&lt;pre-processing/ script init routines&gt;<br />
&lt;sql_statement_1&gt;<br />
&lt;sql_statement_2&gt;<br />
&lt;sql_statement_3&gt;<br />
&#8230;..<br />
&lt;post-processing/ process validation routines&gt;</p></blockquote>
<p>The process was originally designed, in a way that process(or a single step) failure wouldn&#8217;t cause any unintended side effects, similar to the <em><a href="http://en.wikipedia.org/wiki/Atomicity_(database_systems)">ALL or NONE</a></em> transactional philosophy of databases. So I only was optimizing on the not-having-to-restart the process part if some error occurs.</p>
<p>I thought of adding a check step after every SQL statements, which would check what happened to last executed statement and will suspend the shell script if previous step had an error. My script format after this change will be -</p>
<blockquote><p>&lt;pre-processing/ script init routines&gt;<br />
&lt;sql_statement_1&gt;<br />
<strong>Check state of sql_statement_1</strong><br />
&lt;sql_statement_2&gt;<br />
<strong>Check state of sql_statement_2</strong><br />
&lt;sql_statement_3&gt;<br />
<strong>Check state of sql_statement_3</strong><br />
&#8230;..<br />
&lt;post-processing/ process validation routines&gt;</p></blockquote>
<p>After deciding on to the what part, I had the problem of how and for following questions.</p>
<ol>
<li>How to check status of the last executed step in a shell script?</li>
<li>How a running shell script could  suspend itself?</li>
<li>How to notify user of the error situation, also providing the necessary information?</li>
<li>How the suspended process can be resumed later by the user?</li>
</ol>
<p>My solutions were as follows:</p>
<ol> <strong>&nbsp;</p>
<li>How to check status of the last executed step in a shell script?</li>
<p></strong><strong> </strong><strong> </strong><strong> </strong><strong> </strong></p>
<blockquote><p>Two words &#8211; <a href="http://en.wikipedia.org/wiki/Exit_status">&#8220;Exit Status&#8221;</a>. And the fact that exit status of the last executed command in Linux is stored in the bash variable &#8211; <strong>$?</strong></p></blockquote>
<li><strong>How a running shell script can be able to suspend itself?</strong></li>
<blockquote><p>This was an interesting question, and the answer surprised me,  <a href="http://www.linuxjournal.com/article/2156">Named Pipes</a>. I read about it long time back and found it interesting back then, but wasn&#8217;t able to find any use-case for it until todal. The basic idea is that<br />
the process about to get blocked will create a named pipe with a unique name(*Process ID) and will be at the receiving end of the pipe. This will suspend (*Cough* I/O block) the process until it gets the confirmation message (through the named pipe) to resume from the user.</p>
<p>This entire process looks something like this:</p>
<p><a href="http://42bits.files.wordpress.com/2010/12/process_commnuncation.png"><img class="alignnone size-full wp-image-234" title="Notify.sh - Process Commnuncation " src="http://42bits.files.wordpress.com/2010/12/process_commnuncation.png?w=640" alt="Process Commnuncation "   /></a></p></blockquote>
<p><strong> </strong></p>
<li><strong>How to notify user about the error situation, providing the necessary information?</strong></li>
<p><strong> </strong><strong> </strong></p>
<blockquote><p>Sending an e-mail to the user with process information and instructions to resume the process would do just fine. Another BIG plus is, you need not monitor script status continuously for any errors and will automatically get a notification e-mail when/if an error occurs.</p></blockquote>
<p><strong> </strong></p>
<li><strong>How to resume the suspended process later?</strong></li>
<p><strong> </strong><strong> </strong></p>
<blockquote><p>User just has to send the string &#8220;RESUME&#8221; though the named-pipe to the blocked process, which will then break out of the I/O block and continue with the next step. He will also get the instructions on how to do this as a part of notification e-mail sent.</p></blockquote>
</ol>
<p>By the combined awesomeness of python+Linux, It took me one evening to code this entire project. I decided to release the code into open-source later, and was given the permission to do so, thanks, <a href="http://www.serendio.com">Serendio</a>. :)<br />
The project can be accessed <a href="https://github.com/ashish0x90/notify.sh">here</a>. So enjoy the code and if you can think of ways to make code better/ or more features. notify.sh is just one <a href="http://help.github.com/forking/">fork</a> away.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/219/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/219/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/219/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=219&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/12/05/notify-sh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>

		<media:content url="http://42bits.files.wordpress.com/2010/12/process_commnuncation.png" medium="image">
			<media:title type="html">Notify.sh - Process Commnuncation </media:title>
		</media:content>
	</item>
		<item>
		<title>Python Global Interpreter Lock (GIL) explained &#8211; Pycon Tech Talk</title>
		<link>http://42bits.wordpress.com/2010/10/24/python-global-interpreter-lock-gil-explained-pycon-tech-talk/</link>
		<comments>http://42bits.wordpress.com/2010/10/24/python-global-interpreter-lock-gil-explained-pycon-tech-talk/#comments</comments>
		<pubDate>Sat, 23 Oct 2010 19:55:44 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Tech talks]]></category>
		<category><![CDATA[Video]]></category>
		<category><![CDATA[GIL]]></category>
		<category><![CDATA[global interpreter lock]]></category>
		<category><![CDATA[interpreter]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[Pycon]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tech talk]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=200</guid>
		<description><![CDATA[Today I saw a amazing tech talk on the much debated topic of python Global Interpreter Lock a.k.a GIL. Python&#8217;s Global Interpreter Lock or GIL is probably one of the least properly understood parts of python, but is extremely important &#8230; <a href="http://42bits.wordpress.com/2010/10/24/python-global-interpreter-lock-gil-explained-pycon-tech-talk/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=200&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today I saw a amazing tech talk on the much debated topic of python Global Interpreter Lock a.k.a GIL. Python&#8217;s <strong>Global Interpreter Lock or GIL</strong> is probably one of the least properly understood parts of python, but is extremely important to know of if you are dealing with any form of multi-threaded python code.<br />
The talk debunks several GIL myths, explains GIL/Interpreter internals and introductory talk about the better GIL implementation coming up in version 3.2 of python. Apart from the highly informative talk I  liked speaker&#8217;s way of approaching the rather subtle topic in a manner that even novice programmers could relate to, showing interpreter internal code as required, demos showing GIL influencing overall program performance in cases when multi-core systems, running multiple threads etc are involved, and last but not the least the occasional geek humor.</p>
<p><strong>Few takeaways from the Talk:</strong></p>
<ol>
<li>Python threads are <strong>native threads</strong> (POSIX threads on Unix)  and not <a href="http://en.wikipedia.org/wiki/Green_threads">Green threads</a>.</li>
<li>There can only be <strong>one thread running</strong> at any given time in a python process regardless of whether you are using multiple threads, due to the way GIL works, independent of the OS multi-threading support. In other words only one thread can have mutual exclusive access to GIL at any given time.</li>
<li>Splitting a process into multiple threads <strong>won&#8217;t speed up the execution</strong>, On the contrary it might degrade overall performance as now these threads will compete for GIL access.</li>
<li>If you are running multiple threads on a <em>multi-core</em> system, performance might be even worse than compared to single core machine, as OS now supports running multiple thread simultaneously, but GIL will still execute only one thread. So OS will try resuming suspended  threads which will then try to get hold of the GIL, which will fail because some other thread is already using GIL. In other words there will be lot of False alarms, which will cause <a href="http://en.wikipedia.org/wiki/Thrashing_(computer_science)">thrashing</a> leading to overall degraded performance.</li>
</ol>
<p>While you should not worry about your multi-threaded code having performance issues because of the GIL, more often than not it&#8217;s because of badly written code. However as a general rule of thumb if you don&#8217;t need  to synchronize threads/shared resources access but are only concerned about reducing process execution time, you are probably better off <strong>using multiple processes instead of multiple threads</strong>. See <a href="http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers">Multiprocessing</a> for further information on how multiprocessing can replace multi-threading for this case.</p>
<script type="text/javascript" src="http://blip.tv/syndication/write_player?skin=js&posts_id=3273690&cross_post_destination=-1&view=full_js"></script>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/200/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/200/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/200/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=200&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/10/24/python-global-interpreter-lock-gil-explained-pycon-tech-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>Workaround for google app engine&#8217;s &#8211; File not accessible error using virtualenv</title>
		<link>http://42bits.wordpress.com/2010/10/13/workaround-for-google-app-engines-file-not-accessible-error-using-virtualenv/</link>
		<comments>http://42bits.wordpress.com/2010/10/13/workaround-for-google-app-engines-file-not-accessible-error-using-virtualenv/#comments</comments>
		<pubDate>Tue, 12 Oct 2010 21:19:47 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[troubleshooting]]></category>
		<category><![CDATA[app engine]]></category>
		<category><![CDATA[google app engine]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[virtualenv]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=168</guid>
		<description><![CDATA[Google App Engine comes really handy for devs who want to host their application idea/hack on google&#8217;s infrastructure without having to spend any $$ for it (and the resource limits are pretty descent for free account). No wonder it is &#8230; <a href="http://42bits.wordpress.com/2010/10/13/workaround-for-google-app-engines-file-not-accessible-error-using-virtualenv/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=168&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/appengine/">Google App Engine</a> comes really handy for devs who want to host their application idea/hack on google&#8217;s infrastructure without having to spend any $$ for it (and the resource limits are pretty descent for free account). No wonder it is a really useful tool that every developer/hacker should know of.</p>
<p>Few days earlier while trying to implement some pet project idea of mine at google app engine, I got a strange long exception(probably sandbox violation error) when I tried to access the running app engine application in my browser.</p>
<p>Here is the truncated traceback message <strong>(App engine internal function calls removed)</strong></p>
<p><code>WARNING  2010-09-28 19:13:59,854 py_zipimport.py:103] Can't open zipfile /usr/local/lib/python2.6/dist-packages/pyExcelerator-0.6.0a-py2.6.egg: IOError: [Errno 13] file not accessible: '/usr/local/lib/python2.6/dist-packages/pyExcelerator-0.6.0a-py2.6.egg'</code></p>
<p><code> </code></p>
<p><code>........</code></p>
<p><code> </code></p>
<p><code>File "/home/ashish/Desktop/google_appengine/google/appengine/tools/dev_appserver.py", line 2188, in ExecuteOrImportScript<br />
exec module_code in script_module.__dict__<br />
File "/home/ashish/Desktop/google_appengine/shuffler/shuffle.py", line 17, in<br />
import cgi</code></p>
<p><code>.......</p>
<p></code></p>
<p>&nbsp;</p>
<p><code>File "/home/ashish/Desktop/google_appengine/google/appengine/tools/dev_appserver.py", line 1186, in __init__<br />
raise IOError(errno.EACCES, 'file not accessible', filename)<br />
IOError: [Errno 13] file not accessible: '/usr/local/lib/python2.6/dist-packages/cgi.unescape-0.0.2-py2.6.egg'<br />
INFO     2010-09-28 19:13:59,865 dev_appserver.py:3246] "GET / HTTP/1.1" 500 -<br />
</code></p>
<p>I had no idea why I got this error as  <strong>cgi</strong> module was available and even <strong>import cgi</strong> worked on python interpreter prompt. It looked like some kind of sandbox error as I knew google app engine runs application in a security sandbox. Googling for the error didn&#8217;t do much help. Maybe I screwed up directory permissions on my *nix system, or maybe the external python libraries present on my system are giving app engine a hard time.</p>
<p>I remembered from some time ago while working on <a href="http://pylonshq.com/">Pylons</a>, which is another nice pluggable python based web framework, that it recommended installing <strong>virtualenv</strong> as a part of pylons installation step.</p>
<p><a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> is a tool to create isolated Python environments. It comes quite handy when one want to install a python library/framework, while avoiding any <em>side-effects</em> to the existing python installation.</p>
<p><em>As a formal disclaimer, While this process should do no harm, still proceed with caution. Also Note that this has been ONLY tested with python version 2.6 on Ubuntu 10.04 OS.</em></p>
<blockquote><p>sudo easy_install virtualenv==1.4.9 (Or if you prefer apt-get install or pip)</p></blockquote>
<p>Assuming that :<br />
1) You have <strong>python version 2.6</strong> installed.<br />
2) You want to install this separate python installation on <strong>~/GAE_PYTHON</strong> directory.</p>
<blockquote><p>Create the new python environment by running<br />
virtualenv -v -p python2.6 &#8211;no-site-packages ~/GAE_PYTHON_ENV
</p></blockquote>
<p>Assuming that last step completed successfully.</p>
<blockquote><p>
Now run this command to switch to the new created python environment -<br />
source ~/GAE_PYTHON_ENV/bin/activate
</p></blockquote>
<p>You should now see your shell prompt prefixed by <strong>(GAE_PYTHON_ENV)</strong> (Note: I Use bash shell)</p>
<p>If the process so far completed without any errors, try running any of the  demo application that comes with Google APP engine (While remaining in the same environment ) to quickly check if the new setup works. I tried guestbook demo application that ships with app engine&#8217;s setup and was able to use it without any difficulties.</p>
<p>Note that now this setup doesn&#8217;t have access to python libraries that you may have installed on your base python setup, so you may need to install required libraries for this setup separately. You should be able to install any library in the usual way using easy_install or pip while working from within the new environment.</p>
<p>While this will probably work for the system I have described above, if you happen to have a different system setup, try looking for specific installation instructions on how to set up virtualenv on your system.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/168/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/168/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/168/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=168&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/10/13/workaround-for-google-app-engines-file-not-accessible-error-using-virtualenv/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>Find Kth minimum element in a unsorted array</title>
		<link>http://42bits.wordpress.com/2010/04/17/find-kth-minimum-in-a-unsorted-array/</link>
		<comments>http://42bits.wordpress.com/2010/04/17/find-kth-minimum-in-a-unsorted-array/#comments</comments>
		<pubDate>Sat, 17 Apr 2010 17:39:18 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Algorithm]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[interview]]></category>
		<category><![CDATA[kth]]></category>
		<category><![CDATA[minimum]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[quicksort]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=144</guid>
		<description><![CDATA[Some days ago while interviewing a candidate, I asked the candidate a very easy by the book interview question. Design an efficient algorithm to find the 2nd smallest integer in a unsorted integer array of length N, which should run &#8230; <a href="http://42bits.wordpress.com/2010/04/17/find-kth-minimum-in-a-unsorted-array/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=144&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Some days ago while <a href="http://www.serendio.com/contactus.html">interviewing</a> a candidate, I asked the candidate a very easy by the book interview question.</p>
<blockquote><p>Design an efficient algorithm to find the 2nd smallest integer in a unsorted integer array of length N, which should run in constant space.</p></blockquote>
<p>This question is quite easy to solve, and google search returns <a href="http://www.google.co.in/search?hl=en&amp;q=find+2nd+maximum+element&amp;spell=1">tons of results</a> for the question.<br />
In brief one way in which the above problem can be solved is, to store both the smallest element and the 2nd smallest element while traversing the array.This approach will require array to be traversed <span style="text-decoration:underline;">only once </span>.</p>
<p>After the interview was finished I thought of the generalized variant of the above problem, which is  -</p>
<blockquote><p>
Design an efficient algorithm to find the Kth smallest integer in a unsorted integer array of length N which should run in constant space.
</p></blockquote>
<p>As one can see using the same approach we used for k=2, while will be a valid approach(Space complexity &#8211; O(k)), It will not be efficient for cases in which K ~ N/2 (Think!!!)</p>
<p>I thought whether using a appropriate data structure  might work here &#8211; </p>
<blockquote><p>Heap : O(nlg(n)), Building the Heap for n elements will take O( nlg(n) ) time.<br />
Binary search tree: Building the tree will take O(n lg(n)) time.</p></blockquote>
<p>So, as you can see I could as well sort the array in O(n lg(n) ) time and return the element at Kth index.<br />
Lets see if can do better.</p>
<p><strong>Hint:</strong><em> We can make use of partition step of QuickSort, to find the kth minimum element.<br />
Think about it, or read further for the details/implementation code.</em></p>
<p><strong>Step1: Partition the Array.</strong><br />
So if you can remember partitioning step in quicksort algorithm (if not, read below for a quick overview)</p>
<blockquote><p>From the input array select a random element, and call it the  pivot element.<br />
Partition the array in such a way that<br />
All the array elements which are <span style="text-decoration:underline;">less than or equal to pivot are on left side of the pivot.</span><br />
All the array elements which are <span style="text-decoration:underline;">more than pivot are on right side of the pivot.</span></p></blockquote>
<p>And Now the meat of the algorithm:</p>
<blockquote><p>lets say that pivot_idx is the final position of the pivot after partitioning.<br />
That means that all elements values less than pivot are placed before it<br />
<strong>Which means that pivot is Kth smallest element for the array for k = pivot_idx.</strong></p></blockquote>
<p><strong>Step 2: Repeat Step 1 based on some conditions(Divide array into smaller sub-array)</strong><br />
It comprises of 3 simple steps.</p>
<blockquote><p>If k = pivot_idx .return pivot value as the answer.<br />
if k &lt; pivot_idx. the answer lies in left partition and so partition existing left partition.<br />
if k &gt; pivot_idx. the answer lies in right partition and so partition existing right partition.</p></blockquote>
<p><strong>Algorithm complexity analysis</strong><br />
Though this approach have a worst case complexity as Quick Sort, because it reuses its partition (Divide) step.<br />
On the positive side, it also gives good average case time complexity, similar to quicksort.<br />
I can also replace existing naïve partitioning algorithm with a more efficient version, which most of the times can result in partition divide by half.<br />
In that case, the number of comparisons I have to do will be:<br />
<strong>n + n /2 + n/4 + n/8 &#8230; (A geometric progression with ratio 0.5) = 2n .</strong><br />
So the algorithm is not so bad after all <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>And as always, Algorithm&#8217;s implementation in python (<a href="http://gist.github.com/370410">Download Code</a>)</p>
<pre><span style="color:#800000;">#!/usr/bin/env python</span>
<span style="color:#804000;">from</span> random <span style="color:#804000;">import</span> randrange

<span style="color:#804000;">def</span> <span style="color:#000080;">findKMin</span>(arr,k,start=0,end=<span style="color:#804000;">None</span>):
    '''
<span style="color:#006000;">    Find kth minimum element in a array (in-place randomized algorithm, similar to quicksort)</span>
<span style="color:#006000;">    assumption: Input will only contain unique elements</span>'''
    <span style="color:#804000;">if</span> k &gt; len(arr):
        <span style="color:#804000;">raise</span> Exception("<span style="color:#006000;">k should be less than length of the input array</span>")
    <span style="color:#804000;">if</span> <span style="color:#804000;">not</span> end: end = len(arr) -1 <span style="color:#800000;">#Get last index value</span>
    pivot_ridx = randrange(start,end)     <span style="color:#800000;">#Get a random array element as pivot value</span>
    pivot = arr[pivot_ridx]
    pivot_idx = partition(arr,start,end,pivot_ridx) <span style="color:#800000;">#partition to partition array around the pivot value in place</span>
    <span style="color:#804000;">if</span> pivot_idx+1 == k:
        <span style="color:#804000;">return</span> pivot <span style="color:#800000;">#Well, there is your answer</span>
    <span style="color:#804000;">elif</span> pivot_idx+1 &gt; k:
        <span style="color:#804000;">return</span> findKMin(arr,k,start,pivot_idx) <span style="color:#800000;">#lies somewhere in the first partition</span>
    <span style="color:#804000;">else</span>:
        <span style="color:#804000;">return</span> findKMin(arr,k,pivot_idx,end) <span style="color:#800000;">#lies somewhere in the second Partiton</span>

<span style="color:#804000;">def</span> <span style="color:#000080;">partition</span>(arr,start,end,pivot_idx):
    '''
<span style="color:#006000;">    Partitions array in-place around the given pivot value</span>
<span style="color:#006000;">    </span>'''
    pivot = arr[pivot_idx]
    arr[end],arr[pivot_idx] = arr[pivot_idx],arr[end]
    inc_idx = start
    <span style="color:#804000;">for</span> i <span style="color:#804000;">in</span> xrange(start,end):
        <span style="color:#804000;">if</span> arr[i] &lt;= pivot:
            arr[inc_idx],arr[i] = arr[i],arr[inc_idx]
            inc_idx+=1
    arr[end],arr[inc_idx] = arr[inc_idx],arr[end]
    <span style="color:#804000;">return</span> inc_idx

<span style="color:#804000;">if</span> __name__ == '<span style="color:#006000;">__main__</span>':
    <span style="color:#804000;">from</span> random <span style="color:#804000;">import</span> shuffle
    test_input = range(100000)
    shuffle(test_input)
    <span style="color:#804000;">assert</span> findKMin(test_input,50000) == 49999</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=144&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/04/17/find-kth-minimum-in-a-unsorted-array/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>Generating all possible permutations of a sequence.</title>
		<link>http://42bits.wordpress.com/2010/04/12/generating_all_possible_permutations_of_a_sequence/</link>
		<comments>http://42bits.wordpress.com/2010/04/12/generating_all_possible_permutations_of_a_sequence/#comments</comments>
		<pubDate>Sun, 11 Apr 2010 19:39:48 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Algorihtms]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[donald knuth]]></category>
		<category><![CDATA[effecient]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[knuth]]></category>
		<category><![CDATA[permutation]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=122</guid>
		<description><![CDATA[P.S. &#8211; This Post is intended for people who want to know a simple,efficient approach to generate all possible permutations for a sequence.For real world software I would recommend using standard library functions. All of us at some moment while &#8230; <a href="http://42bits.wordpress.com/2010/04/12/generating_all_possible_permutations_of_a_sequence/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=122&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><em> P.S. &#8211; This Post is intended for people who want to know a simple,efficient approach to generate all possible permutations for a sequence.For real world software I would recommend using standard library functions.</em></p>
<p>All of us at some moment while coding have faced the problem on how to generate all possible permutations of a sequence.<br />
In this case algorithm&#8217;s efficiency becomes <span style="text-decoration:underline;">highly important</span>. Use a recursive solution and for even moderately sized sequence, running time (and memory) goes though the roof.<br />
Recently I came across <a href="http://en.wikipedia.org/wiki/Donald_Knuth">Donald knuth&#8217;s</a> elegant linear time non-recursive <a href="http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations">approach</a>. I wanted to see algorithm in action, so I implemented it and thought it would be nice to write a blog post about it.</p>
<p>So Without further ado, I have given below a simple explanation of algorithm working, and code implementation in both java,python.</p>
<p>Algorithm Summary<br />
The idea is to generate permutations of the sequence so given, in <span style="text-decoration:underline;">lexicographical increasing order. </span></p>
<p>for ex. for an array [1,2,4,3]<br />
Resulting Permutations would be [1,2,3,4], [1,2,4,3] &#8230;. [4,3,2,1]<br />
One approach on how to generate this ordered permutation can be read from its  <a href="http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations">wikipedia entry</a>.</p>
<p>Python implementation (<a href="http://gist.github.com/363062">Download code</a>):</p>
<pre><a name="1"></a>
<a name="2"></a> <span style="color:#804000;">def</span> <span style="color:#000080;">getNextPermute</span>(arr):
<a name="3"></a>     """
<a name="4"></a> <span style="color:#006000;">    Implementation of http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations</span>
<a name="5"></a> <span style="color:#006000;">    Algorithm to effeciently generate permutations of a sequence</span>
<a name="6"></a> <span style="color:#006000;">    returns a generator type object, which for each call return next possible permutation</span>
<a name="7"></a> <span style="color:#006000;">    until all possiblities are exhausted</span>
<a name="8"></a> <span style="color:#006000;">    </span>"""
<a name="9"></a>     arr.sort()
<a name="10"></a>     <span style="color:#804000;">yield</span> arr[:]
<a name="11"></a>     <span style="color:#804000;">while</span> True:
<a name="12"></a>         <span style="color:#804000;">for</span> j <span style="color:#804000;">in</span> xrange(len(arr)-2,-1,-1): <span style="color:#800000;">#find larget a[j]</span>
<a name="13"></a>             <span style="color:#804000;">if</span> arr[j+1] &gt; arr[j]:
<a name="14"></a>                 <span style="color:#804000;">break</span>
<a name="15"></a>         <span style="color:#804000;">else</span>:
<a name="16"></a>             <span style="color:#804000;">return</span>
<a name="17"></a>
<a name="18"></a>         <span style="color:#804000;">for</span> l <span style="color:#804000;">in</span> xrange(len(arr)-1,j,-1): <span style="color:#800000;">#find larget a[j]</span>
<a name="19"></a>             <span style="color:#804000;">if</span> arr[l] &gt; arr[j]:
<a name="20"></a>                 <span style="color:#804000;">break</span>
<a name="21"></a>
<a name="22"></a>         arr[j],arr[l] = arr[l],arr[j] <span style="color:#800000;">#swap a[j],a[l]</span>
<a name="23"></a>         arr[j+1:] = arr[j+1:][::-1] <span style="color:#800000;">#reverse array present after the index (j+1)th</span>
<a name="24"></a>         <span style="color:#804000;">yield</span> arr[:]
<a name="25"></a>
<a name="26"></a> <span style="color:#804000;">if</span> __name__=="<span style="color:#006000;">__main__</span>":
<a name="27"></a>     <span style="color:#804000;">assert</span> len(list(getNextPermute([5,1,2,3,4]))) == 120
<a name="28"></a>     <span style="color:#804000;">for</span> each <span style="color:#804000;">in</span> getNextPermute(["<span style="color:#006000;">a</span>","<span style="color:#006000;">b</span>","<span style="color:#006000;">c</span>"]):
<a name="29"></a>         <span style="color:#804000;">print</span> '<span style="color:#006000;">,</span>'.join(each)
<a name="30"></a>
<a name="31"></a></pre>
<p>Java Implementation (<a href="http://gist.github.com/363062">Download Code</a>):</p>
<div align="left" class="java">
<table border="0" cellpadding="3" cellspacing="0" bgcolor="#ffffff">
<tr>
  <!-- start source code --></p>
<td nowrap="nowrap" valign="top" align="left">
    <code><br />
<font color="#7f0055"><b>import&nbsp;</b></font><font color="#000000">java.util.*;</font><br />
<font color="#ffffff"></font><br />
<font color="#7f0055"><b>public&nbsp;class&nbsp;</b></font><font color="#000000">Permute&lt;E&gt;</font><br />
<font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#3f5fbf">/**</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">*&nbsp;&nbsp;&nbsp;&nbsp;Implementation&nbsp;of&nbsp;http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">Algorithm&nbsp;to&nbsp;effeciently&nbsp;generate&nbsp;permutations&nbsp;of&nbsp;a&nbsp;sequence&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">until&nbsp;all&nbsp;possiblities&nbsp;are&nbsp;exhausted&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">*/</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;</b></font><font color="#7f0055"><b>int</b></font><font color="#000000">[]&nbsp;</font><font color="#000000">arrIdxs;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>private&nbsp;</b></font><font color="#000000">ArrayList&lt;E&gt;&nbsp;arr;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">ArrayList&lt;E&gt;&nbsp;get_next</font><font color="#000000">()</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">ArrayList&lt;E&gt;&nbsp;ret&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">ArrayList&lt;E&gt;</font><font color="#000000">()</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for&nbsp;</b></font><font color="#000000">(</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">idx&nbsp;=&nbsp;</font><font color="#990000">0&nbsp;</font><font color="#000000">;&nbsp;idx&nbsp;&lt;&nbsp;arrIdxs.length;idx++</font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">ret.add</font><font color="#000000">(</font><font color="#000000">idx,arr.get</font><font color="#000000">(</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">idx</font><font color="#000000">]))</font><font color="#000000">;&nbsp;</font><font color="#3f7f5f">//Permute&nbsp;integer&nbsp;based&nbsp;array&nbsp;indexes,&nbsp;which&nbsp;can&nbsp;be&nbsp;used&nbsp;to&nbsp;get&nbsp;permuted&nbsp;array&nbsp;in&nbsp;return</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;</b></font><font color="#000000">ret;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#000000">Permute</font><font color="#000000">(</font><font color="#000000">ArrayList&lt;E&gt;&nbsp;arr</font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>this</b></font><font color="#000000">.arr&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">ArrayList&lt;E&gt;</font><font color="#000000">()</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for&nbsp;</b></font><font color="#000000">(</font><font color="#000000">E&nbsp;each:arr</font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>this</b></font><font color="#000000">.arr.add</font><font color="#000000">(</font><font color="#000000">each</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">arrIdxs&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#7f0055"><b>int</b></font><font color="#000000">[</font><font color="#000000">arr.size</font><font color="#000000">()]</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for</b></font><font color="#000000">(</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">i&nbsp;=&nbsp;</font><font color="#990000">0&nbsp;</font><font color="#000000">;&nbsp;i&nbsp;&lt;&nbsp;arr.size</font><font color="#000000">()</font><font color="#000000">;i++</font><font color="#000000">)&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f7f5f">//Set&nbsp;indexes&nbsp;lexicographically&nbsp;minimal&nbsp;value;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>this</b></font><font color="#000000">.arrIdxs</font><font color="#000000">[</font><font color="#000000">i</font><font color="#000000">]</font><font color="#000000">=&nbsp;i;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#ffffff"></font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;</b></font><font color="#7f0055"><b>boolean&nbsp;</b></font><font color="#000000">next_permutation</font><font color="#000000">()</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">i,j,l;</font><br />
<font color="#ffffff"></font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for</b></font><font color="#000000">(</font><font color="#000000">j&nbsp;=arr.size</font><font color="#000000">()&nbsp;</font><font color="#000000">-</font><font color="#990000">2&nbsp;</font><font color="#000000">;j&nbsp;&gt;=</font><font color="#990000">0&nbsp;&nbsp;</font><font color="#000000">;&nbsp;j--</font><font color="#000000">)&nbsp;</font><font color="#3f7f5f">//get&nbsp;maximum&nbsp;index&nbsp;j&nbsp;for&nbsp;which&nbsp;arr[j+1]&nbsp;&gt;&nbsp;arr[j]</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>if&nbsp;</b></font><font color="#000000">(</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">j+</font><font color="#990000">1</font><font color="#000000">]&nbsp;</font><font color="#000000">&gt;&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">j</font><font color="#000000">])</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>break</b></font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>if&nbsp;</b></font><font color="#000000">(</font><font color="#000000">j&nbsp;==&nbsp;-</font><font color="#990000">1</font><font color="#000000">)&nbsp;</font><font color="#3f7f5f">//has&nbsp;reached&nbsp;it's&nbsp;lexicographic&nbsp;maximum&nbsp;value,&nbsp;No&nbsp;more&nbsp;permutations&nbsp;left&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;false</b></font><font color="#000000">;</font><br />
<font color="#ffffff"></font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for</b></font><font color="#000000">(</font><font color="#000000">l&nbsp;=&nbsp;arr.size</font><font color="#000000">()</font><font color="#000000">-</font><font color="#990000">1</font><font color="#000000">;l&nbsp;&gt;&nbsp;j&nbsp;;&nbsp;l--</font><font color="#000000">)&nbsp;</font><font color="#3f7f5f">//get&nbsp;maximum&nbsp;index&nbsp;l&nbsp;for&nbsp;which&nbsp;arr[l]&nbsp;&gt;&nbsp;arr[j]</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>if&nbsp;</b></font><font color="#000000">(</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">l</font><font color="#000000">]&nbsp;</font><font color="#000000">&gt;&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">j</font><font color="#000000">])</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>break</b></font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>int&nbsp;</b></font><font color="#000000">swap&nbsp;=&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">j</font><font color="#000000">]</font><font color="#000000">;&nbsp;</font><font color="#3f7f5f">//Swap&nbsp;arr[i],arr[j]&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">j</font><font color="#000000">]&nbsp;</font><font color="#000000">=&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">l</font><font color="#000000">]</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">l</font><font color="#000000">]&nbsp;</font><font color="#000000">=&nbsp;swap;</font><br />
<font color="#ffffff"></font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>for&nbsp;</b></font><font color="#000000">(</font><font color="#000000">i&nbsp;=&nbsp;j+</font><font color="#990000">1</font><font color="#000000">;i&nbsp;&lt;&nbsp;arrIdxs.length;i++</font><font color="#000000">)&nbsp;</font><font color="#3f7f5f">//reverse&nbsp;array&nbsp;present&nbsp;after&nbsp;index&nbsp;:&nbsp;j+1&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>if&nbsp;</b></font><font color="#000000">(</font><font color="#000000">i&nbsp;&gt;&nbsp;arrIdxs.length&nbsp;-&nbsp;i&nbsp;+&nbsp;j&nbsp;</font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>break</b></font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">swap&nbsp;=&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">i</font><font color="#000000">]</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">i</font><font color="#000000">]&nbsp;</font><font color="#000000">=&nbsp;arrIdxs</font><font color="#000000">[</font><font color="#000000">arrIdxs.length&nbsp;-&nbsp;i&nbsp;+&nbsp;j</font><font color="#000000">]</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">arrIdxs</font><font color="#000000">[</font><font color="#000000">arrIdxs.length&nbsp;-&nbsp;i&nbsp;+&nbsp;j</font><font color="#000000">]&nbsp;</font><font color="#000000">=&nbsp;swap;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#ffffff"></font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>return&nbsp;true</b></font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}&nbsp;&nbsp;&nbsp;&nbsp;</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#7f0055"><b>public&nbsp;static&nbsp;</b></font><font color="#7f0055"><b>void&nbsp;</b></font><font color="#000000">main</font><font color="#000000">(</font><font color="#000000">String</font><font color="#000000">[]&nbsp;</font><font color="#000000">args</font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">/**</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">*&nbsp;Test&nbsp;Run</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#3f5fbf">*/</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">ArrayList&lt;String&gt;&nbsp;test_arr&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">ArrayList&lt;String&gt;</font><font color="#000000">()</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">test_arr.add</font><font color="#000000">(</font><font color="#2a00ff">&#034;ab&#034;</font><font color="#000000">)</font><font color="#000000">;test_arr.add</font><font color="#000000">(</font><font color="#2a00ff">&#034;b&#034;</font><font color="#000000">)</font><font color="#000000">;test_arr.add</font><font color="#000000">(</font><font color="#2a00ff">&#034;c&#034;</font><font color="#000000">)</font><font color="#000000">;test_arr.add</font><font color="#000000">(</font><font color="#2a00ff">&#034;d&#034;</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">Permute&lt;String&gt;&nbsp;test&nbsp;=&nbsp;</font><font color="#7f0055"><b>new&nbsp;</b></font><font color="#000000">Permute&lt;String&gt;</font><font color="#000000">(</font><font color="#000000">test_arr</font><font color="#000000">)</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>while&nbsp;</b></font><font color="#000000">(</font><font color="#7f0055"><b>true</b></font><font color="#000000">)</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">{</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">System.out.println</font><font color="#000000">(</font><font color="#000000">test.get_next</font><font color="#000000">()</font><font color="#000000">.toString</font><font color="#000000">())</font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>if&nbsp;</b></font><font color="#000000">(</font><font color="#000000">!test.next_permutation</font><font color="#000000">())</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#7f0055"><b>break</b></font><font color="#000000">;</font><br />
<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#ffffff">&nbsp;&nbsp;</font><font color="#000000">}</font><br />
<font color="#000000">}</font></code></p>
</td>
<p>  <!-- end source code --><br />
   </tr>
<p>  <!-- start Java2Html link --></p>
<tr>
<td align="right">
<p><a href="http://www.java2html.de" target="_blank">Java2html</a></p>
</td>
</tr>
<p>  <!-- end Java2Html link --><br />
</table>
</div>
<p><!-- =       END of automatically generated HTML code       = --><br />
<!-- ======================================================== --></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/122/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/122/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/122/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=122&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/04/12/generating_all_possible_permutations_of_a_sequence/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>Richard Feynman on Ways of Thinking</title>
		<link>http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/</link>
		<comments>http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/#comments</comments>
		<pubDate>Sat, 13 Mar 2010 11:46:59 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[People]]></category>
		<category><![CDATA[richard feynman]]></category>
		<category><![CDATA[science]]></category>
		<category><![CDATA[Thoughts]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=115</guid>
		<description><![CDATA[I am a big fan of  Richard Feynman. He has this unique ability of explaining what happens around us daily in a way as fascinating and interesting as they can be. He makes us failing in love with science (not &#8230; <a href="http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=115&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I am a big fan of  <a href="http://en.wikipedia.org/wiki/Richard_Feynman">Richard Feynman</a>.</p>
<p>He has this unique ability of explaining what happens around us daily in a way as fascinating and interesting as they can be. He makes us failing in love with science (not that science is not lovable already <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).<br />
No wonder he is treated as rockstar in the field of science, a title only hold by Einstein before him.<br />
I wish I had a teacher explaining stuff like he does while I was still in school.. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_neutral.gif' alt=':|' class='wp-smiley' /> </p>
<p>Recently I came across two such fascinating youtube videos in which he talks about ways in which people think (via HackerNews)</p>
<p>Enjoy watching these videos <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<span style="text-align:center; display: block;"><a href="http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/"><img src="http://img.youtube.com/vi/Cj4y0EUlU-Y/2.jpg" alt="" /></a></span>
<span style="text-align:center; display: block;"><a href="http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/"><img src="http://img.youtube.com/vi/jrk3GbJU0k0/2.jpg" alt="" /></a></span>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/115/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/115/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/115/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=115&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/03/13/richard-feynman-on-ways-of-thinking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>How Google News Recommendation Engine Works!! [Video]</title>
		<link>http://42bits.wordpress.com/2010/03/06/how-google-news-recommendation-engine-works-video/</link>
		<comments>http://42bits.wordpress.com/2010/03/06/how-google-news-recommendation-engine-works-video/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 12:03:01 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[acm]]></category>
		<category><![CDATA[algorithms]]></category>
		<category><![CDATA[google news]]></category>
		<category><![CDATA[Map-Reduce]]></category>
		<category><![CDATA[recommendation]]></category>
		<category><![CDATA[TechTalk]]></category>
		<category><![CDATA[Video]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=91</guid>
		<description><![CDATA[I just finished watching a Great Tech-Talk on how Google news recommends relevant news items one might be interested in and I thought it would be nice to share this video on my blog. Please note the talk was given &#8230; <a href="http://42bits.wordpress.com/2010/03/06/how-google-news-recommendation-engine-works-video/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=91&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I just finished watching a Great Tech-Talk on how Google news recommends relevant news items one might be interested in and<br />
I thought it would be nice to share this video on my blog.</p>
<p>Please note the <em>talk was given in 2008</em>, but is quite informative None the less.</p>
<h4>Some Takeaways:</h4>
<p style="text-align:left;">They mainly use <a href="http://en.wikipedia.org/wiki/Collaborative_filtering">collaborative algorithms<cite></cite></a> algorithms family for coming up with stories to recommend.<br />
Using this not only can they leverage google&#8217;s large user base that they have to their advantage, but it also makes algorithms domain independent, so the same algorithms can also be used to some other domain like google video, etc.</p>
<p style="text-align:left;">They use weights on various applicable methods to come up with a net weighted score for  all the stories.</p>
<p style="text-align:left;">Some of the factors influencing news recommendation:</p>
<ol style="text-align:left;">
<li>Stories which users who have similar interest as yours have clicked [MinHash,<a href="http://en.wikipedia.org/wiki/Probabilistic_latent_semantic_analysis">PLSI</a>]</li>
<li>Stories that you have co-visited with the stories you clicked.</li>
</ol>
<p style="text-align:left;">Recommendation are category specific, so your news clicks in entertainment section won&#8217;t affect items recommended in technology section.</p>
<p style="text-align:left;">Author also talks about how to make these algorithms <em>scalable enough</em> to run them effectively,  which is mostly achieved by using <a href="http://en.wikipedia.org/wiki/Map_reduce">Map-Reduce</a> , a well known distributed computing standard.</p>
<p>To people genuinely interested on this topic, I would suggest reading another great book on the subject &#8211; <a href="http://www.amazon.com/Programming-Collective-Intelligence-Building-Applications/dp/0596529325"><strong>programming Collective Intelligence: Building Smart Web 2.0 Applications </strong></a><br />
A great read for the researchers and the newbies alike.</p>
<span style='text-align:center;display:block;'><object width='400' height='330' type='application/x-shockwave-flash' data='http://video.google.com/googleplayer.swf?docId=7238273896874148108'><param name='allowScriptAccess' value='never' /><param name='movie' value='http://video.google.com/googleplayer.swf?docId=7238273896874148108'/><param name='quality' value='best'/><param name='bgcolor' value='#ffffff' /><param name='scale' value='noScale' /><param name='wmode' value='opaque' /></object></span>
<p><img style="border:0 solid blue;z-index:90;position:absolute;left:69px;top:383px;" src="//dictionarytip/skin/dtipIconHover.png" alt="" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/91/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/91/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/91/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=91&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/03/06/how-google-news-recommendation-engine-works-video/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>PostgreSQL tips and tricks !! (Part 1)</title>
		<link>http://42bits.wordpress.com/2010/02/07/postgresql-tips-and-tricks-part-1/</link>
		<comments>http://42bits.wordpress.com/2010/02/07/postgresql-tips-and-tricks-part-1/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 10:00:55 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=27</guid>
		<description><![CDATA[For a long time I wanted to have an online catalog of various sql nifty queries and hacks that i have found helpful and continue to use till date . Many times  I got help from various blogs written on &#8230; <a href="http://42bits.wordpress.com/2010/02/07/postgresql-tips-and-tricks-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=27&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>For a long time I wanted to have an online catalog of various sql nifty queries and hacks that i have found helpful and continue to use till date .<br />
Many times  I got help from various blogs written on this topic.<br />
Now It&#8217;s my time to give back something to the community, I learned so much from <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>This post is most useful for people who have intermediate to advanced knowledge of postgresql/SQL.</p>
<p>Note : Please use these queries <strong>at your own risk</strong>, hopefully it should help you get your work done without any hiccups <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>1) <strong>Using query aliases in table joins for better performance</strong>:<br />
While doing a join between two (or more ) tables, using aliases gives gives performance gain over ordinary joins in certain cases. Like for ex.<br />
Suppose there are two tables having Bank information (bankinfo) and Transaction Information (trinfo) , They share a common column named IFSC number.<br />
I need Bank Information,and total number of transactions present for each bank. Now I can write needed sql query in two ways.</p>
<blockquote>
<p style="text-align:justify;"><span style="color:#808080;"><strong>select bankinfo.name,trinfo.ifsc,count(*) from bankinfo left outer join trinfo on bankinfo.ifsc=trinfo.ifsc group by bankinfo.name,trinfo.ifsc;</strong></span></p>
</blockquote>
<p>Or using query aliases</p>
<blockquote>
<p style="text-align:justify;"><span style="color:#808080;"><strong>select bankinfo.name,q.count from bankinfo left outer join </strong><strong>(select ifsc,count from trinfo group by ifsc)q on bankinfo.ifsc = q.ifsc;</strong></span></p>
</blockquote>
<p>You can see that we are reducing rows that would need to be joined, which will most of the times will result in improved performance.This mostly works if join involves one of the tables which is relatively large in size or if you are using group by clauses.</p>
<p><span id="more-27"></span></p>
<p>2)<strong>Using multicolumn indexes if you are using a same set of multiple columns in all your queries.</strong><br />
This improves query performance drastically for some cases. Use multicolumn indexes wisely because they need more space/time resources to keep them updated !!.<br />
You can read more about them on the well-maintained <a href="http://www.postgresql.org/docs/8.2/interactive/indexes-multicolumn.html">Postgresql Online docs</a>.</p>
<p>3)<strong>Calculate Database, Tablewise disk space sizes.</strong></p>
<ul>
<li>Total Database Size:</li>
</ul>
<blockquote>
<p style="text-align:left;padding-left:30px;"><strong><span style="color:#808080;">select pg_size_pretty(pg_database_size(&#8216;#database_name#&#8217;));</span></strong></p>
</blockquote>
<ul>
<li>Size per table ordered by largest size descending:</li>
</ul>
<blockquote>
<p style="padding-left:30px;"><strong><span style="color:#808080;">select n.nspname, c.relname, pg_size_pretty(pg_total_relation_size(c.relname)) FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace<br />
WHERE c.relkind IN (&#8216;r&#8217;,&#8221;) AND n.nspname NOT IN (&#8216;pg_catalog&#8217;, &#8216;pg_toast&#8217;)<br />
AND pg_catalog.pg_table_is_visible(c.oid) order by pg_total_relation_size(c.relname) desc;</span></strong></p>
</blockquote>
<p><strong>4</strong>) <strong>Calculate nth highest column value in a  table:</strong></p>
<blockquote>
<p style="text-align:justify;"><strong><span style="color:#808080;">select rank from students order by rank asc <em>offset n</em> limit 1;</span></strong></p>
</blockquote>
<p><strong>5)Using set operators in your queries</strong>:</p>
<p>Using Set Operators In SQL queries is handy at times.</p>
<p>Sometimes using <em>&#8221; except</em> &#8221; instead of  <strong>highly expensive</strong> <em>&#8220;  not in &#8220;</em> operator can reduce query execution time many folds.</p>
<p>For ex : To check which bank branch don&#8217;t have deposits transaction for amount more than 100k in last week:</p>
<blockquote><p>Using not in clause:</p>
<p style="padding-left:30px;text-align:justify;"><span style="color:#808080;"><strong>select branch_name from branches where branch_id not in (select branch_id from transactions where type=&#8217;deposit&#8217; and transaction_time &gt; interval &#8217;1 week&#8217;  and amount &gt; 1000000) </strong></span></p>
<p>using Except clause:</p>
<p style="padding-left:30px;text-align:justify;"><strong><span style="color:#808080;">select branch_name where branch_id in (select branch_id from branches except select branch_id from transactions where type=&#8217;deposit&#8217; and transaction_time &gt; interval &#8217;1 week&#8217;  and amount &gt; 1000000)</span></strong></p>
</blockquote>
<p>In Detail you can refer to : http://www.postgresql.org/docs/8.2/static/queries-union.html</p>
<p><strong>Always Remember &#8211; </strong>When in Doubt use <a href="http://www.postgresql.org/docs/8.1/static/sql-explain.html" target="_blank">Explain Analyze</a> to see the query cost estimates to come up with the right query.</p>
<p><strong>Links,Tools I have found to be useful:</strong><br />
<a href="http://explain.depesz.com/" target="_blank"> Postgresql Query plan Analyzer tool</a><br />
<a href="http://www.dpriver.com/pp/sqlformat.htm" target="_blank"> Sql Pretty Formatter </a><br />
<a href="http://www.postgres.cz/index.php/PostgreSQL_SQL_Tricks" target="_blank"> Some Cool PostgreSQL tricks</a></p>
<p><img style="border:0 solid blue;z-index:90;position:absolute;left:209px;top:36px;" src="//dictionarytip/skin/dtipIconHover.png" alt="" /></p>
<p><img style="border:0 solid blue;z-index:90;position:absolute;left:55px;top:780px;" src="//dictionarytip/skin/dtipIconHover.png" alt="" /></p>
<p><img style="border:0 solid blue;z-index:90;position:absolute;left:136px;top:895px;" src="//dictionarytip/skin/dtipIconHover.png" alt="" /></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/27/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/27/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/27/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=27&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2010/02/07/postgresql-tips-and-tricks-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
		<item>
		<title>Python Wrapper for Google Translate AJAX API.</title>
		<link>http://42bits.wordpress.com/2009/08/22/python-wrapper-for-google-translate-ajax-api/</link>
		<comments>http://42bits.wordpress.com/2009/08/22/python-wrapper-for-google-translate-ajax-api/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 19:52:01 +0000</pubDate>
		<dc:creator>Ashish Yadav</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Google AJAX API]]></category>
		<category><![CDATA[Language Translation]]></category>
		<category><![CDATA[Wrapper]]></category>

		<guid isPermaLink="false">http://42bits.wordpress.com/?p=13</guid>
		<description><![CDATA[Few Days Ago, i needed some Non English documents to be translated to English language, for which Google AJAX Language API can be used. I wrote a small script which got the work done ,and why put it to waste &#8230; <a href="http://42bits.wordpress.com/2009/08/22/python-wrapper-for-google-translate-ajax-api/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=13&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Few Days Ago, i needed some Non English documents to be translated to English language, for which Google AJAX Language API can be used.</p>
<p>I wrote a small script which got the work done ,and why put it to waste when there is a chance that it can be used by others.</p>
<p>So without further ado, here is the code <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> , Feel free to use it in any commercial/open source projects</p>
<p><code> </code></p>
<p><code> </code></p>
<p><code></p>
<pre><a name="1"></a> <span style="color:#800000;">#By Ashish Yadav, released under WTFPL</span>
<a name="1"></a> <span style="color:#800000;">#http://sam.zoy.org/wtfpl/</span>
<a name="1"></a> <span style="color:#800000;"># -*- coding: utf-8 -*-</span>
<a name="2"></a>
<a name="4"></a> <span style="color:#804000;">import</span> sys
<a name="5"></a> <span style="color:#804000;">import</span> urllib
<a name="6"></a> <span style="color:#804000;">import</span> simplejson
<a name="7"></a>
<a name="8"></a> baseUrl = "<span style="color:#006000;">http://ajax.googleapis.com/ajax/services/language/translate</span>"
<a name="9"></a>
<a name="10"></a> <span style="color:#804000;">def</span> <span style="color:#000080;">getSplits</span>(text,splitLength=4500):
<a name="11"></a>     '''<span style="color:#006000;"> </span>
<a name="12"></a> <span style="color:#006000;">    Translate Api has a limit on length of text(4500 characters) that can be translated at once, </span>
<a name="13"></a> <span style="color:#006000;">    </span>'''
<a name="14"></a>     <span style="color:#804000;">return</span> (text[index:index+splitLength] <span style="color:#804000;">for</span> index <span style="color:#804000;">in</span> xrange(0,len(text),splitLength))
<a name="15"></a>
<a name="16"></a>
<a name="17"></a> <span style="color:#804000;">def</span> <span style="color:#000080;">translate</span>(text,src='<span style="color:#006000;"> </span>', to='<span style="color:#006000;">en</span>'):
<a name="18"></a>     '''
<a name="19"></a> <span style="color:#006000;">    A Python Wrapper for Google AJAX Language API:</span>
<a name="20"></a> <span style="color:#006000;">    * Uses Google Language Detection, in cases source language is not provided with the source text</span>
<a name="21"></a> <span style="color:#006000;">    * Splits up text if it's longer then 4500 characters, as a limit put up by the API</span>
<a name="22"></a> <span style="color:#006000;">    </span>'''
<a name="23"></a>
<a name="24"></a>     params = ({'<span style="color:#006000;">langpair</span>': '<span style="color:#006000;">%s|%s</span>' % (src, to),
<a name="25"></a>              '<span style="color:#006000;">v</span>': '<span style="color:#006000;">1.0</span>'
<a name="26"></a>              })
<a name="27"></a>     retText=''
<a name="28"></a>     <span style="color:#804000;">for</span> text <span style="color:#804000;">in</span> getSplits(text):
<a name="29"></a>             params['<span style="color:#006000;">q</span>'] = text
<a name="30"></a>             resp = simplejson.load(urllib.urlopen('<span style="color:#006000;">%s</span>' % (baseUrl), data = urllib.urlencode(params)))
<a name="31"></a>             <span style="color:#804000;">try</span>:
<a name="32"></a>                     retText += resp['<span style="color:#006000;">responseData</span>']['<span style="color:#006000;">translatedText</span>']
<a name="33"></a>             <span style="color:#804000;">except</span>:
<a name="34"></a>                     <span style="color:#804000;">raise</span>
<a name="35"></a>     <span style="color:#804000;">return</span> retText
<a name="36"></a>
<a name="37"></a>
<a name="38"></a> <span style="color:#804000;">def</span> <span style="color:#000080;">test</span>():
<a name="39"></a>     msg = "<span style="color:#006000;">      Write something You want to be translated to English,\n</span>"\
<a name="40"></a>         "<span style="color:#006000;">      Enter ctrl+c to exit</span>"
<a name="41"></a>     <span style="color:#804000;">print</span> msg
<a name="42"></a>     <span style="color:#804000;">while</span> True:
<a name="43"></a>         text = raw_input('<span style="color:#006000;">#&gt;  </span>')
<a name="44"></a>         retText = translate(text)
<a name="45"></a>         <span style="color:#804000;">print</span> retText
<a name="46"></a>
<a name="47"></a>
<a name="48"></a> <span style="color:#804000;">if</span> __name__=='<span style="color:#006000;">__main__</span>':
<a name="49"></a>     <span style="color:#804000;">try</span>:
<a name="50"></a>         test()
<a name="51"></a>     <span style="color:#804000;">except</span> KeyboardInterrupt:
<a name="52"></a>         <span style="color:#804000;">print</span> "<span style="color:#006000;">\n</span>"
<a name="53"></a>         sys.exit(0)
<a name="54"></a></pre>
<p></code></p>
<p>Python Code Formatting is done using the awesome <a href="http://tom.idealog.info/blog/20031205-1070600658.shtml">Python2Html</a> utility</p>
<p>Also present as a <a href="http://code.activestate.com/recipes/576890/">recipe</a> on Activestate</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/42bits.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/42bits.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/42bits.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=42bits.wordpress.com&amp;blog=8388996&amp;post=13&amp;subd=42bits&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://42bits.wordpress.com/2009/08/22/python-wrapper-for-google-translate-ajax-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/8ceaabf19fa1c963722b680e9f1b2a43?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">ashish</media:title>
		</media:content>
	</item>
	</channel>
</rss>
