Thursday, January 17, 2013

Merging from one branch to other branch


Merging all the commits from one branch to another branch.

For example, currently I am working with 5.5 branch for new features and wanted to pull the changes from 5.0 for fixes which are made.

Currently my branch is pointing to Dev-5.5
$ git merge Dev-5.0

If you have all the 5.0 changes in local system, above command will work fine. 
If your local Dev-5.0 branch is not up-to-date, first pull the changes from central repository.

$ git checkout Dev-5.0

Now you are in Dev-5.0 branch.

$ git pull origin Dev-5.0

This will fetch all the latest commits from origin/Dev-5.0 to local Dev-5.0 branch.

Now, go back to Dev-5.5 branch, to where you want to merge.

$ git checkout Dev-5.5

Now, you are in Dev-5.5 branch.

$ git merge Dev-5.0

This merges Dev-5.0 commits to Dev-5.5 branch, if none of the files having conflicts.

If any file is having conflict, merging will be failed and shows the conflicted files in the console.

Go to the specific files and resolve the conflicts.

Once conflict is resolved, add that file and commit them.

$ Git add hello.java // this is my conflicted file.

$ git status // this will show all the files still need to be merged and including with conflict resolved file.

$ git commit // remaining things are as usual.

Friday, January 11, 2013

Algorithm for random number


I was trying understand the implementation of Java.util.Random implementation but could not crack through it!!

In Java, If we want to generate random number between 1 to 6 (dice game), we can implement like below.

Using  Java.util.Random

public class CheckRandom {

public static void main(String[] args) {
Random random = new Random();
for (int i =0; i< 10;i++) {
int nextInt = random.nextInt(6)+1;
System.out.println(nextInt);
}
}
}

Where random.nextInt(x), uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability.

Using Java.math.random() 
This also works internally based on the java.util.random only. but it generates the values between 0.0 to 1.0.

We can make use of this in the following way to generate random number.
 int diceValue = (int)(Math.random()*6) + 1;



Here is the interesting algorithm for generating a random number. This explains in terms of mathematical expression.
http://www1.i2r.a-star.edu.sg/~knandakumar/nrg/Tms/Probability/Probgenerator.htm



What is a Linear Congruential Random Number Generator?

          Many computer applications rely on random number generation. For example, if you want to write a program to simulate a poker game, you don't want each player to get the same cards every hand. Since some programs require a large number of random numbers, we can greatly speed up the program by using a faster, more efficient random number generator. The method of this  random number generation by linear congruential method, works by computing each successive random number from the previous. Starting with a seed, Xo, the linear congruential method uses the following formula:

Xi+1 = (A*Xi + C) mod M
           In his book, The Art of Computer Programming, Donald Knuth presents several rules for maximizing the length of time before the random number generator comes up with the same value as the seed. This is desirable because once the random number generator comes up with the initial seed, it will start to repeat the same sequence of random numbers (which will not be so random since the second time around since we can predict what they will be). According to Knuth's rules, if M is prime, we can let C be 0 and he suggests that this variant of the line
THEOREM : (By Greenberger in 1961 )

The LCG defined above has full period . if and only if the following conditions are satisfied 

a)      m and c are relatively prime
     b)      If q is a prime number  that divides m , then q divides a-1
    c)      If 4 divides m, then 4 divides a-1
 The LCG tend to behave differently for c>0 and c=0
 A linear congruential generator lnc( ) generates a sequences of integers
                                      U0, U1 ,  ����.   , Uk
that are restricted to the range to m. On each call to lnc( ), you must
give it as argument the previous number in the sequence. It returns the following by
                                       Uk+1   =  ( a Uk +b ) mod (  m + 1).
 where a, b, and can be chosen to be any positive integers. (The operation mod n p is the integer remainder when the integer is divided by the integer p. This remainder must be between 0 and p-1, inclusive.) Once you�ve chosen these three constants and the starting value 0 you�ve completely defined the sequence that lnc( ) will produce. If you set a, b, and to reasonably large values (there are rules of thumb to follow in choosing these values so as the maximize the apparent disorder in the sequence: see Knuth, 1971), the resulting sequence looks satisfyingly random. Of course, you want numbers between 0 and 1, not integers between 0 and m. But you need only divide 1 k U + by m+2 to map the output of lnc into the desired range.

It�s easier to see what lnc( ) is doing if we pick small values a=5, b=1, and m=7. If 0 is set to 2, the resulting sequence is
           
2, 3, 0, 1, 6, 7, 4, 5, 2, 3, 0, 1 �.




Thursday, January 10, 2013

When we will get this debug feature in eclipse ?


When do we get this feature ?

As a java/eclipse developer, will come across this use case everyday. Most of times we wanted to maximize the debug value dialog(I don't know what is this called!) and see the results in one shot.
Expanding and checking the results is really a painful task.



Wednesday, January 9, 2013

Story around Eclipse dropins folder

Generally, if you would like to add new plug-ins we will directly put it into Eclipse\plugins folder and restart the eclipse.

I have joined in a new company, I was wondering why these people are using eclipse dropins folder instead of eclipse plug-ins folder.

Here is the brief story, I found from the below mentioned source.


Do you need the Dropins folder ?

A year ago I had much more inside the Dropins folder then now, because most of the plug-ins in the meantime have a Software-Site.
But if you’re using Plug-ins where no Software Site is available, then the Dropins folder is a great place to store the downloaded Plug-Ins and Features.
It’s easy to use: just copy the Plug-ins (and perhaps features) into the dropins folder.
You’ll find the dropins folder after installation of Eclipse directly inside the eclipse folder:
eclipse/dropins
you can use some different  structures to place the plug-ins into the Dropins folder – I prefer to separate them by domain:
  • /dropins/exampleA/plugins/…
  • /dropins/exampleB/plugins/…
  • /dropins/exampleC/eclipse/features/…
  • /dropins/exampleC/eclipse/plugins/…
The Dropins folder is also very handy if you’re testing some of your  plug-ins.
After copying plug-ins into the Dropins folder its the best to restart Eclipse – if there’s a problem try restarting using -clean (inserted into eclipse.ini)

How To share a Dropins folder ?

If you have some Eclipse installations using same bundles , then you can also share these plug-ins instead of copying them into each installation.
Create a folder like /mySharedDropins anywhere. Inside the folder use the same structure then in your normal Dropins folder.
Now you have to tell your Eclipse that there’s a shared Dropins folder:
Edit eclipse.ini and insert this line:
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=/<myPath>/mySharedDropins

sources:
http://wiki.eclipse.org/Equinox_p2_Getting_Started
http://ekkescorner.wordpress.com/2009/06/27/galileo-install-plug-ins-into-eclipse-ide/





Tuesday, January 8, 2013

Reading resources from a Eclipse plugin


Project structure:









How do you get the path for services.xml file while you working in plug-in development  ?

String file = "services/services.xml"; //$NON-NLS-1$
String pluginlocation;
try {
Bundle bundle = Platform.getBundle("com.kk"); //my class pkg
URL pLocationUrl = FileLocator.find(bundle, new Path("/"), null);
URL pFileUrl = FileLocator.toFileURL(pLocationUrl);
pluginlocation = pFileUrl.getFile();
} catch (IOException e) {
//log error
}


String completePath = pluginlocation.append(File.separator).append(file);

Best Practice: String concatenation with Java


Introduction:
Exercise extra caution when choosing a technique for string concatenation in Java™ programs. Simply using the "+=" operator to concatenate two strings creates a large number of temporary Java objects, since the Java String object is immutable. This can lead to poor performance (higher CPU utilization) since the garbage collector has additional objects to collect. Use the Java StringBuffer object to concatenate strings because it is more efficient.

Recommendation:
String concatenation using the "+" operator creates many temporary objects and increases garbage collection. Using the StringBuffer class is more efficient.The servlet code sample shows how this can be implemented. Lab tests have shown up to a 2.3X times increase in throughput using StringBuffer class over the immutable String class.
The StringBuffer class represents a mutable string of characters. Unlike the String class, it can process text in place. Instead of the "+=" operator, the StringBuffer uses the append method, as shown below:
                    
res.setContentType("text/HTML");
PrintWriter out = res.getWriter();
String aStudent = "James Bond";
String aGrade = "A";
StringBuffer strBuf = new StringBuffer();
strBuf.append(aStudent);
strBuf.append("received a grade of");
strBuf.append(aGrade);
System.out.println (strBuf);

Alternative
The String class is created by the Java compiler when it encounters characters contained within double quotes in an object. The String class is immutable; there are no methods provided that allow you to manipulate the contents of the string once it is created. Methods that operate on a string return a new string not an updated copy of the old one.
You can concatenate a string to create a dynamic string of data to be used in a println statement. In this example, several additional String objects are created. The "+=" operator is used to concatenate strings in this servlet example:
String typical_string;
Res.setContentType("text/HTML");
PrintWriter out = res.getWriter();
String aStudent = "James Bond";
String aGrade = "A";
typical_string += aStudent;
typical_string += "received a grade of ";
typical_string += aGrade;
System.out.println (typical_string);



Monday, December 31, 2012

SoftHashMap - hashmap with soft values


The biggest problem with WeakHashMap is, it will only weakly reference the keys but not the values. This may lead to memory issues if we are using weakhashmap as a cache.

We can try this!!



import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;



public class SoftHashMap<K, V> extends AbstractMap<K, V> {

/** The internal HashMap that will hold the SoftReference. */
private final Map<K, SoftValue<V>> hash = new HashMap<K, SoftValue<V>>();

/** The number of "hard" references to hold internally. */
private final int HARD_SIZE;

/** The FIFO list of hard references, order of last access. */
private final LinkedList<V> hardCache = new LinkedList<V>();

/** Reference queue for cleared SoftReference objects. */
private final ReferenceQueue queue = new ReferenceQueue();

public SoftHashMap() {
this(150);
}

public SoftHashMap(int hardSize) {
HARD_SIZE = hardSize;
}

public V get(Object key) {
V result = null;
// We get the SoftReference represented by that key
SoftReference<V> soft_ref = hash.get(key);
if (soft_ref != null) {
// From the SoftReference we get the value, which can be
// null if it was not in the map, or it was removed in
// the processQueue() method defined below
result = soft_ref.get();
if (result == null) {
// If the value has been garbage collected, remove the
// entry from the HashMap.
hash.remove(key);
} else {
// We now add this object to the beginning of the hard
// reference queue. One reference can occur more than
// once, because lookups of the FIFO queue are slow, so
// we don't want to search through it each time to remove
// duplicates.
hardCache.addFirst(result);
if (hardCache.size() > HARD_SIZE) {
// Remove the last entry if list longer than HARD_SIZE
hardCache.removeLast();
}
}
}
return result;
}

/**
* We define our own subclass of SoftReference which contains not only the
* value but also the key to make it easier to find the entry in the HashMap
* after it's been garbage collected.
*/
private static class SoftValue<V> extends SoftReference<V> {
private final Object key; // always make data member final

private SoftValue(V obj, Object key, ReferenceQueue queue) {
super(obj, queue);
this.key = key;
}
}

/**
* Here we go through the ReferenceQueue and remove garbage collected
* SoftValue objects from the HashMap by looking them up using the
* SoftValue.key data member.
*/
private void processQueue() {
SoftValue sv;
while ((sv = (SoftValue) queue.poll()) != null) {
hash.remove(sv.key); // we can access private data!
}
}

/**
* Here we put the key, value pair into the HashMap using a SoftValue
* object.
*/
public V put(K key, V value) {
processQueue(); // throw out garbage collected values first
SoftValue<V> softValue = new SoftValue<V>(value, key, queue);
SoftValue<V> put = hash.put(key, softValue);
if (put != null) {
return put.get();
}
return null;
}

public V remove(Object key) {
processQueue(); // throw out garbage collected values first
SoftValue<V> remove = hash.remove(key);
if (remove != null)  {
return remove.get();
}
return null;
}

public void clear() {
hardCache.clear();
processQueue(); // throw out garbage collected values
hash.clear();
}

public int size() {
processQueue(); // throw out garbage collected values first
return hash.size();
}

public Set entrySet() {
throw new UnsupportedOperationException();
}
}