When you know a thing, to hold that you know it, and when you do not know a thing, to allow that you do not know it - this is knowledge. -Confucius-

The gift of fantasy has meant more to me than my talent for absorbing positive knowledge. -Albert Einstein-

Science investigates religion interprets. Science gives man knowledge which is power religion gives man wisdom which is control. -Martin Luther King, Jr.-

Those who have knowledge, don't predict. Those who predict, don't have knowledge. -Lao Tzu-

Our treasure lies in the beehive of our knowledge. We are perpetually on the way thither, being by nature winged insects and honey gatherers of the mind. -Friedrich Nietzsche-

Tuesday, March 1, 2016

JavaScript here and there





  • Variables created without the keyword var , are always global, even if they are created inside a function
  • A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables. A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.

Thursday, February 18, 2016

Why it's bad to use floting point numbers for equality or condition checking ?




Most of the suggestions are to avoid floating-point numbers from equality checking or in condition checking. Because small errors in the rightmost decimal places are likely to arise when calculations are performed on floating-point numbers, And two float or double values (float and double are also different) rarely are exactly equal.

assume ,
double oneThird = 1.0 / 3.0;
double x = oneThird + oneThird + oneThird;

actually expected result is x to be equal to 1. But it probably doesn't. Because the first assignment statement stores an approximation of 1/3 in to oneThird, which is likely to be 0.3333333 (But actually it's 0.33333.....)
So the second statement stores something like 0.9999999 in to x.
So the computer will compare x with 1 and it recognize it as a mismatch. so eventually it will yield false.

Some interesting code snippets are listed below.

double a = 0.9999999999999999999;
if (1 == a) {
    System.out.println("1 equals to 0.9999999999999999999");
} else {
    System.out.println("1 does not equals to 0.9999999999999999999");
}
// prints "1 equals to 0.9999999999999999999"
float x = 1.1f;
double y = 1.1;
if (x != y) {
    System.out.println("1.1f and 1.1 does not match");
}
// prints "1.1f and 1.1 does not match"
double oneThird = 1.0 / 3.0;
double one = oneThird + oneThird + oneThird;
if(1.0000000000000000001 == one){
    System.out.println("1.0000000000000000001 equals to one");
} else {
    System.out.println("1.0000000000000000001 does not equals to one");
}
// prints "1.0000000000000000001 equals to one"
double a1 = 1.0/3.0;
double a2 = 0.333333;
if(a1 == a2){
    // programmer might think this will be the case !!!
    System.out.println("1.0/3.0 is equal to 0.33333");
}else{
    System.out.println("1.0/3.0 is not equal to 0.33333");
}
// prints "1.0/3.0 is not equal to 0.33333"
So how can we avoid this. Instead of checking for equality, we can test for near equality. one famous way to do this is to compute the difference between the numbers and see whether the result is less than some maximum allowable difference.
double EPSILON = 1.0e-7;
if (Math.abs(1 - a) < EPSILON) {
    System.out.println("yes");
} else {
    System.out.println("no");
}
// prints "yes"
Some interesting articles about this area are listed below.
0.999...
Why do so many people reject proofs that 0.999999... = 1?
Relational operators with floating point types
What Every Computer Scientist Should Know About Floating-Point Arithmetic ?
Comparing floating point numbers
Comparing Floating Point Numbers - by Random ASCII
Doubles are not floats, so don’t compare them
Why not use Double or Float to represent currency?

Thursday, February 11, 2016

When we need to override equals and hashcode methods in Java ?



If a class does not implement the 'equals' and 'hashcode' methods, the default implementation which inherited from the Object class will be used.

equals:

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). can be called as reference equality.

The default implementation is something like below,
public boolean equals(Object object) {
    return this == object;
}

hashCode:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
The default implementation is something like below,
public int hashCode() {
    return VMMemoryManager.getIdentityHashCode(this);
}
Consider the sample class Dog.

class Dog{
 String name;
 int age;
 
 public Dog(String name, int age) {
  super();
  this.name = name;
  this.age = age;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 } 
}

Let's initialize some objects from it.
Dog d1 = new Dog("tim",10);
Dog d2 = new Dog("tim",10);
Dog d3 = d1; // point it to the d1, so d3 will be referencing to the same object as d1.

if(d1.equals(d2)){
    System.out.println("yes");
}else{
    System.out.println("no");
}
/* this code block will print 'no' since d1 and d2 are not pointing to the same object, though we feel like both should be equal since attributes of that object are the same.
*/

if(d3.equals(d1)){
    System.out.println("yes");
}else{
    System.out.println("no");
}
// prints 'yes' because d3 and d1 are pointing to the same object.   
So what will happen when using collections framework,
HashMap map = new HashMap<>();
map.put(d1, "dog1");
map.put(d2, "dog2");
map.put(d3, "dog3");
   
System.out.println(map.size()); // prints '2' because d1 and d3 are considered as a single object since equals method will verify them as the same object
System.out.println(map.get(d2)); // prints 'dog2'
System.out.println(map.get(new Dog("tim",10))); // prints 'null'
   /* 'new Dog("tim",10)' has a new reference, it's a newly created object, though it has the attributes same as the other Dog instances. Since it's reference is different we can't use it as a Key in the map. If we want to retreat a value, we need that exact object we set as key. so when using the collections we need to overide the equals and hashcode methods properly*/

As we can see default equals method implementation provides 'reference equality'. But most of the cases we would normally override equals to implement "value equality" - where two distinct objects are deemed equal, usually by virtue of having equal field values themselves. The exact meaning of equality will depend on the design - the two objects could still be distinguishable in other ways, for example.

If you override equals, you should also override hashCode to be consistent with equals, such that if a.equals(b) is true, then a.hashCode() == b.hashCode(). This will allow instances of your class to be used as keys in hash-based collections (e.g. HashMap) so that you can look up a value, based on a key which is EQUAL to the original one(not the original one), rather than having to use a reference to the exact original key object.

Friday, September 19, 2014

Convert Sinhala Word-Net to Text Files



There are 3 main projects you have to configure before create the word-net flat file system for Sinhala. 1) Sinhala-WordNet-MongoDBToText 2) Sinhala-WordNet-API 3) Sinhala-WordNet-CSS When getting the Sinhala-WordNet-CSS project from the git chose not the master branch the branch but the individual_commits It has 5 projects 1) Sinhala-WordNet-CSS-Common 2) Sinhala-WordNet-CSS-DAL 3) Sinhala-WordNet-CSS-JWNL 4) Sinhala-WordNet-CSS-Model 5) Sinhala-WordNet-CSS-Util 6) Sinhala-WordNet-CSS-Web But the important one is the "Sinhala-WordNet-CSS-DAL" Okay now to successfully generate the flat files (i.e. to do MongoDB to Text transformation) we need to configure the below 3 projects 1) Sinhala-WordNet-CSS-DAL 2) Sinhala-WordNet-API 3) Sinhala-WordNet-MongoDBToText First locate the file "file_properties.xml" in Sinhala-WordNet-API-master\SinhalaWordNetAPI\src\extjwnl\src\main\resources\net\sf\extjwnl In the XML file find the Replace the value "XXXXXXXX" with the full file path to "Sinhala-WordNet-API-master\SinhalaWordNetAPI\data\clean-file" Then go to Sinhala-WordNet-API-master\SinhalaWordNetAPI\src\utilities\src\main\java\net\sf\extjwnl\utilities and find the "shakshara.java" file. Find the below code block, String propsFile = "XXXXXX"; and replace the value "XXXXXX" with the full path to "file_properties.xml" file. Now Run the App.java in "Sinhala-WordNet-MongoDBToText" project (in Sinhala-WordNet-MongotoText\SinhalaWordNetMongotoText\src\main\java\org\sinhala\wordnet\DBconvert\core) If it prints "done" or else run successfully then check the folder "Sinhala-WordNet-API-master\SinhalaWordNetAPI\data\clean-file" . there will be the flat files. you can view them by clicking and open through an editor

Thursday, September 4, 2014

The Senate Bus problem - Java Solution



Problem : This problem was originally based on the Senate bus at Wellesley College. Riders come to a bus stop and wait for a bus. When the bus arrives, all the waiting riders invoke boardBus, but anyone who arrives while the bus is boarding has to wait for the next bus. The capacity of the bus is 50 people; if there are more than 50 people waiting, some will have to wait for the next bus. When all the waiting riders have boarded, the bus can invoke depart. If the bus arrives when there are no riders, it should depart immediately. Puzzle: Write synchronization code that enforces all of these constraints.
 

import java.util.Scanner;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *               Concurrent Programming
 *                       
 *           
 */
public class BusProblem {

    private static Counter waiting = new Counter(0);
    private static Semaphore mutex = new Semaphore(1);
    private static Semaphore bus = new Semaphore(0);
    private static Semaphore boarded = new Semaphore(0);

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of Riders (suggest a value larger than 100) : ");
        int n = sc.nextInt();
        System.out.println("");
        
        // Demonstrate the behaviour of the Bus. this thread's run method will keep running
        new Bus(n,waiting, mutex, bus, boarded).start();
        
        // We created 'n'number of riders to  demonstrate the behaviour of the riders pool 
        for (int i = 0; i < n; i++) {
            new Rider(i, waiting, mutex, bus, boarded).start();
        }

    }
}

class Bus extends Thread {

    private Counter waiting;
    private Semaphore mutex;
    private Semaphore bus;
    private Semaphore boarded;
    
    private int countNumberOfRidersWent;

    public Bus(int countNumberOfRidersWent,Counter waiting, Semaphore mutex, Semaphore bus, Semaphore boarded) {
        this.waiting = waiting;
        this.mutex = mutex;
        this.bus = bus;
        this.boarded = boarded;
        this.countNumberOfRidersWent=countNumberOfRidersWent;
    }

    @Override
    public void run() {

        while (true) {
            try {
                mutex.acquire();  // bus gets the mutex and holds it throughout the boarding process
                System.out.println("\nBus locked the BusStop");
            } catch (InterruptedException ex) {
                Logger.getLogger(Bus.class.getName()).log(Level.SEVERE, null, ex);
            }
            int n = Math.min(waiting.getCount(), 50);
            
            // remove the below line to get the infinite loop , and then remove block 'check'
            countNumberOfRidersWent-=n; // this is to easily demonstrate the problem
            System.out.println("Available Passengers = " + waiting.getCount() +"  and "+ n+ " will be boarded...");
            for (int i = 0; i < n; i++) {
                bus.release();  // signal bus is ready to get a passenger in
                try {
                    boarded.acquire(); // rider has boarded
                } catch (InterruptedException ex) {
                    Logger.getLogger(Bus.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //When all the riders have boarded, the bus updates waiting
            waiting.setCount(Math.max(waiting.getCount() - 50, 0));
            
            mutex.release(); // release the mutex

            System.out.println("Bus depart...\n");
            
            // block 'check'
            if(countNumberOfRidersWent==0){
                break;
            }
        }
    }
}

class Rider extends Thread {

    private int id;
    private Counter waiting;
    private Semaphore mutex;
    private Semaphore bus;
    private Semaphore boarded;

    public Rider(int id, Counter waiting, Semaphore mutex, Semaphore bus, Semaphore boarded) {
        this.waiting = waiting;
        this.mutex = mutex;
        this.bus = bus;
        this.boarded = boarded;
        this.id = id;
    }

    @Override
    public void run() {

        try {
            mutex.acquire();
        } catch (InterruptedException ex) {
            Logger.getLogger(Rider.class.getName()).log(Level.SEVERE, null, ex);
        }
        waiting.incrementCount();
        mutex.release();
        try {
            bus.acquire(); // waiting for the bus
        } catch (InterruptedException ex) {
            Logger.getLogger(Rider.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("rider got in to the bus..");
        boarded.release(); // got in to the bus

    }
}

// We cannot simply have a integer type variable for share amonge the threads. So we have to create 
// an object which can be shared among the threads. it is the Counter 
class Counter {

    private int count;

    public Counter(int count) {
        this.count = count;
    }

    public int getCount() {
        return count;
    }

    // reasign a value to the counter
    public void setCount(int count) {
        this.count = count;
    }

    // add 1 to the present value
    public void incrementCount() {
        this.count = ++count;
    }
}

 
==================================================================================================
     Concurrent Programming

==================================================================================================

class "BusProblem" contains the main method. 

If you are using the command prompt :
1) compile it using : javac BusProblem.java
2) run it using : java BusProblem
  - give the input parameter (rider count)
  
NOTE : the program is implemented to stop after all riders boarded to the bus. If you don't want that to happen just disable that by removing 

countNumberOfRidersWent-=n;  in line 69

line 87,88,89
// block 'check'
            if(countNumberOfRidersWent==0){
                break;
            }  
   
==================================================================================================

Wednesday, September 3, 2014

Simple Java Concurrent Program to handle a Thread Pool Using Semaphores




in a program there are multiple resources. And multiple users may be trying to access them at the same time. This will lead to various sort of problems which we have to consider when trying to create that application. That is the basic idea of concurrent process management. So the main objective to protect resources from multiple user access at once. to do that we may need to use locks and semaphores as we learn in the theories. Java has built in facility to create semaphores. like java.util.concurrent.Semaphore here is a simple example of the functionality of semaphore. Problem : there are equal number of threads which prints A and which print B. We need to print the pattern ABABAB....
 

import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class Handle {

    // declare and initialize the semaphores
    private static Semaphore s1 = new Semaphore(0);
    private static Semaphore s2 = new Semaphore(1);
    
    public static void main(String[] args) {
        // make the threads and make them start.
        for (int i = 0; i < 10; i++) {
            new P1(s1, s2).start();
        }
        for (int i = 0; i < 10; i++) {
            new P2(s1, s2).start();
        }
    }
}

class P1 extends Thread {

    private Semaphore s1;
    private Semaphore s2;

    public P1(Semaphore s1, Semaphore s2) {
        this.s1 = s1;
        this.s2 = s2;
    }

    @Override
    public void run() {
        try {
            s2.acquire();// --1
        } catch (InterruptedException ex) {
            Logger.getLogger(P1.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.print("A");
        s1.release();
    }
}

class P2 extends Thread {

    private Semaphore s1;
    private Semaphore s2;

    public P2(Semaphore s1, Semaphore s2) {
        this.s1 = s1;
        this.s2 = s2;
    }

    @Override
    public void run() {
        try {
            s1.acquire();
        } catch (InterruptedException ex) {
            Logger.getLogger(P2.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.print("B");
        s2.release();
    }
}

Tuesday, August 6, 2013

Encapsulation - A simple approach to OOP

We wrote a class. And some other developers will use it. And somehow we want to change our class because others use it for their purposes in a way that we don't want to be. It is like there is a variable in our class and we don't want it to be less than zero , but the developers who use our class can easily change it to any value because lack of our code quality.
Take a look at this code.
class BadClass {
    
    // public unprotected variables
    // any one who has an instant can change them to any value
    public int age;
    public String name;
 }

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        //Since we can access the age variable directly
        //we can change it to any value
        b.age = -10;

        //this assignment is not illegal. But obviously an age cannot be negative !! 
        //So this is bad and we have to stop this been happening. 

    }
}

Think that now we want to change our class. Will our changes affect other codes ? Will our changes bring errors to others codes. ?
That means our code not supporting flexibility and maintainability (which are two main benefits of OOP ).So we have to write our code in a way that it supports flexibility and maintainability . The ability to make changes in our implementation code without breaking others code who use our code is a key benefit of ENCAPSULATION.
The idea of ENCAPSULATION is hiding information behind a Public Programming Interface. That means our codes API. !!
To do that we have to keep instance variables protected (by making them private). and make public methods to access the variables and force others to use them. (our API)
after that our code will looks like this
 
  
class BadClass {

    //protect the instance variables 
    private int age;
    private String name;

    // make publicly accessible methods   
    // we can now protect our code and others as well !!
    public void setAge(int age) {
        if (age > 0) {
            this.age = age;
        }
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class UseBadClass {

    public static void main(String[] args) {
        BadClass b = new BadClass();

        b.setAge(-10);

        // (-10) will not be assigned 
        System.out.println(" age = " + b.getAge());
    }
}

A well protected code !!! :)