Print to console without using semi colon

April 24, 2008

One of my friend asked : “How can one write to console without using semi colon in Java ?”.
I tried many work-arounds . Even Googling did net help much .

I thought i should raise an exception some how thats it some thing will be written on the console. Naa , its did not work well.

Then a stupid workaround was to enable the verbose argument , thats it every class loaded in the JVM is traces on console.

The some how i tried real tricks to print my name on console ,

This is what i got,


public class Test {

 public static void main(String a[]){

 if ( System.out.append(”jasdeep”) instanceof Object ){

               }
         }
  }

You might be wondering , why i did not use System.out.println() . Because it does not return anything , So it can not be compared in if block.


When Synchrozation Fails in Java

April 21, 2008

My blog title goes like “Ramblings about workplace, java, python, linux and web ” . But my recent posts were distracted from this tagline. The frank answer to this is I was procrastinating. It is not i have not been learning much. I have learnt a lot of new things professionally but could not get them together to share my learning on the blog.

I was surfing the web to dig deep into Java, When i came across this great post by Curious Schemer.

Mr Ray deliberately explains things in the post that we are rhetorically asked to use ArrayList over Vector for better performance .
If we need to make it thread safe. We do it this way :
List list = Collections.synchronizedList(new ArrayList());
But it does not solves the purpose. The thread safety breaks if we do something like this :

final List list = Collections.synchronizedList(new ArrayList());
final int nThreads = 1;
ExecutorService es = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++) {
  es.execute(new Runnable() {
  public void run() {
  while(true) {
  try {
  list.clear();
  list.add(”888″);
  list.remove(0);
  } catch(IndexOutOfBoundsException ioobe) {
  ioobe.printStackTrace();
  }
  }
  }
  });
}

As long nThreads is 1, everything runs just fine. However, increase the number of nThreads to 2, and you start getting this:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

at java.util.ArrayList.RangeCheck(Unknown Source)

at java.util.ArrayList.remove(Unknown Source)

at java.util.Collections$SynchronizedList.remove(Unknown Source)

Now the workaround to get away with this problem , is to use block level synchronization . Synchronize the methods which update the list to the fine grain level is the best approach to avoid such exceptions .


synchronized (list) {
  list.clear();
  list.add(”888″);
  list.remove(0);
}

I learnt my lesson here , one should use atomic level synchrozation to keep the performance and effeciency intact.

The Full Post by Mr.Ray is worth read it explains further conflicts in using synchronization .


Fighting Traffic Chaos

April 20, 2008

Some years back when I came to City Beautiful ‘Chandigarh’ . Like everybody who comes here I fell in love with the place. For its planned Living,Gardens, Broad roads with trees along sides. There was hardly any traffic problem those days.
There is a duet Punjabi songs which goes like :

“To drive on roads of Chandigarh is like, paper boat sailing on water flow”
“The decorated round abouts are like , The embroidery done by you “

This was true some years back, when traffic was sparse.

Chandigarh is a heaven for students for its academic institutes,entrance coaching centers,training institutes.It has attracted students here like a magnate. Industry has also been set up here in Chandigarh/Panchkula/Mohali tricity. So almost every Punjabi youth comes here looking for a job. Industry also attracts/recruits people from all over India. Although the Industrial growth has not been so steep here relative to other cities.

Accumulation of people here has given rise to traffic chaos in the City Beautiful. To accommodate traffic administration has to cut down the trees along side one of the main roads to broaden it,has changed round abouts into traffic signals,has improved public transportation system. But still it is unable to contain the rising traffic. Driving at 8-9 PM has become like hell.

The workaround to fight traffic chaos which people like us can do is :

  • Car Pooling for offices
  • Increase Use of bikes and bicycles
  • Better public transportation system

Car Pooling

In Western countries a concept of Car Pooling was stated way back Seventies . It has broadened to SMS based / Web Based Carpooling system, and is quite successful also.

In India MyKoolPool is such venture which provides Web/SMS based in Mumbai and Pune. Maybe there such venture like Commute Easy in Bangalore and other cities too .
We have to give push to such ventures in our cities too and In City Beautiful Chandigarh so that it can be kept beautiful.

Using Bikes / Bicycles
The economic rise has thwarted the use of cars, with exponential rate . Which has definitely made the traffic more chaotic than anything else.
Using a bicycle for commuting is rare by people like us. Although it is common for laborers an economically weaker people.
We need to start a bicycle riding campaign, Such that people like us make lesser use of motor vehicles for common commuting , like visiting nearby places or offices.
Yes I know, there is status conscience setup in our psyche, That is the only reason we don’t use bicycles anymore. But It will be great if we can change this status conscienceness.
Use of bicycle has many advantages like :

  • Zero Pollution , It has no Carbon emission.
  • Lesser traffic , It does not need a Broad Road .
  • Better health, Cycling is a good Exercise for body

Yes , Bicycle is non feasible for commuting to longer distances, But use of motor bike is still more traffic friendly , than a car.

Personally i use a mix of Bicycle and Motor Bike for commuting . I go to office on a bicycle and sometimes on the motor bike. In my previous organization which was near to my living place. I always used bicycle for commuting there. And mind you I was not labeled psycho or My status qoutiont was not questioned. It was welcomed by most of my friends actually. I have inspired One of my friend to ride bicycle. there are 3-4 more guys in my new organization which commute on bicycle. But we are quite a small no. people. We need to start a campaign such that It becomes a trend to ride to office on a bicycle. It is quite common in some of European countries.

Come On , Ride Bicycle a day and Keep the Doctor Away. :)

Public Transportation
The public transportation system is quite messy in almost all the cities. Either the buses/trains are crowded with passengers, or the the time taken to reach the destination is quite long.
I Wish If we can make public transportation system such that it gives one preference over using Car to commute.
It is only possible if the

  • buses/trains are made high on comfort.
  • Better routes to the common destinations

Moreover for commuting to office locations , Initiative needs to be taken for Public/Private partnership. Although some corporates have there private commuting vehicles. but they are not much effective. People prefer personnel vehicles over them. I hope public-private partnership can provide a better alternative. As small enterprises can also afford to tie up with public transportation system.

Happy Commuting, People :)


Reservation and Education System of India

April 11, 2008

The headlines today are huddeled with Reservation being introduced into the IIMs and IITs (the premier institutes for giving higher education and management) for Backward and Other Backward Classes (BC and OBC) excluding their creamy layer. There has been mostly anti-reservation campaigns and little pro-reservation campaigns too.But the state has the stick in its hands , it can do what it wants.

Rather than going into same debate whether reservations should be or should not be. I want to know :

Will reservations help in socio-economic upliftment of targeted masses?

Reservation is a just a shock therapy to prevent the damage done by our grass root Public education system. There is no sight of any improvement in Public education system.

I won’t go into statistical details, But what i have experienced 

I am product of an Village Government School in State of Punjab(One of the affluent states of India). The school where i studied was called the best school in the locality, But the study culture there was like, we were made to learn from the help books rather than reading texts. English was started in 6th grade by Social Sciences teacher because there was no English teacher and After 8th grade there was no arrangement for English language teaching. There were no extra-curricular activities, no games. It was the time when the school was called in its prime time.

After that the school has gone to worst conditions , the only way the kids clear is by Mass cheating in the exams. The alternative to the government schools are private schools which employ teachers on salaries of 1000 to 1500 and who are product of those government schools. They are called English medium schools , but there is hardly any healthy learning environment.

The economically weaker parents put there kids into Government schools and economically stronger put them into those private schools out come from both schools are almost the same. This is the story of nearly 70% of Punjab and one can imagine the status of other states.

Those to who study in good city schools , are taught good English, are given good environment, are made to take part extra curricular activities. They face the pressure of doing good in the exams in terms of scores . The focus is on getting scores by hook or crook rather than learning. there is no healthy competition ,There is lethal competition. We don’t study what we love. We study what we are made to study. I want to know :

Are there any measures taken to improve the quality of education?

Revolutionary changes needs to be done in Education system, But i don’t think there is any step being taken in this direction because this will have long term benefits.

Improvement in Education system would not fetch votes, But Reservations will fetch them quick votes .

We are amused by the way India is progressing , we are amused the way Dhoni’s are fetching crores. We are amused be the way India’s riches  has made into the Forbes list.

We don’t care how the other half lives, and  Then we are worried about the biggest Internal threat to security are Naxalites. We are amused why they are so evil, we are amused why they can’t be like us.

 


My Shell history

April 11, 2008

When i opened my Google reader this morning , cam across this little awk kiddie. So ran it for my ubuntu shell. It tells the story that i have not been doing anything worthy , only procrastinating

history|awk '{a[$2]++ } END{for(i in a){print a[i] ” ” i}}’ |sort -rn|head
84 cd
66 ls
43 sudo
15 python
10 django-admin.py
6 svn
6 ln
4 youtube-dl
4 pidgin
4 cd..

The original script lies here.


Lisp,Python and Java

January 29, 2008

While acting on my new year resolutions, I started reading the SICP book .
The book focuses on the aspects of computer programming fundamentals and making the reader learn this by problem solving through LISP  programming language.

So in the first chapter i had to solve some problems , and one of them was :

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

So my implementation of this problem in LISP is here :

(defun square(x) (* x x) )
(defun sum-of-square(x y) (+ (square x) (square y)))
(defun grt(a b) (if(> a b) a b))
(defun grt-2-sum-of-square (a b c )
(sum-of-square (grt a b) (grt b c) )
)
(grt-2-sum-of-square 1 2 3)

I implemented the same problem with python as following :


#Returns Square
def square(x):
return x*x
#Returns Sum of the Squares
def sum_of_square(x,y):
return square(x)+square(y)
#Returns greater number
def grt(a,b):
if (a>b):
return a
else:
return b
#Returns the sum fo square of greater numbers
def grt_2_sum_of_square(x,y,z):
a=grt(x,y)
b=grt(y,z)
return sum_of_square(a,b)
# If main mein module is called
if __name__==”__main__”:
#print result
print grt_2_sum_of_square(1,2,3)

and implementation of same problem in Java goes like this :


public class Test {
// Returns the Square
public int square(int x){
return x*x;
}
// Returns sum of the Squares
public int sum_of_square(int x,int y){
return square(x)+square(y);
}
//Returns greater number
public int grt(int x,int y){
return (x>y)?x:y;
}
//Return the sum fo square of greater numbers
public int grt_2_sum_of_square(int x,int y,int z){
int a=grt(x,y);
int b=grt(y,z);
return sum_of_square(a,b);
}
// Main Method
public static void main(String a[]){
//instantiates class
Test t=new Test();
int res=t.grt_2_sum_of_square(1, 2, 3);
System.out.print(res);
}
}

There are easier ways of implementing it in python and Java though . But i preferred these as i implemented the same LISP construct. I am amused by the simplicity and cleanliness of LISP code here and no. of lines i had to write for doing this.

I wish i should have been taught LISP in school and i would have been a better programmer :)

Python gives me pleasure of code elegance and simplicity, but Java is the one i am working with . The one that got me a Job.

Learning new things make me feel better, that there is no end to learning.

Powered by ScribeFire.


My New Year Resolutions - 2008

January 3, 2008

Its dawn of the new year. Every things seems fresh, though its just a psychological feeling.The past is past, everybody make plans for the future, and I have some too.I scribbled some lines in Punjabi on new year eve.Here is English translation :

"have dreams in the eyes,
and passion to live the dreams..
have tides of wishes,
and courage to achieve those.. “

Punjabi Source Here

So my new year resolutions will be a progress in living my dreams .

Professional/ Academic :

Personal :

  • Learn Urdu langauge/script , to be efficient in reading and translating Pakistani Punjabi /Shahmukhi.
  • Have personnel web space and host/migrate my blogs there.
  • Will make cycling/exercising a habit.
  • Will start writing a diary
  • Will look for a girl friend… :)

Books To Read:

My Predictions :

  • Open Source is going to rule that is for sure . Linux (especially ubuntu) will give the fight to windows in desktop war.
    I am excited about KDE4 release.
  • Google will be drifting from ” Don’t Be Evil ” policy .
  • A Multipolar world order as US hegemony gets counter balanced by Russia, Iran and Venezuela trio.

Hmmm. It has become quite a long list . Hope I make all of these . I will appreciate if anybody has similar/anti thoughts on this, please do drop me a comment..


Alvida 2007

December 18, 2007

2007 has come to an end … Here is my analysis of my surroundings and things i am interested in . Here are the happenings :

Globally

  • Open Source has arrived , It was more vibrant this year. Sun Micro systems open sourced its premier programming language Java , its operating system Solaris , even its processor chip ultraspark ( a first).
  • Ubuntu captured the buzz in the Linux word and has become the alternative to windows along with opensuse . Its Linux era now as Windows Vista failed to create any impact . Go Linux Go. KDE4 is going to launch in January next year. Which is going to be another feather in the cap as its looks will be rock the Vista look and feel. Go Linux Go
  • Google joined hands with various telecom companies and formed open handset alliance which announced its mobile SDK andriod in November this year. Google joined hands with IBM-Sun camp for ODF as document standred to challenge Microsoft’s OpenXML. Although being involved in open source ventures , Google is said to be drifting from its “Don’t be Evil” policy.
  • The world is fastly moving to multipolar world as US hegemony is weakened by various elements like weakning of Dollar diplomacy, President Bush’s wrong stance on Iraq war. The countries like Russia,Iran ( in Asia ), Venezuela, Cuba (in Latin America) have risen as poles of new word order. Venezuelan President Hugo Chavez is the greatest challenger of the US hegemony in his region . With his oil diplomacy and pro people policies he has won support of earlier US allies in Latin America.

Personally

The year was a great learning experience in many aspects of life , professionally and personally :


XKCD:Python

December 5, 2007

Python

XKCD:Python import antigravity …


Exploring Display Tags

November 7, 2007

Being a J2EE developer you have an edge over others , as you can explore thousands of prebuilt open source components over internet . Display Tag is one cool component which i explored recently .

It provides pagination to the JSP page , one just have to set the arraylist of bean object int the request scope of the page and display tags iterate that arraylist and provides a cool tabular view of the data. One just have to mention property names of beans in the dispaly column tag. It uses commons beanutils for iterating the beans.

Now my point in exploring is that i had to provide much more functionalty for my project .

1. Sorting by table headers
2. Exporting to CSV , Excel file .

Both had a simple solution i just had to mention “export=true” in the table header for exporting the table data.

I had to write “sortable=true” in the table column.

Sorting worked out fine with String values but , there was error for date column as it took date as string also. So i had explore more .

What i did, I changed the type of my date field in bean to java.util.Date . The sorting problem was resolved , But the date format caused problem as i had to show it in GMT . For that I downloaded the source code of display tag from sourceforge. There is org.displaytag.sample package in the source . I placed the source of this package in my code and added decorator to the column :

Now it displayed the proper output.

Now with export set to true in table header . It display links to export in CSV,EXCEl,PDF,RTF formats etc. for exporting to be prper ihad to add ‘displaytag.properties’ to the classpath of my application .

export.types=csv excel xml pdf rtf
export.excel=true
export.csv=true
export.xml=true
export.pdf=true
export.rtf=true
export.excel.class=org.displaytag.export.excel.DefaultHssfExportView
export.pdf.class=org.displaytag.export.DefaultPdfExportView
export.rtf.class=org.displaytag.export.DefaultRtfExportView
export.excel.filename=data.xls
export.pdf.filename=data.pdf
export.xml.filename=data.xml
export.csv.filename=data.csv
export.rtf.filename=data.rtf

But it still didn’t work it displayed all the records on the next page.

So what i had to do to sort out the problem was to add a filter fior exporting in the web.xml.

Configure the Filter in your web.xml:

ResponseOverrideFilter
org.displaytag.filter.ResponseOverrideFilter

And add mappings for urls the filter will intercept, for example:

ResponseOverrideFilter
*.do

ResponseOverrideFilter
*.jsp

Thats it . I made my report table specfic to the client needs.
Thanks Display Tags.

Long Live The open Source Revolution.


  • Support Them

  • DefectiveByDesign.org
    Protect your freedom!
  • bad vista
  • Archives

  • Blog Stats

  • Meta