Ranged Switch Case C++

Ranges in C++ Switch Case block

Today, we will do something really stupid! Yes, I am talking about the ranged switch case support that is available in C++. In all the commercial/hobby source code that I have seen, implemented and used, rarely have I come across the ranged switch case use. Most of the code when in need of ranges inside a switch case start using multiple case cascading or (the more niche programmers) resorting to nested if..else blocks!
So much so that when I told one of my co-workers that we can use ranges in C++ switch case, he started laughing (hysterically if I may add). Taken aback, I wanted to see if I have learned stuff wrong. So here it is, just to brush up your basic cpp knowledge and fall in love with it again! Below is the code in ideone ready for you to take for a spin.

Just to make it plain simple, you can use ranges in your cpp switch case block. And you can do it using ” … ” without the block quotes as shown in the code snippet above. This is quite useful when you don’t want to pollute your code using nested if..else blocks. Switch case is simple, readable and maintainable. Of course, don’t forget your “breaks” :).

Send in your comments & Suggestions. Follow me on Twitter @wolverine2k and share the love by clicking the buttons below and posting this on your social networks.

Simple Downloader!

I come across this very nice site http://www.dwarkadheeshvastu.com/ which has a collection of excellent MP3s (Devotional Music). I congratulate the maintainer of that site for the excellent collection of texts/mp3s in multiple languages. So the site is more or less static with mp3s arranged inside folders starting from 000.mp3 to the .mp3. And you want to download them all.

Layman way is to keep right clicking on each link and do save as. But we are lazy programmers. We will just give our job to the computer to increment the URL and download the file for us. This can very simply be done in a bash script. Below is a snippet. I will not go into explaining all the details, just that the script takes in 3 parameters (start of the count, end of count and the absolute URL of the folder). Run the script and get all the mp3s that you need. One can extend the script to pass in the kind of file we are interested in (like mp3, pdf, etc.). But that is left as a user exercise. The folder path can be got by looking at the HTML code (in case you are wondering how I got it).

Example invocation to get the whole of Ram-Charit-Manas in Avdhi language:

./getRamayan.sh 0 195 http://parthtechsolutions.com/001-MData/Ram-Charit-Manas-Avdhi

Enjoy the code below. PS: Of course it is bash and it runs on Linux. Create a windows batch file and post it in comments.

 #!/bin/bash

i=$1
while [ $i -lt $2 ];
 do
 if [ $i -gt 99 ]; then
   wget -O "$i.mp3" "$3/$i.mp3"
 elif [ $i -lt 10 ]; then
   wget -O "00$i.mp3" "$3/00$i.mp3"
 elif [ $i -gt 9 ]; then
   wget -O "0$i.mp3" "$3/0$i.mp3"
 fi
 ((i+=1))
done

echo "Enjoy!"

Forgot your EXCEL Password?

Okay. It is a bit sneaky and I will not explain everything but if by any chance you are using Excel and are password protecting the sheets and if you forget what your password was, “You are dead… ;)”. NOT REALLY! Use the following VBA script to recover the password. No need to download any softwares. Just press Alt+F11, put in the code and run it. It will soon pop up a box with the actual password which you can use to unlock.

ENJOY!

PS: I found the code on the internet in one of the comments and have just copied it blatantly. I have used it and it works great.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ActiveSheet.ProtectContents = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

SSHFS on Linux & Windows

SSHFS does come into play when connecting to a remote client and/or working on a remote server. I am pretty sure most of you are aware of how to do this. But if not, the below can help a lot with your development using your favorite tools. The problem is that on the remote servers is either not having root access, or updated and latest software and/or most of our new age tools might not work as expected (eg: try to run atom on it or sublimeText). Also using NX is pain… You can of course run Linux or X-Server on windows and get native X-forwarding but losing the SSH session will invalidate your window and you might have data loss. Worst of all, such X-sessions are not restored (on windows).

So one idea is to use SSHFS on both your Linux and Windows client and load your $HOME directory as a shared drive on which you can operate. If you want to read more about it (http://www.linuxjournal.com/article/8904).

For Linux:
    – If you do not have sshfs installed, install it (sudo apt-get install sshfs)
    – sudo mkdir /mnt/ (create a mount point)
    – Mount your drive using: sudo sshfs -o allow_other @remote-server_ip:/home/ /mnt/

Of course, I assume that on your local linux machine you have sudo rights ;). Now you can do stuff on your /mnt/ and all the changes are reflected back on the main server (so no more copy creations for those who were doing it). You can mount as many folders from the remote server as needed and replicate that environment on your local machine and use your machine to build/compile/test, etc.

For Windows:
    – Download http://www.expandrive.com/download-expandrive/ or http://www.netdrive.net/download/download_click.html (both are similar)
    – Install and mount your Hercules repo as a drive on windows and operate on it.
    – Open source lovers can use dokany or tuissh GUI package 

Advantages:
    – No more NX problems
    – Use your favorite editors/analysis tools
    – No more copies of code.
    – FUN UNLIMITED

Hope it helps. ENJOY!

Angular2: Beyond the “Todo” list!

Angular2 is the latest buzz word in web programming and frankly speaking, I am in love with it. It seems to be the “Docker” for web! Well I am also in love with “Docker” and the good part is that both Angular2 and Docker do not mind me loving them at the same time ;). Jokes apart, I particularly like Angular2 because of the component concept and its inherent support for TypeScript (TS). Components truly allow for creation of re-usable web components since they also encapsulate the “view” aspect. Hence no more grappling / switching between a model/view/controller. Everything is inside a component. You use the component and you get an automatic binding with the needed controller and view. This takes re-usability to the next level. Also for someone like me whose background is systems programming, components can be seen as class object exposing certain methods/properties (i.e. basic encapsulation). Components also allows for extension (i.e. inheritance) and can be tested individually, so once confirmed working, they are always working without any external dependency. That said, there are quite a few tutorials out there which creates a basic ToDo app with Angular2 and yes, it is pretty cool. But when you try to make something useful out of what has been learned from the ToDo App, the details bog us down. In any case, #FreeCodeCamp (#FCC) project on Pomodoro Clock was my trigger to use Angular2. I have the project hosted on Plunker (Pomodoro Clock) which uses Angular2, TS and Semantic-UI. I am also a big fan of Jade so have used it a little bit in the index.html but using it inside a component template seems to be a bit awkward. Though we can do so, I have used normal HTML since the components are broken down and are quite simple. Pomodoro clock is basically a countdown timer which alternates between a session time and break time and increases productivity (Google it if you want to know more).

Enough talk, lets start with the code explanation. The first file in the plnrk is a config.js file. This file basically allows for using the typescript transpiler and tells our web application to use angular2 and rxjs. This file will be automatically generated with the right parameters if you select a new AngularJS->2.0.x(TS) project in Plnkr menu. So nothing interesting really. We skip it and go to the next index.jade file. This is the jade file that I am using i.e. it is the one which is compiled into html and rendered in the browser window and which also creates and loads the Angular2 application. The structure is pretty easy to know if you have done any jade programming. There is a title and then a bunch of scripts which are brought in for including jade, jade runtime, zone, reflect, transcript, semantic-ui, jquery (needed by semantic-ui) and rxjs. We also see our config.js being referenced and our ‘app’ imported. There is also a custom font that I generated from enjoycss.com which I am using across my #FCC projects with some very basic beautification css. Rest of the the file is self-explanatory, but look particularly at line 33.

app

That is exactly where our src/app.ts is getting called. But you say that app is in src directory, how does angular find it. Look into config.js which has a map which tells the system loader as to where to look for the ‘app’. Before I forget, we see div.ui.grid.container.centered on line 31 which is using the UI class from semantic-ui. I like that one too since it provides a host of components out of the box for use. But before we go to app.ts, lets look at the main.ts. This file is the one which bootstraps our App class i.e. its loads/initializes/starts our angular app. There is generally only one class that is bootstrapped (though I have played with multiples and it all seems to work. It can look as a bad design though so avoid it). Main.ts imports the bootstrap class from angualr2 and the app class from app.ts and bootstraps it. If there is an error, it is directly printed in the HTML.

Now we go to src/app.ts which imports Component class from Angular2 with break and session (which I have written) and observable from rxjs. The part to know about is @Component({…}). The selector in here defines the selector we should use inside our HTML to load the particular class. In our case, I have named it app but you can name it whatever you like and call it in the index.jade on line 33. We are not using any providers in this app. Then we have a template which shows our top level UI again using components from semantic-ui. Line 25-26 are the important ones which invokes our session and break components using the specified selector.

< session-length >
[sessionTime]="sessionTime" (changedSessionTime)="sessionTimeChanged($event)" [sessionDisabled]="inputDisabled"
< /session-length >
< break-length >
[breakTime]="breakTime" (changedBreakTime)="breakTimeChanged($event)" [breakDisabled]="inputDisabled"
< /break-length >

We are passing some input parameters and also waiting for an event which we expect to be generated from the component. Between, this code can be optimized to just use only one component instead of break & session but that we can do in the next post. For the template to work properly, we need to use Session and Break as directives to App component. Then we have the App class exported which has logic to update the progressbar as well as manipulate the parameters which are passed to the break & session classes. Before going into details here, lets look at the break.ts file. Basically, it is a simple component wrapping a number input defining the minimum and maximum values. The class Break expects breakTime and breakDisabled as input values. The field is disabled when the timer is ongoing. And then we have a valueChanged function which emits the value of the component as an output to whoever would like to know the value of the field. Since the initial value is given as an input, we do not need to emit the value in constructor. Note that we are using property binding in the template using []=””. More details on bindings are in the Angular2 documentation. This is a one-way binding. We also have a property(breakTime) and event(change) two-way binding. The session.ts is similar. So if we take the min and max as input values as well, and modify the emit output to include some kind of indication on the output object, we can just have one component instead of 2.

Now back to app.ts, we can see that we are using the semantic-ui progress bar. The weird part with this one is that one needs to call the progress() function to get the progress bar to move. Just passing a value will not work. Do note that I can access my UI components in the class by using $(“#”) and call the resulting methods/properties. This took quite a lot of time for me to figure out. Rest of the code is pure logic which I will not explain. Give your comments and see if you can progress from here. This sample code paves way for more complex applications by breaking it down into components as well as using classes, components, inputs, outputs and eventemitter.

HAPPY CODING!