Thursday, 29 December 2016

Real Time Currency Converter in AngularJS using Yahoo Finance API

index.html

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="invoice3.js"></script>
<script src="finance3.js"></script>

<div ng-app="invoice3" ng-controller="InvoiceController as invoice">

  <b>Invoice:</b>

  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required ><br><br>
  </div>

  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required ><br><br>
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>

  <div><br>
    <b>Total:</b>
    <span ng-repeat="c in invoice.currencies">
      {{invoice.total(c) | currency:c}} &nbsp;&nbsp;&nbsp;
    </span><br>

<span>&nbsp;&nbsp;{{invoice.CurrentDate | date:'dd/MM/yyyy hh:mm:ss a'}}</span>  </div>
</div>

invoice3.js

angular.module('invoice3', ['finance3'])
.controller('InvoiceController', ['currencyConverter', function InvoiceController(currencyConverter) {
  this.qty = 1;
  this.cost = 2;
  this.inCurr = 'EUR';
  this.currencies = currencyConverter.currencies;
  this.CurrentDate = new Date();

  this.total = function total(outCurr) {
    return currencyConverter.convert(this.qty * this.cost, this.inCurr, outCurr);
  };


}]);


finance2.js

angular.module('finance3', [])
.factory('currencyConverter', ['$http', function($http) {
  var YAHOO_FINANCE_URL_PATTERN =
        '//query.yahooapis.com/v1/public/yql?q=select * from ' +
        'yahoo.finance.xchange where pair in ("PAIRS")&format=json&' +
        'env=store://datatables.org/alltableswithkeys';
  var currencies = ['USD', 'EUR', 'CNY'];
  var usdToForeignRates = {};

  var convert = function(amount, inCurr, outCurr) {
    return amount * usdToForeignRates[outCurr] / usdToForeignRates[inCurr];
  };

  var refresh = function() {
    var url = YAHOO_FINANCE_URL_PATTERN.
               replace('PAIRS', 'USD' + currencies.join('","USD'));
    return $http.get(url).then(function(response) {
      var newUsdToForeignRates = {};
      angular.forEach(response.data.query.results.rate, function(rate) {
        var currency = rate.id.substring(3,6);
        newUsdToForeignRates[currency] = window.parseFloat(rate.Rate);
      });
      usdToForeignRates = newUsdToForeignRates;
    });
  };

  refresh();

  return {
    currencies: currencies,
    convert: convert
  };

}]);


Output:







Currency Converter in AngularJS


index.html

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="invoice1.js"></script>

<div ng-app="invoice1" ng-controller="InvoiceController as invoice">

  <b>Invoice:</b>

  <div>
    Quantity: <input type="number" min="0" ng-model="invoice.qty" required ><br><br>
  </div>

  <div>
    Costs: <input type="number" min="0" ng-model="invoice.cost" required ><br><br>
    <select ng-model="invoice.inCurr">
      <option ng-repeat="c in invoice.currencies">{{c}}</option>
    </select>
  </div>

  <div>
    <b>Total:</b>
    <span ng-repeat="c in invoice.currencies">
      {{invoice.total(c) | currency:c}} &nbsp;&nbsp;&nbsp;
    </span>

    <button class="btn" ng-click="invoice.pay()">Pay</button>
  </div>
</div>


invoice1.js

angular.module('invoice1', [])
.controller('InvoiceController', function InvoiceController() {
  this.qty = 0;
  this.cost = 0;
  this.inCurr = 'USD';
  this.currencies = ['USD', 'EUR', 'CNY'];
  this.usdToForeignRates = {
    USD: 1,
    EUR: 0.74,
    CNY: 6.09
  };

  this.total = function total(outCurr) {
    return this.convertCurrency(this.qty * this.cost, this.inCurr, outCurr);
  };
  this.convertCurrency = function convertCurrency(amount, inCurr, outCurr) {
    return amount * this.usdToForeignRates[outCurr] / this.usdToForeignRates[inCurr];
  };
  this.pay = function pay() {
    window.alert('Thanks!');
  };
});


Output:




Wednesday, 28 December 2016

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title> AngularJS | Welcome </title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

    <script>

        var myObj = {Name : 'Sagan', Comapny: "Apptivo Sollutions"};
        console.log(typeof myObj);
        console.log(myObj);
    </script>

 
</head>
<body>


<h3> Sample Code : (ng-controller) </h3>

<div ng-controller="LanguageCtrl">

    Select your Favourite Language:
    <button ng-click = "java()"> Java </button>
    <button ng-click= "cpp()"> C++ </button>
    <button ng-click= "python()"> Python </button>

    <p> You have Selected : {{getLanguage}} </p>

</div>

<script>

var app = angular.module("myApp",[]);
app.controller("LanguageCtrl",function($scope)
{

$scope.getLanguage = "None";

$scope.java = function()
{
$scope.getLanguage = "Java";
}

$scope.cpp = function()
{
$scope.getLanguage = "C++";
}

$scope.python = function()
{
$scope.getLanguage = "python";
}

});

</script>

<h3> Sample Code : (ng-init)</h3>

 <div ng-init= "myLanguage = [
        {name:'Java',extension:'.java'},
        {name:'JavaScript',extension:'.js'},
        {name:'Ruby',extension:'.rb'}]">
<p ng-repeat = "language in myLanguage">
Name : {{language.name}} <br>
Extension : {{language.extension}}

</p>

</div>

 <h3> Sample Code : (ng-init) with Expression </h3>

    <div> 10* 10 = {{10*10}}</div>

    <div ng-init=" number = 10"> {{number+10}}</div>


 <h3> Sample Code : (ng-init) with Expression and Bind </h3>

<div ng-init=" name = 'AngularJS'">

    <input type ="text" ng-model="name">
    <div> Hello {{name}}</div>

    <div ng-bind="name"></div>
    <div ng:bind="name"></div>
    <div x-ng-bind="name"></div>
    <div data-ng-bind="name"></div>
    <div data:ng:bind="name"></div>

 

<h3> Sample Code : Filters </h3>

<div> Upper Case Filter       :   {{ name | uppercase}}</div>

<div> Lower Case Filter       :   {{ name | lowercase}} </div>

<textarea ng-model="name"></tetxtarea>


</div>

</body>
</html>

Tuesday, 27 December 2016

Single Page Navigation App in AngularJS

index.html

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
<script src="app.js"></script>
  </head>
  <body>
    <script type="text/ng-template" id="pages/home.html">
      <h1>Home</h1>
      <h3>{{message}}</h3>
    </script>
    <script type="text/ng-template" id="pages/blog.html">
      <h1>Blog</h1>
      <h3>{{message}}</h3>
    </script>
    <script type="text/ng-template" id="pages/about.html">
      <h1>About</h1>
      <h3>{{message}}</h3>
    </script>

    <a href="#/">Home</a>
    <a href="#/blog">Blog</a>
    <a href="#/about">About</a>

    <div ng-view></div>

    <script src="app.js"></script>
  </body>
</html>


app.js

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider

  .when('/', {
    templateUrl : 'pages/home.html',
    controller  : 'HomeController'
  })

  .when('/blog', {
    templateUrl : 'pages/blog.html',
    controller  : 'BlogController'
  })

  .when('/about', {
    templateUrl : 'pages/about.html',
    controller  : 'AboutController'
  })

  .otherwise({redirectTo: '/'});
});

app.controller('HomeController', function($scope) {
  $scope.message = 'Hello from HomeController';
});

app.controller('BlogController', function($scope) {
  $scope.message = 'Hello from BlogController';
});

app.controller('AboutController', function($scope) {
  $scope.message = 'Hello from AboutController';
});

Wednesday, 21 December 2016

Garbage Collection in Java

In the Java programming language, dynamic allocation of objects is achieved using the new operator. An object once created uses some memory and the memory remains allocated till there are references for the use of the object.
When there are no references for an object, it is assumed to be no longer needed and the memory occupied by the object can be reclaimed. There is no explicit need to destroy an object as java handles the de-allocation automatically.
The technique that accomplishes this is known as Garbage Collection. Programs that do not de-allocate memory can eventually crash when there is no memory left in the system to allocate. These programs are said to have memory leaks
Garbage collection in java happens automatically during the lifetime of a java program, eliminating the need to de-allocate memory and avoiding memory leaks. 
In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically using free() function. This is where Java memory management leads. 


 All objects are created in Heap Section of memory. More on this in a later tutorial.
Step 1) Copy the following code into a editor
class Student
{
int a;
int b;

  public void setData(int c,int d)
  {
    a=c;
    b=d;
  }

  public void showData()
  {
    System.out.println("Value of a = "+a);
    System.out.println("Value of b = "+b);
  }
  public static void main(String args[])
{
    Student s1 = new Student();
    Student s2 = new Student();

    s1.setData(1,2);
    s2.setData(3,4);

    s1.showData();
    s2.showData();

    //Student s3;
    //s3=s2;
    //s3.showData();

    //s2=null;
    //s3.showData();

    //s3=null;
    //s3.showData();
  }
}

Step 2) Save, Compile and Run the code. As shown in the diagram , two objects and two reference variables are created.

Step 3) Uncomment line # 20,21,22. Save , compile & run the code.

Step 4) As show in diagram below, two reference variables are pointing to the same object.

Step 5) Uncomment line # 23 & 24. Compile , Save & Run the code

Step 6) As show in diagram below , s2 becomes null , but s3 is still pointing to the object and is not eligible for java garbage collection.



Step 7) Uncomment line # 25 & 26 . Save , Compile & Run the Code

Step 8) At this point there are no references pointing to the object and becomes eligible for garbage collection. It will be removed from memory and there is no way of retrieving it back.


If you want to make your object eligible for Garbage Collection , assign its reference variable to null.


Monday, 19 December 2016

Comparable Vs. Comparator

Comparable and Comparator are two interfaces provided by Java Core API. From their names, we can tell they may be used for comparing stuff in some way. But what exactly are they and what is the difference between them? The following are two examples for answering this question. The simple examples compare two HDTV's size. How to use Comparable vs. Comparator is obvious after reading the code.
1. Comparable
Comparable is implemented by a class in order to be able to comparing object of itself with some other objects. The class itself must implement the interface in order to be able to compare its instance(s). The method required for implementation is compareTo(). Here is an example:
// A Java program to demonstrate use of Comparable
import java.io.*;
import java.util.*;

// A class 'Movie' that implements Comparable
class Movie implements Comparable<Movie>
{
    private double rating;
    private String name;
    private int year;

    // Used to sort movies by year
    public int compareTo(Movie m)
    {
        return this.year - m.year;
    }

    // Constructor
    public Movie(String nm, double rt, int yr)
    {
        this.name = nm;
        this.rating = rt;
        this.year = yr;
    }

    // Getter methods for accessing private data
    public double getRating() { return rating; }
    public String getName()   {  return name; }
    public int getYear()      {  return year;  }
}

// Driver class
class ComparableTest
{
    public static void main(String[] args)
    {
        ArrayList<Movie> list = new ArrayList<Movie>();
        list.add(new Movie("Force Awakens", 8.3, 2015));
        list.add(new Movie("Star Wars", 8.7, 1977));
        list.add(new Movie("Empire Strikes Back", 8.8, 1980));
        list.add(new Movie("Return of the Jedi", 8.4, 1983));

        Collections.sort(list);

        System.out.println("Movies after sorting : ");
        for (Movie movie: list)
        {
            System.out.println(movie.getName() + " " +
                               movie.getRating() + " " +
                               movie.getYear());
        }
    }
}
Output(Comparable):
Movies after sorting : 
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983
Force Awakens 8.3 2015
2. Comparator
In some situations, you may not want to change a class and make it comparable. In such cases, Comparatorcan be used if you want to compare objects based on certain attributes/fields. For example, 2 persons can be compared based on `height` or `age` etc. (this can not be done using comparable.)
The method required to implement is compare(). Now let's use another way to compare those TV by size. One common use of Comparator is sorting. Both Collections and Arrays classes provide a sort method which use a Comparator.
//A Java program to demonstrate Comparator interface
import java.io.*;
import java.util.*;
// A class 'Movie' that implements Comparable
class Movie1 implements Comparable<Movie1>
{
private double rating;
private String name;
private int year;

// Used to sort movies by year
public int compareTo(Movie1 m)
{
return this.year - m.year;
}

// Constructor
public Movie1(String nm, double rt, int yr)
{
this.name = nm;
this.rating = rt;
this.year = yr;
}

// Getter methods for accessing private data
public double getRating() { return rating; }
public String getName() { return name; }
public int getYear() { return year; }
}

// Class to compare Movies by ratings
class RatingCompare implements Comparator<Movie>
{
public int compare(Movie m1, Movie m2)
{
if (m1.getRating() < m2.getRating()) return -1;
if (m1.getRating() > m2.getRating()) return 1;
else return 0;
}
}

// Class to compare Movies by name
class NameCompare implements Comparator<Movie>
{
public int compare(Movie m1, Movie m2)
{
return m1.getName().compareTo(m2.getName());
}
}

// Driver class
class ComparatorTest
{
public static void main(String[] args)
{
ArrayList<Movie> list = new ArrayList<Movie>();
list.add(new Movie("Force Awakens", 8.3, 2015));
list.add(new Movie("Star Wars", 8.7, 1977));
list.add(new Movie("Empire Strikes Back", 8.8, 1980));
list.add(new Movie("Return of the Jedi", 8.4, 1983));

// Sort by rating : (1) Create an object of ratingCompare
// (2) Call Collections.sort
// (3) Print Sorted list
System.out.println("Sorted by rating");
RatingCompare ratingCompare = new RatingCompare();
Collections.sort(list, ratingCompare);
for (Movie movie: list)
System.out.println(movie.getRating() + " " +
movie.getName() + " " +
movie.getYear());
// Call overloaded sort method with RatingCompare
// (Same three steps as above)
System.out.println("\nSorted by name");
NameCompare nameCompare = new NameCompare();
Collections.sort(list, nameCompare);
for (Movie movie: list)
System.out.println(movie.getName() + " " +
movie.getRating() + " " +
movie.getYear());

// Uses Comparable to sort by year
System.out.println("\nSorted by year");
Collections.sort(list);
for (Movie movie: list)
System.out.println(movie.getYear() + " " +
movie.getRating() + " " +
movie.getName()+" ");
}

Output(Comparator):

Sorted by rating
8.3 Force Awakens 2015
8.4 Return of the Jedi 1983
8.7 Star Wars 1977
8.8 Empire Strikes Back 1980

Sorted by name
Empire Strikes Back 8.8 1980
Force Awakens 8.3 2015
Return of the Jedi 8.4 1983
Star Wars 8.7 1977

Sorted by year
1977 8.7 Star Wars 
1980 8.8 Empire Strikes Back 
1983 8.4 Return of the Jedi 
2015 8.3 Force Awakens 


Difference between Comparable and Comparator

Comparable and Comparator both are interfaces and can be used to sort collection elements.
But there are many differences between Comparable and Comparator interfaces that are given below.
ComparableComparator
1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc.Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
2) Comparable affects the original class i.e. actual class is modified.Comparator doesn't affect the original class i.e. actual class is not modified.
3) Comparable provides compareTo() method to sort elements.Comparator provides compare() method to sort elements.
4) Comparable is found in java.lang package.Comparator is found in java.util package.
5) We can sort the list elements of Comparable type byCollections.sort(List) method.We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.

Friday, 16 December 2016

Multi Threading in Java Demonstration by Tortoise and Hare Story

Multithreading in Java gives the ability to execute code by different threads to perform tasks in parallel or as a separate task without waiting for other to complete.Computer games are the best examples of the Multithreading concept. The ability to make different objects act on a platform is enabled with the concept of Multithreading.

We can Create Threads in 2 ways:

1.) By Extending Thread Class

class MyClass extends Thread
{

public void run()
{

for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getId() + " Value : "+i);

}

// Running Concureency 
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block       
e.printStackTrace();
}
}

}


public class CreateThreadByExtendingClass 
{
  public static void main(String args[])
  {
MyClass m1 = new MyClass();
m1.start();

MyClass m2 = new MyClass();
m2.start();


  }

}

2.) By Implementing Runnable Interface

class myclass extends Thread
{
@Override
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println(Thread.currentThread().getId() + " Value : "+i);

}
// Running Concureency 
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block       
e.printStackTrace();
}
}

}

public class CreateThreadByImplementRunnable 
{
public static void main(String args[])
 {
MyClass m1 = new MyClass();
m1.start();

MyClass m2 = new MyClass();
m2.start();

 }

}

-- Thread Without Extra Class

public class CreateThreadwithoutExtraClass 
{
private static int count=0;

public synchronized static void count()
{
count++;

}

public static void main(String args[])
{

Thread t1 = new Thread (new Runnable(){

@Override
public void run() {

for(int i=0;i<10000;i++)
{
count();
}
}
});

Thread t2 = new Thread (new Runnable(){

@Override
public void run() {

for(int i=0;i<10000;i++)
{
count();
}

}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println( " Value : " +count);


}

}

Tortoise and Hare Demonstration using Multi Threading in Java

Consider a Race where two threads race to complete a 100 meters distance. Given below is the implementation of Race example:
A player is considered as Racer and the class implements Runnable Interface which indicates to Threads that its run method is implemented in Racer class.

This class makes the thread to iterate for 100 times and for each iteration, it checks if some one has won the race and if already a Thread won the race, then the other quits.



RacerDemo.java

package TortoiseHareStoryImplementation;

public class Racer implements Runnable 
{
    public static String winner;

    public void race()
    {
for(int distance=1;distance <= 100;distance++)
{

System.out.println("Distance Covered by "+Thread.currentThread().getName()+ "is:"+distance +"meters");

boolean isRaceWon = this.isRaceWon(distance);

if(isRaceWon)
{
break;
}
}
}

private boolean isRaceWon(int totalDistanceCovered)
{
boolean isRaceWon =  false;

if((Racer.winner==null )& (totalDistanceCovered==100))
{
String winnerName = Thread.currentThread().getName();
Racer.winner = winnerName; //setting the winner name
System.out.println("Winner is :"+Racer.winner);
isRaceWon = true;
    }

else if(Racer.winner==null)
{
isRaceWon = false;
}
else if(Racer.winner!=null)
{
isRaceWon = true;
}
return isRaceWon;
}

@Override
public void run()
{
this.race();

}

}



RacDemo.java

package TortoiseHareStoryImplementation;

public class RaceDemo 
{
public static void main(String[] args)
{
Racer racer = new Racer();

Thread tortoiseThread = new Thread(racer, "Tortoise");
Thread hareThread = new Thread(racer, "Hare");

//Race to start. tell threads to start
tortoiseThread.start();
hareThread.start();

}

}


Output: