Sunday, April 17, 2016

Installing gnome and enabling all windows in top bar

Ubuntu comes with the default launcher as Unity Launcher that looks like this:


Now this launcher is pretty but if you want the Gnome desktop you can continue or else press the (X) button :D .
  1. For installing the Gnome desktop, we first install tasksel, that is pretty useful in order to install many packages.
  2. For that go to Ubuntu Software Center and type tasksel
  3. Install the package and run using sudo tasksel 
  4. Pressing arrows you can navigate and pressing space bar can check/uncheck the package
  5. Go to Ubuntu Gnome desktop and press space bar to select it and pressing tab will take you to ok at the bottom.
  6. Press space bar being at OK
  7. Wait till the package is installed and after that restart the system using either command or either via UI.
  8. When you restart the system you will find out that now your desktop is changed to Gnome.
Now the problem with gnome (or feature) is that it only shows the active window in the top bar and not all the windows that are opened. In this pic although there are 3 windows opened but only one is showing in the top bar in left corner which is active one:

In order to do get all the windows we have to install the extension and enable it to work with GNOME desktop.

Extensions are very useful in extending the functionality of the Gnome desktop. 

The extension we need for showing all the opened windows in the top bar is YAWL, which you can get here
  1. sudo apt-get install gnome-common autoconf autogen automake intltool libglib2.0-dev
  2. cd /path/to/where/you/want/subdir/with/yawl
  3. git clone https://github.com/dbfin/gnome-shell-extension-yawl
  4. cd gnome-shell-extension-yawl
  5. ./install-extension yawl
Once this is done, this means that you have installed the extension but till now didn't enabled it. For enabling the extension we have to install the gnome-tweak-tool, which is capable of tweaking the settings of Gnome desktop. For installing gnome-tweak-tool use:
  1. sudo apt-get install unity-tweak-tool gnome-tweak-tool
Once this is done you can start it using sudo gnome-tweak-tool .
Go to extensions, scroll to Yawl and enable it once that is enabled you have all the windows and favorites available at the top bar


This will give you all the opened windows at the top bar including the favorites.

Also in some cases you might see the message that the extension is not compatible with shell version, this is because as the shell is updated their might be the chance that extension might not support that change in that cases we have to switch off the default feature of the gnome that checks for the compatibility of the extension by the command:

gsettings set org.gnome.shell disable-extension-version-validation "true"


Phew this was a pain in my case since I have actually searched a lot in order to all these things. Hope this helped you all :) .

Creating a node module and using it

As you all knows, Node is getting better day by day and also there is an option of using node modules that are generated by other developers and are available to use.

Also, there is no good in making a Node project without user defined modules or in other words I can say that there is not possible (all though you can create a single module project but that is of no use) to generate the project in which you do not create the modules.

So, going forward Node modules are just the way of exposing a functionality from a Node file so that you can use that in other functions. For instance you want to create a calculator in Node js and for that you have decided that there would be four different modules namely add, subtract, division and multiply so that you can control them very gracefully and also tracing bugs would be easy since there are individual modules so when the bug got traced you can easily go to specific module in order to debug it.

So in order to do that, follow the steps:
  1. lets create a folder named node-calculator, for that browse to your docs and create a new folder either through right click and new folder or from shell using
    $ mkdir node-calculator 
  2. Go inside the folder using cd node-calculator and create one more directory named my_modules using :
    $ mkdir my_modules
  3. Now our basic setup is ready so we will code the things.
  4. Let us first create a module named add. 
  5. For that we will create a directory inside my_modules named add
  6. We will create a file inside add folder named index.js with following contents:
    var addition = function(a,b){
      return a+b;
    }
    
    module.exports = {
      addition_two_numbers  : addition 
    }
  7. In this the function addition is pretty simple and in order to expose that function to be useful in other files we have exported it with the name, addition_two_numbers
  8. Now create a file in node_calculator directory named calc.js with following contents:
    var add_module = require("./my_modules/add");
    console.log("Add module ", add_module.addition_two_numbers(2,2));
    
  9. Similarly create other modules named div, sub and mul. 
  10. Now the tree node-calculator command to see the contents and you will see something like this :
For your information:
  1. Code is available here
  2. The output shown at step 10 is of the command tree node_calculator
  3. If you don't have the tree command you can get it by:
    apt-get install tree
  4. In order to run the file use the node filename.js .
So for us it would be node calc.js and you will get the answer 4.

Saturday, April 16, 2016

Wifi router speed issues and solutions

I have been working lately in my laptop (while connected to wifi) and suddenly the internet becomes very slow. I have tested the speed of internet using the www.speedtest.net. The result of speedtest was awesome and I thought it might be the case with my laptop since it is running from 2 days (not continuously, uses hibernates when need to stop working, ;) ) let us restart the machine and then will look again on the issue. But surprisingly the issue didn't solved, then I called the ISP provider call center and have scheduled a time for next day when their engineer might come and look in to the issue.

Okay, next day the engineer came and before saying anything he took my laptop and used some of the commands like:
  • ping google.com
  • ping youtube.com
to see that the net is working or not. He shown me the result saying sir there is no loss in the packets.

I was also confused how this is possible I am unable to play a single youtube video without buffering even when my internet speed package is 40 mbps plan which is pretty descent to run youtube videos in HD.

Then I started searching the internet that what is the issue and came to know that since Wifi is a machine that works in radio waves, there may be chances that other systems might be interfering in the signals of the router and so you might face some of the issues. The solutions are pretty simple and here are some of them what I got from internet.
  1. Don't place the router near to TV, Sound Systems, Microwaves or anything that is capable of creating the Radio waves and might be responsible to interfere in the signals of your router.
  2. Place the router somewhere at top, since it is tested that the signals never broadcast parallel to the position of router rather they actually circulate and go down after some distance so if you place the router at some where which is at more height than it might be the case that you can get better connectivity at the corners of your house.
  3. Check the interference of the signals with the help of an Android program named Wifi Analyser that analyses all the wifi signals in both the bands (2.4ghz, 5ghz) under all channels, and then decide which channel is best suited for your router to work properly. The output of the wifi analyser is somewhat looks like this:



    Now this is pretty confusing but let me give you a brief explanation that this is actually showing all the wifi signals that you are receiving in your area and all the channels under which the wifi routers are broadcasting their signals. Most of the wifi routers work at the auto mode of channels so this application tells you which signal is best for your router to work so that you can change the settings of your router from the settings page that you can get at  http://192.168.1.1
I actually did all these and the problem never gets solved. At last I came to know that the solution of these situations are either you gets shifted to places where there is less congestion that is next to impossible or you have to change your router, this means change the router and get the one that has high frequency meaning 5 ghz. Since my router works on 2.4 ghz and there are too many routers that are working in the same frequency I am getting the issues but if you change your router there are very chances that you might get the interference since very few people takes 5 ghz router. 

So for all of you, you can follow some of the above steps to get the problem solved or either get the new router with 5 ghz frequency, their might be the case that you can get the same problem in 5 ghz router as well but chances are very low.

Hope you guys enjoyed my info, sorry but there is no solution I got that worked for me, that's why I have given the solution which is not that feasible but its ok :)

Wednesday, April 6, 2016

Callback hell and promises


Callback? What the hell is callback? Well in a nutshell, call back means:

Now this is what just the English meaning of call back. This in turn means executing something when other thing is finished and this in turn is not something that keeps on waiting for the thing to finish, rather keeps on doing its other stuff and executes when the thing is finished on an event basis.

1. What is callback?

The statement above is a bit lengthy in a way to understand, but think of this that when you give exams in school you never waits for the result( although you do :D ), rather you start preparing for the next class and when the result arrives, go to school to collect it. So if we have to think this in a code manner it would look something like this:

giveExams(getResult(){
     //when results arrive
})


This pattern is very common in Javascript world. If you ever been worked with Javascript in client side ( or server side, since Node js made that possible ) you would have faced the situation when you have to get some data from the server without doing the full reload of the page using ajax call and then have to display the result on the page at some specific div or text area.

This can be done using callback in Javascript like this:

$.ajax({
     url : "", //where to hit

     type : "POST",//how to hit, POST, GET, DELETE, PUT
     data : {},//what to send
     success : function(resposne){//in case of success
          //this executes when call gets successful and we have the response in the response object of the function paramter
     },

     error : function(error){//in case of failure
          //this executes when call faces some error

     }
});


FYI : The call above uses Jquery framework to call the ajax function.

The function named success and error are nothing but the callbacks, since they are going to be called once the main call comes back either with the failure or with the success status.

2. What is callback hell?

The way callback is handled a pretty different then most of the other languages handle the stuff. For instance in Java:
public static void sleepAndPrint() throws Exception{
     System.out.println("I am before sleep");
     Thread.currentThread().sleep(2000);
     System.out.println("I am after sleep");
}

Calling the above function will provide you the output as:

I am before sleep. (There will be a pause of 2 seconds and then next statement occurs)
I an after sleep.

Now considering the same and making it in Javascript we have something like this:
function sleepAndPrint(){
     console.log("I am before timeout");
     setTimeout(function(){
          console.log("I am in timeout");
     }, 2000);
     console.log("I am after timeout");
}

Now when you run this you will get some thing like this:

I am before timeout.
I am after timeout.
I am in timeout.

If you see at the time of timeout function the code didn't stopped and keeps on executing so the statement that was inside the timeout block actually got executed after the whole program gets done.

This is good in a way that Javascript actually follows Non-Blocking I/O model, but it also creates a problem for those who wants to do the stuff in a sequential basis, like you want to get the data of a user from the database, that will contain the github id of the user from which you can query the github servers using the github api and get the avatar url of the user so that you can download it in a temporary folder. Now the above mentioned sequence is a straight forward one if we have to do it in Java like this:
public User getData(final int userId) {
     //this will be having the code to access the db layer and get the User model out of it
     return user;
}

public String getUserAvatarUrlFromUser(final int userId){
     User user = getData(userId);
     String avatarUrl = user.getAvatarUrl();
     return avatarUrl;
}

public Image getImageFromGihubForAvatarUrl(final int userId){
     String avatarUrl = getUserAvatarUrlFromUser(userId);
     Image image = github call to get the image of the avatar url just found;
     return image;
}
//Some where in the code
getImageFromGihubForAvatarUrl(1);

This will go on the way we have planned and the code when talking to database actually waits for the operation to complete and in the same way while talking to the github servers actually waits which makes our program to run in sequence and thus does not make any problem for us.

But in case of Javascript since the default behavior is different this sequence is not going to work properly.

So we have to do work like this, not exactly but something like this:
var getUserAvatarWithCallback = function(userId, callback){
  db.getUsers("userId", function(error, response){
    if(error){callback(error, null);}
    else{
      var userIdOfGh = response.user.githubId;
      github.search.users({ q : userIdOfGh }, function(err, res){
        if(err){ callback(err, null); }
        else{
          var avatarUrl = res.items[0].avatar_url;
          callback(null, avatarUrl);
        }
      });
    }
  })
};

Using this will be something like this:
getUserAvatarWithCallback("userIdToFind", function(error, response){
     if(error){console.error("Error", error);}
     else{
          console.log("Found the user, url is ", response);
     }
});

Now can you imagine how the indentation is going inward and inward since in order to do the stuff in a sequential manner we have to keep on making the calls inside the callbacks again and again, that makes the stuff pretty ugly. This is termed as the CALLBACK HELL or PYRAMID OF DOOM.

3. What is a Promise?

A Promise represents a proxy for a value not necessarily known when the promise is created. via Mozilla, here

Now if you go through the definition you find out it says that it is a proxy whose value is not known or available at the time of creation of the promise. So when we make promise we just code the way we do it in other languages.

Let us take an example of Promise using the above example only:
var getUserGithubIdFromDb = function(userId){
     return (new Promise(function(resolve, reject){
          db.getUsers(userId, function(error, response){
               if(error){reject(error);}//(A)
               else{
                    resolve(response.user.githubId);//(B)
               }
          });
     }));
};
var getAvatarUrlFromGithub = function(githubUserId){
     return(new Promise(function (resolve, reject) {        
          github.search.users({q: githubUserId}, function(error, response){
               if(error){reject(error);}
               else{
                    resolve(response.items[0].avatar_url);
               }
          });
     }));
};

The code above is going to be used as follows:
getUserGithubIdFromDb("userIdToFind")
     .then(function(response){//(D)
          getAvatarUrlFromGithub(response);
     })
     .catch(function(error){//(C)
          console.log("error", error);
     });

If you see this code is pretty maintainable and also is continuous in nature meaning it will be chained to more promises the way we did for 2 functions.

The main thing to note is that at equation (A) we called the reject(error), where reject is the parameter in the Promise constructor which will stop the further execution of the function and throw the error there itself which is going to be caught at (C), and if you are successful in your execution then you have to call resolve(response) [please see equation(B)], where response is passed as a parameter to equation (D), where we have passed it as a parameter to my further processing. This pattern is continuous in nature and you can chain as much promises as you want.


Tuesday, April 5, 2016

Installing Keepass with a plugin in Ubuntu

Today I want to tell you guys how can we install Keepass in Ubuntu.

Although this is pretty basic tutorial but I  have faced some of the issues while installing it in Ubuntu OS.
  1. Install Keepass using the Ubuntu Software Center
         For this just open the Ubuntu Software Center (USC), and type Keepass. Install it by giving the password and accepting the terms if you have been asked for it.
  2. Now since we are in Linux OS the plugins didn't worked by default. This is because the plugins comes with dll's which are not supported in Linux. 
  3. For the above point you have to install mono framework in Linux. For that go to terminal and type the following command:
         sudo apt-get install mono-complete
  4. Give the password and it will install the mono framework in Linux.
  5. Now the Keepass is up and the required frameworks are up too.
  6. So now download the respective keepass plugin, say KeepassHttp, so download its plgx file.
  7. Copy it to the directory where keepass.exe is there and restart the Keepass. 
This will start the keepass and also the plugin is installed. 

Thanks

Tuesday, March 22, 2016

Updating nodejs without downloading it from the Node Js Site

Hello friends, I have started working with node.js and have found that installing the node js in a Linux based machine is pretty simple.

These are the following steps that can be followed in order to install node.js directly in Ubuntu.
  1. To install Node.js, open a terminal and type
    sudo apt-get install nodejs
  2. Then install the node package manager, npm:
    sudo apt-get install npm
  3. Create a symbolic link to node, as some apps uses nodsjs as a command
    sudo ln -s /usr/bin/nodejs /usr/bin/node
In order to get the version of the node you can use:
  1. node -v
  2. nodejs -v
    Since you already created a symbolic link for nodejs command in step 3 of previous section.
And this installs the node js in your machine. The main thing with this is that the version which is installed at this moment can be outdated or might be old, since the commands fetches the Node js that is available at the repository of Ubuntu, which may not be updated one.

So in order to update the Node.js version to the latest and stable version, instead of downloading it from the Node js website and building it from the scratch we can actually use the NPM, the node package manager itself to update the node pretty easily. For this I have found a very exiting blog here, but I am giving the commands that are used in order to update the node.
  1. sudo npm cache clean -f
  2. sudo npm install -g n
  3. sudo n stable
These commands will actually hit the node js repository in order to get the latest package of Node from there.

Although this will update the node pretty easily but there might be the case that you might get the old version of the node, so in that case please restart the machine and you might get the correct version of node by typing the command :
  • node -v
Hope this post helped you.
Thanks.

Tuesday, March 15, 2016

What is order in terms of Big Oh notation and how they are calculated

Hello all, I have been working in this industry from past 4.5 years and have been asked about the complexity of the algorithm and order of complexity of the algorithm and always faces a hard time to answer that.

Although being a Masters of Computer Application, I always struggled to understand how these things are calculated and derived. (speaking the truth :D ).

So after going through studying a couple of days with the complexity I have finally got an idea how complexity is actually calculated and how it is derived from the program.

So lets start this.

Before moving forward I have to tell you some facts in regards to this complexity thing. Here they are:
  1. There are different ways of representing the complexity of the algorithm, Big Oh notation is one of them, Asymptotic Notation is another one.
  2. When you want to calculate the complexity of the algorithm the basic steps are considered to take the unit cycle to complete and thus is ignored in process. For example, a = b+c; is not going to be considered as a part of the complexity since in any CPU, it is considered to take 1 CPU cycle to complete itself.
  3. Most important, only loops are considered while actually deriving the order of complexity.
Now as we know the basic stuff of complexity, let us now jump in to the pool of complexity. :D

1. Let us start with a very basic example of adding 2 numbers.

public int fun(final int a, final int b){
     return a+b; --------- A
}

In this program the equation A is considered to be taking 1 CPU cycle and that's why the Order of complexity in case of this program is 0(1).

2. Now let us take another example of printing n numbers given by user.

public void fun(int n){
     for(int i=0; i<=n; i++){
          System.out.println((i+1));-------------B
     }
}

Now in this case, there is a loop and our main purpose of calculating the order is going to be entertained here.The equation B is considered to be the one that runs for n number of times where n is the number passed to the function. So the order would be O(n).

3. Now let us take an example of same loop but the increment is little changed.

public void fun(int n){
     for(int i=0; i<=n; i+=2){
          System.out.println((i+1));-------------C
     }
}

In this case the equation C is going to run for n/2 number of times, since the increment is going for +2 times meaning it is actually cutting out the total iterations in half, so in this case the order of the algorithm would be O(n/2).

4. Now lets change the conditional part to a different mode.

public void fun(int n){
     for(int i=0; i<=n^2; i+=2){
          System.out.println((i+1));-------------D
     }
}

In this case the equation D is going to run for n/2 number of times till n2 , since the increment is going for +2 times meaning it is actually cutting out the total iterations in half but running till n2, so in this case the order of the algorithm would be O(n2/2).

I hope I am making enough explanation of how the complexity is calculated. It will be more clear once you see more examples going forward.

5. So coming back to the complexity lets now take an example of 2 loops.

public void fun(int n){
     for(int i=0; i<=n; i++){
          for(int j=0;j<=n;j++){
               //-------------E
          }
     }
}

This equation E is the part where your logic is going to work. So in this case the outer loop of i will run for n number of times and for each iteration of i, the inner loop executes for n number of times. So if i want to draw a chart of number of iterations it would be:
i E executed
1 n
2 n
...n n

Now in this case, total number of times the equation E runs would be, n+n+n..n number of times, which is n*n, and so the order would be O(n2).

6. Now taking an example of 2 loops where 1 loop is dependent on other 1

public void fun(int n){
     for(int i=0; i<=n; i++){
          for(int j=0;j<=i;j++){
               //-------------F
          }
     }
}

In this case if you look closely the inner loop is dependent on the outer loop. So if I have to create a table that will give info regarding how many loops it might run :

i F executed
1 1
2 2
...n n

This means the equation F or in other words the inner loop is executing 1 + 2 + 3 + .... + n number of times which is an Arithmetic Progression or sum of n natural numbers, whose formula is [(n)*(n+1)] / 2 which on expansion will give [n2 + n ]/2. Now for mathematical students the order of an equation is the number of the highest derivative in a differential equation. 

So the order of this program is O(n2). 

You might ask why we just considered the n2 term and not the n in that (n2 + n)/2. The reason is that in case of large values of n , the part n is not going to make a much difference and when the order of any algorithm is calculated only the highest degree of the equation is taken into consideration.

7. Taking an example of loops with a condition when variable increments drastically

public void fun(int n){
     for(int i=0; i<=n; i=i*2){
               //-------------G
     }
}

This part is a bit tricky and please give some attention to it. I am going to give you the idea how the complexity in these types are calculated. So for every iteration i is going to get 2 times. So if I have to view the growth then the growth would be 2^k till i<=n is not achieved, where k is arbitrary constant till the condition is met. So if I have to show this mathematically it will be :

Mathematical Explanation for order
n = 2^k
Taking log both sides
log n = log 2 + log k
If log is taken in base 2, then RHS wold be 1 + log2 k

So the LHS would be log2 n and RHS would be constant and thus the order would of the above code would be log2n which in one way or the other says that if the increment is done in multiples, the order is going to be in terms of log, which says that the algorithm will be pretty efficient.

8. Taking an example of loops with a condition when variable increments drastically and the condition is in orders

public void fun(int n){
     for(int i=0; i<=n^2; i=i*2){
               //-------------H
     }
}

This case is pretty interesting to understand and I will leave that to you guys to think on that, but let me tell you the order in this. If you see the loop structure is same except the condition is going till n2. So for this case the order will n2log2n. This part is pretty confusing but think that the overall loops runs for the same amount till n2 is met so log2 remain same and it will incremented by n2 times.

9. Taking an example of loops where variable increments in powers

public void fun(int n){
     while(n>k){//k is any constant
          n = n1/2//in simple words square root of 2
     }
}

In this case the decrement is happening square root times for every iteration. This loop keeps on going and for 1st iteration n becomes 2n , for 2nd n becomes 4n , 3rd n becomes 8n and so on. Loop will go on till n^1/x reaches k as per the condition.So if I have to show this mathematically it will be :

Mathematical Explanation for order
n1/2x = k
Taking log both sides with base k
1/2x X logk n = 1
logk n = 2 x
Taking log both sides again with base 2
log2logkn = log2 2 + log2 x
log2logk n = 1 + some constant or in other words this is the order

This gives the order as log2logkn . This part is a bit tricky and therefore please give some attention to it.

Now coming to the end part I am going to summarize the things in a pretty simple manner and you guys can easily understand how the order of the algorithm is calculated.

Now let me tell you very basic rule that when the value increments the condition will always (most of the times) is less than in nature and vice versa. If you see our examples it is pretty evident that things move this way only. Also when the value decrements, the condition will be greater than in nature. So I am going to sum up the whole discussion in a table that will help you to understand the extraction of order for the algorithm.

I am going to make a table that have three columns, namely the increment part, decrement part and order it would project. So here it goes.

Summary of the order
Increment Decrement Order Would be
(n+x)(n-x)O(n/x)
(n*x)(n/x)O(logx n)
(nx)(n1/x)O(logxlog n)

This order will be multiplied by the end condition of the loop. So if the loop is going to run till n2, the order would be O(n2logxn). This case can be understand by point number 8.

Note: In most of the cases we never mention the bases since it is constant in nature and so does not going to effect in large values of n. So order is written as O(log log n).