tag:blogger.com,1999:blog-65160274895208679932024-03-14T00:50:47.317+05:30Technical OutletA place to learn, share and grow.Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.comBlogger23125tag:blogger.com,1999:blog-6516027489520867993.post-48149511673908092962012-12-10T01:40:00.003+05:302012-12-10T01:45:21.229+05:30[Quora Challenges] Typeahead Search - I<div dir="ltr" style="text-align: left;" trbidi="on">
This is the first post amongst a few that would follow in an attempt to solve the Quora challenge <a href="https://www.quora.com/about/challenges#typeahead_search" target="_blank">Typeahead search</a>. This problem particularly interests me. Why? Because during my internship at <a href="http://www.media.net/" target="_blank">Media.net (Directi)</a>, I worked on a similar problem. Having spent an entire summer working on an equivalent of Google's "instant search", I realized how complex it is. "Bigger dataset, lesser query time", this was all that was on my mind for most of my summer.<br />
<br />
Having done a lot of research earlier, I referred back to the following to see if I can apply any ideas directly<br />
<ol style="text-align: left;">
<li><a href="http://dhruvbird.blogspot.in/2010/09/very-fast-approach-to-search.html">A very fast approach to auto complete (or search suggestions)</a>
</li>
<li>
<span style="font-size: small;"><a href="http://igoro.com/archive/efficient-auto-complete-with-a-ternary-search-tree/" title="Link to Efficient auto-complete with a ternary search tree">Efficient auto-complete with a ternary search tree</a></span></li>
<li>
<a href="http://rmandvikar.blogspot.in/2008/10/trie-examples.html">Trie examples</a><span style="font-size: small;"> </span></li>
<li><span style="font-size: small;"><a href="http://stackoverflow.com/questions/1783652/what-is-the-best-autocomplete-suggest-algorithm-datastructure-c-c">What is the best autocomplete/suggest algorithm,datastructure</a><span style="font-size: small;"> </span></span></li>
</ol>
<span style="font-size: small;"><span style="font-size: small;">As is evident, most of these point towards the use of a trie to solve the problem. Considering </span></span>that I developed a fascination towards Tries during the internship, I might even end up using the same structure here. However, I'm considering exploring other methods that might suit this problem better. For instance, tries are exceptionally good to reduce the time taken to search for a word, it requires a lot of space. Also, since there would be at most 40k insertions, other methods such as the 4th Approach <a href="http://dhruvbird.blogspot.in/2010/09/very-fast-approach-to-search.html">here</a>. I also need to check how much memory usage is allowed to solve this problem and how much pre-processing time would be acceptable. <br />
<br />
[More discussion in follow-up posts] </div>
Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-86438980022041869152012-10-26T19:04:00.003+05:302012-10-27T11:02:58.042+05:30[InterviewStreet Problem] Find Strings<div dir="ltr" style="text-align: left;" trbidi="on">
Update <br />
The mistake was in counting the number of children. I have now passed all but two test cases, which probably require that I implement the Suffix Tree using lists instead of arrays.<br />
---------------------------------------------------------------------------------------------------------------------------- <br />
<br />
So I have been trying to solve problems under the "Strings" section in InterviewStreet. <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4efa210eb70ac" target="_blank">Find Strings</a> is one of those questions and I am here to discuss a possible strategy to solve the problem. <strike>I'd like to make it clear from the beginning that my own solution has not been accepted yet, but I am unable to see the flaw in the approach and am expecting someone to point it out.</strike><br />
<br />
So, the question requires us to find the number of unique substrings in a given set of strings. At first I thought as the question unfolds and since I use C++ for most problems, I was thinking in terms of the available data structures in STL. So, at first I thought of storing the unique substrings (of the order of the square of the length of the string) in a 'set'. The set takes care of the uniqueness, but the problem arises if I try to find the 'k-th' smallest string. This would take really long, for each query.<br />
<br />
So, the things that led me to another solution were the following realizations :-<br />
<ul style="text-align: left;">
<li>First solution takes too long inserting each string</li>
<li>Insertion of the substrings of a string like "aab", will require steps to insert each of {a, aa, aab, ab, b}, i.e. 5 different insertion steps. Here, I thought if I could simply mark {a,aa} as unique substrings as well when inserting aab</li>
<li>Searching for a string in a set (when checking for uniqueness) requires comparison of almost the entire string even if a similar string has already been compared with. For instance, in a set of {abc, abe}, I am checking if "abd" exists, then I would need to carry out 6 comparisons (between characters). This wastes the earlier learnt lesson that the first two characters are 'ab'.</li>
</ul>
These things led me to think in terms of tries and consequently I related that it is possible find substrings of a string in its Suffix Tree. A suffix tree is, basically, a trie of suffixes of a string. So, if I create one suffix tree as the set of the unique substrings, I have the following advantage :-<br />
<ul style="text-align: left;">
<li> I have to insert only the m suffixes of a string of length <i>m</i>. This reduces the number of insertions to linear from quadratic in the previous algorithm.</li>
<li>While checking if the string to be inserted is already present in the set, I need only O(d) comparisons, where <i>d</i> is the length of the string to be inserted.</li>
<li>While checking for the k-th smallest string (lexicographically), I can make use of the information about the number of children of a node (not the number of leaves it leads). The number of children of a node can be related to the number of unique "substrings" (not suffixes, which is given by the number of leaves). </li>
</ul>
<br />
So, eventually, I ended up coding up a SuffixTree and the solution I submitted can be found below (or follow this <a href="https://gist.github.com/3958818" target="_blank">link</a>). <strike>But again, this solution has been able to pass only one of the test cases. So, either there's some serious flaw with the approach or I've failed to code what I had in mind. </strike><br />
<br />
<br />
<script src="https://gist.github.com/3958818.js"> </script><strike></strike>I'd be glad to hear suggestions for improvements in the algorithm or the code.</div>
Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-37026505123882283942012-07-03T14:16:00.001+05:302012-07-03T14:16:44.577+05:30Converting a file descriptor to an I/O Stream in Linux [C++]<div dir="ltr" style="text-align: left;" trbidi="on">
Recently, if one can call something that happened over 2 months ago 'recent', I decided to do a Networks assignment entirely in C++ and using streams. Why, you ask ? Well, the simplest answer is, "I was bored." I had done another network assignment in C, through which I had seen quite a lot of functions that are required to connect, send/receive messages, etc. So, this was something like a challenge.<br />
<br />
And that's exactly what it turned out to be, a challenge. Four hours into the assignment, which was obviously just 2 days before the submission, I was struggling to understand how could I convert all the file descriptors that were being returned from various C based functions into C++ streams.<br />
<br />
As it turns out, due to difference in uses and implications of file descriptors in different operating systems, there was no standard function to convert a File Descriptor to a stream. That was what I learnt after hours of scouring over StackOverflow and running into answers that explained "<a href="http://stackoverflow.com/questions/109449/getting-a-file-from-a-stdfstream" target="_blank">How to get the underlying FILE* from fstream?</a>" until I finally found out a solution that works on G++.<br />
<br />
<br />
This may definitely not be the best approach, but a hack.<br />
<script src="https://gist.github.com/2012695.js?file=fdToStream.cpp">
</script>
<br />
I used it <a href="https://github.com/rajatkhanduja/Network-assignments/blob/master/FTP_Server_Client/common/src/TcpSocket.cpp">here</a> and built upon it. Besides the problem of handling Unicode characters (which I understand was because I was using <a href="http://www.cplusplus.com/reference/string/string/" target="_blank">string</a> and not <a href="http://msdn.microsoft.com/en-us/library/wt3s3k55(v=vs.80).aspx" target="_blank">wstring</a> ), I did not face any problem with streams; so I would assume that the solution worked well.<br />
<br />
If you are aware of a smarter, quicker and cleaner method of doing this, please share it in comments.</div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-72940071145072863072012-01-09T15:15:00.002+05:302012-01-09T15:18:36.424+05:30Alias a URL on Apache<div dir="ltr" style="text-align: left;" trbidi="on">Many a times I have needed to share a page using <a href="http://www.apache.org/">Apache</a>, without copying the page into the '/var/www' folder. Discussed below is one of the solutions that I often use. <br />
<br />
Lets say you have a folder '/home/user/images' that you would like to share over Apache but you might not want to put it over into '/var/www' maybe because you have other scripts performing on this folder or taking backup from time to time. <br />
<br />
In such a scenario, <a href="http://httpd.apache.org/docs/2.0/mod/mod_alias.html">Apache's mod_alias</a> comes to our rescue. This module allows us to provide an alias URL for the required directory. To achieve the same, insert the following lines in the '/etc/apache2/httpd.conf'<br />
<br />
<blockquote class="tr_bq"><code>Alias /image /ftp/pub/image</code></blockquote><br />
<blockquote class="tr_bq"><code><Directory /ftp/pub/image><br />
<span class="indent"> Order allow,deny<br />
Allow from all<br />
</span> </Directory> </code></blockquote>Care must be taken regarding the trailing slash ('/') in the directory's name. Among the options available, I suggest not using the trailing slash in any path (neither the alias, nor the actual path).<br />
<br />
This is not the end to the process though. One important step is to ensure that the path is 'executable' by other users as well. Each of the parent directory should be also be executable by other users. <br />
<br />
Use 'chmod 711' on each of the parent directories.<br />
<br />
Voila, now you are done. Just restart apache and visit the URL<br />
<blockquote class="tr_bq">site-address/alias </blockquote></div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-14595330407651364672012-01-06T19:56:00.000+05:302012-01-06T19:56:19.592+05:30Chrome becomes the most popular browser in India<div dir="ltr" style="text-align: left;" trbidi="on">TechRaga reported in September, "<a href="http://blog.arpitnext.com/2011/09/chrome-beats-internet-explorer.html">Chrome Beats Internet Explorer And Becomes #2 Browser in India</a>". The latest statistics from <a href="http://statcounter.com/">StatCounter</a> show that <a href="https://www.google.com/chrome">Chrome</a> is now the most popular browser in India, closely followed by <a href="http://www.mozilla.org/en-US/firefox/all.html">Firefox</a>.<br />
<br />
<div height="400" id="browser-IN-weekly-201143-201153" style="height: 400px; width: 550px;" width="550"></div>Source: <a href="http://gs.statcounter.com/#browser-IN-weekly-201143-201153">StatCounter Global Stats - Browser Market Share</a><br />
<script src="http://www.statcounter.com/js/FusionCharts.js" type="text/javascript">
</script><script src="http://gs.statcounter.com/chart.php?browser-IN-weekly-201143-201153" type="text/javascript">
</script><br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div>The above image depicts the share of browsers in the last 10 weeks, and it clearly shows that Firefox and Chrome are fighting for the top spot.<br />
<br />
Despite the 3rd spot in India, IE enjoys the first spot worldwide, while Chrome stands at the 2nd spot after <a href="http://gs.statcounter.com/press/chrome-overtakes-firefox-globally-for-first-time">recently overtaking Firefox globally</a>.<br />
<br />
<div id="browser-ww-weekly-201143-201153" width="550" height="400" style="width:550px; height: 400px;"></div><!-- You may change the values of width and height above to resize the chart --><p>Source: <a href="http://gs.statcounter.com/#browser-ww-weekly-201143-201153">StatCounter Global Stats - Browser Market Share</a></p><script type="text/javascript" src="http://www.statcounter.com/js/FusionCharts.js"></script><script type="text/javascript" src="http://gs.statcounter.com/chart.php?browser-ww-weekly-201143-201153"></script><br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div><br />
According to <a href="http://statcounter.com/">StatCounter</a>, among various browser versions Chrome 15.0 has already taken over the global market followed by IE 8.0.<br />
<br />
<div height="400" id="browser_version-ww-weekly-201143-201153" style="height: 400px; width: 505px;" width="550"></div>Source: <a href="http://gs.statcounter.com/#browser_version-ww-weekly-201143-201153">StatCounter Global Stats - Browser Version Market Share</a><br />
<script src="http://www.statcounter.com/js/FusionCharts.js" type="text/javascript">
</script><script src="http://gs.statcounter.com/chart.php?browser_version-ww-weekly-201143-201153" type="text/javascript">
</script><br />
<br />
These browser wars remind us of the IE-Netscape war which was won by IE, but it looks like Open Source Browsers are becoming more popular, even among ordinary users. </div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-53225214821924999332011-11-10T23:26:00.001+05:302011-11-10T23:59:54.776+05:30Lets grow with Facebook<div dir="ltr" style="text-align: left;" trbidi="on">
Now, this is not some expert advice; just giving words to the thoughts of many. Many of us have realized, at some point of this year or another, that <a href="http://www.facebook.com/">Facebook</a> is not just another site, not anymore. With a user base of over <a href="https://www.facebook.com/press/info.php?statistics">800 million</a>, there's barely anyone left out of the social networking site.<br /><br />So what does that mean to us ? Firstly, we must realize that all your dreams to start now and grow up to compete against Facebook, might be a little too far-fetched. I am, generally, not a pessimistic person, so I would like to add that former statement holds for most of the people out there planning to go up against Facebook; you might be an exception.<br />
<br />
Secondly, and in my opinion more importantly, the large user base of Facebook gives others the idea to make use of the user base. We need to realize that the number of 'active' users on Facebook is a good indicator of 'active' internet users. These are the people any one wants to attract to their own products. But, if the number of people on facebook includes the people you want to target, why not target them directly ? Facebook now offers plethora of <a href="https://developers.facebook.com/">API</a>s giving developers a whole new world still left to be explored.<br />
<br />
The point I am trying to convey should be clear from the following example. Say, you are a developer/entrepreneur with a idea that you think could change the way people think about 'something'. But again, your idea is heavily dependent on the input from your users; their participation is what drives your idea. In that case, you need a lot of users to visit your site. <a href="http://en.wikipedia.org/wiki/Mark_Zuckerberg">Mark Zuckerberg</a>, on the other hand, is trying to make sure that <a href="http://www.technologyreview.in/computing/38656/">people spend more time on Facebook and have less reasons to go outside</a>. Given the resources, including the user base and money, they are expected to do a good job at that. I suggest, that we help him do this. How ? Why do you need a new site, when you can just create an application 'within' facebook. Looking at various apps such as <a href="https://apps.facebook.com/theguardian/">The Guardian</a> and <a href="https://apps.facebook.com/wpsocialreader">Washington Post Social Reader</a>, one can only begin to imagine the possibilities of such applications.<br />
<br />
So what's the advantage ? For you, users; for users, the fact that they get the content without leaving facebook. At first, it might sound naive, but think about it and remember what they say,<br />
<blockquote class="tr_bq">
"If you can't beat them, join them." </blockquote>
</div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-17042739141681939952011-08-17T05:01:00.006+05:302011-08-21T13:14:28.689+05:30Tab completes my life<div dir="ltr" style="text-align: left;" trbidi="on">Sorry for the somewhat awkward title. I just couldn't resist the geeky pun, and couldn't come up with a better phrase to express it. Hope you got the short message from the title. Also please forgive the awful (or awesome?) prose below. I've always wanted to write a post like this :)<br />
<br />
Having been a happy Linux user for the past year-and-a-half, I respect the art of command line-fu. The most useful, yet simple, trick in the bag of the CLI ninja is, of course, the all-powerful <a href="http://en.wikipedia.org/wiki/Tab_key">Tab key</a>. In one stroke - literally - it can help him type even the longest of commands with minimal key presses. I just <i>love</i> going <code>..<Tab>..<Tab>..<Tab><Enter></code> on my terminal, commands flowing at the speed of thought.<br />
<br />
Now I'm <i>so</i> used to it, I expect it to be present everywhere - my browser, my text editor, in git commands, in the python interactive interpreter. Basically, I expect my computer to do its job - that is, helping me out while I try to do mine. That does not happen easily, however. So I set out on a quest - to try to have some form of Tab-completion in as many programs as possible. Below, I chronicle my journey, for the benefit of the traveller seeking the same end :-<br />
<br />
<b>The Switch from Bash to Zsh:</b><br />
All Linuxes come with the same default shell: <a href="http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29">bash</a>. However, there's another shell out there - <a href="http://en.wikipedia.org/wiki/Zsh">zsh</a> - which is little known, but extremely powerful. It's the first step from CLI apprentice to CLI productivity master. There are some excellent plugins available for zsh which add tab completion for many commands like <code>git</code>, <code>pip</code>, <code>gem</code>, and <code>kill</code> along with some bonuses. It'll also help you out with many other small things, like ignoring case and correcting spelling mistakes.<br />
<br />
If you're thinking to try out zsh, I'd recommend installing <a href="https://github.com/robbyrussell/oh-my-zsh/">Oh My Zsh!</a> first thing after you install zsh itself. It'll make it much easier to set up zsh to your liking, replete with themes, plugins, and aliases. Also, as it turns out, <a href="http://wiki.redbrick.dcu.ie/mw/Account_Customisation_%28zsh%29#Changing_The_Command_Prompt">the <code>$RPS1</code> environment variable</a>, along with the git support in Oh My Zsh!, pretty much renders <a href="http://yetanothercomputermaniac.blogspot.com/2011/07/alternative-and-very-useful-bash-prompt.html">my alternative (and very useful) bash prompt</a> obsolete.<br />
<br />
<b>The Text Editor:</b><br />
Since I'm a die-hard <a href="http://www.gnu.org/software/emacs/">Emacs</a> user, this section's a bit biased. For Emacs, I use <a href="http://cx4a.org/software/auto-complete/">Auto Complete Mode</a>. It's fairly easy to setup, and blazing fast once you get used to it. Note that this is not <i>code</i> completion, it's simple, cross-buffer <i>word</i> completion, so it'll suggest words based on what's in the rest of the buffer, or in other open buffers. I find this better than code completion for the simple reason that code completion would require me to install separate plugins for each language I use, while on the other hand, word completion is universally effective, if not as accurate. Heck, it even works in comments. Combine that with <a href="http://www.emacswiki.org/emacs/?action=browse;oldid=YaSnippetMode;id=Yasnippet">YASnippet</a>, and you'll find yourself with one finger on the Tab key nearly perpetually, and code flowing from your fingers.<br />
<br />
Oh, and let's not forget <a href="http://www.emacswiki.org/emacs/InteractivelyDoThings">ido-mode</a>. It's <i>the</i> coolest, dead-simplest Emacs plugin ever.<br />
<br />
For Vim users who feel left out, a quick Google search yields <a href="http://www.google.com/search?client=ubuntu&channel=fs&q=emacs&ie=utf-8&oe=utf-8#sclient=psy&hl=en&client=ubuntu&channel=fs&source=hp&q=vim+tab+completion&pbx=1&oq=vim+tab+completion&aq=f&aqi=&aql=1&gs_sm=e&gs_upl=474679l480512l0l480710l20l11l0l0l0l0l1431l10560l7-9l9l0&bav=on.2,or.r_gc.r_pw.r_cp.&fp=c07e2a9fa93d3c36&biw=1565&bih=765">this</a>.<br />
<br />
<b>The Interactive Interpreters (Python and Ruby):</b><br />
I <i>hated</i> it when I fired up <a href="http://python.org/"><code>python</code></a> the first time and it didn't offer Tab-completion. I later understood that since whitespace is significant in Python, completion is not enabled by default in the interpreter (or the Python <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a>, in purist-speak). I figured spaces could be used for indentation just as easily as tabs, so I enabled completion using <a href="http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html">this .pythonrc</a>. It's not like I miss tabs for indentation now.<br />
<br />
Coming to <a href="http://en.wikipedia.org/wiki/Interactive_Ruby_Shell"><code>irb</code></a> (the <a href="http://www.ruby-lang.org/en/">Ruby</a> interpreter), you can have Tab-completion <i>and</i> syntax highlighting in it <a href="http://www.rubyinside.com/wirble-tab-completion-and-syntax-coloring-for-irb-336.html">using the wirble gem and a .irbrc</a>. Pretty straight forward, supremely effective, no down-sides.<br />
<br />
<b>The Browser:</b><br />
Not much to say here. Probably the only thing you <i>can</i> Tab-complete in a browser is URLs, which the latest versions of Firefox and Chrome already do, anyway (it's not true, CLI-style tab-completion; just passable). If you want word completion too and you're on a recent version of Firefox, use <a href="https://addons.mozilla.org/en-US/firefox/addon/prospector-speak-words/">this</a> addon. Or, if you're using an older Firefox version, you could try <a href="https://addons.mozilla.org/en-US/firefox/addon/url-tab-completion/">this</a> one.<br />
<br />
<br />
Here ended my quest. Let your chronicles and criticisms be outlined in the comments below.</div>Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com5tag:blogger.com,1999:blog-6516027489520867993.post-43027635216045719982011-07-29T19:28:00.001+05:302011-07-29T19:32:04.317+05:30Ack!<div dir="ltr" style="text-align: left;" trbidi="on">I'm sure you've used <code><a href="http://linux.die.net/man/1/grep">grep</a></code> at some point in your life as a programmer to search for that piece of code in your code base. I was using it myself — until today. It turns out there's a better alternative to all that time spent trying to get the perfect <code>grep</code> alias so it works as it should: searching recursively, ignoring the <code>.git</code>/<code>.svn</code> directory, ignoring backup files (<code>foo~</code>/<code>#foo#</code>), printing out the file names and line numbers, grouping matches by file name. You've got to listen when <a href="http://jacobian.org/">Jacob Kaplan-Moss</a>, creator of <a href="http://www.djangoproject.com/">Django</a>, has this to say about it:<br />
<blockquote>"Whoa, this is *so* much better than grep it's not even funny."</blockquote>It's called <code><a href="http://betterthangrep.com/">ack</a></code>. Without further ado, you can install it on your Ubuntu system using <code><a href="apt://ack-grep">sudo apt-get install ack-grep</a></code> (for other distros, check out <a href="http://betterthangrep.com/"> the <code>ack</code> homepage</a>). Then use it as: <code>ack-grep search_term</code>. It's really that simple (although the default colours are a <i>little</i> irritating). You can see what files/directories it ignores by default using <code>ack-grep --help</code>. Here's a screenshot for the impatient reader:<br />
<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-Rii1COAVF08/TjK6tNIKQQI/AAAAAAAAA8Y/mAq6Jb8sGl4/s1600/Screenshot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="240" src="http://4.bp.blogspot.com/-Rii1COAVF08/TjK6tNIKQQI/AAAAAAAAA8Y/mAq6Jb8sGl4/s400/Screenshot.png" width="400" /></a></div><br />
'nuff said. I'm gonna go explore <a href="http://linux.die.net/man/1/ack">the man page</a>.</div>Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-43452229462076896402011-07-28T07:26:00.008+05:302011-07-28T07:50:07.714+05:30The alternative (and very useful) bash prompt<div dir="ltr" style="text-align: left;" trbidi="on">Almost all Linux users have used <a href="http://en.wikipedia.org/wiki/Bash_(Unix_shell)">bash</a> at some point, but how many of them know how to customize it to their liking? Here is a screenshot of one custom bash prompt I've created, which I find much better than the default (it took me a few hours to reach this point, owing mainly to my poor skills in bash scripting):<br />
<div><br />
</div><div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-uuB1ToYm3U8/TjC-TTsoXuI/AAAAAAAAA8U/MxrXP4bpnJo/s1600/Screenshot-2.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="258" src="http://3.bp.blogspot.com/-uuB1ToYm3U8/TjC-TTsoXuI/AAAAAAAAA8U/MxrXP4bpnJo/s400/Screenshot-2.png" width="400" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Click the image to view it properly.</td></tr>
</tbody></table>So, other than showing useful stuff related to git repositories, it gives me a full line to type my command, and separates each command with a hyphenated separator and a newline, so I can see it clearly as I scroll upwards. The corresponding code snippet is (put it at the end of your <code>~/.bashrc</code> if you wish to use it):<br />
<br />
<pre class="brush:bash">PS1='\[\033[01;34m\]\$\[\033[00m\] '
parse_git_dirty () {
[[ $(__git_ps1) != "" ]] && [[ $(git status 2> /dev/null | tail -n1) != "nothing to commit (working directory clean)" ]] && echo "*"
}
print_pre_prompt () {
# the first part of the prompt, i.e., the user's name
local PS1U=$USER
# the second part of the prompt, i.e., the present working directory
local PS1WD="${PWD}"
if [[ $PS1WD = "$HOME" ]]; then PS1WD=\~; fi
if [[ $PS1WD = *"$HOME"/* ]]; then PS1WD=\~${PS1WD#$HOME}; fi
# the fourth and last part of the prompt, i.e., the git stuff
local git_dirty=$(parse_git_dirty)
local git_dirty_color="\033[1;31m"
local git_clean_color="\033[1;30m"
if [[ $git_dirty = "*" ]]; then local git_color=$git_dirty_color; else local git_color=$git_clean_color; fi
local PS1R=`__git_ps1 "%s"`$git_dirty
# the third part of the prompt, i.e., the separator consisting of hyphens
local PS1SEP=""
while [ $(echo ${#PS1U}+${#PS1SEP}+${#PS1WD}+${#PS1R}+3 | bc) -lt $COLUMNS ]; do
PS1SEP=$PS1SEP-
done
# putting it all together
printf "\n\033[1;32m%s \033[1;34m%s \033[0;36m%s $git_color%s" "$PS1U" "$PS1WD" "$PS1SEP" "$PS1R"
}
PROMPT_COMMAND=print_pre_prompt
</pre><br />
Rather than explaining the code (which I'm not very clear about myself), I'll point you to some links which helped me along the way:<br />
1. <a href="https://wiki.archlinux.org/index.php/Color_Bash_Prompt">https://wiki.archlinux.org/index.php/Color_Bash_Prompt</a><br />
2. <a href="http://superuser.com/questions/187455/right-align-part-of-prompt">http://superuser.com/questions/187455/right-align-part-of-prompt</a><br />
3. <a href="https://gist.github.com/306785/4da3e39fc012475140fdf33ef0f6bc0a6e7c04a5">https://gist.github.com/306785/4da3e39fc012475140fdf33ef0f6bc0a6e7c04a5</a><br />
<br />
-----<br />
Liked this article? How about following <a href="http://twitter.com/#!/vickychijwani">me</a> or <a href="http://twitter.com/#!/rajatkhanduja">Rajat</a> on Twitter?</div></div>Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com1tag:blogger.com,1999:blog-6516027489520867993.post-68719280767540828392011-07-15T00:50:00.000+05:302011-07-15T00:59:34.354+05:305 Cool Things in Git<span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif; font-size: large;"><u>Thing #1: Pretty coloured output</u></span><br />
<div><span class="Apple-style-span" style="font-family: inherit;">Command: <code>git config --global color.ui auto</code></span></div><div><span class="Apple-style-span" style="font-family: inherit;">This will make all output colour-coded. So now <code>git diff</code> and <code>git status</code> will show up in red-green awesomeness (<a href="http://theswirlingpensieve.blogspot.com/2011/06/limited-edition-human.html">not that that's a great help to me</a>, but it will be to you, undoubtedly).</span></div><div><br />
</div><div><span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif; font-size: large;"><u>Thing #2: Aliases</u></span></div><div>Command: <code>git config --global alias.<i>shortcut</i> <i>command</i></code></div><div>The beloved time-savers. Here are some of my aliases:</div><div><code>git config --global alias.l log</code></div><div><code>git config --global alias.s status</code></div><div><span class="Apple-style-span" style="font-family: monospace;">git config --global alias.co checkout</span></div><div><br />
</div><div><u><span class="Apple-style-span" style="font-size: large;"><span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif;">Thing #3: </span><span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif;">Awesome-looking git log</span></span></u></div><div>Command: <code>git log --pretty=oneline --graph</code></div><div>Combine that with Thing #1, and you've got an ASCII-art style, rainbow-coloured, <code>git log</code>. And, if you have a <i>lot</i> of free time, or if you're just way too interested in git, you can read <code>man git-log</code>. There's ton of options in there.</div><div><br />
</div><div><span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif; font-size: large;"><u>Thing #4: A bucket-load of ways to refer to commits</u></span><br />
<div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;">Ok, first of all, branches are not branches. Yes, you read that right. A "branch" is actually just a reference to the latest commit in it. A commit's lineage defines its history, and so arises the idea of a "branch".</div><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div></div></div><div>You can refer to commits in many ways. Let's agree on some common notations before I explain that. Every commit can be referred to by a <i>commit pointer</i>. The commit pointer may be followed by any number of <i>modifiers</i>, which will together constitute another commit pointer. A commit pointer without any modifiers can have any one of the following forms:</div><div> a. the SHA key of the commit (the first 6-7 characters should suffice)</div><div> b. <code>HEAD</code> (refers to the latest commit in the current branch)</div><div> c. <code><i>branch_name</i></code> (refers to the latest commit in the branch specifed by <i>branch_name</i>)</div><div> d. <code><i>tag_name</i></code> (refers to the commit pointed to by the <a href="http://learn.github.com/p/tagging.html">tag</a> called <i>tag_name</i>)<br />
<br />
A modifier, on the other hand, can be either one of the following:<br />
a. <code>~<i>n</i></code> (refers to the <i>n</i>th ancestor of the commit pointed to by the commit pointer preceding it)<br />
b. <code>^</code> (refers to the parent of the commit pointed to by the commit pointer preceding it. If a commit has multiple parents, you can use <code>^<i>n</i></code> to refer to the <i>n</i>th one)<br />
<br />
We all learn by example, so let's consider a possible scenario. Say we have a git repository with 2 branches, <i>master</i> and <i>testing</i>. Say the master branch has 2 commits with SHA keys <code>0af4780...</code> (=<code>HEAD</code>) and <code>326399d...</code>, and say the testing branch has 3 commits. Say the current branch is testing. Here are some examples in the context of that scenario:<br />
a. <code>0af4780...</code> = <code>HEAD</code> = self explanatory<br />
b. <code>HEAD~1</code> = commit <code>326399d...</code><br />
c. <code>testing^^</code> = the oldest commit in the testing branch</div><div><br />
<span class="Apple-style-span" style="font-family: 'Trebuchet MS', sans-serif; font-size: large;"><u>Thing #5: Alternate usages</u></span><br />
In commands like <code>git diff</code>, which make sense for both commits <i>and</i> files, the commit pointers passed to them can be followed by <code>:<i>file_path</i></code>, if you wish to compare 2 past versions of a file instead of 2 whole commits. For example, say we have a file called <code>blah.c</code> in the <code>lib/</code> directory in our repository (which happens to be <i>huge</i>), and we want to see what changes were made to it between the second last and fourth last commits. We could do something like:<br />
<br />
<code>git diff HEAD~1:lib/blah.c HEAD~3:lib/blah.c</code><br />
<br />
Another interesting thing is <i>commit ranges</i>, which you can pass to commands like <code>git log</code> to see what has changed in that range of commits. They have the form <code><i>commit_pointer1..commit_pointer2</i></code>.<br />
<br />
If this got you interested, you really should read <a href="http://ftp.newartisans.com/pub/git.from.bottom.up.pdf">this <i>amazing</i> PDF</a> on the internals of git.</div><br />
----<br />
If you liked this article, why not extend your appreciation by following <a href="http://twitter.com/#!/vickychijwani">me</a> or <a href="http://twitter.com/#!/rajatkhanduja">Rajat</a> on Twitter?Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com4tag:blogger.com,1999:blog-6516027489520867993.post-61445760416916934322011-07-14T17:30:00.000+05:302011-07-14T17:38:43.699+05:30Sed - reducing effort since '74<a href="http://www.gnu.org/s/sed/">Sed</a>, short for '<a href="http://en.wikipedia.org/wiki/Sed">stream editor</a>', is a (pretty awesome) utility created by <a href="http://en.wikipedia.org/wiki/Lee_E._McMahon">Lee E. McMahon</a> of <a href="http://en.wikipedia.org/wiki/Bell_Labs">Bell Labs</a>. I would like to take a detour here and mention that I am in real awe of Bell labs. They have given us so much, starting from <a href="http://en.wikipedia.org/wiki/C_(programming_language)">C</a> and <a href="http://en.wikipedia.org/wiki/C%2B%2B">C++</a> to <a href="http://en.wikipedia.org/wiki/Unix">Unix</a> itself. Another useful utility (which I should cover here soon) made by them is <a href="http://cscope.sourceforge.net/">cscope</a>.<br />
<br />
Now, coming back to 'sed', it saved me quite some effort today while working with <a href="http://kate-editor.org/">Kate</a>. Well, frankly, the time it took me to learn some basic tricks and perfect the command might have taken a little longer than it would have taken me to manually make the change, but I won't add that time. Why ? Because the time invested would save me plenty more in the future, whereas doing the task manually wouldn't save me anything in the future.<br />
<br />
So what was this task ? As I have explained <a href="http://yetanothercomputermaniac.blogspot.com/2011/07/kates-variable-editor.html">here</a>, I am working on the modeline variable editor in Kate. The widget that my mentor and I had created, to be used in place of the '<a href="http://doc.qt.nokia.com/latest/qlineedit.html">QLineEdit</a>' , had some help text. I had forgotten to wrap the text in <a href="http://web.fe.up.pt/~jmcruz/etc/kde/kdeqt/kde3arch/kde-i18n-howto.html">i18n()</a> wrappers.<br />
<br />
The initial text was something like this :-<br />
<pre class="brush:c" style="text-align: justify;">item-> setHelpText(" Help text goes here ") ;
</pre>
<br />
Now had there been just two or three of such occurrences, I wouldn't have thought about using sed; but there were a lot more (I didn't check then, but as it turns out, about 40 changes were made using sed). Anyways, I needed the text to be modified to :-<br />
<br />
<pre class="brush:c" style="text-align: justify;">item->setHelpText(i18n(" Help text goes here"));
</pre>
<br />
With sed, that wasn't too hard.<br />
<br />
<pre class="brush:bash" style="text-align: justify;">sed 's:setHelpText(\"\([a-zA-Z0-9.() ]*\)\"):setHelpText(i18n(\"\1\")):g' <old >new
</pre>
<br />
Just one line and all the changes were made. And I had with me another patch to offer to the community ;-).<br />
<br />
Combined with <a href="http://www.regular-expressions.info/">Regular Expression (Regex)</a>, sed has a lot to offer.<br />
<br />
Suggested links :<br />
<br />
For more information on Internalization (i18n), check out the <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization">Wikipedia page</a>.<br />
For a tutorial on Sed, I would suggest <a href="http://www.grymoire.com/Unix/Sed.html#uh-0">this</a>.<br />
Online manual for Sed is available <a href="http://www.gnu.org/software/sed/manual/sed.html">here</a>.Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-74787955974934315262011-07-07T11:34:00.000+05:302011-07-07T22:53:07.053+05:30Kate's Variable EditorWell, as I have mentioned before, I am part of '<a href="http://blog.lydiapintscher.de/2011/04/25/announcing-season-of-kde-2011/">Season of KDE</a>' this year and am working on <a href="http://www.kate-editor.org/">Kate</a>. My project statement is to create a '<a href="http://kate-editor.org/2006/02/09/kate-modelines/">Modeline</a> Editor'.<br />
<br />
Frankly speaking, modeline variables is a feature that I was unaware of before I read about this project. It is one of those subtle features that can make editing and formatting very easy. With just a line at the beginning (or end) of the file you can tell the editor things about tab-width, syntax-highlighting, background-color and what not.<br />
<br />
With a lot of assistance from my mentor, <a href="http://kate-editor.org/the-team/">Dominik Haumann</a>, we began working on the variable editor by creating a new 'widget'. For now, this remains independent of the rest of the Kate but once it is ready (which it almost is), we'd merge it.<br />
<br />
Some important lessons learnt during the process that I'd like to share :-<br />
<br />
<ol><li><u>Make use of version control</u> :- After spending about 24 hours on a part of the project, I e-mailed my mentor the new source code; only to learn that those very changes had already been made. So how did I miss it ? I thought I was smart enough to update my working copy in the beginning of those 24 hours, but not once during those working hours did I bother to check if some changes had been made. That was one valuable lesson. As <a href="http://www.blogger.com/profile/08331365805973688358"><span id="goog_1271531222"></span>Vicky<span id="goog_1271531223"></span></a> correctly pointed out though, there was a silver lining : I wrote some code that was written by a more experienced person as well; I had the opportunity to compare and learn. </li>
<li><u>Develop complex widgets separately</u> : As I mentioned above, the variable editor is being developed as a widget separately. It required a combination of combo-boxes to cater for boolean, integer, colors, fonts and other strings. The development of widget 'within' the editor would have made it harder. With only this segment to focus on, we can forget about the rest of the editor and develop and test the variable-editor. Here are some snapshots of the widget :-</li>
</ol><div><br />
</div><div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://1.bp.blogspot.com/-E7DzR46XJIY/ThVJlp-mWvI/AAAAAAAAAFM/vMGND3er5Kw/s1600/Screenshot.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="253" src="http://1.bp.blogspot.com/-E7DzR46XJIY/ThVJlp-mWvI/AAAAAAAAAFM/vMGND3er5Kw/s320/Screenshot.png" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Here you can see the combo-boxes for boolean and color values<br />
Spin box for integer</td></tr>
</tbody></table><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-3oieyfoqyGE/ThVJmfNQ_xI/AAAAAAAAAFQ/gVxvjbj8evM/s1600/Screenshot-1.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="252" src="http://4.bp.blogspot.com/-3oieyfoqyGE/ThVJmfNQ_xI/AAAAAAAAAFQ/gVxvjbj8evM/s320/Screenshot-1.png" style="cursor: move;" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">The color combo and the line-edit for string values.</td></tr>
</tbody></table><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-7cmE-w8k1jE/ThVJnSCHWGI/AAAAAAAAAFU/kMKwHPBRkE4/s1600/Screenshot-2.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="251" src="http://3.bp.blogspot.com/-7cmE-w8k1jE/ThVJnSCHWGI/AAAAAAAAAFU/kMKwHPBRkE4/s320/Screenshot-2.png" style="cursor: move;" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">The color combo-box (KColorCombo)</td></tr>
</tbody></table><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://2.bp.blogspot.com/-CbQMUH_oiFs/ThVJoEypKXI/AAAAAAAAAFY/BQ-w2uCnMfs/s1600/Screenshot-4.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="252" src="http://2.bp.blogspot.com/-CbQMUH_oiFs/ThVJoEypKXI/AAAAAAAAAFY/BQ-w2uCnMfs/s320/Screenshot-4.png" style="cursor: move;" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">The font combo-box (KFontCombo)</td></tr>
</tbody></table><div style="margin-bottom: 0px; margin-left: 0px; margin-right: 0px; margin-top: 0px;"><br />
</div><table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://1.bp.blogspot.com/-oBF713bOFDA/ThVJpBVdj5I/AAAAAAAAAFc/CcDm_11TDEg/s1600/Screenshot-5.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="251" src="http://1.bp.blogspot.com/-oBF713bOFDA/ThVJpBVdj5I/AAAAAAAAAFc/CcDm_11TDEg/s320/Screenshot-5.png" style="cursor: move;" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Yet another integer spin button and color-combo.</td></tr>
</tbody></table><div>Soon, this widget would be a part of the Kate text editor.</div><ol></ol></div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com1tag:blogger.com,1999:blog-6516027489520867993.post-89895104664724640062011-07-03T14:48:00.000+05:302011-07-08T16:24:48.135+05:30Beautiful code == poetry<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on"><div style="text-align: justify;">This post is long and a little on the non-technical side, but I think the implications <i>are</i> very relevant to the readers. You might be somewhat pissed that I'm not <a href="http://yetanothercomputermaniac.blogspot.com/2011/06/introduction-to-jquery.html">talking about how sweet jQuery is</a>, but here goes.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">How many of us programmers just drool over clean, self-documenting code? I do. I literally <i>strive</i> to have my code look like elegant poetry, so much so that I spend a good portion of my time refactoring. Some might call that over-the-top. I call it an eye for detail. I believe code is like literature; you have to write it in a way so that others (and more importantly a future you) can immediately understand what you mean without getting bogged down with pathetic, obscure syntax or poor style. After all, code is not meant to be "write-once". Moreover, a few years down the line, you want to be able to look back on your code and say, "Whoa. I used to write amazing code <i>even back then</i>".</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">I try to take extreme care about naming my functions in just the right way. So whenever I read it later on, I know exactly what it does. I won't say I'm very good at it, but I believe I'm getting better.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">The language syntax is crucial to how readable the code is. That is one thing <a href="http://www.ruby-lang.org/en/">Ruby</a> does well. Let's see a contrived example:</div><div style="text-align: justify;"><br />
</div><pre class="brush:ruby" style="text-align: justify;">a = [1, 2, 3] + [4, 5, 6] - [5] # = [1, 2, 3, 4, 6]
b = "blah"
return true if a.include? 4 and not b.empty?
</pre><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">Another thing Ruby is good at: <a href="http://en.wikipedia.org/wiki/Domain-specific_language">Domain Specific Languages</a> (DSLs). They're an attempt to make non-geeks write code to get stuff done easily. As an example, consider this: rocket scientists are good at space-talk, but bad at writing code. What if we could create a program which exposes an API that looks like rocket science? It doesn't get any cooler. The scientist doesn't need to know Ruby, only the API. He can think in terms of space shuttles and takeoff times and things like that. For example, a rocket science DSL in Ruby might allow a rocket scientist to write stuff like:</div><div style="text-align: justify;"><br />
</div><pre class="brush:ruby" style="text-align: justify;">shuttle.fill_tank 50 # tank up 50 liters
shuttle.launch_after 3 if shuttle.prepared? # 3... 2... 1... go!
</pre><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">You might say, "Wait a sec. Isn't that your regular object-oriented code?". Yes, but normally we create that <i>for ourselves</i>. A DSL's API is meant to be used <i>by the users</i> to write code.</div><div style="text-align: justify;"><br />
</div><div><div style="text-align: justify;">A related example comes to mind. The other day my friend and I were working on a DSL for access control in a web application, which controls what user gets to access what part of the application. The most important thing in a DSL, as you might've noticed, is the API. Everything else is secondary. We needed to name a function which would take a condition, and a result to be returned if the condition was met. We thought up names like <code>make_rule</code>, but we weren't satisfied. After some brainstorming, we came up with an API like this one:</div></div><div style="text-align: justify;"><br />
</div><pre class="brush:ruby" style="text-align: justify;">given :condition => user.admin?, :return => true</pre></div><div style="text-align: justify;"><br />
</div><div><div style="text-align: justify;">I feel the function name <code>given</code> is <i>the most important thing</i> in this API. It conveys the purpose unambiguously and reads like natural English. Any other name would've made it confusing or misleading. And remember again, some John Doe titled "Maintainer" at a company is going to be using this API directly, without being good at Ruby, that's why the nomenclature is so very important.<br />
<br />
If you're more of a JavaScript guy, you should check out <a href="http://jashkenas.github.com/coffee-script/">CoffeeScript</a>. It's "a little language that compiles into JavaScript", with and Ruby and <a href="http://python.org/">Python</a>-inspired syntax. Imagine being able to write stuff like the following and have it run as JavaScript:<br />
<br />
<pre class="brush:ruby" style="text-align: justify;">volume = 10 if band isnt SpinalTap
letTheWildRumpusBegin() unless answer is no</pre></div><div style="text-align: justify;"><br />
</div><div><div style="text-align: justify;">I've presented my (rather long) case. Let the comments fly.</div></div><div></div><div style="text-align: justify;"><br />
<b>UPDATE:</b> We're finally done with the access control DSL, and the API now looks like this:<br />
<br />
<pre class="brush:ruby" style="text-align: justify;">given :condition => { :controller.is => :admin, :action.not.in => [:create, :show] },
:return => true</pre><br />
isn't that beautiful? :)<br />
<br />
</div><div><div style="text-align: justify;">----</div></div><div><div style="text-align: justify;">If you like this article, consider following <a href="http://twitter.com/#!/vickychijwani">me</a> and <a href="http://twitter.com/#!/rajatkhanduja">Rajat</a> on Twitter.</div></div></div></div>Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-69618436111940669342011-06-30T01:17:00.000+05:302011-06-30T01:17:46.483+05:30APIs and OAuth<div dir="ltr" style="text-align: left;" trbidi="on"><a href="http://oauth.net/">OAuth</a> (or Open Authorization) has become the norm these days. What is it ? In simple terms, it is a protocol that allows developers and third-party applications to use data on a server without giving away the password of the served user.<br />
<br />
A little history about OAuth first ! Interestingly, as mentioned on <a href="http://en.wikipedia.org/wiki/OAuth">Wikipedia</a>, OAuth sprang from "<a href="http://www.twitter.com/">Twitter </a><a href="http://en.wikipedia.org/wiki/OpenID">OpenID</a> implementation". Soon, this turned into a project in which people from some well known organizations such as <a href="http://www.google.com/">Google</a> were involved. Eventually, the draft for OAuth Core 1.0 was released in October 2007 and the protocol was published in April 2010.<br />
<br />
So now where is this protocol used ? Pretty much every site that offers developers to access their data use this protocol. As Twitter and <a href="http://www.facebook.com/">Facebook</a> Applications become popular, so does this protocol.<br />
<br />
So how does it work ? The basic idea is simple (as is for most great inventions), the developer registers his application with the data provider. The provider then generates a "<u>Consumer key</u>" and a "<u>Consumer Secret key</u>". These two strings need to be a part of the request sent by the application to request any data or authentication. When the user, through the application, tries to access his data, a URL is created which allows the application to be '<u>authenticated</u>' by the user. Once the user accepts to authorize the application to access the data, a <u>PIN</u> (a string of numbers) is provided. Entering this PIN into the application allows the application to identify itself (along with the Consumer Key) and obtain an "<u>Access Token</u>". This access token (yet again a hashed string), is used by the application with each request. Obviously, this is just the basic idea of the protocol and a lot of numbers and parameters are introduced in order to make it more secure.<br />
<br />
So, why is it better ? Or rather I should first answer, what is it better than ? Earlier, most websites like Twitter used "<a href="http://en.wikipedia.org/wiki/Basic_access_authentication">Basic Access Authentication</a>". It required the user to give his username and password to the application for accessing its data. (Yeah, basic authentication was really basic ;-) ). So, why is OAuth better ? It is better for applications as :-<br />
<br />
<ul style="text-align: left;"><li>Applications need not maintain the username and password of the user, which is a responsibility of the application (or developer). </li>
<li>If the password is changed, the application would be rendered useless, unless it is reset in the settings.</li>
</ul>It is better for the users as :-<br />
<br />
<ul style="text-align: left;"><li>User is not required to give away his or her password.</li>
<li>List of the applications authorized to access the data is available on the website. This allows the user to revoke access, especially to applications which are no longer used.</li>
</ul>List of OAuth libraries for various languages can be obtained <a href="http://oauth.net/code/">here</a>.<br />
</div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-58256004665531681252011-06-27T02:02:00.000+05:302011-06-28T11:41:32.748+05:30An introduction to jQuery<div dir="ltr" style="text-align: left;" trbidi="on"><div style="text-align: justify;">This is my first attempt at a <i>technical</i> article, so please bear with me. Comments/feedback on the content and writing style are welcome :)</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">You've probably heard of JavaScript: the hacky, ugly language that drives most of the <a href="http://bellard.org/jslinux/">cool</a> <a href="http://www.jplayer.org/">stuff</a> <a href="http://safalra.com/web-design/javascript/mac-style-dock/demonstration.html">on</a> <a href="http://www.hotajax.org/slider-tabs/jquery/108-quicksand-jquery-plugin.html">the</a> <a href="http://adrianpelletier.com/sandbox/jquery_hover_nav/">web</a>. I whole-heartedly agree. Hell, the language itself has <a href="http://blog.rakeshpai.me/2008/10/understanding-eval-scope-spoiler-its.html">more inconsistencies than one can imagine</a>. There is no cross-browser standard implementation of JavaScript. Why then is it so popular?</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">I can't say I have the answer, but there is one crucial JavaScript library, in my opinion, that has contributed to its popularity significantly: <a href="http://jquery.com/">jQuery</a>. It is one the few code tools I'd say is "cute" (the others on my list, as of now, are <a href="http://www.ruby-lang.org/en/">Ruby</a> and <a href="http://www.python.org/">Python)</a>. Also one of the few things with <a href="http://docs.jquery.com/Main_Page">great documentation</a>.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">It's great at manipulating elements on a webpage, and at making cross-browser, pain-free <a href="http://en.wikipedia.org/wiki/Ajax_(programming)">AJAX</a> requests. Let's dive in and see some jQuery code:</div><div style="text-align: justify;"><br />
</div><pre class="brush:js; highlight:[3]" style="text-align: justify;">$(function() {
$("input#animator").toggle(function() {
$('div#foo.bar').slideUp('fast');
$(this).val('Show');
}, function() {
$('div#foo.bar').slideDown('fast');
$(this).val('Hide');
});
});
</pre><div style="text-align: justify;"><br />
<div class="bar" id="foo" style="background-color: red; height: 100px; width: 100px;"></div><input id="animator" type="button" value="Hide" /><br />
<script>
$(function() {
$("input#animator").toggle(function() {
$('div#foo.bar').slideUp('fast');
$(this).val('Show');
}, function() {
$('div#foo.bar').slideDown('fast');
$(this).val('Hide');
});
});
</script></div><div style="text-align: justify;">Believe it or not, the highlighted line is all the jQuery code needed to hide the <code><div></code> element with id <code>foo</code> and class <code>bar</code> with a quick sliding animation. The first part of that line (<code>'div#foo.bar'</code>) is called a <i><a href="http://api.jquery.com/category/selectors/">selector</a></i>. jQuery selectors are very similar to <a href="http://www.w3.org/TR/CSS21/selector.html">CSS selectors</a>. This is one of the many qualities of jQuery: it doesn't force you to learn new, obscure syntax if you're already into web development. The <code>$</code> is actually <a href="http://www.vfstech.com/?p=40"><i>the jQuery object</i></a> (yes, <code>$</code> is a valid JavaScript identifier); it creates a <i>wrapped set</i> out of <a href="http://en.wikipedia.org/wiki/Document_Object_Model">DOM elements</a>, which you can then manipulate using the extensive <a href="http://api.jquery.com/">API methods</a> (in this example, the <code>slideUp()</code> method is shown, which accepts 2 arguments: the duration of the animation, and an optional <a href="http://docs.jquery.com/Tutorials:How_jQuery_Works#Callback_and_Functions"><i>callback</i></a>). This is the basic idea of jQuery: manipulations on a wrapped set of DOM elements.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">There's also another interesting thing in jQuery: plugins. Like <a href="http://vickychijwani.github.com/jquery-notify-osd/">this one</a>, developed by me. If you're interested in the code, I've got it on <a href="http://github.com/vickychijwani/jquery-notify-osd/">GitHub</a>.</div><div style="text-align: justify;"><br />
</div><div style="text-align: justify;">I'll stop here. Anyway the world doesn't need yet another full-fledged jQuery tutorial. This article was just intended to get you interested in jQuery (and get me started writing on this blog). If you want to continue, you could start working your way through the docs, starting <a href="http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery">here</a>. And you might want to consider learning some JavaScript too. Sad as it is, you can't use jQuery solely. For that purpose, I'd recommend <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">this</a> great book.<br />
<br />
<b>UPDATE:</b> Interesting fact on the popularity of JavaScript: It accounts for <a href="https://github.com/languages">19% of all code on GitHub</a>, higher than any other language.<br />
<br />
------<br />
If you liked this post, consider following <a href="http://twitter.com/#!/vickychijwani">me</a> and <a href="http://twitter.com/#!/rajatkhanduja">Rajat</a> on Twitter.</div></div>Vickyhttp://www.blogger.com/profile/08331365805973688358noreply@blogger.com12tag:blogger.com,1999:blog-6516027489520867993.post-65258315652998907502011-06-07T15:56:00.000+05:302011-06-22T14:01:01.171+05:30Base conversion in BASH<div dir="ltr" style="text-align: left;" trbidi="on">As programmers, we often encounter numbers written in binary or hexadecimal format. Mostly it is written as the context is made easier. For example, a set of flags is better represented as binary than integer. Here's an example :-<br />
<pre class="brush:c">#define IS_TRUE 0b01 // same as 1
#define IS_FALSE 0b00 // same as 0
#define CONFIRM 0b10 // same as 2
#define DOUBTFUL 0b00 // same as 0
</pre>This example might not be very common, but this demonstrates the use of binary representation. These flags are useful at binary level to facilitate " bit-level AND " and various other operations.<br />
<br />
In such scenarios, it could get confusing as to what the number represents in integers. Many, here, would suggest creating a program in the language of your choice and using it for base conversion. So, here I explain how one can use BASH itself.<br />
<br />
BASH allows base conversion very easily. Fire up a terminal and try this :-<br />
<pre class="brush:bash">echo $((2#1010101))</pre>I assume, I needn't explain <code>$((<operation>))</code> is necessary for mathematical operations in BASH. The output of the above command is 85, which is the decimal value of the number "0b1010101".<br />
<br />
So here we have a simple base converter. Interestingly, the base conversion allows to convert from any base to decimal this easily :<br />
<code><br />
<base>#<number_in_base></code><br />
The above is sufficient to convert number given in any base to decimal value. Go ahead, try it out. </div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-55865923577843680702011-06-07T12:59:00.000+05:302011-06-07T12:59:41.677+05:30Mail in the future<div dir="ltr" style="text-align: left;" trbidi="on">Long time ago, I used a service for <a href="http://123greetings.com/">online greeting cards</a> and I loved a particular feature; it was the feature to schedule the delivery to a future date. I am not sure if other providers had this feature or not, but they surely didn't make it easy to find; and this made me love this service above all the others. Since then I have wondered how great it would be to able to schedule mails to be delivered in the future. <div><br />
</div><div>Starting from Birthdays and Anniversaries that I couldn't risk forgetting to serious reminders to myself or others, scheduling an email in the future would be a 'desirable' service. Imagine that you are working on a project and would like to personally mail the team each week to request for their progress. Now this would require time, even if you had to send a simple "What's the progress" message each Monday. It would be cumbersome as it would demand you to take out time from the numerous other tasks that you have to do. Won't it be easier, if on one weekend, you fix 4 such mails to be sent in the future on the appropriate dates and set a reminder for yourself to fix more for later (if the project is not over by then). Such a service would save you the effort, while still getting you the response.<br />
<br />
Another scenario where such a service seems useful to me is sending the 'last words' of a man to his kin. Very often, certain secrets die with people. Sometimes it is because of the fear or of the want of a better moment, that words just don't come out. In such a scenario, if a person could create a mail to be sent in the future once he/she is dead, to a few chosen recipients. Some wonder, at this point, how could the service know about his/her death ? Well, before the mail is sent (on the specified date by the sender), a confirmation mail could be send to the creator of the mail, giving him some time to react (cancel or reschedule). There are many such possibilities. </div><div><br />
</div><div>Determined to create such a feature for myself (and use by others), I set out on a domain search. Looking for ideas, I stumbled over 'existing' services that partly fulfill the goals, here are some of them : -</div><div><ul style="text-align: left;"><li><a href="http://www.futureme.org/">FutureMe</a> : This service was the first that I had seen (and brought back my childhood ideas about future mails). In terms of a <a href="https://www.facebook.com/apoorvaag">friend</a> , this is like a 'time-capsule'. </li>
<li><a href="http://futuremail.bensinclair.com/">FutureMail</a> : This service fulfills the 'reminder' aspect of my discussion. It allows one to send himself reminders at any particular time in the future.</li>
<li><a href="http://mylastemail.com/">MyLastEmail</a> : This service targets on the final email, mostly in case of death. Although, at the time of writing, the domain seems to have gone dead. </li>
<li><a href="http://www.lettermelater.com/">LetterMeLater</a> : This service combines most of the features as it allows you to send messages to both yourself and others at any time in the future. One of the attractive features about this is that you don't need to access the site to create a new message; using <a href="http://www.lettermelater.com/forum.php?id=2">this</a> feature, you can send a mail from your own email client to 'me@lettermelater.com' with a few details on the top, and ZOOP, you have scheduled a mail in the future. </li>
<li><a href="http://www.hitmelater.com/">HitMeLater</a> : As the website boasts, this is like creating a 'snooze' button for yourself; more like reminders.</li>
</ul><div>While these kind of services do solve most of the things that I have in mind, some aspects can't be achieved with one service itself. This motivates me to work on one of my own service to cater my own needs (and that could be used by others as well). </div><div><br />
</div><div>One of the things mentioned <a href="http://www.quickonlinetips.com/archives/2005/12/send-email-messages-in-future/">here</a> is note-worthy :-</div></div><blockquote>What if your (or the recipients) email address changes ? </blockquote>I believe that this is an acceptable risk. Although, I am convinced that the service provider should facilitate change of 'recipient-address' , 'sending date' or even 'cancellation' of a scheduled mail.<br />
<br />
What do you think about such a service ? If I start one, what would be 'your' requirements ?<br />
<blockquote> </blockquote></div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com1tag:blogger.com,1999:blog-6516027489520867993.post-66463524229038494272011-06-05T00:10:00.000+05:302011-06-05T00:10:04.563+05:30Software projects and 'grep'<div dir="ltr" style="text-align: left;" trbidi="on">It might sound as weird title, especially when I emphasize that by 'software project' I refer to absolutely 'any' project. After a few days of trying to understand the source code of a few projects (including Kate), I have come to realize that it is hard to understand the entire code at once.<br />
<br />
Realizing the impossibility of understanding the entire code-base (which could be well over a hundred thousand lines) I started trying other means. The first step was to identify the 'main' file. As I am working with C/C++, this file is easy to identify as it is the one containing the function :-<br />
<blockquote style="text-align: center;"><span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">int main (int argc, char *argv[] ) </span></blockquote><span class="Apple-style-span" style="font-family: inherit;">Knowing what I am looking for, this simple command (or a few variations) allow me to spot the file where it all begins :-</span><br />
<blockquote style="text-align: center;"><span class="Apple-style-span" style="font-family: 'Courier New', Courier, monospace;">grep "int main" * -R </span></blockquote><span class="Apple-style-span" style="font-family: inherit;">As should be clear, this would search the source code directory 'recursively' to find me the file with the keywords. At this point, I would like to highlight why it would be easy to maintain a program that called the 'first' function by the name 'main'. Whichever language it is written in, use of this convention can make it easier to maintain. </span><br />
<br />
Once the main file has been spotted, I proceed to find the functions in almost a similar fashion. This saves me the effort of going through pieces of code that are rarely (or at times never) used. I can follow the 'flow of program' more easily and I know which function lies where. As and when I proceed to understand the functions, I try to make certain notes about the functions, in the form of comments. These notes could be something describing the task of the function, or could point to some other piece of information, or at times hints for improving the function later.<br />
<br />
'grep' has proved very useful to me, and although I am not very good with RegEx (regular expressions), I now plan to get hold of them so as to be able to use them to spot what I want in combination with 'egrep'.<br />
<blockquote> </blockquote></div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-73582418566567339872011-06-04T16:26:00.001+05:302011-06-04T16:26:26.767+05:30Season of KDE (SoK)<div dir="ltr" style="text-align: left;" trbidi="on">Well, this is my first post regarding the Season of KDE 2011. On advice from the mentors, I have decided to put up my progress on the project on this blog. I realize this would be a good exercise, as over the years the single most important thing that I have learnt is that explaining difficult things to others, only makes my own understanding better.<br />
<br />
With that selfish motive hidden deep inside, I look forward to an exciting experience writing about my progress. Starting from the difficulties to the work-arounds, I plan to post about it all.<br />
<br />
Hope you enjoy reading it as much. </div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com1tag:blogger.com,1999:blog-6516027489520867993.post-39604815054019173562011-06-03T10:29:00.000+05:302011-06-03T10:31:18.121+05:30Definying variable names using macros<div dir="ltr" style="text-align: left;" trbidi="on">This is an interesting piece of information I came across while working on a project. Macros, provided by C, have always been something holding a lot of power. Today, I realized another powerful use of it.<br />
<br />
Here is the piece of code that I came across (something similar)<br />
<blockquote>#define SOME_FUNC(l,i) int l##_flag=i;</blockquote>Now this note is made for future reference. Here the most intriguing (and confusing) was the use of the two hashes '#'. I just guessed that it helps use the 'name' of the variable. For example, if I call it as<br />
<br />
<blockquote>SOME_FUNC(debug,3);</blockquote>Using the rules of macro, this would change to<br />
<blockquote>int debug_flag=3;</blockquote><br />
Now this is useful. A small test confirmed that this is exactly what was happening. Also, using the '--save-temps' attribute of 'gcc', I confirmed what I thought it was. <br />
<br />
This could be very useful for debugging, as in the above example. Also, this could help us create a general function for creating flags to be created later. It is worthwhile to note that it cannot be used in an 'actual function' (that is not in the form of a macro). This is for the reason that when a function is called, the name of the variable is 'lost', and what remains is either the address or the value of the variable. Unlike function calls, macro expansion can allow the use of the name of the variable. The same could be used to make more complex functions (through the macro expansions).<br />
<br />
NOTE: The above information is based on my own tests. I couldn't find any information on the net for the same and thought it was worthwhile making note of it. <br />
<blockquote></blockquote><blockquote></blockquote></div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-91926209494287546212011-03-08T00:50:00.000+05:302011-03-08T00:50:08.805+05:30Hacked (victimised)!! First experience<div dir="ltr" style="text-align: left;" trbidi="on">Today, I had my first experience as a victim of a intranet based attack. The attack was by a friend and hence nothing severe, but it came as an eye-opener. Here is what happened.<br />
<br />
<br />
<br />
The friend shared this image. This was being hosted from my own computer in one of the 2 folders that had access for all the users on the computer. <br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://lh3.googleusercontent.com/-X9M_FNn2I6M/TXUtr2E2PKI/AAAAAAAAACg/CUMuZS7o76M/s1600/191018_207413405939869_100000136334310_909743_6722144_o.jpg" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="179" src="https://lh3.googleusercontent.com/-X9M_FNn2I6M/TXUtr2E2PKI/AAAAAAAAACg/CUMuZS7o76M/s320/191018_207413405939869_100000136334310_909743_6722144_o.jpg" width="320" /></a></div>What I had missed out all this while was that my computer had a 'guest' user account made once for some work. The account had one of the most trivial passwords, 'guest123', and it wouldn't take anyone who knew the circumstances under which such an account was created to guess the password.<br />
<br />
Now, leaving such a door open and keeping it unchecked was probably the most foolish thing I've ever done. Here I'd like to commend my friend's skill at identifying the weak-spot and hitting it only hard enough to make me feel the pain and yet not bleed.<br />
<br />
But this experience does come as an eye-opener. Thanks once again, my friend.<br />
<br />
PS : By the way, the guest account was deleted SOON after this security bug was found and the necessary permissions (which seemed best) were allotted to the folder(s). Also, this suggests that I keep an eye on the traffic flowing through my APACHE server. </div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com2tag:blogger.com,1999:blog-6516027489520867993.post-36497601575852475452011-03-04T23:08:00.000+05:302011-06-05T00:18:25.430+05:30Bash script for Extracting text<div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" style="text-align: left;" trbidi="on">This is a script that I made today to solve a particular problem, but I do realise that many a times I, or anyone for that matter, would need to use something similar. For the same reason, I decided I'd share the script here.<br />
<br />
The script was made (as my IITG friends would understand) to extract a set of e-mail addresses from a text file that contained a lot more data. Basically, the file contained the information of each student (Roll no, name, email) in a single line with 'space' as the delimiter. Using this (space as delimiter) characteristic, I extracted the necessary information and dumped it in a file.<br />
<blockquote><br />
<code>while read line <br />
do<br />
line=${line##* }<br />
echo $line<br />
done<br />
</code></blockquote><br />
This script was sufficient to extract the necessary information. The next task was to dump the output into another file. (if the above was saved as script.sh)<br />
<br />
<blockquote><code> $ cat list| bash script.sh > list</code></blockquote><br />
This should have been sufficient, but in my case, I had to pass the 'list' file once again through the script.sh file to generate the desired result.<br />
<br />
Consequently, to create a list with commas, the following thing could be performed.<br />
<br />
<blockquote><code><br />
while read line<br />
do string=$string,$line<br />
done<br />
string=${string#,*}<br />
echo $string </code></blockquote></div><br />
This takes care of concatenating the strings with a comma in between consecutive elements.<br />
<br />
The above set of commands helped me create a list of over 580 e-mail addresses in less than 10 minutes (including the time taken to create the scripts), way faster than the manual method of 'copy-paste'. Note that I call it a manual method.<br />
<br />
I hope this tutorial sheds some light on the use and power of simple bash scripts to solve everyday problems and save a lot of time. Do revert in case of any doubts or confusions through comments.<br />
<br />
exit(0) // End of post</div>Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0tag:blogger.com,1999:blog-6516027489520867993.post-31284376692632944352010-12-24T04:20:00.000+05:302010-12-24T04:27:09.627+05:30Hello World!The title is nothing new for programmers; a simple yet effective of way of beginning a new language, a new experience. In exactly the same way, I shall begin this blog with the same 'Hello World' Post. Although I'm not new to blogging, but technical blogging is like a new language for me and hence the title seems apt.<br /><br />Being keenly interested in computers and technology, I've come across a lot of technical blogs and I <b>don't</b> assure the readers that this one will be anything like them. This blog will just be an attempt to share whatever interesting stuff I learn in the COMPUTER WORLD. It might have some tutorials, some basic information on topics, some interesting links; but in case you are looking for a serious technical blog, I think you should go somewhere else. This is a place where I'll learn by teaching and that's my motto. <br /><br />So .. once again ."HELLO WORLD"Anonymoushttp://www.blogger.com/profile/11686498963122639788noreply@blogger.com0