Category: Uncategorized

  • Merge 2 sorted Arrays Inplace (JavaScript)

    Time complexity: O(n)
    Here n represents the sum of the lengths of both the arrays.

    Code

    // Merge 2 sorted Arrays Inplace (JavaScript)
    
    var a = [1, 2, 3];
    var b = [4, 5];
    
    var sort = function(a, b) {
      var alen = a.length - 1;
      var blen = b.length - 1;
      var index = alen + blen + 1;
      while (blen >= 0) {
        if (a[alen] >= b[blen])
          a[index--] = a[alen--];
        else
          a[index--] = b[blen--];
        if (alen < 0) {
          while (blen >= 0) {
            a[index--] = b[blen--];
          }
          break;
        }
    // if (blen<0) a's contents are already in place, so we don't need to worry about them.
      }
      return a;
    }
    
    console.log(sort(a, b));
    

    Output

    [1,2,3,4,5]

    Demo

  • How to fix ng-if error in AngularJS

    The ng-if directive has it’s own scope, so if you have issues with why a certain component is added or removed from the DOM even though your condition is true. It is probably because you aren’t referring to the right property. So this is how that can be fixed easily by referring to the parent scope.

    Some content here...
  • User Registration Form using PHP 7.1.5

    github

    The first step would be to create a new MySQL database and then add a user with all privileges except GRANT. Now replace the values in the file db_connection.php with those.

    $link = new mysqli("localhost","user-name","user-password", "your-database-name");

    Now once you are done with this run the file createTables.php from the browser. You should see a success message. If not make sure you have entered the right credentials and that MySQL server is running.

    Now, if you don’t have a registration form UI (HTML5+js) then you can use postman from the chrome web store or any other testing tool.

    You can use the following JSON to post to userRegistration.php

    {
    "fname": "Shiva",
    "lname": "Charan",
    "email": "shiva007charan@yahoo.co.in",
    "gender": "m",
    "pwd": "Password"
    }

    This should give you a success message when executed once and you should see the row added to your database in your PhpMyAdmin. If executed more than once, then you will get a message “User already exists”.

    Note: Make sure that you have PHP 7.1.5 installed. This program works on HHVM as well.

  • How to Automate your Releases using only git & crontab?

    You can easily automate your code deployment using crontab and git.
    Lets assume you push your code to your remote PROD branch and a cronjob on prod keeps running or runs at a certain time checks if your branch is behind the remote or not and if it is, then it pulls code and restarts your application.

    To start off make sure you have both git and a git repository. If you do then you can skip to Automation, if not then start by installing git and initializing a git repository on your local. For Ubuntu, here is how,

    sudo apt-get update
    sudo apt-get install git
    cd /your-path-to-git
    sudo mkdir project
    cd project
    git init
    git remote add origin https://github.com/user/repo.git
    git pull origin
    git checkout -b branch-name
    git add *
    git commit -a -m "initial commit"
    git push origin branch-name
    

    Note: replace ‘https://github.com/user/repo.git’ with your HTTPS git repo URL.
    If you see an error that remote already exists then you can use the following to remove it and then add your new repository under the same name or you can add a new name

    git remote rm origin
    git remote add origin https://github.com/user/repo.git
    

                                                              or

    git remote add newremotename https://github.com/user/repo.git
    git remote add origin https://github.com/user/repo.git
    

    Automation

    Replace ‘/your-path-to-git/project’ with the path to your git project.
    replace ‘branch-name’ with the branch you want to automate.
    Save this in a file called automate.sh.

    cd /your-path-to-git/project
    
    git checkout -b branch-name
    git remote update
    
    UPSTREAM=${1:-'@{u}'}
    LOCAL=$(git rev-parse @)
    REMOTE=$(git rev-parse "$UPSTREAM")
    BASE=$(git merge-base @ "$UPSTREAM")
    
    if [ $LOCAL = $REMOTE ]; then
        echo "Up-to-date"
    elif [ $LOCAL = $BASE ]; then
        echo "Need to pull"
        sh pull_code.sh     
    fi
    

    Replace both the occurences of ‘branch-name’ with your required branch name and then save the code in a file named ‘pull_code.sh’ in the same directory as the ‘automate.sh’.

    git reset --hard origin/branch-name
    git pull branch-name

    If you run the file using the following command then it should check for changes in the remote branch and pull them. Make sure to change ‘branch-name’ to whatever branch name you are using.

    sudo sh automate.sh "remote/origin/branch-name"

    Make the two files executable by the user

    sudo chmod u+x *.sh
    

    Cronjob

    The next step would be to create a cronjob for this using crontab.
    Use the following command for that,

    crontab -e

    Then hit ‘i’ start editing using vi (Visual Editor – The default editor that comes with the UNIX operating system).

    # MAILTO="your-email@example.com"
    # This is a comment
    * * * * * /yourpath/automate.sh > /dev/null 2>&1
    

    You can add your email in the MAILTO parameter.  But this works only if  you don’t have logging set, here we have set all the output and standard error output to null, so it won’t work. For the email functionality to work, you need to have the mail server setup for this.

    To log all the output to a file, replace the job with the following.

    * * * * * /yourpath/automate.sh >> /var/log/cron.log 2>&1

    After adding the above code to your crontab, use the following to write changes and quit the vi.
    ‘ESC’ + ‘wq!’

    This job is set to run every minute. It should have already output some data into your logs. Just to be sure we can restart the cron service once after the changes are saved.

    sudo service crond restart
  • Handling Date objects in Javascript

    Handling date objects in javascript can be very tricky at times. Here are few tricky scenarios.

    Comparision with ‘===’

    When you compare two date objects that contain the exact same time stamp using ‘===’, then this will not be true as two objects can only be equal if they refer to the same object.

    var date1 = new Date('2017-05-19T01:56:09.218Z');
    var date2 = new Date('2017-05-19T01:56:09.218Z');
    
    if(date1===date2) 
       console.log('yes');
    else 
       console.log('no');
    

    Output

    no

    Demo

    The solution to this, is to convert this to some other format like date.getTime() or date.getISOString(), etc. Here is the example implementation of that.

    var date1 = new Date('2017-05-17T14:48:12.000Z');
    var date2 = new Date('2017-05-17T14:48:12.000Z');
    if (date1.toISOString() === date2.toISOString()) {
     console.log('yes');
    }

    Output

    yes
    

    Demo

    Copying a Date Object

    When you try to copy date objects like the following example, then both the variables refer to the same date objects and whatever changes you make on either of them reflects on the other, which is not the required outcome

    var date1 = new Date('2017-05-17T14:48:12.000Z');
    var date2 = date1;
    date1.setHours(5, 30, 0, 0);
    console.log(date2);
    console.log(date1);

    Output

    Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)
    Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)
    

    Demo

    To solve this we need to create a new Date object while assigning the date to a new variable.

    var date1 = new Date('2017-05-17T14:48:12.000Z');
    var date2 = new Date(date1);
    date1.setHours(5, 30, 0, 0);
    console.log(date2);
    console.log(date1);

    Output

    Wed May 17 2017 10:48:12 GMT-0400 (Eastern Daylight Time)
    Wed May 17 2017 05:30:00 GMT-0400 (Eastern Daylight Time)
    

    Demo

  • Sort javascript objects based on multiple properties

    When you want to sort javascript objects based on 2 properties,  you can use the following code. In this example here we have an array of people (objects) here. I want to sort them by first name and then by their last names. So, what I do in my compare function to get the required output is to sort them by their last names, only when their first names are equal.

    var people = [{
     "fname": "shiva",
     "lname": "kiran"
    }, {
     "fname": "aru",
     "lname": "wind"
    }, {
     "fname": "shiva",
     "lname": "charan"
    }];
    
    var compare = function(a, b) {
     var ret = a.fname.localeCompare(b.fname)
     if (ret === 0) {
     return a.lname.localeCompare(b.lname);
     }
     return ret;
    };
    
    people.sort(compare);
    console.log(people);

    Output

     [{
     "fname": "aru",
     "lname": "wind"
    }, {
     "fname": "shiva",
     "lname": "charan"
    },
    {
     "fname": "shiva",
     "lname": "kiran"
    }]
    

    Demo

    If you would like to use integers then, this example with ages would help. Here the people are sorted by first names and then by their ages.

    var people = [{
     "fname": "shiva",
     "lname": "kiran",
     "age": 20
    }, {
     "fname": "aru",
     "lname": "wind",
     "age": 21
    }, {
     "fname": "shiva",
     "lname": "charan",
     "age": 19
    }];
    
    var compare = function(a, b) {
     var ret = a.fname.localeCompare(b.fname)
     if (ret === 0) {
     return a.age - b.age;
     }
     return ret;
    };
    
    people.sort(compare);
    console.log(people);

    Output

    [{
     "fname": "aru",
     "lname": "wind"
     "age": 21
    }, {
     "fname": "shiva",
     "lname": "charan"
     "age": 19
    },
    {
     "fname": "shiva",
     "lname": "kiran",
     "age": 20
    }]
    

    Demo

    If you would like to sort objects in descending order (strings or integers), then just return the negative of the result.

    var people = [{
     "fname": "shiva",
     "lname": "kiran",
     "age": 20
    }, {
     "fname": "aru",
     "lname": "wind",
     "age": 21
    }, {
     "fname": "shiva",
     "lname": "charan",
     "age": 19
    }];
    
    var compare = function(a, b) {
     var ret = a.fname.localeCompare(b.fname)
     if (ret === 0) {
     return b.age - a.age;
     }
     return -1*ret;
    };
    
    people.sort(compare);
    console.log(people);
    

    Output

    [{
     "fname": "shiva",
     "lname": "kiran",
     "age": 20
    }, 
    {
     "fname": "shiva",
     "lname": "charan"
     "age": 19
    },
    {
     "fname": "aru",
     "lname": "wind"
     "age": 21
    }] 
    

    Demo

  • Download Files using only AngularJS 1.X

    We create a new Blob object using dummy data and then use it as an object URL in an anchor tag which is created dynamically. We don’t need to attach this element to the DOM (Document Object Model), so we simply trigger a click event on it, to begin downloading. The dummy data used here is a String Array. This code was tested using Chrome and AngularJS 1.6.
    Note: For this to work, blob must be added to your whitelist configuration in the angular app.

    angular.module('app', [])
    .config(['$compileProvider',
    function($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
    }
    ])

    Here is the complete example 1,

    angular.module('app', [])
    
    .config(['$compileProvider',
     function($compileProvider) {
     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
     }
    ])
    
    .controller('appController', function($scope, $window) {
    
     var data = [
     "This is a log number 1.",
     "This is a log number 2.",
     "This is a log number 3.",
     "This is a log number 4."
     ];
    
     var blob = new Blob([data.join('\r\n')], {
     type: 'text/plain'
     });
    
     var downloadLink = angular.element('<a></a>');
    
     var url = $window.URL || $window.webkitURL;
    
     downloadLink.attr('href', url.createObjectURL(blob));
    
     downloadLink.attr('download', 'logs_file_name');
    
     downloadLink[0].click();
    });

    Demo

    We can also output Javascript Objects in the form of JSON data.

    angular.module('app', [])
    
    .config(['$compileProvider',
      function($compileProvider) {
        $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|tel|file|blob):/);
      }
    ])
    
    .controller('appController', function($scope, $window) {
    
      var jsObj = {
        name: "Shiva",
        country: "US"
      };
    
      var blob = new Blob([angular.toJson(jsObj)], {
        type: 'text/json;charset=utf-8'
      });
    
      var downloadLink = angular.element('');
    
      var url = $window.URL || $window.webkitURL;
    
      downloadLink.attr('href', url.createObjectURL(blob));
    
      downloadLink.attr('download', 'logs_file_name.json');
    
      downloadLink[0].click();
    });
    

    Demo

  • Create a talking webapp in 5 mins

    Code

    
    
    

    This works only on the latest Chrome browsers.
    When you run this code, you need to allow the browser to use your microphone.
    Make sure you turn on your speaker volume, to listen to the response.

    Demo

    Improvements
    You can add more accents in speech recognition and audio output, you can also add in more specific speech processing to check the speech for synonyms of commands to be executed. For that purpose I recommend using words.bighugelabs.com as your API endpoint for the synonyms.

  • How to set $http timeout in AngularJs

    http://

    Global Timeout

    To set a global http timeout in angularjs, we need to use the following code, which takes time in milliseconds to override the default http timeout value.

    angular.module('myApp',[])
      .factory('timeoutHttpIntercept', function ($rootScope, $q) {
        return {
          'request': function(config) {
            config.timeout = 1 * 60 * 1000; 
                          // 1 minute or 60 seconds or 60,000 milliseconds
           return config; } 
          }; 
        });
    
    angular.module('myApp')
      .config(function($routeProvider) { $httpProvider.interceptors.push('timeoutHttpIntercept');  });
    

    Call specific Timeout

    To specifically set a custom timeout for a particular http call that you make, you can include it as part of the config object.

    var app = angular.module('myApp', []);
    app.controller('myCtrl',   function($scope, $http) {
    
    // 1 minute or 60 seconds or 60,000 milliseconds
    var config = {
              method : "GET",
              url : "https://www.example.com/post",
              timeout: 1 * 60 * 1000
         };
    
    $http(config)
            .then(
               function mySuccess(response) {
                $scope.myWelcome = response.data;
               },
               function myError(response)   {
                 $scope.myWelcome =   response.statusText;
             });
    });

                                                             or

    var app = angular.module('myApp', []);
    app.controller('myCtrl',   function($scope, $http) {
        
       $http({
              method : "GET",
              url : "https://www.example.com/post",
              timeout: 1 * 60 * 1000
          })
            .then(
                function mySuccess(response) {
                   $scope.myWelcome = response.data;
                },
                function myError(response)   {
                   $scope.myWelcome = response.statusText;
              });
    });
  • How to redirect passport to referrer after authentication

    How to redirect passport to referrer after authentication

    PassortJSPassportJS by default redirects to the homepage and not the referrer, after authentication. To achieve redirection to the referrer without installing any additional plugins, all that needs to be done is to store the referrer URL in session.redirectTo variable. This can be used to later redirect the user once the authentication is performed successfully. It does not matter whether the session is stored locally or remotely (scalable applications).

    Storing the referrer URL

    app.use(function (req, res, next) {
        if (req.user) {
            next();
        } else {
            session.redirectTo = req.url;
    
           // or   session.redirectTo = req.originalUrl;
           // if that doesn't work try this
           //     require('url').parse(req.url).path;
    
          res.redirect('/login');
        }
    });

    Redirecting to required URL after successful login

    // For 0Auth 2.0 Passport Strategy
    
    app.get('/auth/provider/callback',
     passport.authenticate('provider',
      { failureRedirect: '/login' }, 
      function(req, res) {
        // You can log the user to backend API logs and then upon success        
        //redirect to referrer
       
       if (session.redirectTo)
          res.redirect(session.redirectTo);
       else 
          res.redirect('/');
     }
    ));