Node Internationalizatio(I18N) approach

While searching for some work on I18N implementation approach on Node, I came across following three approach.

  • User library, example i18Next library. Example
  • Using html/javascript translation with html 5 data- attributes. Example. Here top language header is added dynamically. And translation is done using javascript node value manipulation.
  • Using different subdomain. Example

    .

  • ArrayList for loop puzzle

    Let me start this entry by asking a question. What would be the output of following two programs?
    Program1:-

    import java.util.*;
    public class ClassA{
            public static void main(String args[]){
             List<String> list = new ArrayList<String>();
             list.add("1");
             list.add("2");
             for(String x: list){
              list.remove("1");
             }
            System.out.println(list);
       }
    }
    

    Program2:

    import java.util.*;
    public class ClassA{
            public static void main(String args[]){
             List<String> list = new ArrayList<String>();
                             list.add("1");
             list.add("2");
             list.add("3");
            for(String x: list){
              list.remove("1");
             }
            System.out.println(list);
    }
    }
    

    Output:

    Program 1:

    [2]


    Program 2:-

    Exception in thread "main" java.util.ConcurrentModificationException
            at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
            at java.util.AbstractList$Itr.next(AbstractList.java:343)
            at ClassA.main(ClassA.java:8)
    

    Description:-

    Program 1 will run without any issue and delete “1” from the list and hence the output will print list content with having one element “2”. Whereas program 2 throws ConcurrentModificationException.
    Why?
    Here is the explanation.
    Java for each loop internally uses Iterable and Iterator to loop through each element of the collection. When we are looping through the foreach loop, we implicitly call list.iterator(), list.hasNext() and list.next() methods. In case of ArrayList list.iterator() returns instance of ArrayList.Itr class. This instance has a expectedModCount varable which keep track of current state of list. We can assume it to be the stamp of current state of the list. Whenever we modify the list(add/update/delete element) this modCount variable gets changes. When AbstractList.Itr is instantiated it initialized expectedModCount with current modCount of the list.(Fir understanding purpose we can say that Itr has variable which keep track of current state of the underlying list.
    When we delete an element modCount is increased and when next time itr.next() is called Itr.next() matches the mod count and throws ConcurrentModificationException if it does not match.

    The whole idea is to stop someone from modifying the underlying collection once we get Iterator and working on it.

    Then comes last question? Why no error was throws in case of Program1. It is because there are no element to be loop over and no Itr.next() method is called and hence no ConcurrentModificationException.

    Itr.remove() keeps the consistency and reassign expectedModCount.

    ArrayList source code:- http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java

    atan2 function problem in db2,java,javascript

    Last day I was working on a formula to calculate the bearing(and finally direction from point 1 to point 2). I was using the formula described here. I was running same formula in java as well as DB2. But getting different result. After much analysis I found the problem with the atan2 API in DB2 and Java.

    Java API accept y and x as first and second argument where as DB2 API accepts in reverse order.  I also found that  java script also accept y argument first. This is quite bad. I don’t know which one is right but everyone should follow same pattern. This difference in API was the source of the bug.

    During this analysis I also found that Db2 client(squirrel) was not returning the precise value where as Db2 client was returning. sqirrel_db2

     

    2013 in review

    The WordPress.com stats helper monkeys prepared a 2013 annual report for this blog.

    Here’s an excerpt:

    The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 20,000 times in 2013. If it were a concert at Sydney Opera House, it would take about 7 sold-out performances for that many people to see it.

    Click here to see the complete report.

    A random good thought

    Our life is possible only because we have faith on the machines around us. Just imagine the situation what life would have been if we don’t have faith on any machine around us. “The idea to develop a faithful machine/program” is the statement that always keeps me motivating. A program on which people have faith. People can have blind faith. A program on which many life can faithfully depend. I want to reach that level of perfection. Like all our perfect machines around us…like Airplanes, Train… etc…

    A CountDownLatch Example Explained

    A CountDownLatch is a thread synchronization construct that held current thread till the count of the latch reaches to zero. We can assume it to be a lock on main thread which opens only when its count reaches to zero.

    There are three things which we need to understand to know about this.
    • Initial Count
    await() method
    countdown() method

    Initial count is generally the total number of threads.
    When a thread call awaits on a countdown latch object, the flow of the current threads stops, till count reaches to zero. 
    Each thread call countdown() after finishing the work which decrease the count of a latch.

    Lets consider below example:-

    There are two sets of CountDownLatch used below.

    startSignal:-

    startSignal is used to make sure that all threads starts at same time. When we call .start()on the threads all threads will wait at “startSignal.await();”. These threads will not proceed till count on startThread reaches zero which happens at “startSignal.countDown();” When “startSignal.countDown();” is called count of that latch reaches zero and hence all threads process from “startSignal.await();”.

    endSignal:-

    This latch make sure that main thread continues only after all threads finished. Here we initialize endSignal with number of threads. We pass endSignal object to each thread. Each thread continue its work and decrease the count. When Main thread calls “endSignal.await();” The main thread will wait till endSignal count reaches zero. Each thread will end their work and call “endSignal.countDown();” which decreases count. Main thread will continue only when count reaches to zero, which means all thread have executed “endSignal.countDown();” which means all thread finished their work.


    import java.util.concurrent.CountDownLatch;
    public class CountDownLatchDemo
    {
    private static final int THREAD_COUNT = 5;
    public static void main(String[] args) throws InterruptedException
    {
    CountDownLatch startSignal = new CountDownLatch(1);
    CountDownLatch endSignal = new CountDownLatch(THREAD_COUNT);

    for(int i=0; i&lt; THREAD_COUNT; i++){
    new Thread(new Worker(startSignal, endSignal), "Thread:"+i).start();
    }
    System.out.println("Lets start all thread at once..");
    startSignal.countDown(); // let all threads proceed
    System.out.println("All threadsa are running..");
    System.out.println("Lets wait all thread to finish..");
    endSignal.await(); // wait for all threads to finish
    System.out.println("All threads finished..Main thread terminited");
    }
    }

    class Worker implements Runnable {
    private CountDownLatch startSignal;
    private CountDownLatch endSignal;

    public Worker(CountDownLatch start, CountDownLatch end) {
    startSignal = start;
    endSignal = end;
    }
    public void run() {
    final String threadName = Thread.currentThread().getName();
    try{
    startSignal.await();
    for(int i=0;i &lt; 3; i++){
    System.out.println("Thread:"+ threadName + " is working");
    try{
    Thread.sleep((int)(Math.random()*300));
    }catch (InterruptedException ie){
    }
    }
    System.out.println("Thread:"+ threadName + " is finishing");
    //Indicate end of a thread.
    endSignal.countDown();
    }
    catch(InterruptedException ex){
    ex.printStackTrace();
    }
    }
    }

    Output:

    Lets start all thread at once..
    All threadsa are running..
    Lets wait all thread to finish..
    Thread:Thread:1 is working
    Thread:Thread:2 is working
    Thread:Thread:0 is working
    Thread:Thread:3 is working
    Thread:Thread:4 is working
    Thread:Thread:4 is working
    Thread:Thread:4 is working
    Thread:Thread:4 is finishing
    Thread:Thread:0 is working
    Thread:Thread:2 is working
    Thread:Thread:1 is working
    Thread:Thread:3 is working
    Thread:Thread:2 is working
    Thread:Thread:0 is working
    Thread:Thread:2 is finishing
    Thread:Thread:1 is working
    Thread:Thread:3 is working
    Thread:Thread:1 is finishing
    Thread:Thread:0 is finishing
    Thread:Thread:3 is finishing
    All threads finished..Main thread terminited

    Runtime Problem with Arrays.asList()

    Few days back I came across this interesting problem. One of my friend called me up and asked that following code is compiling without any error but showing “java.lang.UnsupportedOperationException”  in runtime.

    public class Test {
        public static void main(String[] args) {
            String[] words = {“ace”, “boom”, “crew”, “dog”, “eon”};
              List<String> wordList = Arrays.asList(words);
              //Create list of words to be removed.
              List<String> toBeRemoved = new ArrayList<String>();
              toBeRemoved.add(“ace”);
              //Remove all the strings present in toBeRemoved
              wordList.removeAll(toBeRemoved);
              for (String e : wordList) {
                 System.out.println(e);
              }
        }
    }

    Error:-

    C:\Users\xyz>java Test
    Exception in thread “main” java.lang.UnsupportedOperationException
            at java.util.AbstractList.remove(AbstractList.java:144)
            at java.util.AbstractList$Itr.remove(AbstractList.java:360)
            at java.util.AbstractCollection.removeAll(AbstractCollection.java:337)
            at Test.main(Test.java:13)

     

    He wanted me to find the reason for this runtime behavior and solve it. After analyzing the code I found that Arrays.asList() does not return instance of java.util.ArrayList. It returns instance of static class java.util.Arrays.ArrayList. When we call removeAll() it in turn calls AbstractList.remove() and this method throws hrow new UnsupportedOperationException.

    One solution could to change the code to use java.util.ArrayList instead of java.util.Arrays.ArrayList .

    Modified working code:

    public class Test {
        public static void main(String[] args) {
            String[] words = {“ace”, “boom”, “crew”, “dog”, “eon”};
              List<String> wordList = new ArrayList<String>(Arrays.asList(words));
              //Create list of words to be removed.
              List<String> toBeRemoved = new ArrayList<String>();
              toBeRemoved.add(“ace”);
              //Remove all the strings present in toBeRemoved
              wordList.removeAll(toBeRemoved);
              for (String e : wordList){
                 System.out.println(e);
              }
        }
    }

     
    Output:- C:\Users\123916>java Test

    boom
    crew
    dog
    eon