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

Backup to a .sql file and Restore from .sql database file (MySQL)


Backup

From above link :-
In your command, you can't have a space between -p and the password. Also, mysqldump has to be run on the command line, not in a mysql shell.

Try this on your command line

mysqldump -u username -ppassword databasename > backup.sql

Restore
  • Go to the folder with the backup.sql file from console
  • Start MySQL server
  • Type in source backup.sql
Reference

November 27, 2011

Fixing ConcurrentModificationException

Here I am discussing the instances where, iterating over a collection throws the ConcurrentModificationException. As mentioned in the API documentation, the reason here is, "it is not generally permissible for one thread to modify a Collection while another thread is iterating over it."

Following is a code segment which can throw this exception.
Iterator itr = purchased_products.iterator();
while (itr.hasNext()) {
  if (itr.next().getProduct_id() == product_id) {
    Purchase p = itr.next();
    purchased_products.remove(p);
  }
}

There are a number of different solutions provided in forums. Almost all of them are provided as tweaks to iteration which is already happening.If you need to keep using the iterator, solution here will not work.

This solution gives up the iterator. This is a simple code which we all have being through, but may have missed out for situation as this. I found this by referring the remove method in java.util.ArrayList.

for (int index = 0; index < size; index++)
  if (elementData[index] == null) {
  fastRemove(index);

As in the above code segment from remove(Object o) method, I too used a for loop to find the index of the item to be removed and then called upon the remove(int index) method to remove the element. This will not result in any such errors and is efficient than using iterator. But it will highly depend on your requirement.

So the revision for the above code segment given earlier would be as,
for (int index = 0; index < purchased_products.size(); index++) {
  if (product_id == purchased_products.get(index).getProduct_id()) {
    purchased_products.remove(index);
    index--;
  }
}

November 23, 2011

SqlFairy

"sqlfairy" is a pretty cool software which helps you in instantly visualizing any huge sql database, when all you have is it's schema.

You just have to do a quick installation with sudo apt-get install sqlfairy and you are all good to go.

Just refer some tutorials are available from :

November 21, 2011

Eclipse block comment problem

Eclipse by default formats the block comments when you save changes of a file. It is additional trouble when you need to uncomment.

To solve this problem,

  • Go to Windows->Preferences->Java->Code Style->Formatter->Edit->Comments 
  • Uncheck Enable block comment formatting
  • Click on Apply

November 20, 2011

Git Reference Sheet

Git Repository

It contains a set of 'commit objects' and 'heads' which are references to those commit objects. Commit objects are a set of files that reflect the state of project at any given time. They also include references to parent commit objects. Head is a reference to a commit object. a head has a name. By default, every repository has a head called "master". A repository can contain many heads but at any given time, one head is selected as the "current head" which is always named as "HEAD".

(In simple terms, HEAD is the current branch. But there are exceptions to this. Another definition is to refer to HEAD as a reference to the last commit in the current checked out branch.)

Delete

delete a remote branch
git push git@github.com:....git :mahee2

delete a branch

git branch -d mahee

Push

Push is done when you want to push the work you have done upstream for sharing purposes.

General command is git push [remote-name] [branch-name]

If you want to push your master branch to origin server, run git push origin master

example : git push git@github.com:charithsoori/Cart-beta.git mahee

The real scene behind above commands are a little explanatory. when you give a command as git push origin mahee it means, to take the local branch named 'mahee' and push it to the remote 'mahee' branch. git push origin mahee:mahee does the same. (Take my local 'mahee' and make it remote 'mahee'). If it is a different branch in remote (e.g. test) just give the command as git push origin mahee:test

if above push doesn't work due to not having a common ancestor and you get the following error :-

To git@github.com:.....git
! [rejected]        mahee -> mahee (non-fast-forward)
error: failed to push some refs to 'git@github.com:charithsoori/Cart-beta.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.


Do force push using
git push --force
or
git push git@github.com:.....git mahee --force (untested)

Actually force is not a very good option and is not encouraged. if a simple git pull and then pushing doesn't work, then you might have to use force.

Fetch

to pull any new work since clone or last fetch

git fetch origin

here "origin" refers to the remote repository when a clone is taken. The fetch will pull all the data from the remote project which isn't currently available. after this fetch, references to all branches are available and it is possible to merge branches or inspect them at will. Fetch only pulls data to local repository. It does not do any merging or modification to current work. Those should be done manually.

Pull

git pull

If a branch is set to track a remote branch, you can use pull to automatically pull and merge a remote branch to the current branch.

When to fetch and when to pull?

http://longair.net/blog/2009/04/16/git-fetch-and-merge/

Merge

git merge local mahee

merges local and mahee branches to local.

also, another method to do this merging is to checkout to local and then call on git merge mahee

Conflicting merge

git checkout branch1
git fetch origin branch2
git merge FETCH_HEAD

Auto-merging ......
CONFLICT (content): Merge conflict in ...........
Removing ..........
Auto-merging .........
CONFLICT (content): ..........
Automatic merge failed; fix conflicts and then commit the result.

when above output is received you can use a mergetool and perform merging in a little bit of a manual way.


git mergetool
merge tool candidates: opendiff kdiff3 tkdiff xxdiff meld tortoisemerge gvimdiff diffuse ecmerge p4merge araxis emerge vimdiff
Merging:
.........
.........

Normal merge conflict for '....':
{local}: modified
{remote}: modified
Hit return to start merge resolution tool (kdiff3):

Normal merge conflict for '.........':
{local}: modified
{remote}: modified
Hit return to start merge resolution tool (kdiff3):


References

September 11, 2011

July 22, 2011

Regex matching any sign(.) + whitespace characters

To match any sign with a regex the following simple piece of code would work just fine.

Pattern pattern = Pattern.compile(".*"); //compile the pattern
Matcher marcher = pattern.matcher(string); //assign the string to be matched
matcher.find() //find whether the pattern exists. Returns a boolean

But, if you need to include whitespace characters, that is \n,\t, etc the '.' regex will not do the trick. (There is also "\s" regex which captures whitespace characters, but it didn't quite address my problem)

While wandering through the Java API I found a flag which addresses this problem. That is  DOTALL. It will include line terminators into the regex while compiling the pattern. Therefore the new code would be,

Pattern pattern = Pattern.compile(".*", Pattern.DOTALL); //compile the pattern with terminating characters
Matcher marcher = pattern.matcher(string); //assign the string to be matched
matcher.find() //find whether the pattern exists. Returns a boolean

Failed attempt :
  • Tried to include '\n' in the regex.
To specify any two types of characters in a regex usually it is as "[ab]*". Pattern  "[a\\n]*" also works fine. But for some reason "[.\\n]*" doesn't work. So above was the successful solution I found to deal with it.

For a very good tutorial on regex refer here.

Tips
  • Match period
    "." is the symbol used for any character. So if you want to match "." specifically, you need to define the regex as "\\."

June 8, 2011

Using EclipseFP for Haskell

Reference : 

May 20, 2011

Displaying Sinhala in JTextArea

When I first tried to display Sinhala characters in a JTextArea, I got the following result, where all the Sinhala letters were replaced by boxes.

Original text : තමා_PRP හයිටිය_NNPI අතහැර_VNF පලා_VNF ගියේ_VP කැමැත්තකින්

The reason for this is that, it does not render Sinhala fonts.It is not a problem with detection of encoding. You can simply check the system default encoding with code below.
System.out.println(System.getProperty("file.encoding"));
This produced with UTF-8 encoding, which was ok for my requirement.

Now this meant, that the problem is in using an appropriate font for the JTextArea.
 
File fontFile = new File(fontpath); //load the font file
Font newFont = Font.createFont(Font.TRUETYPE_FONT, fontFile);
txtOutput.setFont(newFont); //set the font to JTextArea

The above code will add a font to a JTextArea. Out of the many fonts I tried, only "dinamina.ttf" rendered properly. Even lklug did not provide proper results (It only rendered Sinhala and English characters were not at all displayed). Following is the final output.



Download sinhala fonts from here

Updates :

  • Found our that lklug has only Sinhala fonts
  • Also Bhashitha is another font that worked fine with me
  • May 1, 2011

    for, while and do..while

    for, while and do..while are the three types of loops available for almost all imperative languages. But the concept is same for all of them and they only carry slight variations is syntax.

    One of the concerns when writing a loop is to identify which of the above three is most suitable. It is important if efficiency is an expectation of your program.

    while
    while(condition){
      //code here
    }

    do..while
    do{
      //code here
    }while(condition)

    for
    for( i = 0; i < 10; i++){
      //code here
    }

    while vs do..while
    The while and do..while loops both loop until a condition is false. But the difference between them is that the while loop will check the condition before the first iteration and the do..while will perform the first iteration and then after check the condition. Therefore the change is in the first iteration and after it is finished, there is no difference between the two loops.

    while vs for

    A common mis-use of the while loop is using a counter within it. That is use a counter to keep track of the number of iterations of the loop and making sure to exit the loop when the counter is exceeded.

    i = 0;
    while ( i < 5){
      //code here
    i++;
    }

    The purpose of the for loop is to be used in such situations.

    for ( int i = 0; i < 5; i++){
      //code here
    }

    Therefore, the main difference between the two would be to use the for loop when the number of iterations is known and use the while or do..while when unknown. But there is no real difference in efficiency for a situation as above. Hence, I believe its more of de facto.

    April 25, 2011

    Working on your thesis with OpenOffice Writer

    I admit that open office writer is not as much as user friendly and resourceful as MSWord. But when you cannot use MSWord, I am going to tell you how to customize your headings, section breaks and page numbering.

    Headings

    • Goto Tools->Outline Numbering ->Numbering
    • Select the paragraph style to whichever specify the before, after separators and the Number.
    • Do this for all heading styles.


    Page Numbering

    • Goto Insert->Footer->Default (Default will ignore the cover page)
    • Leave the cursor on the footer
    • Goto Insert->Fields->Page Number
    • Now format the footer as in alignment etc
    • If you want to change the numbering style,
    • Goto Format ->Styles and Formatting ->Page Styles
    • Select the footer and right click->Modify
    • In Page tab, the Layout settings has Format, which can be changed to customize the numbering

    Section Breaks

    April 14, 2011

    Ceylon Tea to replace Java coffee?

    I just came across a new project called "Ceylon Project", thanks to a tweet by @charithsoori. I couldn't find why it is called "Ceylon" though, I am curious to know.
    It has being a secret project for 2 years at RedHat and the first breifing of it has happened on last 9th at Beijing by Gaving King. A copy of the briefing presentation is available from here. I really didn't have time to go through what it is all about, but from what I read it seems to be a very revolutionary language and a challenge for Java. Gavin King has mentioned it as "The Ceylon Project - the next generation of Java language?" at his briefing. This is a good enough statement to give a little thought to as whether tea will replace coffee.

    The aim of the project has being to create a new programming language and SDK for business computing, to overcome the drawbacks of Java. When it is released it will run on the JVM itself. It seems to me as a little into functional programming. Any way hope I had more time to research on it and write a better post :|. The thing which interested me was the name. Why was it named "Ceylon"? Maybe I will be able to write about it some later time.

    සිංහලයාගේ හින්දු අළුත් අවුරුද්ද (ගෞතම සංදේශය 14)

    ජ්‍යෝතිෂය උපන් රට ඉන්දියාවයි. නමුත් එහි බමුණන් වත් සිංලහයන් තරම් ජ්‍යෝතිෂය අදහන්නේ නැත.

    ලංකාවේ බෞද්ධයන් වශෙයන් පෙනී සිටිනා අය සමඟ කතා බස් කළ විට පෙනන්නේ තිසරණය ගැන ඔවුන් තුළ කිසි විශ්වාසයක් නැති බවයි. ඔවුන් ලාභ ප්‍රයෝජන උදෙසා ඕනෑම වෙලාවක කිසි හිරිකිතයකින් තොරව බුදු දහම පාවා දෙන්නට සූදානම්ය. ඔවුන් තිසරණයට වඩා ජ්‍යෝතිෂය විශ්වාස කරන්නේත් කර්ම-කර්ම ඵලයන්ට වඩා නැකත විශ්වාස කරන්නේත් සාධාරණ කරුණු මතය.

    දැන් කාලයක් මුළුල්ලේ කේන්දරයටත් නැකතටත් අනුව කටයුතු කොට ඒ තුළින් ලත් සාර්ථකත්වය ලෝකයටම ඔප්පු කොට තිබේ. සිංහල ජනතාව මේ ලෝකය තුළ දියුණුවේ හිනිපෙත්තටම නැග්ගේ නැකතේ ආනුභාවෙයන් බව දැන් සියල්ලෝම දනිති. කොටින් ම ඇමරිකානු ජනාධිපතිවරයා පවා දැන් සිංහලයන්ගෙන් නැකැත් බලා ගන්නේලු. කේන්දරයේත් නැකතේත් ආනුභාවෙයන් දැන් මහා බලසම්පන්න සිංහල නායකත්වයක් බිහි වී තිබේ. දැන් රට තුළ කිසි ප්‍රශ්ණයක් නැත. ඒ තරම් ම සරුසාරය. ඔවුහු නැකතට කුඹුරු වපුරති. දැන් රට සහලින් ස්වයංපෝෂිතය. ඔවුහු නැකතට එළවළු පළතුරු වවති. දැන් ලෝකයටම එළවළු පළතුරු යවන්නේ ලංකාවෙනි. නැකතට කර්මාන්තශාලා අරඹති. ඒවා කොතරම් සරු ද යත් දැන් සියළු යාන වාහන ඉතා දියුණු මට්ටමින් නිෂ්පාදනය කෙරන්නේ ලංකාවේ ය. ඔවුහු නැකතට බැංකු විවෘත කරති. දැන් දුප්පත් රටවලට ණය දෙන්නේත් ලෝකයට ආධාර දෙන්නේත් ඒ නැකතේ ආනුභාවෙයන් දියුණු වූ බැංකු වලිනි. ලංකාවේ භික්ෂූන් වහන්සේලාත් අතිශයින්ම සිල්වත් ය. ගුණවත් ය. ධර්ම විනය පිළිබඳව අංග සම්පූර්ණ බහුශ්‍රැත බවකින් යුක්තය. ඔවුන් ධර්මය හැටියට පවසන්නේ ශ්‍රී සද්ධර්මයම පමණි. ඔවුන්ගේ මේ සා ආනුභාවයේ රහස කිම? ඒ වෙන කිසිවක් නොව නැකතට මහණ කිරීම නිසාය. දැන් දේශපාලකයෝ පවා සාමය ස්ථාපිත කිරීමට නැකතට පහන් පත්තු කරති.

    දැන් බොහෝ දෙනක් මත්පැන් බොන්නේ ත් නැකතටලු ය. නොහොඹිනා වැඩ කරන්නේ ත් නැකතටලු ය. හරියටම නැකතට ඒ කටයුතු කිරීමෙන් අපල නැතිවේ ලු.

    මේ දිනවල ඔවුන් කඩිමුඩියේ සූදානම් වන්නේ ඔවුන්ට මේ සා සෞභාග්‍යයක් ලබා දුන් සියළු නැකැත් වලින් සපිරි ඔවුන්ගේ අළුත් අවුරුද්ද සමරන්නට ය. සූර්යයා මීන රාශියෙන් මේෂ රාශියට සංකමණය වන්නේ ලු. එය යි ඔවුන්ගේ අවුරුද්ද. ඒ වෙනුවෙන් ඔවුන්ට සියළු කටයුතු කරන්නට සිදු වී තිබෙන්නේ නැකතට ය. ඔවුන්ගේ අවුරුද්ද සමරන්නට දැන් ඔවුන් හමුදාවක් මෙන් සීරුවෙන් සිටිති. නැකතට අනුව සියළු චාරිත ඉෂ්ට කරගත්තොත් ඔවුන්ගේ ජීවිත කිරියෙන් පැණියෙන් ඉතිරී යනු නිසැක ය.

    ඔවුන් සියළු වැඩ නවත්වන වේලාවක් තිබේ. ඒ නැකැත් නැති වේලාව ලු. ආයෙමත් නැකත පටන් ගනී. එවිට නැකතට ලිප පත්තු කරති. නැකතට බත් කති. නැකතට ඇඳුම් මාරු කරති. නැකතට වැසිකළි යති. ඔවුන් ඒ දිනවල සාමාන්‍ය විධියට වතුර නාගන්ටවත් කැමති නැත. ඒකට ද නැකතක් තිබේ. හිසට කොහොඹ කොළ පයට නිදිකුම්බා කොළ තබා නානු ගාගෙන ය නැකතට නා ගත යුත්තේ. ඒ අනුහසින් සියළු රෝග පීඩා සිරුරින් පහවී යනු ඇත.

    නැකතට ආරම්භ කරන ලද ලෝකෙය් දියුණු ම කර්මාන්තශාලා ඔවුන් සතු ය. ඔවුන්ගේ අවුරුද්ද වෙනුවෙන් ඔවුන් එහි වැඩ අල්ලන්නේ නැකතට ය. ඔවුන්ට සල්ලි වලින් කිසි අඩුවක් නැත. නැකතට පටන් ගත් ඔවුන්ගේ බැංකු වලින් නැකතට ගනුදෙනු කළ යුතුය. එවිට ඊළඟ අවුරුද්දේ නැවත සූර්යයා මාරු වී යන තුරු ඔවුන්ට මිළ මුදල් වලින් හිඟයක් නැත. නැකත යනු ඔවුන්ට සියළු දේ ලබා දෙන කප් රුකක් වැන්න. නැකත යනු ඔවුන්ට සිතූ පැතූ සම්පත් ලබා දෙන සිතුමිණක් වැන්න.

    මෙතරම් දේවල් නැකැත් තුළින් සාර්ථක කරගත් ඔවුන්ට තව දුරටත් කළ යුතු එක දෙයක් තිබේ. එනම් නැකතට දිවි නසා ගැනීම යි. එවිට ඒ නැකෙත් අනුහසින් ඔවුන් සුගතියේ යනු ඇත. ඊට ප්‍රථමයෙන් හොඳ නැකතක් බලා අං තට්ටුවක් පැළඳ ගත යුතු ය. එවිට ඒ නැකෙත් අනුහසින් කකුල්වල කුර හට ගැනීමෙන් ඒ කටයුත්ත සම්පූර්ණ වනු ඇත.

    මේ ගැන කිව යුතුව තිබෙන්නේ එකම එක දෙයකි.
    නැකැත් කේන්දර පිස්සුව අතහැර තිසරණය ට පැමිණෙන තුරාවට ඔවුන් සතර අපාය කරා ගෙනයන මිථ්‍යාදෘෂ්ඨියෙන් නම් ගැලවිල්ලක් නැති බවයි.
    - පූජ්‍ය කිරිබත්ගොඩ ඤාණානන්ද ස්වාමීන් වහන්සේ විසින් බෝධිඤාණ සඟරාවට සපයන ලද ලිපියක් ඇසුරෙන් -

    ‘ගෞතම සංදේශය’
    - මුලාවෙහි ගිලෙන්නට නොව අවබෝධයෙහි සැරිසරන්නට....

    (Copied from a note on FB)
    If you still believe in New Year, wow..you are hard to break. congrats :P