Monday, January 28, 2013

Pushing a specific commit to repository


git status says:

$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 2 commits.

You want to git push only one of those commits to the public repo. Here’s how:

First use git log to get the commit hash of the commit you want to push. Then:

$ git push origin <thelonghash>:master

example:
$ git push origin 7605596d45d2e3812da1e22db447fc6f1fe6f876:Dev-5.0

Friday, January 25, 2013

Viewing Unpushed Git Commits


It was useful for me to avoid unnecessary commits with a push.


git log origin/master..HEAD
You can also view the diff using the same syntax
git diff origin/master..HEAD


Source:  http://stackoverflow.com/questions/2016901/viewing-unpushed-git-commits


Thursday, January 24, 2013

GIT: reverting a second commit of the push from central repository

Have you ever come across the issue, where you have pushed your code to a central repository but unknowingly old commit also has been pushed which is not required any more.

In general, If you want to revert a last commit:

$ git revert d768b8d6a709ba5524e2cf68915d718b9e9ae0bf


In your last push, you have pushed two commits and imagine second commit now you want to roll back,

$ git revert a768b8d6a709ba5524e2cf68915d718b9e9ae0be

fatal: Commit 137ea95 is a merge but no -m option was given.


You will come across above issue,

To resolve that, we need use -m option with order of a commit. Like below,

$ git revert a768b8d6a709ba5524e2cf68915d718b9e9ae0be  - m 2

This will revert second commit which you have made.

Source:  http://gitready.com/intermediate/2009/03/16/rolling-back-changes-with-revert.html



Tuesday, January 22, 2013

Eclipse debug configuration setting and reading

 Here is the way to specify the debug configuration parameters through VM arguments in eclipse.



In VM arguments section, as you can see I have passed following debug parameter.
-Dkony.debug=true


These parameters I can read in the following way in Java.

String isdebug = System.getProperty("kony.debug");
Boolean DEBUG_MODE = new Boolean(isdebug);

if(DEBUG_MODE) {
        System.out.println("My application is running in debug mode");
      //Do your action here!!
}


Other sources:
http://www.avajava.com/tutorials/lessons/whats-the-difference-between-program-arguments-and-vm-arguments.html








SAXON: Failed to compile stylesheet. 1 error detected.


What would be a reason to come across this issue ? There are several..

Tue Jan 22 17:10:38 IST 2013
Failed to compile stylesheet. 1 error detected.

javax.xml.transform.TransformerConfigurationException: Failed to compile stylesheet. 1 error detected.
at net.sf.saxon.PreparedStylesheet.prepare(PreparedStylesheet.java:176)
at net.sf.saxon.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:139)
at net.sf.saxon.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:91)
at com.kony.sync.offlineservices.util.TransformUtil.transform(TransformUtil.java:35)
at com.kony.sync.ide.actions.GenerateOfflineServicesAction$GenerateOfflineServicesJob.run(GenerateOfflineServicesAction.java:105)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)


Since, I don't have log for what had happened internally it was very difficult to figure it out the actual cause by looking at the above issue.

Finally, i figure it out that it was because of '*.xslt' does not exist in the specified location.

Other reasons from various sources:
http://zvon.org/xxl/XSLTutorial/Output/example11_ch15.html






Friday, January 18, 2013

Very useful Eclipse Debug option:Suspending Threads


Suspending Threads


This would be useful If incase eclipse is blocked and you exactly don't know the reason why call is blocking. You can just go to eclipse debug mode and suspend the main thread and worker threads. That will show you the stack frame.
To suspend an executing thread:
  1. Select the thread in the Debug View.
  2. Click the Suspend button [ Suspend ] in the view toolbar.
The thread suspends its execution. The current call stack for the thread is displayed, and the current line of execution is highlighted in the editor in the Debug Perspective.
When a thread suspends, the top stack frame of the thread is automatically selected.  The Variables View shows the stack frame's variables and their values.  Complex variables can be further examined by expanding them to show the values of their members.
When a thread is suspended and the cursor is hovered over a variable in the Java editor, the value of that variable is displayed.

Thursday, January 17, 2013

Stashing your changes


Stashing is a great way to pause what you’re currently working on and come back to it later. For example, if you working on that awesome, brand new feature but someone just found a bug that you need to fix. Add your changes to the index using
git add .
Or add individual files to the index, your pick. Stash your changes away with:
git stash
And boom! You’re back to your original working state. Got that bug fixed? Bring your work back with:
git stash apply
 
  You might have stashed more than one, now you want to get the last one.

   git stash pop

   






GIT: How to reset your local branch to master branch


Imagine you have made few local commits and you don't want to commit all of them. Instead you want to go back to the master branch state.
git reset --hard origin/master     // This won't work!

Setting your branch to exactly match the remote branch can be done in two steps
git fetch origin
git reset --hard origin/master

If you want to save your current branch's state before doing this (just in case), you can do:
git commit -a -m "Saving my work, just in case"
git branch my-saved-work


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);