Categories
interview

Sorting Objects in a Priority Queue

This is an implementation that shows you how to override the comparator to sort objects by a property in a Priority Queue. You can use Priority Queues in algorithms like Dijkstra’s and A* to remove the element with the least f(n) value in each iteration. Overriding the compare method can be used to sort ArrayLists (Dynamic Arrays in Java) with sort() method.

Comparator

package algos;
import java.util.Comparator;
import java.util.PriorityQueue;

class StringLengthComparator implements Comparator {
	@Override
	public int compare(Node x, Node y) {
		// Real code should
		// probably be more robust
		// You could also just return x.val- y.val,
		// which would be more efficient.
		if (x.val < y.val) { return -1; } if (x.val > y.val) {
			return 1;
		}
		return 0;
	}
}

class Node {
	String name;
	int val;

	public Node(String name, int val) {
		this.name = name;
		this.val = val;
	}
}

public class pqcls {
	public static void main(String[] args) {
		Comparator comparator = new StringLengthComparator();
		PriorityQueue queue = new PriorityQueue(10, comparator);
		Node n1 = new Node("Shiva", 2);
		Node n2 = new Node("John", 1);
		queue.add(n1);
		queue.add(n2);
		while (queue.size() != 0) {
			System.out.println(queue.remove().name);
		}
	}
}

Output:
John
Shiva

Lambda Functions

If you want to use a more shorter format you can use lambda functions

package algos;

import java.util.PriorityQueue;

public class pqcls {
 public static void main(String[] args)
 {
 PriorityQueue<Node> queue = 
 new PriorityQueue<Node>(10, (a,b)->a.val-b.val);
 Node n1 = new Node("Shiva", 2);
 Node n2 = new Node("John", 1);
 
 queue.add(n1);
 queue.add(n2);
 
 while (queue.size() != 0)
 {
 System.out.println(queue.remove().name);
 }
 }
 }

Output:
John
Shiva

Categories
interview

Generate All Subsets for a Set using Javascript

The total number of subsets for any given set of size ‘n’ is 2^n (nC0 + nC1 + nC2 + ….. + nCn). In the following program we use all the possible binary values between 0 (inclusive) and 2^n. In every number if it is 1 then the element is in the subset or else it is omitted.

 const generateSubsets = (inp) => {
    if (!Array.isArray(inp)) {
     return;
    }
    var n = inp.length;
    var allSubsets = [];

    for (var i = 0; i < (Math.pow(2, n)); i++) {
      var subset = [];
 
      for (var j = 0; j < n; j++) {
        if (i & (1 << j)) {
          subset.push(inp[j]);
        }
      }

      allSubsets.push(subset);
      } 

      return allSubsets;
 };

 console.log(generateSubsets([1, 2, 3]));
 // [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]

Demo

Method 2

 const generateSubsets = (inp) => {
   if (!Array.isArray(inp)) {
     return;
   }
   let subsets = [];

   for (const val of inp) {
     const tempSubsets = […subsets];

     for (const currSubset of tempSubsets) {
       subsets.push([…currSubset, val]);
     }

     subsets.push([val]);
   }

   subsets.push([]);
   return subsets;
 };

 console.log(generateSubsets([1, 2, 3]));
 // [[], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3], [0]]

Demo

Categories
interview

Convert Integer to Binary using Javascript

var test = 3;
var pow;
var str='';
for(var i=0; (test/Math.pow(2,i)) > 1; i++) {
 pow = i;
}

for (var j=pow; j>=0; j--) {
 if ( (test & (1<<j)) > 0) 
 str = str + '1';
 else
 str = str + '0';
}
console.log(str);
// logs the value 11 to console.

 

Demo

 

Categories
Uncategorized

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;
          });
});
Categories
Uncategorized

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('/');
 }
));
Categories
Uncategorized

How to use AngularJS Services

angularjs by googleThere are many ways in which one can use Angular Services in an Angular project. The following is a good example of a frequent use case for the angular factory. (Services can be implemented by either angular service or angular factory)

When we write a service, the main goal is to be make it modular and reusable. In the following service named ‘serviceModuleName’, we have added support for HTTP GET & POST calls. We are handling them using promises being returned. For this purpose we use the $q service in angular.

Define a Service

(function () {
    'use strict';
    angular.module('App').factory('serviceModuleName', function ($http, $q) {
        var httpDeferGet = function (url) {
            var deferred = $q.defer();
            $http.get(url)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

        var httpDeferPost = function (url, obj) {
            var deferred = $q.defer();
            $http.post(url, obj)
                .then(function successCallback(response) {
                    deferred.resolve(response.data);
                }, function errorCallback(response) {
                    deferred.reject(response.status);
                });
            return deferred.promise;
        };

   var getLaunch = function () {
    return httpDeferGet('www.example.com/test-get-endpoint');
    };

var postLaunch = function (obj) {
    return httpDeferPost('www.example.com/test-get-endpoint', obj);
};

return {
getLaunch: getLaunch,
postLaunch: postLaunch
}

});
})();

Injecting a Service into the Controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, serviceModuleName) {
 
});

Calling a Service from inside a Controller

Since a promise is being returned by the service we need to handle it with then, catch and finally blocks. ‘then’ returns the data, ‘catch’ catches the exception thrown and it can be handled here. Finally the ‘finally’ block of statements are executed regardless of success/failure.

$scope.callService = function(postObj) { 

 $scope.loading = true;
 
serviceModuleName.postLaunch(postObj) 
 
.then(function (data) { 
 $scope.returnedData = data; 
 }) 

 .catch(function (err) { 
 $scope.error = 'Sorry something went wrong! ' + err; 
 }) 

 .finally(function () { 
 $scope.loading = false; 
 }); 
 
};
Categories
Uncategorized

AngularJS 1.X ng-options

Using the predefined angularjs ng-options directive can be quite tricky at times. The following is a basic example of how to iterate through list of people. The value of the person that is chosen from the drop down list is store in $scope.chosenPerson and can be accessed with the same from the controller.
Example 1:


  

Output:
ng-options 1

Demo

Example 2: If you just want the value to be last name instead of the whole object  use this.


  

Output:
ng-options 1

Demo

To access a nested array and show it as part of the dropdown the following example demonstrates how to do that,

Example 3


  

Output

ng-options output2

Demo

In the above example if the countries and locations were 2 completely different objects, then a hashmap can be used to link those two objects by keys and values.

Categories
Uncategorized

Generate/Check valid JWTs using PHP

jwt

https://github.com/Shiva1029/token

Pull the latest code from the repository onto your web server with php 5.x+ pre-installed.

  1. Run index.php first to generate a JWT (JSON Web Token) token.
  2. Paste the JWT into the variable $jwt in check_token.php within 5 mins after generating it, to validate the JWT. The JWT expiration time is set to until 300 seconds after 10 initial seconds delay. If the JWT is validated after this time period, then you will get an error that states that the token is invalid as it is expired.
  3. The server side secret key can be regenerated using genSecret.php
    This value can be used  to replace the existing secret key in the config/config.php file.

This code uses the following composer libraries:
{
“require”: {
“firebase/php-jwt”: “dev-master”,
“zendframework/zend-config”: “~2.3”,
“zendframework/zend-http”: “~2.3”
}
}

Categories
Uncategorized

Samsung Fast Wireless Charging Stand for Samsung Galaxy S7 Edge

 

The Samsung  Fast Wireless Charging Stand comes in a Black Saphire color. It is very ideal for daily use, as you no longer need to charge your phone for long hours or need to plug in the cord to your phone while charging. You could use it at home, office and also in your car. The base of this charger has a sticky rubber finish, that stops the stand from easily being displaced.

This charger is compatible with the following Samsung devices.

Galaxy S7, Galaxy S7 edge, GS6 edge, GS6, GS6 edge+, Note5

It also charges most Qi-enabled devices. Fast charge only works when your phone is compatible. For example, my Samsung Galaxy S7 Edge works in Fast charging mode with this charger, as it has that feature built into the phone. At the bottom of the device you have a multi-colored LED indicator to depict the status of the charging. This wireless fast charger from Samsung works with a micro USB charger, which is included in the box with this purchase. This means that you get a spare wired fast charger for your phone.

It costs only 69.99$ + Taxes.

Buy here from Samsung. The shipping is free and it usually arrives in about 2-3 business days. I got mine from here, and fedex delivered it on time.

Categories
Uncategorized

New CPU installed press F1 to setup or F2 to load defaults – Fixed!

new cpu installed

Most of us are faced with this problem on booting after reconnecting/replacing few components on their Desktops. I had this issue and fixed it by unlatching the Processor and putting it back more firmly. This booting issue doesn’t appear after placing the Processor chip firmly into it’s position.