The Sound Of Commits

Well, all I can say is that I’ve been busy. How busy you ask? Let this post answer it for you.

I had come across the Github API a while back and ever since I have been contemplating ways to use the data provided by the API in a meaningful way. After weeks of brain-wracking, I finally hit upon the idea that why not render the commits for a year long period as musical notes? If you have a Github account, you might have noticed in your “Repositories” tab there is a wonderful little visualizer that has blocks of varying green colorations, showing your Github activity over the past 1 year. Why not audiolize it?

So first things first, I head over to Github’s API docs. Now the beauty of Github’s API is that it to read user and public repository a.k.a. repo information, I don’t need to sign in. That enabled me to write the whole thing in client side Javascript and not worry about Cross Origin Resource Sharing (CORS) since the audiolization would be hosted on my website. This made my task much, much easier (and more hassle-free for the user). Some quick jQuery setup and custom wrappers to the AJAX calls had me pulling the data in a jiffy.

The next step was preparing the data, i.e. getting the commits from the last one year for a user across repos and grouping them by date. Github allowed me to limit the data returned to the past 1 year, but grouping it was still an issue. That is where moment.js comes in. This intuitive and feature-rich library gave me all that I needed to manipulate and compare the date-time signatures on each commit as well as taught me the standard for representing dates and times. Couple this with a few articles on Javascript promises and closures (Lisp throwback!!) and I have my data ready to be audiolized.

A small digression: For all my difficulty with JS and its weak-typing model, the fact that Lisp has inspired JS and that JS allows me to come from a functional programming school of thought, made my code really clean and easy to work with. I was strictly against creating a global variable to store and work on the final data in the JS file since side effects from functions could mess up the data and be really hard to track down and fix. Functional programming, which by design avoids side affects on your data, really helped me out and JS’ closures really sold me to the language.

Now for the music. Musical Instrument Digital Interface or MIDI is the de facto standard for rendering music and this is no different on the web. Here is where I found this amazing project called MIDI.js on, you guessed it, Github! I forked the repo so I had my own version to play around with, and after some digging around since the documentation was substandard, I had attached MIDI musical notes to my commit data.

After some quick HTML and CSS where I set up the web page, I finally published it to the web. Sharing with people via Facebook and Twitter helped get some good feedback on it. You can find it here. Be sure to try it out, especially if you have a Github account. Seeing all my Github activity rendered as music was a joy like no other and I was glad to be able to help others see that joy as well.

Let me play you a song of your commits. If you have any suggestions, do feel free to comment.



2 Month Notice

Well, technically it’s been more than 2 months since I joined my new workplace, but I guess it is high time I gave an update as to what I am up to.

As expected from working at one of the top tech companies in the world, there is a lot of work (and fun), but there is a great potential for learning as well. And man have I learned a lot!! In my first month here, I worked on a Windows 8 Modern UI app and understood the architecture of building a Modern app hands-on. Not only that, but I also had to integrate the app with a web service using Javascript (which, by the way, is my weakest programming language), and after a lot of fumbling in the dark, I can now bend JS to my absolute will (Evil laughter)!!

In my free time, I got together with a senior of mine, Prakhar Gupta, who works at the same company albeit in the Bangalore office, and quickly coded up a Windows Phone 8 app. The app basically acts as a birthday reminder for all those like me who are poor at remembering dates. Expect to see the app in the Windows Marketplace soon! Along the way, I have also been drawn to Cloud Computing, thanks to the amazing Windows Azure (they have tutorials on creating Android apps with an Azure back-end), and hope to soon gain certifications in Cloud Computing. This along with some other projects that I really can’t talk about (Non Disclosure Agreement, you see) have made my life coding bliss!!

Oh, and did I mention that I have also started development on the Leap Motion? Expect to see more on that and Kinect development in my next few posts. This is from a practical standpoint. From a knowledge standpoint, I am learning everyday. I have learned about good design and best practices while coding in C# and am also re-exploring functional programming with F#. SQL and database querying now seem to come more naturally than ever, and I have also started looking into query execution plans to further optimize my SQL code. I have also been trying to read up on the Common Language Runtime (CLR) which so far looks great with the way the CLR handles managed modules and the variety of support provided for different languages, but with all the work and coding going on, I am having a hard time actually removing time for myself to read more. Will have to stretch more on the reading front!

In the pipeline are some more apps (maybe on Android?) and reading papers and texts on NLP (for WishWasher) and Computer Vision (which is still my favoured field). I do seem to be loaded with work, but hopefully, I will keep inventing things and inspiring you to try new things. Keep an eye out for more on this domain.


Interesting C++ Notions

Hey there!

Been really busy with coding and projects these past few days so no updates. But I have learned a lot of cool new stuff which I now wish to share with you.

Let’s dive in: I am guessing you remember what a stringstream is? If you don’t, there is an old post that I have explaining its super-utility. Once you can get your head wrapped around it, one interesting thing to note is how to clear the stream. On careful scrutiny of the API, you find it has 2 methods, flush() and clear(), which you may think might get the job done. Well, turns out both are quite misleading. The flush() command is actually used to synchronize the stream buffer so that it writes any unwritten characters on the next opportunity it gets, and the clear() command is actually used to reset the flag bits associated with the stream. Thus, none of them achieve our basic objective of clearing the stream.

The answer is actually in the constructor. The str() method is the way to go. Simply call ss.str(“”) and ss.clear() to reset any fail bits (where ss is my stringstream variable), and there you have it.

Another neat trick is that of manipulator functions. We use endl when dealing with cin and cout. Turns out, you’ve been using a manipulator function all along. Other uses include printing decimals in scientific notations and changing the base of your output/input.

Probably the most useful of all the ideas here is the use of a comparator function in the sort function. The template of sort() is sort(start_iterator, end_iterator, comparator_func) and we don’t usually use this form simply because of the awesome overloaded capabilities of the sort() function. However, this form gives us greater control over our execution and I have personally used innumerable times.

The comparator function takes 2 parameters of the same type as the list to be sorted. We return true if the first parameter goes before the second and false otherwise. Thus, this allows us to define the comparison criteria for user types like classes and structs. 😀

A final trick that I would like to mention is the transform function. A handy tool for performing various transformative operations on lists, the most basic being changing the case of strings. This one needs some memory to remember the manipulator functions, but I am sure you can handle it.

Hope this helps you write more succinct, poignant code in the future.

Till then, eviva!

Project Euler 58 : The Ulam Spiral

Alrighty! Back to Project Euler after a really long time and the difference is pretty noticeable, both in PE as well as my thinking.

PE’s got a new interface and an awesome new badge system for would-be Eulerians. However the cooler thing is that I was able to solve a problem that initially gave me many a sleepless night.

Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.

37   36   35   34   33   32   31
38   17   16   15   14   13  30
39   18     5    4     3   12  29
40   19     6    1     2   11  28
41   20    7     8    9   10   27
42   21   22   23  24   25   26
43  44   45   46  47   48   49

It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?

Pretty harrowing at first glance, but the solution is really straightforward. 🙂

This spiral is nothing but the Ulam Spiral and it has some interesting properties. Notice the left-down diagonal has all squares? The square value is simply twice the spiral layer plus 1 squared. So the first layer i.e. 1 gives (2*1 + 1)^2 = 9. Then the other 4 values are obtained by subtracting the previous even number’s 3 multiples from the square.

E.g. Take 49. That is the square of 7, 6 is the even number before it. So to get the other diagonal elements, all I do is 49 – 6, = 43, 49 – 12 = 37 and 49 – 18 = 31. This simple pattern works all the time for every layer, feel free to check!

Now, the code to solve this is even simpler. C++ can do this, but finding the range of prime numbers is a big hassle and I couldn’t find a good enough upper bound to apply The Sieve without getting a Segmentation fault, and too large values just can’t be accommodated.

Thankfully, I learnt Python this last semester while doing the coursework of an online Robotics class by Prof. Thrun. So, I decided to write a terse program to achieve the solution. Here it is:

from math import *

def isprime(n):
    if n < 2:
        return False
    elif n == 2:
        return True
    for x in range(3, int(n**0.5)+1):
       if n % x == 0:
           return False

    return True;

def calculate():
    primes = 3
    count = 5
    layer = 1

    while float(primes)/count >= 0.1:
        layer += 1
        m = 2*layer + 1

        for i in range(4):
            if isprime(m*m - i*(m-1)):
                primes += 1
            count += 1

    return 2*layer + 1

print calculate()

So I hope you understand what I am trying to do. The code is short and sweet and pretty self-explanatory, except, for the sake of the while loop, I am starting from the first layer rather than the zeroth layer which only has 1.  Now I better get back to my other programs!


Crypto Cracking

Well, round 2 of InCTF 2012 was a blast! There was lots to do and considering that 2 of my team-mates had very limited internet access, I had to do quite a lot of heavy-lifting.

The challenges were fun and varied, ranging from Reverse-Engineering to Website Hacking. But the category that elicited the most interest from me was the Cryptography challenge. Having an old love affair with puzzles and ciphers, I got cracking.

Sadly, I do not have the questions with me as the 2nd round portal has been deactivated, however I can easily explain the concept to cracking them.

The premise was that you are a decoder in a top-secret intelligence agency that has an agent who has infiltrated a dangerous terrorist outfit. The agent’s job is to relay encrypted terrorist messages to you and our job is to decode the message and save the world.

In the first question a.k.a. the 1st transmission, we were given the encrypted message and our job was to find the location of the next meeting place of the Terrorist leaders. Well, you might’ve played this game in the newspapers that involves deciphering a message by substituting characters and looking for common words and patterns in order to figure out the cipher, that was the stratagem I applied. Finally on closer inspection, you realize the cipher is pretty simple:

“Each alphabetic character has been replaced by its numerical equivalent from the reverse alphabet, i.e. if a=1, b=2..z=26, then in the encrypted message you’ll have a=26,b=25..z=1.”

So all I had to do was write a program to manipulate the ASCII values such that whatever character I was reading, I would substitute it with 26-(ASCII value of character) and thus print out the complete legible message.

Question 1: CRACKED!

The second question was even easier than the first, on account of the hint mentioning that the agent had used a DVORAK keyboard to type the message. Simple patter recognition will tell you that all the Capital letters are conforming to the QWERTY keyboard whereas all lower-case characters have been typed using a DVORAK board but with a QWERTY board in mind. So it was simply a physical translation of keys. 🙂

Immediately fired up Wikipedia and got the layout of the DVORAK keyboard. This allowed me to do the translation in a matter of minutes. Ofcourse, I did not decipher the whole message, just the location of the next meeting.

Question 2: CRACKED! Feeling good.

Sadly, that is where the good feeling lasted till. The next two questions were supposedly easy, but since the cryptographical code was written in Python, I could not make heads or tails of what the code was doing. And since I had never worked on Python, I didn’t even have a clue as to how to run the darn code. 😛

Well, no issues. I did my part, with my team managing a rank of 16 in the 2nd round. Now looking forward to the 3rd round and some serious Flag-Capturing!!

Eviva! 😀

Semester V of Computer Science

Ah. Another semester gone by and another treasure trove of knowledge discovered and assimilated.
This was semester V and what a semester it was. We finally dove right into core Computer Science and Engineering with the following awesome sujects:

  • Algorithm Analysis and Design
  • Microprocessor Interfacing Techniques
  • Principles of Programming Languages
  • Computer Networks
  • Computer Graphics

Truly great subjects for a Computer Science major to undertake. So let’s dissect them and see what it meant to study these topics.

1. Principles Of Programming Languages
A subject which involves the study of various programming paradigms so that one understands what are the benefits of the multitude of features being introduced in Programming Languages on a daily basis, so that we can understand the motivation behind it as well as better use it in our program design. Sadly, marred by not-so-good teachers who decided they would teach us C++ and Prolog programming rather than cool concepts like the Liskov Substitution Principle.

2. Microprocessor Interfacing Techniques
A fundamental and challenging subject, it made us truly think about the Simplicity vs. Efficiency Model of programming. Learning about the underlying hardware that controls our machines and lets you see this text here, was simply great. Read about the PS3 Cell Broadband Engine after taking this course and found that I was really able to understand all the hardware jargon on the page. All in all, 8085 and 8086 coding was FUN!

3. Computer Networks
A genuine rote subject made interesting by the fervour and enthusiasm of the faculty, this subject stands as a fine example of how great education can be undertaken provided the teacher has the motivation for it. Initially not a fan of Computer Networks due to the mugging tendency of the subject, was thrilled to see how succinctly all the various protocols and their algorithms were presented in a manner that was perfectly logical. Doubts were effortlessly quelled and the various abstractions used just made the learning curve gentler. Coupled with some great laboratory sessions (the teacher actually wanted to do a lot more), this subject became one of my learning high-points this semester.

4. Computer Graphics
A subject with a bad reputation for having outdated curriculum, I took it because the faculty in charge of it was going to revamp the topics and introduce us to OpenGL. Started great, awesome practical submissions and fun classes. Got a little drab in the middle because of redundant topics like Matrices and Vector Geometry as these had already been taught in High-School Maths. In the end, it was a good introductory class to the magical world of Computer Graphics.

5. Algorithm Analysis and Design
Saved the best for the last. My favourite subject of the semester as it coupled pure Computer Science and Mathematics to form a foundation for Computing everywhere. I already had good algorithm skills thanks to all those hours poured in Project Euler and UVa Toolkit, but this course really cleared my head and gave me the tools to really understand just what the heck I was coming up with. Intuitive solutions were given names and ideas were presented as theorems. Various problem-solving approaches helped me understand how to better analyze and tackle problems and applications were given as much importance as the concepts themselves. Someone once famously sayed, “To be a great coder, you can either write codes for ten years or take a semester-worth course on Algorithms”. Guess I saved myself 9 years of pain. 😛

Thus, great semester, lots of nice topics, finally got some Computer Science and Engineering done. Let’s hope the new semester is as much enthralling as this one.