Saturday, September 24, 2016

Apidocs for Rest in Node js

Hey guys, I know I am pretty late in creating the content but this sharing a worth .

So now for all of you I want to tell you that I started working in Node js from past 6 months and found it really interesting in the way it handles the stuff and ease by which new things gets created in Node.

Now a days the frameworks are getting created by keeping a motto in mind that the client feels very less friction in attaching it. So for that only the concept of REST is becoming very popular.

Since in case of REST you don't need that the client have to install any executable or generate any stubs (as in case of SOAP), to interact with your server. Its just a normal HTTP/HTTPS call on which you send your data and the result is sent to you either in the form of JSON or XML depending on the request.

Now one thing that really bothers for all developers is that how will you document your api so that the client have clear cut understanding how to call an api and what kind of data he will get back as the response. For documenting the REST apis number of libraries are there that gives you the functionality, out of which some of the names are :
  1. Swagger
  2. ApiDocs
Now there are many more but these 2 are mainly used in the Node js community.

Today we are mainly going to concentrate on ApiDocs although Swagger is more popular but when I wanted to do the documentation I felt ApiDocs much more easy to understand and maintain as compared to Swagger.

This is because the Swagger forces you to learn a whole new way of creating the documentation like you have to write the info of documentation in YAML language which in turn is translated in to JSON by the Swagger API and that JSON is then utilized to show the HTML view of the documentation.

So coming back to the ApiDocs, let me tell you the system works very simple. You create a rest layer in a folder named rest (most of the times, there is a rest folder where you write the code for routes).

So what you can do is that you write the normal comments in a special format that is given by ApiDocs and then ask ApiDocs plugin to generate the documentation by the help of the these comments to a specific folder.

The only draw back which I felt is not that important is that ApiDocs doesn't provide the demo caller functionality as in case of Swagger that means you can't test the call from the ApiDoc UI itself.

Lets start coding. :D 
  1. Okay so first of all you have to install the ApiDoc module. 
    • npm install --save apidoc
  2. Now this will install the apidoc in a local mode and believe me its more than sufficient although the documentation of ApiDoc say that you should have to install it globally but its ok to install in locally.
  3. Configure the ApiDoc. 
    • For this there are 2 modes either you can give a json file individually and then tell the ApiDoc to pick this json file of you can give the config in package.js file (the same file which is the npm file).
    • Config looks like :
      "apidoc": {
          "name": "Name",
          "version": "1.0.0",
          "description": "Name API's",
          "title": "Title",
          "url": "http://localhost:3555/api/1.0.0"
        }
    • The name shown in the UI in the top is Name, Version is 1.0.0, title as Title, and the base Url is http://localhost:3555/api/1.0.0
  4. You have to put the comments in a specific format like:
         /***
         * @apiDefine ServerError
         * @apiErrorExample 500:
         * HTTP/1.1 500 Server Error
         * {
         *      "statusCode": 500,
         *      "status": false,
         *      "message": "Internal Server Error.",
         *      "data" : "{Message with the Internal server error}"
         * }
         */
         /***
         * @api {get} /users/:userId Get Users
         * @apiName GetUserById
         * @apiGroup Users
         * @apiVersion 1.0.0
         *
         * @apiParam {String} userId Users unique ID.
         *
         * @apiSuccessExample {json} Success-Response:
         * HTTP/1.1 200 OK
         *
         * {
         *      "statusCode": 200,
         *      "status": true,
         *      "message": null,
         *      "data": {
         *          "_id": "{userId}",
         *          "userName": "{userName}",
         *          "addresses": {
         *              "user": [
         *                  {
         *                      "_id": "{addressId}",
         *                      "name": "{addressName}",
         *                      "addressLine1": "{addressLine1}",
         *                      "addressLine2": "{addressLine1}",
         *                      "street": "{street}",
         *                      "city": "{city}",
         *                      "country": "{countyCode}",
         *                      "pincode": "{pincode}"
         *                  }
         *              ]
         *          }
         *      }
         * }
         *
         * @apiUse ServerError
         */
         router.get("/:userId", function(request, response){
            //rest handler
        });
  5. Now after this if we have to generate the documentation.
    • base_directory_of_your_project/node_modules/.bin/apidoc -i folder_with_files_commented/ -o folder_to_get_output_to
    • -i -> Input Parameter
    • -o -> output parameter
Now this is just an example, that is self explanatory. 

The command in step 5 will generate the html files with the documentation on the basis of the special comments you have given to the rest layer.

FYI: In order to automate the building process you can use gulp tasks.

Hope you guys liked it, happy coding
:D

Friday, August 19, 2016

Dango - the dragon for the gifs and emoticons

Hello guys, I am back with a whole new app named Dango, here.

Now coming to the usage of this app, the app provides you the emoticons and gifs based on the word you type. The catch here is that it doesn't restricts you to use any specific keyboard, like the Google or Swiftkey, rather it actually reads the input of the user and then calls the server to get the list of GIFS or emoticons that matches the word.

Here are some of the snapshots :


Now some of the key features of this app is that it converts the gifs into MP4 if the app does not support GIF animation as in case of whatsapp.

The app automatically downloads the mp4 version of the gif and sends it to the contact you are chatting with.

Now coming to the setup of the app the app asks for Accessibility setting for itself. You can find accessibility setting in Settings->Accessibility.

Here is the snapshot:


After giving the permission we are set to go. Just open any app where you want to type and the Dango Assistant will be there with the suggestions of the emoticons and gifs. Also there is one more option in the dango app where you can blacklist the apps in which you don't want to get disturbed.

Hope you guys like the app and please subscribe, share, comment and like the my page as well as channel.

Happy coding :)

Friday, August 12, 2016

Terrrium, the Swiss knife of Series and Movies

Hey, all, I am back with new android app, that is too cool to be handled, and the name is Terrarium. 

Believe me guys its really a Swiss knife for Movies and Series.

This app is not available in Play store, so can install it by suppressing the setting for unknown sources installation and downloading the Terrarium app from the site, terrariumtv.com

Download the apk and install it.

Prerequisites to installation:
  • Allowing unknown sources to get installed in the mobile
    • For this please follow following.
      • Settings -> Security and FingerPrint ->Unknown Sources, this is with respect to One Plus 3 View
      • As soon as you want to enable them, android system will show you the warning about the stuff that this is not good and blah blah, ignore it and just enable it.


After the above condition is done, please open the apk that you downloaded before and install it by following the wizard.

And, ta da......the app is ready to use, and I can say its by far one of the most simple app I have ever used.
  • There are 2 sections of the app
    1. Series
    2. Movies
  • You can search in the specific section for a specific series/movies, bookmarks them and can browse them in future.
The app view is like this:


You can search the series/movies, bookmark them like:




Almost every series is available with all the seasons in here is the most important thing that you can even select the resolution in which you want to watch the episode with subtitles. Yes you heard it correct we can watch the seasons in our own preference of the resolution and that too without having hassle of finding the matched subtitles and all.

The app itself gives the option to download as well as stream the content directly without downloading the video.

All though you need the MX Player, to see the stream-able link because the app by default streams the content via MX Player.

I was pretty surprised the first time I have used the app. I can tell you guys that this app is too good to follow the series, and also a blessing for series lovers, who don't want to waste the time in collecting the seasons or viewing them as a stream-able content.

Go try it.

I hope you guys have liked the app.

:) 

Wednesday, July 20, 2016

Microsoft VScode, new beast in town

Javascript has emerged as a non serious language, a client side language that was meant for just validating the client side and showing the errors as and when required. But from past few years it is emerging more of a serious language and also is getting more and more advanced as well as more matured.

While competing with already available, settled and matured languages like Java, Php and .Net the requirement for an IDE is must. Also its becoming a prominent factor for the success of any language that how good the support of it is available via IDE.

I still remember my old college days when people say that coding in .Net is so much fun then in Java since in my college using any IDE for Java is strictly prohibited. In a way or the other it was pretty good since using the text editor to code gives you more insight view of the language. But yeah when the language roars over newbie, IDE is the only saviour.

Some of the things that I feel for an IDE to provide includes better RAM management, ease of use and one of the most important being light in nature both in case of speed and weight, :D.

If you have worked on the IDE's like Eclipse, Netbeans, Webstorm and .Net Visual Studio you might have faced the issue where your whole PC gets slows down and not able to even play a simple song in VLC.

For all those guys who don't need hell lot of features rather just needs an editor that gives you features of an advanced editor with very few but important features like plugin, github and last but not the least lint support. For all those Microsoft VsCode editor is like a blessing.

It has almost everything that you thinks of.

Some of the most promising features are:
  1. It is very small in size, just 30-35 mb
  2. It is light in nature
  3. It supports github by default
  4. Supports plugins
  5. It supports linting, tested javascript linting via a plugin called jshint, can be found here
  6. Last but not the least, and most imoprtant it is FREE, yes you heard it right it is free.
I have been using this IDE and really found it quite fascinating to work with.

Here is the view that you get when you first open the VsCode after installation.


The support to github comes by default.

One more feature which I really liked is the ability to create snippets, that means you can create short hands that on being used expands itself and saves your lot of time. 

Let me tell you how a basic snippet in case of Javascript can be created. Lets think you want to create a snippet for :
  • console.log(""); with the shorthand of cl
that means when you type cl and press enter, it will be expanded in to console.log("|"); and your cursor is being blinking at |

For this you have to follow: 
  1. open File->Preferences->User Snippets->Select Javascript
  2. It will open a file named javascript.json. Add the following into that file.
    {
       "Print to console" : {
          "prefix" : "cl",
          "body" : [
              "console.log('$1');"
          ],
          "description" : "Logs output to console"
       }
       //more snippets can be added here
    }
  3. In the above Json, 
    • Print to console -> name of the snippet
    • prefix -> shortcut
    • body -> by what prefix is going to be replaced with
    • $1 is the first position of the cursor after the snippet is expanded, you can keep as many pointers and the cursor will follow them via ENTER or TAB
  4. One more feature is that code snippet in VsCode supports the placeholders as well like in case of:
    {
       "Print to console" : {
          "prefix" : "hello",
          "body" : [
              "Hello ${name:Enter your name}.",
              "Goodbye ${name}!"
          ],
          "description" : "Logs output to console"
       }
       //more snippets can be added here
    }
    when we type hello and press enter it gets changed to:
  5. As soon as you start typing a string the place holder in line number 3 starts updating, these helps a lot while you have to do the same stuff again and again as in case of loop this might be useful like:
    {
       "For Loop": {
             "prefix": "for",
             "body": [
                 "for (var ${index} = 0; ${index} < ${array}.length; ${index}++) {",
                   "\tvar ${element} = ${array}[${index}];",
                   "\t$0",
                 "}"
             ],
             "description": "For Loop"
         }
    }
I hope you all liked this post do share comment like and subscribe, happy coding and keep smiling, thank you.
:)

Tuesday, July 19, 2016

Alias Creation in Linux

We all uses commands to do the stuff in any OS. We often face situations where we have to issue the same commands again and again in order to do the stuff.

For instance we might face the situation in which we have to come to a particular directory and have to issue the commands. Also there might be case that the command issued have to be keep running and because of which we have to open another terminal and have to issue other command but in the same directory in which the last command is issued.

For those type of things there is a trick of creating the alias in Linux OS.

Now before going forward let me explain you what does ALIAS means?
    In simple language, Alias is a shortcut to do some specific stuff.

Lets try to create one alias that takes you to the specific directory. For example, your working directory is ~/user/work. And you have to issue all the commands in this specific directory. In that you have to open a terminal and always have to issue a command that looks like this:
  • cd /home/user/work
For this we will create an alias named cdw (change directory to work, for instance).
  • Open the bashrc file for the user to whom you have to provide alias for.
    • vi ~/.bashrc
  • Come to insert mode and add the following line at the end of the file with following syntax.
    • press i to come to insert mode
    • Add following at the end:
      • alias cdw='cd /home/user/work'
  • Save and exit the vi editor.
    • press ESC, then :wq then ENTER 
  • Exit the terminal and reopen new terminal to get the new settings.
The commands used are self explanatory and tells that the name of the alias would be cdw which will redirect you to the /home/user/work directory.

Using above steps will create an alias and makes your life a bit easier.

Happy coding to you all.  :)

Tuesday, May 24, 2016

Getting MotoG active display without Root

Hey guys, I am starting a new series of introducing some of the very cool apps of Android.

Today I am going to review an app that will emulate MotoG Active Display feature. The app is ACDisplay.

Here are steps to install ACDisplay and make it look alike Active Display.
  1. Install it using the play store, link.
  2. After installation open it.

  3. Clicking the yellow mark will tell you what all permissions you have to give AcDisplay.


  4. Give all the permissions to it, namely Device Administrators and Notification Access.

      
  5. Device Administrators is required to lock the Device and Notification Access is required so that you can read all the notifications(although you can configure it, which Apps you don't need).
  6. You are almost done (yellow mark is also gone), after you give the permissions your basic setup is ready to use.
  7. Enable the global button on the top right hand corner.

  8. This will enable the app. Now lets change some config. 
  9. Settings will have 2 sections:
    1. Features
      1. LockScreen
        1. Go to this and enable it on the top right hand corner, this will make this as the lock screen
        2. Check Enable when no notifications if you want to show it irrespective of whether there are 0 notifications or more than that.
      2. Active Mode
        1. Go to this and enable it on top right hand corner, this will give you options for the behavior of the AcDisplay, wave to wake, disable on low battery etc.
    2. Settings
      1. Notifications
        1. This will give you the option what to do with the notification, like wake up or not on arrrival of new notification, to show always on notifications or not etc.
      2. Interface
        1. This will give you the option to use the desktop wallpaper as background for this lock screen, animation, colors etc.
      3. Apps
        1. This will be useful to blacklisting the app, that means app which you don't want to show the notifications for.
      4. More
        1. This gives you the option when to make this app active, only on charging or everytime, inactive hours (for which app will be in sleep), shortcuts like lower left hand shortcut, lower right hand shortcut etc.
  10. After then when you lock the device and wake it up, AcDisplay will spread its magic, but the main problem is that it just disappears if you press the home button, and comes to home screen, so in order to solve that we will pattern protect our phone via default locker. 
  11. For that go to Settings->Lock Screen->Screen Lock->Pattern and give the pattern, confirm it.
  12. Enable :
    1. Directly Show pattern view, 
    2. make pattern visible
    3. show pattern error
    4. show pattern dots
  13. Set automatically lock to immediately, enable power button instantly locks
  14. At last we will disable notifications in lock screen, since our notifications will come at AcDisplay, for that Settings->Notifications->When device is locked->Don't show notifications at all
  15. Now lock the screen, and whenever notification come, depending on the wake up setting of the AcDisplay, mobile will lighten up, and show the notification very similar to the Moto Active Display, tap the small icon and read the notification, tapping after selecting the notification will take you to the app itself, but before that you have to give correct pattern.

Notes:

  1. The AcDisplay best works with default lockscreen, do not use with other lock screens.
  2. Don't forget to set the pattern or pin or password lock for default lock since pressing the menu button bypasses the AcDisplay screen.
  3. It acts as a module of Xposed as well, which is an optional setting, you can enable it in Xposed Module, modules section, if your Xposed module is setup, that means both rooted and Xposed installed and configured.

Monday, May 16, 2016

Remove duplicates from sorted array.

There are a number of approaches when it comes to remove the duplicates, from the array. Here are some of them:

  1. Make a Set out of the array so that you have only the unique elements out of it, also considering the further point if you want to keep track of the order of the elements you can use LinkedHashSet that guarantees the uniqueness as well as order of the Collection.
  2. Next approach is bit granular and we traverse the array and keeps on pushing the pointers till I am getting the same element:
    1. Start with 2 pointers first marked at 0 (since it is an array, lets name it as f) and second marked at 1(lets name it as s).
    2. Keep incrementing the second pointer till the elements at ARRAY[f] and ARRAY[s] are equal.
    3. When above condition is false make ARRAY[f] = ARRAY[s] and increment both f and s since the position of f and s are traversed.
Coming to the implementation, here is the working code.

This is the code you can find the running code here.

import java.util.*;
import java.lang.*;
import java.io.*;
 
class Ideone
{
      public static int[] duplicatesRemoval(int[] input){
 
        int f = 0;
        int s = 1;
        //RETURN IF THE ARRAY LENGTH IS LESS THAN 2;
        if(input.length < 2){
            return input;
        }
        while(s < input.length){
            if(input[s] == input[f]){
                s++;//
            }else{
             /*
             **THIS PART CAN BE SHORTENED BY input[++f] = input[s++];
             */
             f++;//SINCE LAST POSITION IS 1 BACK TO CURRENT ONE
                input[f] = input[s];
                s++;//SINCE s POSITION IS ALREADY TRAVERSED SO INCREMENT IT
            }   
        }
        //reassigning to new array element
        int[] result = new int[f+1];
        for(int k=0; k<result.length; k++){
            result[k] = input[k];
        }
 
        return result;
    }
    public static void main(String a[]){
        int[] input = {2,3,6,6,8,9,10,10,10,12,12};
        int[] output = duplicatesRemoval(input);
        for(int i:output){
            System.out.print(i+" ");
        }
    }
}