March 2, 2014

Git - Useful Commands

Commit Changes without Staging Stage : 
$ git commit -a -m "committing without staging"

To Push to a Branch : 

Assuming a branch is created and checked out :
git push origin branch

If pushing to a non-default branch, you need to specify the source ref and the target ref :
git push origin branch1:branch2


Fetch from Original Forked Repository or any other Related Repository : 

First you need to add the desired repository as a remote :

$ git remote add upstream https://github.com/wso2/product-esb

This remote will be referred to as 'upstream' now. Then you can fetch from this upstream. You can verify the added remote repositories as below :

$ git remote -v
origin https://github.com/maheeka/product-esb.git (fetch)
origin https://github.com/maheeka/product-esb.git (push)
upstream https://github.com/wso2/product-esb (fetch)
upstream https://github.com/wso2/product-esb (push)

Now merge the changes to the local branch :
$ git merge upstream/master master

upstream/master is the upstream branch that you need to merge from and master is your local branch. If you are merging to another branch use that branch name instead of master.
$ git merge upstream/branch branch

Now push these commits to your repository :
$ git push origin master


Checkout a Branch from Upstream :

Create a branch tracking upstream branch and checkout :
$ git checkout -b branch1 upstream/branch1
Branch branch1 set up to track remote branch branch1 from upstream.
Switched to a new branch 'branch1'

Now you can commit and push as you would for any other branch.

Edit Committed (and Pushed) Commit Message : 
  1. $git commit --amend -m "new commit message"
  2. $git push origin master -f

Adding an Existing Project to git (bitbucket) :
  1. Create a project in bitbucket - you will get "clone url"
  2. Issue the following commands on git bash :

Initialize git repository : 
leo@LEODEN ~ $ git init Initialized empty Git repository in C:/Users/leo/.git/ 

Navigate to the project location
leo@LEODEN ~ (master) $ cd C:/Users/leo/git/timesheetApp/TimeSheet 

Initialize existing git repository
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git init Reinitialized existing Git repository in c:/Users/leo/git/timesheetApp/TimeSheet /.git/

Add(Stage) all files and folders
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git add * 

Check status (optional) which will list down the files to be committed
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git status 
# On branch master # 
# Initial commit # 
# Changes to be committed: 
# (use "git rm --cached <file>..." to unstage) # 
# new file: .classpath 
# new file: .project 
# new file: .settings/org.eclipse.jdt.core.prefs 
# new file: .settings/org.eclipse.jdt.ui.prefs .....

Commit the staged
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git commit -m "first project add" [master (root-commit) 71447ea] 
first project add 56 files changed, 707 insertions(+) 
create mode 100644 .classpath 
create mode 100644 .project ..... 

Check the status (optional) which will show that all are committed
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git status 
# On branch master nothing to commit, working directory clean 

Push the changes to bitbucket repository
leo@LEODEN ~/git/timesheetApp/TimeSheet (master) $ git push -u origin master 
Password for 'https://maheeka@bitbucket.org': 
Counting objects: 90, done. Delta compression using up to 4 threads. 
Compressing objects: 100% (71/71), done. 
Writing objects: 100% (90/90), 1.47 MiB | 14 KiB/s, done. 
Total 90 (delta 5), reused 0 (delta 0) To https://maheeka@bitbucket.org/maheeka/timetracker.git * [new branch] master -> master Branch master set up to track remote branch master from origin.


Reference : 

August 16, 2012

Access outer class members from inner class

The following example shows how to access outer class members from inner class
public class OuterClass{

   public void method() {
      //do something
   }

   class InnerClass {

      public void innerMethod() {
          OuterClass.this.method();
         //do something
      }
   }
}

August 8, 2012

Right align tabs in JTabbedPane

Some useful tips for aligning tabs in JTabbedPane :-

Align tabs to right
pnlMainTabbedPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Place tabs on right of the JTabbedPane

pnlMainTabbedPane.setTabPlacement(JTabbedPane.RIGHT)

August 7, 2012

Java Swing UI Settings

To set global UI settings in Java Swing, use UIManager and set the properties as needed. All components have their respective keys and default values. For a complete list of properties, refer http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/_nimbusDefaults.html

These settings should be done before creating the JFrame where all these components are put into.

Example :
UIManager.put("Button.background", Color.RED);
UIManager.put("Button.font", new FontUIResource(new Font("Arial", Font.BOLD, 12)));

July 23, 2012

OLE Exception in Eclipse for MSOffice files






If you have got the above error message when you try to open a MS Office file in eclipse, that means your OLE editor is not working in eclipse. When i googled I found that this is a common problem for Excel files. So I suggest to set the Excel files to open in Excel editor instead of OLE editor. So, do the following ;

  1. Go to Eclipse -> Window -> Preference -> General -> Editors -> File Associations



  2. Add the .xls file type (or any other file type you want)


  3. Choose the Excel WorkBook 97-2003 WorkSheet (or any other file editor you want)



  4. Click OK-> OK

  5. Now the .xls file will opens in Ms Excel

July 4, 2012

JDOM Document to String

XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
String scenarioStr = outputter.outputString(jdomDoc);


Reference : http://cafeconleche.org/books/xmljava/chapters/ch14s04.html

June 29, 2012

Java Varargs - Unlimited parameters to a Java method

When you cannot decide the number of parameters you need for a method, varargs becomes the solution. Earlier, if we couldn't determine such, we had to use a collection as a parameter to help with this scenario. But varargs simplifies this.

Varargs does use an array underneath, but using varargs syntax hides the process.

public static String format(String pattern,
                                Object... arguments);

Example :

If you need to write a file name extension filter for a number of extensions, you can use this method of defining the method.

public FileNameExtensionFilter(String description, String... extensions) {

Read more on varargs at :
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

JFileChooser - Useful Tips

Set Starting Directory
JFileChooser fileSaver = new JFileChooser();
String cpath = "C:/MWork/Test1/script/";
File f1 = new File(cpath);
fileSaver.setCurrentDirectory(f1);

File Filter
FileNameExtensionFilter filter = new FileNameExtensionFilter("eXtensible Markup Language file (*.xml) ", "xml");
fileSaver .setFileFilter(filter);

Default File Save Name
jFileChooser.setSelectedFile(new File("untitled.xml"));

June 22, 2012

Get Frame of a Component


In order to find the frame that contains a component, it is necessary to walk up the component's parents until the frame is encountered. SwingUtilities.getRoot() is a convenience method that finds the frame.

This example implements an action that finds and hides the frame of the component that triggered the action. See also Creating a JButton Component.

// Create an action
Action action = new AbstractAction("Action Label") {
  
    // This method is called when the action is triggered
    public void actionPerformed(ActionEvent evt) {
        
        Component c = (Component)evt.getSource();

        // Get the frame
        Component frame = SwingUtilities.getRoot(c);

        // Hide the frame
        frame.setVisible(false);
    }
};

http://www.exampledepot.com/egs/javax.swing/frame_FrameFind.html

June 21, 2012

XML Editor for Eclipse




Edit:
Make sure you go to Open With -> XML Editor to make XML Editor the default for that XML

June 19, 2012

Focus to newly added JComponent in Frame

int h = (int) pnlPrerequisites.getBounds().getHeight();
Component frame = SwingUtilities.getRoot(pnlPrerequisites);
System.out.println(h + "=" + frame.getHeight());
if (h > frame.getHeight()) {
    scrollPnlPre.setViewportView(p);
    // scrollPnlPre.getViewport().setView(p);
}

Problem : this removes the scroll

June 18, 2012

Get the string that matches the regex

If you want to get the string that matches the regex pattern you have defined, you might have noticed there isn't any direct method. As a solution a simple code as below can be used.

I wanted to read the number within the brackets in str.
(Note: The numbers always appear within brackets)
String str = "CLor (23)";
String search = "\\(\\d*\\)";
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(str);
boolean matchFound = matcher.find();
if (matchFound) {
   int start = matcher.start();
   int end = matcher.end();
   String num = str.substring(start + 1, end - 1);
   System.out.println(num);
}

Above, in substring method I used
(start + 1, end -1)
because I needed to omit the brackets. If the whole string that matches the regex was needed method needs to have parameters
(start,end)

May 25, 2012

JTextBox Select all on Click

Following code will select all the content from the text box at click on it, if the textbox content is "<comment>".

Use focus listener - JTextArea does not have ActionListener like JTextField

public static JScrollPane getCommentBox() {

    final JTextArea txtComment = new JTextArea();
    txtComment.setText("<comments>");
    txtComment.setForeground(Color.GRAY);
    txtComment.setColumns(50);
    txtComment.setRows(3);

    FocusListener fl = new FocusListener() {
    
       @Override
       public void focusLost(FocusEvent arg0) {
          System.out.println("not typing....");
       }

       @Override
       public void focusGained(FocusEvent arg0) {
          if (txtComment.getText().equals(Constants.COMMENTS)) {
              txtComment.selectAll();
              txtComment.setForeground(Color.BLACK);
          }
       }
    };

    txtComment.addFocusListener(fl);
    JScrollPane jScrollPane1 = new JScrollPane();
    jScrollPane1.setViewportView(txtComment);

    return jScrollPane1;
}

Fixed size text area with scroll

JTextArea txtArea = new JTextArea();
txtArea.setColumns(50);
txtArea.setRows(2);
JScrollPane jScrollPane1 = new JScrollPane();
jScrollPane1.setViewportView(txtArea);

May 15, 2012

ArrayList and Array Conversions

ArrayList to Array Conversion :
List<T> list = new ArrayList<T>();
T[] array = list.toArray(new T[list.size()]);

Array to ArrayList Conversion : 
String[] array = {"a", "b", "c"};
List list = Arrays.asList(array);

Here the list is immutable. So if you want to be able to modify this list, create the list as below :
List list = new ArrayList(Arrays.asList(array));

February 5, 2012

No. of Spanning Trees for a Complete Graph with Constraints

For a graph with v vertices, the spanning tree contains (v-1) edges. Also the number of spanning trees can be given by vv-2 (Cayleys, 1889). Using this formula, lets determine a relationship between number of constraints and the number of spanning trees. Consider the following complete graph with 4 vertices. The colored edges will be the constraints (compulsory edges) we will consider.


According to Cayleys formula there has to be 44-2=16 spanning trees for the graph and each spanning tree contains (4-1) = 3 edges. The image below shows all the spanning trees.




According to the spanning trees, lets consider the number of spanning trees when constraints are present.


# ConstraintsConstraints# Spanning trees
0No constraint16
1Blue8
1Red8
1Green8
2Blue, Red3
2Blue, Green4
2Red, Green3
3Red, Green, Blue1

Conclusion:

According to the above numbers, although there is a relationship when one constraint is present (Vv-2/2), there is no such linear relationship when two or more constraints are present. If the two compulsory edges are adjacent then the number of spanning tree is lesser. When the number of constraints equals the number of edges in spanning tree, only one spanning tree exists.

January 20, 2012

Apps not working after google 2-step verification enabling

Pidgin was not working after I activated 2-step verification for my google account.

Solution : generate application specific password from https://accounts.google.com/IssuedAuthSubTokens#accesscodes