A Basic Command-Line Parser in C++

Most of the OpenCV programs that I have written so far require explicitly taking some input from the user as a command-line argument. For example, it is highly likely that a OpenCV program would require an image (or video) to operate upon and hence requires a path to that multimedia file as an input. Instead of having the user type in the path in response to a program-generated prompt after the code has begun it’s execution, it is much more orderly, compact and convenient to supply those parameters as command-line arguments and have the logic to parse the input parameters embedded in our code.

For this exact purpose, I wrote a small, minimalist command-line parser in C++ that works out-of-the box with OpenCV programs.

The functionality of the parser is bestowed upon by three functions which are described in detail:

  1. void setCommandOptions(vector<string>& args, int argc, char** argv)

    The parameters argc and argv the variables through which the command-line arguments are actually passed down into the main() function where argc is the number of strings (arguments) pointed to by argv. This function does the simple task of copying all the command-line arguments from argv into the vector of strings named args. The for loop starts from 1 nbecause, by default the first argument in argv (corresponding to the index 0 i.e. argv[0]) is the name of your executable. For example, if I run a C++ program by executing ./myprogram arg1 from the terminal, argv[0] points to “myprogram” whereas argv[1] would point to “arg1”.

  2. string getCommandOptions(const vector<string>& args, const string& opt)

    The primary aim of this function is to retrieve the arguments corresponding to the command-line option opt (the 2nd argument to the function). So, if the program was invoked using the command ./sample-code -image ~/Pictures/picture.jpg, then the function call getCommandOptions(args, “-image”) would return the string “~/Pictures/picture.jpg”. Note that “-image” is the option and “~/Pictures/picture.jpg” is the argument here. The implementation uses the find() function from the <algorithm> header to accomplish the task along with certain sanity checks as to whether the option opt exists or not and ensuring that there is a argument corresponding to the sought after option. That is, in cases like ./sample-code -image , a function invocation of the form getCommandOptions(args, “-image”) would return an empty string because of the absence of a argument with the “-image” option.

  3. bool doesCmdOptionExist(const vector<string>& args, const string& opt)

    A predicate to check whether the command line option opt exists in args.

The complete code can be viewed here.


The BookMyShow Fiasco

My batch-mates and I decided to catch Interstellar in Dehradun on the 14th of November. One of the things I hate about Roorkee is the absence of a good multiplex nearby. The nearest theater is Wave Cinemas in Bahadrabad, but that only screens Bollywood flicks. To satiate our appetite for the occasional Hollywood movies, we have to indulge ourselves in a 2 hour bus journey to Doon! So, here we are, a merry group of 7 friends, excited about the prospects of some Nolan powered intellectual orgasms! But, we got a little more than we bargained for. Little did I know, that 12 hours after we started off from Roorkee, I would be writing this angry email to BookMyShow, the contents of which I am reproducing in this blog post.


I had booked 7 tickets for Interstellar, 4:50 PM show on the 14th November (Booking ID : GLDD0000647080) at Glitz Cinemas, The City Junction Mall, Dehradun. I received an email as well as a S.M.S. confirmation for the same. We reached the venue (Glitz cinemas) to collect our tickets from the box office with sufficient time to spare (like the punctual and responsible people we are), only to realize that we were handed printed tickets to the movie “Kill Dill”. We immediately pointed out the mistake to the guys at the ticket counter and they cross-referenced, double checked, triple checked our Booking IDs and then called in the manager who cross referenced, double checked and triple checked our bookings again. All this while, we were waiting patiently for the correct set of tickets to be handed over to us. The manager then proceeded to inform us, to our utter dismay, that Glitz was not screening Interstellar at all. Naturally, we were heartbroken (talk of “Kill Dill”, huh)! After each of us had passed through the seven stages of grief, we ruled out watching Kill Dill. I think  you would agree that it would be utter blasphemy to replace Nolan with Aditya Chopra. No sir, not in this, or any of the parallel universes can this happen. Thankfully, the manager was co-operative and promptly returned the money for the 7 tickets (Rs. 1680/-) in cash and we were on our way.

FYI, we are residents of Roorkee which is more than 70 kms from Dehradun, a 2 hour bus journey on a road which is not really meant for F1 races, if you know what I mean. We wanted to see a movie on time travel, not spend the entirety of our time on travel. I have immense respect for you guys, but when such incidents happen with names like BookMyShow, it sort of makes you lose faith in the sanctity and authenticity of online transactions! I request to arrange for the reimbursement of the “Internet Handling Fees” amounting to Rs. 196.63/- when clearly all the “handling” of the predicament bestowed upon us by the “Internet” was done by us and the travel expenses amounting to Rs. 1120/-.  #RefundMyShow

Hoping to hear from you guys very soon!

Things did not sort themselves out after this though. There wasn’t any response form their side for about more than a week, after which I had to fire another angry email. But this time, they were prompt with their replies and within the next few days, I had received the reimbursement! What surprised me though was that such an incident could happen with someone like BookMyShow. This was not the first time that online transactions had deceived us and left us in an uncomfortable situation. About a year back, 4 of my friends had planned a trip to Shimla and we had made our hotel reservations through an online portal named Travelguru. Upon reaching our destination, we found, to our utter dismay that the hotel authorities failed to identify any association of theirs with Travelguru. Thankfully, mid-January was not the busiest time of the year for tourists in Shimla and we were able to find rooms in the same hotel. But, it did involve a lot of convincing, reprimanding, threatening – all of which left a bad taste in our mouths.

These two separate incidents have one very subtle implicit similarity between them. Both of them involve a broken connection between people and technology. Although Dehradun cannot be considered as rural or even semi-urban, but from my limited experiences with Glitz cinemas, the majority of the audience that it caters to still finds solace in the traditional and orthodox stand-in-a-queue-and-book tickets method. While the situation in Shimla on the technology front was even more dire. The hotel manager, at one point of time made his discontentment and qualms with online booking pretty evident by saying that the soft-copy of a PDF file does not count as a reservation. The metropolitan cities might have stood witnesses to the widespread infiltration of the world wide web and technology into all spheres of life, but when it comes to the slightly less urbanized cities (mind you, we do not need to go down to villages, as is clear from my examples), we still have a long way to go!

Google’s Project Loon and Zuckerberg’s noble initiative of bringing internet to the villages are all commendable, but what really is required is training. Training of those people who would be directly or indirectly affected by this advent of internet. We would be able to reap the fruits of benefit only when we are successfully able to alleviate man’s deep distrust for the unknown.

My Experiences with System Design Interview Questions

I faced system design questions  while interviewing for both Google and  Directi, co-incidentally during my final round of interview for both  companies. Personally, I feel that these questions make up for an  excellent measure to gauge a candidate’s knowledge and software  engineering skills. You should treat these problems as discussions and not as your conventional interview questions. In contrast to algorithmic problems which have a consistent and clear approach to a solution (or solutions), system design questions tend to be very open-ended. The interviewer may often consciously make room for ambiguities as a test of your design skills. From what I’ve learnt during my interview process, there are some points which you should keep in mind, while tackling system design problems.

Keep it simple, stupid (KISS)!

At the very outset, you should ensure that all the system requirements, design goals, optimization objectives are crystal clear before you proceed to brainstorm on possible solutions. As an example, suppose you are asked to design a minimalist text editor using appropriate data structures. A bad approach would be to straight-away start with advanced concepts such as tries. Agreed, tries are optimized for fast insertion and search, but you need to ask yourself, “Is that really required for a minimalist editor”. It is always a good idea to note down all the data structures you know and write the pros and cons of using each one of them in the problem domain at hand. This not only clears your thought process, but also ensures that you do  not over-complicate things. You will be surprised to know how many seemingly complicated systems can be implemented using data structures which are as simple and elegant as linked lists and stacks!

Divide and Conquer

The problem statements might seem overwhelming at first, but there is absolutely no need to panic. Design questions are supposed to do look intimidating! You are expected to break the problem into modules and tackle each one of them independently. The problems that are generally asked are such that they can be easily decomposed into such fragments and solving the individual sub-problems should be a matter of reducing them to a known algorithm. For example, if I am supposed to design a technique to compress log records (lossless compression), my approach would be to first decide on what kind of fields a log record might contain and then think about efficient ways of compressing each one of them. Date and time can be stored as seconds elapsed since the beginning of the year (assuming we are interested in logs that are not more than a year old, this should fit in a 32 bit integer), verbose error descriptions can be replaced by short error codes which are mapped to their respective descriptions on a separate hash map, and so on!

Think out loud

Another very important strategy is to always keep communicating with your interviewer. As stated earlier, system design questions do not have a 0-1 answer. Whatever solution you proffer, there is always scope for optimizations. In such a scenario, it is imperative to let your interviewer have a glimpse of your thought process. Though this advice is true in general for the entire spectrum of question formats, it holds special significance here. Following this has the added benefit of the fact that the interviewer would be able to correct you if you digress from the intended path and he may have some ideas that you can further build upon in your solution.

Knowledge is power

Since, the systems that you would be asked to design are most likely going to be a simplified prototype of a commercial  system, you might end up having to use some Machine Learning or Data Science in your solution. So, it’s a good idea to brush up on some common M.L. and N.L.P.  concepts before your interview! If you are asked to implement the “Did you mean” feature in Google search, in addition to everything else, it wouldn’t hurt you to know about how spelling correctors work (N.L.P.)!

P.S. : This was originally posted as a Quora answer to this thread.

Getting Started With OpenCV

I happened to mention at the end of my previous post that I had started tinkering around with OpenCV and C++ over the past few weeks. In this write-up, I plan to prep you through the on-boarding process of installing the OpenCV library and getting started with the bare-essential and ubiquitous “Hello OpenCV” C++ program.

Before I get started, some customary declarations are in order. This installation method has been tried and tested on my quad-core, 2.20 GHz Intel i3-2330M processor running Ubuntu 14.04.1 LTS (codename: trusty). Ubuntu’s latest release, 14.10 (Utopic Unicorn) ships with a new version of libav and unfortunately, OpenCV fails to build with the newer version!

The installation process for OpenCV is as simple as downloading and running a shell script.

Step 1: Download this shell script by typing in the following command from your terminal:

 wget https://raw.githubusercontent.com/samyak-268/dotfiles/master/opencv2_4_10.sh 

Step 2: Run the following command in from your terminal:

 chmod +x opencv2_4_10.sh 

The purpose of this command is to make your shell script executable. Alternatively, you could right-click on the file, click on Properties, go to the Permissions tab and check the box for “Allow executing file as program”.

Step 3: Run the script by typing


Running the script will install all dependencies, download and extract the ZIP containing the source files, compile and build the source code to generate all binaries in their proper directories within the repository.

That is pretty much it! After the success message is displayed on your terminal screen, you are all set to dive in! The next post will describe a basic “Hello OpenCV” C++ program that would test your OpenCV installation and also give you a glimpse of what is in store as we explore the C++ library in our subsequent posts!

Back With Some Vision

Just a few posts into the realm of blogging and I have demonstrated all the qualities of a terrible blogger! And that was partly due to the work pressures of the last semester and a busy summer in Mumbai which flew past me before I could take cognizance of what was happening around me! But, now I am back with all guns blazing and a well-charted plan to combat any future instances of writer’s block!

I am doing my Masters dissertation in the field of Computer Vision and under the guidance of Prof. R. Balasubramanian. Like some of my batch-mates, I had the option of continuing my research in the area where I worked during my 2 month internship i.e. Natural Language Processing. But, I went ahead with Vision because first, I wanted to step out of my comfort zone and try a completely new domain, second, the mathematics and Machine Learning that powers the most sophisticated Vision systems today intrigues me and third, my seniors had very strongly recommended Prof. Balasubramanian for any Image Processing/Computer Vision related guidance!

Over the last few months, I have done a fair amount of literature survey for my research work. I am currently working on the problem of emotion classification from facial expressions. What excites me about my work is the varied application domains where this problem may be applied to (robotics, helping people on the Autism spectrum, enhancing H.C.I.) and the fact that Vision offers a well-calibrated blend of theory and practical application.

Speaking of practical application, the last few weeks has also marked the beginning of, well, a lot of things! I started using OpenCV to write some cool Image Processing hacks. Everytime I tinker around with OpenCV and C++, I am amazed by the sheer power and abstraction that the library offers. The elegance with which OpenCV handles the most complex Image Processing tasks leaves you in awe! Over the next few posts, I hope to talk more about OpenCV and Vision, in general.

Quora – The Journey So Far

I woke up one morning and had a few minutes to kill before my 10 AM lecture. The one good thing about being in 4th year is that we don’t have those annoying 8 AM electives anymore. Even better, we have 9 AM classes just 2 days a week! So, in search of something to do to kill those few minutes, I decided to wake my laptop up from its slumber. I removed the heap of clothes piled up on my chair and made myself comfortable as the laptop groaned into operation (A malfunctioning fan makes my laptop sound like a car’s ignition. I swear I have even heard it change gears!).

Out of habit, I opened the 3 customary tabs in my browser – Quora, Facebook and Gmail (precisely in that order) and started the day by browsing through my notifications when this realisation hit me. Very soon (and I am pretty sure this will happen), 4 of my answers* will cross the 1k up-vote mark with the most popular one fetching 6k+ (and counting)! How does this make me feel? Happy, but not ecstatic. Most of my top content has either been a re-share of jokes or popular memes that I came across during my random walks over the internet. My speculation regarding the large chunk of votes that these answers have managed to garner is that I was the really lucky proverbial “early bird”. Almost all of the 4 answers were written when their respective questions were relatively new. From what I have observed since joining Quora, unless the question is sensational, it needs some time before it can gain visibility and attract some good answers that set it apart from its contemporaries (in most of the cases, it might also need some credit-fuelled promotions )! Fortunately for me, the threads started to gain followers after my content had been posted!

But, I believe there is much more to Quora than that. This thought had been drifting in-and-out of my mind for quite some time before I finally resolved (part of my New Year resolution for 2014) to stop sharing jokes and contribute more meaningful and insightful content. Content like this answer by Oliver Emberton is what invokes a feeling of deep respect and admiration for the answerer as well as the community as a whole. For the record, this held the honour of being the most up-voted answer on Quora for a long time before being overtaken by some other answer (whose link I’m unable to locate now)!

Thinking about all this also had me reminiscing about the time I joined Quora (a couple of years back) and how I have evolved over this period in terms of (a) the quality of my answers, (b) the breadth and depth of my writing and (c) the spectrum of topics that I write on. My first contribution to Quora was interestingly, not an answer, but a post.  Dated 26th July, 2012, it was a post on the (now, pretty well-known) board Death By Puns. I remember reading answers and posts for days, being awed by the amount of experience and knowledge users brought to the platform and never really having the courage to push some content from my side! It was probably a week after I first logged-in that I could muster enough courage to put up that one-liner!

Being a data geek, I couldn’t let go without some real statistics. Quora Stats to the rescue!


With a total of 14k up-votes spread across 76 answers and 38 posts (let’s leave the anonymous ones out of this!), it averages out to be roughly 123 up-votes per submission. Not bad at all! Although I am not really sure about the feasibility of such a metric because the distribution of up-votes over answers is terribly skewed. But, I have seen Quorans compare using this. Another point that I observed was that out of the 76 answers, there were 7 answers in total (that makes it roughly 9% of my answers) with no up-votes at all. I did a quick temporal analysis and came to the conclusion that the most of such answers (4 out of 7) came during the phase when I had just started contributing.

*<shameless plug-in>

  1. Which is the best joke about engineers that very few people have heard?
  2. What are some good math jokes?
  3. What’s the best life lesson you’ve ever learned from a fictional character?
  4. What is the funniest translation you have ever heard or read? (Just a few more to go 😉 )

</shameless plug-in>

Many of my friends have come up to me with different versions of the same question – “What keeps me motivated to continue contributing?” A lot of possible answers pop up in my mind – answering questions, helping people, love of writing, and a chance to interact with an awesome intellectual community. But, over time I come to realize that nothing can beat this –


The inexplicable fist pumping joy you experience when someone whom you idealize follows you back! This is what has always motivated me and this is what will keep me going!


I had this nagging doubt in my mind for quite some time now. My thoughts took concrete form when I happened to stumble upon this Quora question sometimes back! The question is pretty old, in fact (latest activity : 12th December, 2012). But thanks to some recent changes, my Quora feed is infused with archaic content like this one.

This particular question discusses the reasons for the inter-changeable use of the words “Recursion” and “Inception”. This is a typical illustration of the influence of pop-culture. You don’t really need to go down to “Wrecking Ball” to notice this impact, it gets involved with every sphere of our existence in even more subtle ways!
If you ask me, the non-programmer folks might not be that well-versed with using “recursion” in their everyday speech. As a natural consequence, they tend to drift towards using “inception” to refer to anything that is remotely self-referential!

Things started to roll when the “XYZ-ception” and “We must go deeper” memes began to surface. Someone comes up to me and says “We were supposed to have an extra class today because one of regular lectures got cancelled. But, today’s (extra-) class got cancelled as well.”. Somehow, “extra-classeption” was the only witty reply that came to my mind!

I might be getting carried away (by sarcasm!), but imagine if the current trend continues. We might leave behind a generation of programmers and who actually believe that recursion and inception mean the same! We might hear high-school kids say things like “Dude look at this code, a function within a function, that’s function-ception!” Umm, no sir! There’s a separate term for it!