## Saturday, December 19, 2009

### Order a list as per list using scheme

The below program takes in a list of arguments and orders them as per the second list.

(define (nth lst1 lst2 n)
(if (= n (car lst2)) (car lst1) (nth (cdr lst1) (cdr lst2) n)))

(define (order lst1 lst2)
(define (order-help n)
(if (> n (length lst1)) '() (cons (nth lst1 lst2 n) (order-help (+ n 1)))))
(order-help 1))

(order '(a b c d e) '(1 2 3 4 5))
; Value 1: (a b c d e)
(order '(a b c d e) '(4 1 2 3 5))
; Value 2: (b c d a e)
(order '(a b c d e) '(5 4 3 2 1))
; Value 3: (e d c b a)
(order '(a b c d e) '(1 5 2 4 3))
; Value 4: (a c e d b)

## Friday, December 18, 2009

### My maximum and minimum procedure in scheme

Scheme comes with two built-in procedures to get the maximum and minimum of a given set of numbers. The documentation explains the procedures as below:

(max x ...+) → real?
x : real?
Returns the largest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact.

Examples:
> (max 1 3 2)

3
> (max 1 3 2.0)

3.0
(min x ...+) → real?
x : real?
Returns the smallest of the xs, or +nan.0 if any x is +nan.0. If any x is inexact, the result is coerced to inexact.

Examples:
> (min 1 3 2)

1
> (min 1 3 2.0)

1.0

My own implementations of max and min also work in the same way, including that fact that (max 1) will return 1 instead of an error that only one number is given. The code for max and min are the same except for the signs.

(define (mymin x . lst)
(define (myleast lst6 last)
(if (null? (cdr (if (pair? lst6) lst6 (list lst6)))) last
(if (<> last (car(cdr lst6))) (myleast (cdr lst6) last) (myleast (cdr lst6) (car (cdr lst6))))))
(myleast lst x))

(mymax 2 3 4 5 6 1)

These procedure demonstrate the simple concept of sending 1 or more arguments to a scheme procedure. The arguments come into the procedure in the form of a list. The operator "." does the trick.

## Wednesday, December 16, 2009

### Scheme program for accumulate - n

The following are two implementations of accumulate - n one that uses map and another that does not. However, both use accumulate procedure.

(define (accumulate op init lst)
(if (null? lst)
init
(op (car lst)
(accumulate op init
(cdr lst)))))

Implementation 1:

(define (accumulate-n op init seqs)
(if (null? (car seqs))
'()
(cons (accumulate op init (car seqs))
(accumulate-n op init (if (pair? (cdr seqs)) (cdr seqs) (list(cdr seqs)))))))

(accumulate-n + 0 (list (list 1) (list 4 5 6)))

Implementation 2:

(define (accumulate-n op init lst)
(define (accumulate-help lst)
(accumulate op init lst))
(map accumulate-help lst))

(accumulate-n + 0 (list (list 1 2 3) (list 4 5 6) (list 7 8 9)))

## Saturday, December 12, 2009

### 3 Missionaries and 3 cannibals - crossing the river

3 missionaries (or sheep or carrots) and 3 cannibals (or wolves or rabbits) stand on a riverbank. On
the same riverbank a boat, that can maximally take 2 persons (minimally 1), lies. The 6 people are
facing a problem: how to optimally transport (minimal number of moves) ourselves from
the current riverbank (the left one) to the opposite bank of the river (the right one) in a way
that guarantees that at any time the number of cannibals never outnumber the number of
missionaries (they will then be eaten)?

The missionaries and cannibal problem is a popular problem used in Artificial intelligence to understand and experiment with search methods. Here is a list of the possible optimal solutions for the various cases

1 cannibal and 1 missionary

Step1:(left 1 1 0 0)
Step2:(right 0 0 1 1)

2 cannibals and 2 missionaries

Solution1:
((left 2 2 0 0) (right 2 0 0 2) (left 2 1 0 1) (right 0 1 2 1) (left 1 1 1 1) (right 0 0 2 2))

Solution2:
((left 2 2 0 0) (right 1 1 1 1) (left 2 1 0 1) (right 0 1 2 1) (left 0 2 2 0) (right 0 0 2 2))

3 cannibals and 3 missionaries

Solution1:
((left 3 3 0 0)
(right 3 1 0 2)
(left 3 2 0 1)
(right 3 0 0 3)
(left 3 1 0 2)
(right 1 1 2 2)
(left 2 2 1 1)
(right 0 2 3 1)
(left 0 3 3 0)
(right 0 1 3 2)
(left 1 1 2 2)
(right 0 0 3 3))

Solution2:

((left 3 3 0 0)
(right 2 2 1 1)
(left 3 2 0 1)
(right 3 0 0 3)
(left 3 1 0 2)
(right 1 1 2 2)
(left 2 2 1 1)
(right 0 2 3 1)
(left 0 3 3 0)
(right 0 1 3 2)
(left 0 2 3 1)
(right 0 0 3 3))

2 cannibals and 3 missionaries

Solution1:

((left 3 2 0 0)
(right 2 1 1 1)
(left 2 2 1 0)
(right 1 1 2 1)
(left 2 1 1 1)
(right 1 0 2 2)
(left 1 1 2 1)
(right 0 0 3 2))

Solution2:

((left 3 2 0 0)
(right 3 0 0 2)
(left 3 1 0 1)
(right 1 1 2 1)
(left 2 1 1 1)
(right 0 1 3 1)
(left 1 1 2 1)
(right 0 0 3 2))

1 cannibal and 2 missionaries

Solution1:

((left 2 1 0 0) (right 0 1 2 0) (left 1 1 1 0) (right 0 0 2 1))

Solution2:

((left 2 1 0 0) (right 0 1 2 0) (left 1 1 1 0) (right 1 0 1 1) (left 2 0 0 1) (right 0 0 2 1))

0 cannibal and 1 missionaries

((left 1 0 0 0) (right 0 0 1 0))

Solutions are not possible for numbers greater than 3 or cases in which cannibals outnumber missionaries.

## Tuesday, December 8, 2009

### Prime number or not program - scheme

There are many different procedures for testing primality of numbers. One way to

test if a number is a prime is to find the number's divisors. If a number n is prime then

n equals the smallest integral divisor of n.

Below procedure tests if a number is a prime based on the above method.

(define (is-prime-help n count) (if (= count 1) #t (if(= (modulo n count) 0) #f (is-prime-help n (- count 1)))))

(define (is-prime n) (if(<>

Another method is related to Fermat’s little theorem:

If n is a prime number and a is any positive integer less than n, then a raised to the

nth power is congruent to a modulo n.

Two numbers are said to be congruent modulo n if they both have the same remainder

when divided by n. Trying a random number a <>, one can be sure that n is not prime

if the remainder of an modulo n is not equal to a. However, the opposite does not

always hold, i.e. a number n is not always prime if the remainder of an modulo n is

equal to a. By trying more and more random a <>, one can get more confident that n

is prime. This algorithm is known as the Fermat test.

Below implements a Fermat test procedure.

(define a 0)

(define (ftp n k) (cond((= k 0) #t) ((= n 2) #t) ((<>

Fermats test is not always accurate as fermat liers can complicate the situation. Modified versions of Fermats test however provide more accurate results.

## Sunday, December 6, 2009

### How many pins?

In bowling one often uses ten pins positioned on four rows. How many pins are needed for five rows, six rows, or n rows (where n is a positive integer)?

The below procedure calculates the number of pins needed for n rows recurssively.

(define (number-of-pins-rec n)(if(= n 1) n (+ n (number-of-pins-rec(- n 1)))))

> (number-of-pins-rec 2)

3

> (number-of-pins-rec 4)

10

> (number-of-pins-rec 5)

15

> (number-of-pins-rec 6)

21

The procedure in a iterative process.

(define (number-of-pins-it-help n sum count)

(if (> count n)

sum

(number-of-pins-it-help n

(+ sum count)

(+ count 1))))

(define (number-of-pins-it n)

(number-of-pins-it-help n 0 1))

> (number-of-pins-it 3)

6

> (number-of-pins-it 4)

10

> (number-of-pins-it 5)

15

> (number-of-pins-it 6)

21

> (number-of-pins-it 7)

28

## Tuesday, August 4, 2009

### Simple encryption method in Unix using grep command

You can encrypt text with the "grep" command in Unix. You need a file with lot of junk data, a regular expression that will be the key and the text that needs to be encoded(with one character in each line).

To encode the text do the following steps.

1)grep -f regularexpressionfile junkdatafile1>result1

• The regularexpressionfile and result1 file should have equal number of lines.
• regularexpressionfile cant begin with "^".
2)paste texttoencode result1>result2

3)grep -vf regularexpressionfile junkdatafile2>junkdatafile3

4)paste -d"\n" result2 junkdatafile3>encryptedtext

To decode the text do the following

1)grep -f regularexpressionfile encryptedtext|cut -c 1

## Saturday, July 11, 2009

### Windows unix cut command - column cut mode

The second part of the Windows Unix Cut command implements the column cut mode of the Cut command. By specifying flags such as -c for column cut mode and -p for entire file cut mode, the program can be used to cut the file based on column and file respectively.

This functionality is available in Editplus which offers column select option, but the command line tool can be very useful while cutting enormous files. The latest code is given below:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[1]);
out = new FileOutputStream("cutoutput.txt");
if(args[0].equals("-p")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
}
else if(args[0].equals("-c")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =1;out.write('\n');/*System.out.println();*/}
count++;
if(count>=llim && count<=ulim){
//System.out.print((char)c);
out.write(c);}
}
System.out.println("Output to be viewed in Wordpad or higer only" );
}

} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

## Saturday, June 27, 2009

### How Often should one change the toothbrush?

Different people use different criteria to change the the tooth brush. Few criteria are as given below:

1. Till the number of days recommended by the dentist(generally 3 months)
2. Till the number of days recommended by the toothbrush company(generally 3 to 6 months)
3. Till after an illness
4. Till the toothbrush just wears out
5. Till the toothbrush starts stinking
6. Till it gets lost
Although the first two criteria seem sensible enough, they are not based on any quantification of individual toothbrushes. The same toothbrush may become worn out and become a breading ground for germs within a week in one case while it may be fine for 3 months in another case.

So a scientific method would be to have a few bristles that act as a Ph strip. The bristles will be white till the Ph value crosses a particular threshold value. After the Ph crosses the threshold value and starts to become a breading ground for either fungus or bacteria(acidic or basic) the bristles will change color. Few other chemical tests(such as tests for toxins) can also be used to change the color of the bristles. The user of the toothbrush can change the brush after the color changes.

Tooth brush change frequency can also be calculated based on Number of bristle breaks per day averaged over a 3 month period to get your individual toothbrush change frequency for any particular brand of toothbrush.

The toothbrush companies will probably introduce these type of toothbrush when they are economical and desirable to all.

Do comment below if you use some other criteria for changing your toothbrush.

## Friday, June 26, 2009

### A Prisoner Of Birth – modern version of the Count of Monte Cristo

A Prisoner Of Birth by Jeffrey Archer is a modern version of the classic “The Count of Monte Cristo”. However, it does not lack in originality and has been well researched. For example, Japanese knotweed can indeed destroy a building site and bring down the lands real estate value considerably.

The similarities between the “The Count of Monte Christo” and “A prisoner of Birth” are many such as the following:

1. Cartwright is the first prisoner to escape from Belmarsh while Dantes is the first to escape from Chateau dlf.
2. Sir Nicholas, a fellow prisoner teaches Cartwright to read, write and the manners of polite society, while Abbe Faria does it for Dantes.
3. Cartwright escapes as Sir Nicholas on the death of Sir Nicholas while Dantes escapes as the dead body of Abee Faria.
4. Both Cartwright and Dantes make use of a title after escaping from prison.
5. Cartwright gets a huge treasure in the form of stamps from Nicholas’s grandfathers will while Dantes gets the treasure hidden by Abbe Faria.
6. Both Cartwright and Dantes set out to exact revenge on those who led to their unlawful imprisonment.
Jeffrey archer has also included many of the features of the musketeers and makes known to all off his admiration for Alexander Dumas and his works. Although the book is continuous and believable for the most part, the part where the trial of Cartwright is dismissed based on the discussion between Spencer Craig and Sir Marshall is rather sudden.

## Tuesday, June 16, 2009

### Program to cut text file from character position x to y

I was searching for a windows equivalent to the Unix "cut" command. However, none could be found. So this java program will eventually do all that the Unix "cut" command does and more.

The functionality i required was to cut a text file between two given positions.Although this seems simple enough, notepad, textpad etc. don't have this facility. Hope this initial version will help those of you who want to cut a text file between two points. The program does not consider newline characters, but tab, space etc.. are considered while counting.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[0]);
out = new FileOutputStream("cutoutput.txt");
int c,count=0,llim=Integer.parseInt(args[1]),ulim=Integer.parseInt(args[2]);

while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

## Monday, June 15, 2009

### Study in Sweden - Part - II - Applying for Residence Permit

Check the Part I of the Study in Sweden series for applying to Swedish Universities.

The first thing to do after getting selected for a university is to apply for a residence permit. You can apply for the residence permit in any of the Swedish consulates or embassies. More details regarding the Residence permit can be found on the website of the Swedish Migration board.

If you are applying for the residence permit at CONSULATE OF SWEDEN at CHENNAI, few details regarding the documents required is given below:
Note:These details may change and its best to contact the consulate for latest details.
1. Two sets of application forms duly completed and signed (Form No. 105031). The forms can be downloaded from the site .
2. Valid passport along with two photocopies (of pages 1,2 and last)
3. Educational certificates (last exam/degree) – original for perusal and return. Two sets of photo copies
4. Admission letter from university/college plus two copies. Study should be fulltime.(PDF file can be downloaded from studera site)
5. Accommodation must be arranged for in Sweden.
6. Separate Demand drafts for Rs.6000 (application fee, subject to change without prior notice) and Rs.300 (courier fee) being the application fee and courier fee drawn in favour of Consulate of Sweden payable at Chennai.
7. One must be able to show a minimum of SEK 7 300 per month for 10 months in a year. Applicant is requested to show proof of financial support for the entire planned study period and show the funds in your savings account. Bank certificate and transaction statement original plus two copies. If your stay is one year or less than one year. Please enclose the insurance papers
8. Three passport size photographs (latest specification given below).
Instructions concerning photographs which are to be used for visa and permit stickers

• The photograph should be maximum 6 months old.
• The width of the photograph should be 35-40 millimeters
• The area of the face should be 70-80 of the photograph.
• The whole face including part of the shoulders should be visible.
• The photograph should have a good colour balance, contrast and sharpness.
• The face should be seen directly from the front against a light background. There must not be other people or objects in back-ground.
• Both eyes with pupils should be completely visible.
• Dark tinted glasses must not be worn, unless required for medical reasons.
• The face should be evenly illuminated and there must be no shadows visible in the background.
• There must not be any reflections visible in Glasses.
• Head coverings are not permitted except for religious reasons. The whole face must be visible.
• The photograph should show the person alone with a neutral facial expression and the mouth closed.
Other points of note:

1. Submission of application between 10.00 am. To 12.30 pm. from Monday to Friday at the Consulate.
2. The application is forwarded to the Migration Board in Sweden for decision.
3. The application must be submitted at least eight weeks prior to departure for Sweden
4. Please note, photocopies of all documents submitted with the application must be on A4 size paper
6. All enquiries on your application will be answered only between 2-3 pm. Mon-Fri. on Tel: +91-044-28112232
The Swedish consulate is located on Cathedral road and can be easily located on google map. If you have any other questions, just comment below.

## Saturday, June 13, 2009

### Study in Sweden - Part - I - Applying for universities

In this series of posts i hope to cover the various steps of Going to study in Sweden.

How to apply to Universities in Sweden?

To apply to any university in Sweden a single application can be submitted through the Studera site . Click on the British flag for English version of the site. The site opens up admissions for different semesters( Autumn or Winter) at different times. Keep watching the site for updates.

Although studying in Sweden is free for all till now. Its expected that a fee will be charged for non-Swedish Nationals in the coming years. See a list of all Swedish universities here. If you want details regarding individual courses offered by each of the institutes, better check the institutes websites. As of 2009, only four courses can be applied per semester.So choose the courses that you want to apply wisely.Also make sure you rank them according to your priority. If you want to go to a university ranked fourth, but have got admission to the first choice, few universities allow you to get admission directly.

The documents that will be required are listed in the studera.nu website. The transcript can be obtained directly from your university by sending a Demand draft and other details. Generally this takes up to 15 or even 20 days by post. So better apply for the transcript early.

The letters of recommendation need to be obtained from your professor's and faculty, need to be sent along with the application.

A motivation letter apart from the CV needs to be sent along with various certificates and proofs. Generally the degree certificates and other marks cards are expected. Its mandatory that all the certificates and marks cards are approved by a Notary.

The application can be sent by Speed post or courier. The Indian speed post is rather reliable and sometimes better than private courier services. On an average it takes at least a week for the letter to be sent to Sweden from most parts of India and costs around INR 800.

If you have any doubts regarding any step, just comment below.

## Wednesday, May 27, 2009

### The cardamom habit - Carry it wherever you go

Cardamom which is known as the Queen of Spices smells good and is not yet known to cause any harm to the body. No wonder the Spices Board Of India is promoting it with gusto.

A soldier came running to the king, and told him about how the Europeans were loading Spice rhizomes onto their ships. The soldier was scared that the Europeans will never come back for spices if they could grow it in their own country. The King laughed at the foolishness of the soldier and said "They can steal the seeds but they cant steal our monsoon".

Although its easy to grow cardamom, it rarely blossoms outside the tropics. So the king was correct in his optimism, but the monsoons brought not only rain but also Europeans to India. So the next time you plan to leave the tropics, don't forget to carry it with you. Habits die hard

## Friday, May 22, 2009

### Flags that have appeared in Google logos - till April 2009

This is a list of all flags that appeared in Google logos from 1999 to April 2009. It goes to prove that google is International and not limited to America.
1. US National flag for the government related sites search. (Uncle Sam search)
2. The French National flag appeared in the Google logo for Bastille Day
4. The Swiss National flag appeared in the Google logo for Swiss National Day 2001
5. The South Korea National flag appeared in the Google logo for Korean Liberation Day or Gwangbokjeol 2001
6. St George's Cross flag or National flag of England appeared in the Google logo for St George' Day 2002.
However, we are yet to see a Non-US ally's flag making it onto the google homepage. Either they are still in the cold war era or just dont know about other countries :) .

### World Turtle Day - Fake Google Logo?

Tomorrow 23rd May is World turtle day. It was started in the year 2000 by American Tortoise Rescue to bring about awareness about turtles and tortoises. It is celebrated in different ways like:

• Dressing up like turtles
• Turtle and tortoise Conservation efforts
• Rescuing of turtles and tortoises from illegal captivity

The main danger to turtles comes from human beings and many turtle species are endangered today due to excessive hunting. The flesh of turtles is considered a delicacy in many cultures. Turtle soup which is made from the flesh of the green turtle or the snapping turtle can lead to the killing of large number of turtles. Few endangered species of turtles are also killed for food, leading to further reduction in the population of the endangered species.

Turtles can be saved from the fate of the dodo by bringing about awareness among people. Hope google decides to support the turtle conservation efforts by putting a logo on World turtle day.If they can come up with a famous Turtle day Google logo, it will do a lot to help conserve turtles. Until then this fake google logo has to do.

### International Day for Biological Diversity - Invasive Alien Species

When I say alien species, I am not referring to green men from mars. These are species alien to a given eco-system. Plants, animals, pathogens and other organisms can all act as invasive alien species to destroy the biodiversity of a place. The conservation of biodiversity is being debated and tackled by the Convention on Biodiversity.

The decline or elimination of native species can occur through:

1. Competition(Ex: Lantana camara, also known as Spanish Flag reproduces and spreads very quickly and poses a threat to other native species in few eco-systems)
2. Predation (EX: Rattus rattus, commonly known as the ship rat has caused extinctions and catastrophic declines of native birds on islands)
3. Transmission of Pathogens (Ex: Pathogens such as avian influenza A(H5N1)are attacking various organisms.)
4. Disruption of natural eco-system(Ex: Eichhornia crassipes, commonly known as Common Water Hyacinth has lead to disruption many ecosystems by choking lakes and making them unfit for fish.)
While Governments perform customs checks, inspect shipments, conduct risk assessments and set quarantine regulations to try to limit the entry of invasive species.

The problem can be best tackled by raising awareness among individuals and cooperation between governments. However, it might not be possible to stop the movement of organisms (especially microbes and plants) from one region to another in this era of globalization.

## Wednesday, May 20, 2009

### The Reluctant Fundamentalist - Mohsin Hamid

The reluctant fundamentalist written by Mohsin Hamid is the story of initial enchantment of a young Pakistani to America and later disillusionment. The novel is unique in that it all occurs over the course of one evening, but captures the life of not only Chengez, but of the untold thousands who are disappointed that America is not what they thought it to be.

Written completely as the narrative of one person, the narrator even poses the questions that the American might have felt like asking. More than once, I felt the novel was written in urdu and then translated into English, no not because of any lack in the language, but of the way in which the narrative proceeds. One simply can’t write few eastern ideas in a western language, but Hamid seems to have succeeded in this as well.

Furthermore the novel seemed to be the expanded form of a short story written in the Afsana form of Urdu literature. The existence of a short story version of the novel, “Focus on Fundamentals” seems to hint at the same.

When Mohsin talks about Lahore with its chai and jallabi’s, one could relate it to any one of the many Indian cities. The threat of a nuclear catastrophe and the futility of a bloody war also echo similar sentiments from across the border.

### Windows Process Monitor in java

It is required to monitor the status of few critical processes and services on business critical systems. Similarly other resources such as memory used and CPU time also require to be monitored.

These simple set of functions make use of the windows tasklist.exe utility to perform following functions:

• Alert when a particular process, service, module is started.
• Alert when memory usage of any particular or any process exceeds a certain value.
• Alert if any particular or any process is not responding.
• Alert if CPU Time for a particular process exceeds a certain value.
• Monitor if a particular number of instances of a service, process, and module is running. If it falls below or goes above the mentioned number of instances- generate alert.
The java functions to use are given below.

import java.io.*;

import java.util.*;

public class GetProcess {

public static void main(String[] args){

//few example uses of the functions.

System.out.println(CheckIfProgramXIsNotResponding(""));

System.out.println(CheckIfProgramXIsUsingMoreThanYKBOfMemory("java.exe",4200));

System.out.println(CheckIfProgramXIsUsingMoreThanZOfCPUTime("System", 0,0,1));

System.out.println(CheckIfNInstancesOfProgramXAreExecuting("svchost.exe",5));

System.out.println(CheckIfNInstancesOfServiceXAreRunning("MDM",1));

System.out.println(CheckIfNInstancesOfModuleXAreRunning("ntdll.dll",29));

}

/*These functions can be used along with a configuration file or a front end to perform monitoring of Windows systems.*/

private static boolean CheckIfProgramXIsNotResponding(String ProgName){

//returns true if given program is NOT RESPONDING. If no argument is passed, returns true if any program is not responding.

String argument="tasklist.exe /NH /FI ".concat("\"").concat("STATUS eq NOT RESPONDING").concat("\"");

return checkProcessInfo(argument, ProgName);

}

private static boolean CheckIfProgramXIsUsingMoreThanYKBOfMemory(String ProgName,int MemoryInKb){

//returns true if given program is using more than Y KB of Memory.If no argument is passed, returns true if any programs memory is more than Y KB.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("MEMUSAGE gt ")+MemoryInKb;

argument=argument.concat("\"");

return checkProcessInfo(argument, ProgName);

}

private static boolean CheckIfProgramXIsUsingMoreThanZOfCPUTime(String ProgName,int Hours,int Minutes,int Seconds){

//returns true if given program is using more than Z CPUTime.If no argument is passed, returns true if any programs memory is using more than Z CPUTime.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("CPUTIME gt ")+Hours+":"+Minutes+":"+Seconds;

argument=argument.concat("\"");

return checkProcessInfo(argument, ProgName);

}

private static boolean CheckIfNInstancesOfProgramXAreExecuting(String ProgName,int n){

//returns true if N instances of ProgramX are executing.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("IMAGENAME eq ").concat(ProgName).concat("\"");

return checkProcessCount(argument,ProgName,n);

}

private static boolean CheckIfNInstancesOfServiceXAreRunning(String ProgName,int n){

//returns true if N instances of Service X are running.

String line,argument="tasklist.exe /NH /FI ".concat("\"").concat("SERVICES eq ").concat(ProgName).concat("\"");

return checkProcessCount(argument,"",n);

}

private static boolean CheckIfNInstancesOfModuleXAreRunning(String ProgName,int n){

//returns true if N instances of Module X are running.

return checkProcessCount(argument,"",n);

}

private static boolean checkProcessInfo(String argument,String ProgName){

String line;

try {

System.out.println(argument);

Process p = Runtime.getRuntime().exec(argument);

while ((line = input.readLine()) != null) {

if (!line.trim().equals("")) {

if(line.startsWith(ProgName)){

return true;}//return status

}

}

input.close();

}

catch (Exception err) {

err.printStackTrace();

}

return false;

}

private static boolean checkProcessCount(String argument,String ProgName,int n){

String line;

int count=0;

try {

System.out.println(argument);

Process p = Runtime.getRuntime().exec(argument);

while ((line = input.readLine()) != null) {

if (!line.trim().equals("")) {

if(line.startsWith(ProgName)){

count++;}

}

}

input.close();

}

catch (Exception err) {

err.printStackTrace();

}

System.out.println(count);

if(n==count){

return true;}//return status

return false;

}

}

## Tuesday, May 12, 2009

### Sequential Screen Capture Utility

This is a simple java program that allows you take sequential screen prints with very less efforts.

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

public class ScreenCapture {

public static void main(String[] argv) throws Exception{

int i,time;
String option="S";
if(argv.length > 0) {
try {
time = Integer.parseInt(argv[0]);
for(i=0;i< time;i++){
captureandstorescreenshot();}}catch(NumberFormatException nfe) {
if (argv[0].equalsIgnoreCase("-help"))
{System.out.println("ScreenCapture Utility \n\n Usage:Run the program to capture screenshots for the next x seconds using the command [javac ScreenCapture x].\n Ex:javac ScreenCapture 20\n");
}
else if (argv[0].equalsIgnoreCase("-SE"))
{
while(!option.equalsIgnoreCase("X")){
InfiniteLoop t = new InfiniteLoop();
if(option.equalsIgnoreCase("S")){
t.start();}
Console console = System.console();
option= console.readLine("Enter E to end,S to start and X to exit?");
if(option.equalsIgnoreCase("E")){
t.interrupt();}
}
}
else{
System.err.println(argv[0]+" is not a valid number of seconds.'javac ScreenCapture -help' for syntax.");
System.exit(-1);}}}
}
public static void CaptureAndStoreScreenShot(){
try{
Calendar rightNow = Calendar.getInstance();
Dimension scrensize = Toolkit.getDefaultToolkit().getScreenSize();
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(scrensize));
//difference (measured in milliseconds) between the current time and midnight, January 1, 1970 UTC
String filename ="screen"+System.currentTimeMillis()+".jpg";
ImageIO.write(img, "JPG", new File(filename));
}catch(Exception e){return;}
}
}

{
public void run(){
for( ; ;){
ScreenCapture.CaptureAndStoreScreenShot();
// System.out.println("Interrupted");
return;
}
}
}
}
The below error occurs in older versions(Pre java 2) while interrupting the thread. It seems like a bug in older versions of java.

AWT blocker activation interrupted:
java.lang.InterruptedException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:429)
9)
at sun.awt.AWTAutoShutdown.setToolkitBusy(AWTAutoShutdown.java:226)
118)
at sun.awt.windows.WToolkit.(WToolkit.java:217)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:274)
at java.lang.Class.newInstance0(Class.java:308)
at java.lang.Class.newInstance(Class.java:261)
at java.awt.Toolkit\$2.run(Toolkit.java:760)
at java.security.AccessController.doPrivileged(Native Method)
at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:739)
at ScreenCapture.CaptureAndStoreScreenShot(ScreenCapture.java:44)
at InfiniteLoop.run(ScreenCapture.java:58)

## Friday, April 24, 2009

### Java Desktop Fortune teller

This is a simple java desktop application that "predicts" your fortune. It makes use of a getfortune method to display predefined fortune texts in a label. The getFortune method uses the random function from the "import java.lang.Math.*" package to choose the fortune to display.

public String getFortune() {
String prediction[]={"You will die a horrible death at 3:00 PM","You will win a lottery today","You will slip and fall today","Beware of red Vehicles","You will get a promotion today","You will become king one day","You will win the Nobel prize next year","You will win every contest you enter today","Your boss will go on leave for the next week","You will buy a car soon","You will become God"};
int forval=(int)Math.round(Math.random()*10);
return prediction[forval];
}

The different fortunes are stored in an array of strings and the value obtained from the random function is used as the array index. The value from random is between 0 and 1, and is multiplied by 10 to get the final value. Hence, the array will not go out of bound.

## Thursday, April 23, 2009

### Crayon Physics - error - limit on number of drawings

After writing a kind of tutorial on wining the seven different crayon physics puzzles or levels (crayon puzzles) in the demo mode, the game showed few limits, not by itself by the physics engine on which it runs. The error says "You Broke my Game! There's too many objects on the screen . The physics engine can't keep up with it. Unfortunately you will have to restart the level :("

The worst thing about this error is it pops up just when you are able to solve :) the puzzle.

The different levels of the demo are:

The background music of the game is pretty melodious and not interfering. The final word is Crayon physics proves beyond doubt tat its an awesomely cool game :)

## Wednesday, April 22, 2009

### Crayon Physics - Nasty

The Nasty level in crayon physics has two stars to collect. Although its possible to collect both stars in a single go, this method shows collecting each of the stars in separate goes.

To collect the first star, first block the ball at the top. and create structures as in image below.

Delete the blocking box to collect the first start. The ball falls down and comes for second go. Block the ball and build the next set of structures as in below image.

Draw both structures together along with guarding wall at the left bottom corner to collect both stars in a single go.

### Crayon Physics - Sky Captain

Sky captain can be solved similar to TEE TERS by balancing the see saws and then setting the ball rolling. But make sure the right side is having some weight to counteract the weight of the square tat gets the ball rolling.

The seesaws can be balanced using a single beam or two separate beams. But make sure to use long beams to get them balanced.

### Crayon Physics - Log

The Log can be solved very easily by removing the log and then setting the ball roll. However, can anybody solve it without making the log fall? The acclaimed tunneling effect from quantum physics is required for this :) Any quantum physicists out there? can u do it?

Anyway for the rest of us the easy solution is given below. First get the log out of the way by dropping beams on top of it. Then just get the ball rolling to collect the star.

If any of you quantum physicists can do the tunneling effect without making the log fall, do let me know how u did it.

### Crayon Physics - Lots Of Space

Lots of space seemed a bit difficult to solve to begin with as it required the drawing of boxes of exact sizes so tat the weight got balanced. If you draw a box tats too small or too big, they will both go tumbling down. The challenge is to fill the space and make the ball roll.
Draw the leftmost vertical box first and make it stand properly. Next draw the slant pole so tat it gets balanced by the vertical box. Once the the two boxes get balanced, draw a third box to get the ball rolling.

A much easier way is to draw multiple boxes to make the levels nearly equal, and drawing a pole connecting the two. Then once the ball comes near the piled up boxes, delete them quickly so tat the ball falls on top of the star.

The way2 to solve lots of space teaches cantilever concept.
So lot of physics learning going on with the crayon.

### Crayon Physics - tee ters

The third puzzle called the Teeters or TEE TERS can be solved by drawing a single bar that balances and equalises the two see saws and drawing another box to get the ball rolling.

This seems to be the simplest solution. So should we try to solve the puzzle by drawing the least number of stuffs? is tat the aim of the game? well tat would make the game boring and does not make the full use of the artistic power of Crayon Physics.

### Crayon physics demo - the 2 towers

As if solving the first puzzle was not easy enough, the second puzzle can be solved like below. Just need to draw two boxes. One Box connecting the two towers and another to set the ball rolling.

This seems to be like a tutorial to solving the demo version of crayon physics, but dont limit your creativity to these solutions. Do explore more fun ways to solve these puzzles.

Actually dont just think of these as puzzles, they are a kind of art with purpose. The purpose of the art is to collect the star:) So wat are u waiting for pickup the crayons and start sketching.

### Crayon Physics - awesomly talented game

Crayon physics is a really great game that tests your artistic sense and physics. No you dont need to be a particle physicist.

The demo version of the game comes with 7 puzzles and is very simple to learn and fun to play. The aim of the game is to collect stars by making a ball to move towards a star. The first puzzle can be solved easily based on the instructions given in the game background.

This is just one way to solve the game, but the same thing can be solved in innumerable different methods. The beauty of the game is tat its not a science, but an art. We learn handling the mouse, physics and art all at the same time :)

Hit the space bar to reset the game and the esc key to goto the menu. Do let me know if you solve the puzzles in the most artistic ways possible.

## Wednesday, April 15, 2009

### Robot Battle – the Dead Target Robot

Robot battle is a game that requires you to write programs to make the robots battle it out for supremacy. The robots have the same physical features; the program (the robot brain) is the only feature that decides the winning robot.

A distinct programming language called Robot Scripting language (RSL) is used to control the actions of the robot. The documentation included with the game is good enough to start writing your own robots (.prg files).

I just created a Dead Target Robot for doing target Practice. The Sample program created using the documentation included with the Robot Battle game defeats Dead Target Robot easily.

#The dumbest robot ever. Just sits and waits to get killed. Good for target practice.
Init
{
author( "Nagarjun V" )
version( "0.1" )
}

Source of Sample.prg:

# Init section sets up robot and registers handlers
Init
{
name( "Sample" )
lockgun( true )
regcore( MyCore )
regdtcrobot( FoundRobot, 1 )
}

MyCore
{
# if scan finds a robot, the event handler runs
scan( )
}

# scan detected a robot, shoot at it then check again
FoundRobot
{
fire( 1 )
scan( )
}

The results of a game between the above two robots:

 Sample 40 20 0 Dead Target 0.1 0 0 20

## Sunday, April 12, 2009

### Borg - inspired from communists ?

Individuality is defined as the state or quality of being an individual; a person separate from other persons and possessing his or her own needs, goals, and desires. Hence, a persons needs, goals and desires make up his or her individuality.

Individualists consider one’s goals and desire more important than any society, group or institution. While collectivism, stresses that communal, community, group, societal, or national goals should take priority over individual goals. A utopia in which the needs, goals and desires of each individual are same or sacrificed for the good of the society will destroy the concept of an individual. Similarly an interconnected collective like the Borg have no individuality.

The Borg is an extreme case of collectivism. Such an extreme type of Collectivism can be considered a fictional form of communism (which prefers common ownership to private ownership). So was the Borg inspired from communists? Does it play on the American fears of communism prevalent at the time Star Trek was written? The assimilation of cultures and beings can be compared to the growth of communism assimilating countries.

The Borg also resemble Ants in many ways:
Ant colonies also have some fertile males called "drones" and one or more fertile females called "queens".
The colonies are sometimes described as super organisms because ants appear to operate as a unified entity, collectively working together to support the colony

So is the Borg inspired from ants or communists or a combination of both?

### Infix to postfix or prefix?

The order of operations or precedence rule is used to determine the order in which operations need to be performed. The order of operations is just a protocol used for easier and common understanding of expressions and is not based on any mathematical or logical theorem. The history of the order of precedence is not very clear and its origins cannot be attributed to any single source. The originator of this rule was not brilliant enough to suggest the post or pre fix notation :)

Various acronyms such as (all of which represent the same order of precedence):
PEMDAS - Parentheses Exponents Multiplication Division Addition Subtraction Also remembered using the sentence - "Please Excuse My Dear Aunt Sally"
BEDMAS - Brackets Exponents Division Multiplication Addition Subtraction
BIDMAS - Brackets Indices Division Multiplication Addition Subtraction
BIMDAS - Brackets Indices Multiplication Division Addition Subtraction
BIODMAS- Brackets Indices Of Division Multiplication Addition Subtraction
BODMAS - Brackets Of Division Multiplication Addition Subtraction
BOMDAS - Brackets Of Multiplication Division Addition Subtraction
BPODMAS- Brackets Power Of Division Multiplication Addition Subtraction

The Microsoft calculator program uses the order of operations in the scientific mode but ignored it in the standard mode. The Google calculator adheres to the order of preference strictly as can be see in the result of 6*3/4^2*3+2*(3/6-4)*3^(2-4).

Humans require the order of operations as we use conventional infix notation. However, the computers use a postfix notation like Reverse Polish notation , which obviates the need for the order of operations. Few computer languages use a prefix notation, which does not require the order of precedence as well. So should humans try to move from the infix to postfix or prefix notation?

### Temporary variables – 5 common mistakes

Temporary variables are a type of variable which are used to store a value obtained from a particular computation or data source, which will be used in a later stage of the program. Although temporary variables serve very useful purposes, they can be the cause of major software bugs that seem to occur inexplicably. The common coding or programing mistakes associated with temp variables:

1. Loss of precision: The use of a lesser precision variable for a temp variable can lead to loss of precision which leads to bugs.

Ex: Using a Integer variable to store the result of a calculation that includes a higher precision like float or double. Even in langauages like java by explicitly typecasting(coders mistake).

2. Value out of bound: Similar to the first mistake but occurs in arrays and strings. Can mainly lead to rendering mistakes.

Ex:While using the last few characters of a string or last few values of an array.

3. Multiple inputs: The temporary variable value can get overwritten by incorrect code even before its value is used.

Ex: Status being changed even before the code required to be executed in previous status completes execution.

4. Excessive memory usage:The excessive use of temporary variables can have an impact on the memory usage of the program.

Ex:Using temp variables even when they are not absolutely needed.

5. No exception handling ( Like Null value, negative value) :The temporary variables can behave in weird ways if various exceptional cases are not anticipated and guarded against.

Ex:Not guarding against storing negative values in temp variables later used as array index etc.

## Friday, April 3, 2009

### Goldilocks - program to check the temperature

import java.io.Console;
import java.io.IOException;

class Goldilocks
{
public static void main(String[] args) throws IOException
{
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
String portemp = c.readLine("Enter the temperature of some porridge in degree centigrade: ");
int temp =(int)Float.parseFloat(portemp);
if (temp>40)
System.out.println("Too hot");
else if(temp<40)
System.out.println("Too cold");
else
System.out.println("just right ");
}
}

## Wednesday, March 25, 2009

### Earth Hour 2009 - time to vote

Wikiepedia defines "Earth Hour" as an annual international event created by the WWF (World Wide Fund for Nature/World Wildlife Fund), held on the last Saturday of March, that asks households and businesses to turn off their non-essential lights and electrical appliances for one hour to raise awareness towards the need to take action on climate change.

Earth hour 2009 is scheduled for 28th MArch 2009 from 8:30 PM t0 9:30 PM local time. The earth hour website hopes to raise awareness by switching of the lights for one hour. However, earth hour might end up leading to higher energy consumption than on normal days. Since, electrical appliances such as refrigerators, air conditioners, heaters etc. will also be switched of for just one hour.

These electrical appliances have to spend more energy in reheating or recooling the surface or room after the end of the hour. As reported in earth hour 2008, New Zealand's power consumption during Earth Hour was 335 megawatts, higher than the 328 megawatt average of the previous two Saturdays. Similarly in Calgary, Canada power consumption actually went up 3.6% at the hour's peak electricity demand.

Is earth hour a great idea, implemented without thinking of the science behind it? Hopefully the organisers will make sure such wastage of power does not occur.

## Thursday, March 19, 2009

### A grease monkey script to view tab and new line characters in a browser

In certain cases its necessary to recognize tab and newline characters in a document. Microsoft word comes with an option to hide or show such punctuation marks like newline and tab characters. The short cut for enabling the display of punctuation marks is “Ctrl + *”. It can be very beneficial I differentiating space characters from tab characters.

Internet explorer or any other browser such as firefox, safari, opera or chrome does not come with such a option to view newline and tab characters. Simple one line greasemonkey script can do the job for firefox.

As can be seen in above screen, the newline characters in wikipedia home page been replaced by “q|” and tab characters have been replaced by “-->”.

The code for the oneline greasemonkey script is given below:

document.documentElement.innerHTML=document.documentElement.innerHTML.replace(/\t/g,"-->").replace(/\n/g,"q|");

Hopefully future versions of Internet browsers will provide this facility to view tab and newline characters when required.

## Wednesday, March 18, 2009

### The elusive program bug

Some bugs can drive a programmer crazy by its unpredictability and complexity. These bugs have been named after famous scientists who discovered laws that seem to be false, but are actually true.

Heisenbug named after the famous German theoretical physicist who discovered the Heisenberg uncertainty principle. The Heisenbug is a type of computer bug that alters its behavior when it’s tried to be analyzed.

Ex: An example of Heisenbug is a bug that behaves differently in debug mode and compile mode.

Bohrbug named after Neils Bohr, the Danish physicist who made fundamental contributions to understanding the atomic structure. The Bohrbug is a type of computer bug that manifests itself consistently under well-defined set of conditions. Although a Bohrbug can be easily caught, it might be elusive when its present in rarely executed parts of the code.

Ex: A rare condition that is executed only in an exceptional condition may have a very simple logical bug, which does not manifest itself until the exceptional case is encountered.

Mandelbug named after Benoit B. Mandelbrot, a French mathematician famous for his work in fractal geometry. Mandelbugs are computer bugs that are so complex, that they appear to be chaotic.

Ex: A bug that is occurring due to some variable component like the hardware, Operating system, other applications etc, but appears to be a simple logical bug.

Schroedinbug named after Erwin Schrodinger an Austrian theoretical physicist famous for his contributions to Quantum physics. An Schroedinbug manifests itself when the program is analysed to realise that the program is not working as it was designed to. However, the program might have been used effectively due to some other error committed by the user or environment.

Ex: A program that’s actually designed to accept capital alphabets, which has a bug that accepts small letter alphabets. The program stops to work after the users realise that the program is not supposed to accept small letter alphabets. (Note: The program was working while accepting small letter alphabets as all the users were using small letter alphabets leading to the program to work as if all alphabets had been entered in capitals.)

Bosebug named after Satyendra Nath Bose, an Indian physicist famous for his work in Bose-Einstein statistics. A Bosebug commonly known as a statistical bug is a type of bug that manifests itself only when analyzed from a statistical point of view over a considerable duration of time.

Ex: A program that’s supposed to generate random numbers may not actually be producing random numbers from a statistical point of view. Although such bugs may not affect the program in a single run, can create major problems in the long run.

## Monday, March 16, 2009

### Novelty software distribution terms

Software has been distributed with different rules governing it use. The"Postcardware", requires the user to send an actual postcard to the author of the program to use the software. The postcardware is not enforced strictly and can be considered a type of freeware. Emailware is similar to postcardware but instead of an actual physical postcard, an email is sufficient.

Beerware a term coined by John Bristor in 1987 asks the users of the software to buy the author a beer if they meet some day. The license is a very simplified version of the GPL. Probably Bill Gates dint release Windows under beerware for the fear of being killed by over dose of beer or fear of people avoid meeting him.So it did do him a lot of good by releasing it as payware.

Shareware (also called demoware or trialware) refers to software thats distributed without payment on a trial basis and is limited by any combination of functionality, availability, or convenience.Crippleware is a type of trialware which requires payment for access to advanced features of the program. Nagware (also known as begware or annoyware) is type of shareware that reminds(or nags) the user to register by paying a fee.

Careware (also called charityware,helpware, or goodware) is software distributed in a way that benefits a charity.The term "careware" is a variant on shareware and freeware. Similar to careware is Donationware is a licensing model that supplies fully operational software to the user and requests a donation be paid to the programmer or a third-party beneficiary(usually a non-profit).

Freeware is software given away for free(without any cost) use without any limitations.A donation might be requested by few authors.

Adware is advertising supported software that automatically shows advertisements to the users.Most adware are considered a security threat and are not popular.Firefox distributed with Google search bar can be considered a type of adware as google ends up earning from the ads displayed to users using the google search bar.Ransomware, spyware are other softwares that dont have any explicit distribution terms, but make use of illegal methods to delete/obtain sensitive data.

The author of the holy rosary program went a step further and declared his software as Prayware.The software is free for use,the users can however pray for the author as payment. Do let me know if you know of any other more novel software distribution terms.

## Saturday, March 14, 2009

### Software program to make a Quiz - multiple choice

If you want to create a quiz with multiple choice questions, the Quiz program by Luzius Schneider seems to do the job. The program is free to use as long as we are OK to share the questionnaires we create using the software. The program makes use of the Borland Database engine to easily store and retrieve the questions. There are options to set time limits, provide hints about the answer and even further explanations for an answer if you are interested.

Quiz also has few shareware upgradations which run on the network, a intranet or even the internet.

### Tipu Sultan's Tomb - Gumbaz Srirangapatna

Gumbaz is the tomb and mosque built by Tipu Sultan as a tribute to his illustrious father, Hyder Ali (1722-1784 A.D.), after his death.

The Gumbaz is situated at the eastern extreme of Srirangapatna. It enshrines the cenotaphs of Hyder Ali,his wife Fakr-Un_Nisa and Tipu Sultan, after his death in 1799 A.D. It is built on a stone plinth, with polished black granite pillars that run along the corridor around the inner chamber.A magnificent dome crowns the building. The chamber is painted with the tiger stripes that were associated with Tipu.

The structure, laid out amidst a garden, typical of Islamic architecture, also houses the Masjid-E-Aksa.

At the eastern entrance of the Mausoleum is a tablet in Persian script that speaks of the martyrdom of Tipu Sultan in 1799 A.D.

There are numerous other cenotaphs of the relatives of Tipu's family.

## Saturday, March 7, 2009

### When the English language runs out of words

The English language is reported to have as many as 500,000 words based on major publicised dictionaries. If various technical words are included the number grows to 1,500,000 words. With the growth of the Internet the number of words that are being coined and used is growing everyday. So the day when we literally run out words to describe things will arrive.

Although the debate over the longest English word still continues, we could probably say that words longer 20 letters are difficult to use in normal speech. Considering the words to be maximum of 20 characters long a total of 26 to the power of 20 words can be made. (26 to the power of 20 = 1.99281489 × 10 to the power of 28. So we have more than enough words in English Language to last a few centuries?? Or will we out grow this number by discovering or inventing those many new things to describe? Time will tell if we Will have to add more characters to the English Language.

Probably we will resort to using numbers along with the alphabets before actually going on to create new alphabets. So a word like "10potato" might mean an actual word that has no connection whatsoever to a potato as we know it today.

Linguists may argue that humans would rather add few more alphabets to a language than use such long words. However, based on the way the lanuage is going to be used in the future, we may not add more alphabets but actually use long words which are cross-referenced in huge online dictionaries.

## Monday, February 2, 2009

### Simple Java Program to understand enum basics

/*
------------------------------------------------------------------------
Simple Java Program to understand enum basics
------------------------------------------------------------------------
*/
enum Cars{ESCORT,FIAT,ALTO,ZEN}
class EnumExample{

public static void main(String args[]){

Cars oldest = Cars.FIAT;
System.out.println(oldest);

for(Cars c :Cars.values())
System.out.println(c);
}
}
/*
------------------------------------------------------------------------
Output of enum example
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac EnumExample.java

C:\Users\flower\Documents\javaprogs>java EnumExample
FIAT
ESCORT
FIAT
ALTO
ZEN

*/

## Sunday, January 25, 2009

### Simple Java Program that uses my assertion

/*
------------------------------------------------------------------------
Simple Java Program that uses my assertion
------------------------------------------------------------------------
*/

class MyAssertionExample{

static boolean myassertionenabled;//default value is false
static void myassert (boolean b){
if(myassertionenabled & !b){
throw new AssertionError();
}

}

public static void main(String args[]){

try{
if (args[0].equals("ea")){
myassertionenabled=true;}
}catch(ArrayIndexOutOfBoundsException AE){}//dont throw exception if no arguments are passed
int a=1;
try{
myassert(a==2);//value of 'a' should be 2, else throw an assertion exception error
}catch(AssertionError E){
System.out.println("Value of a is not equal to 2 and assertion is enabled");
}
}
}
/*
------------------------------------------------------------------------
Output of AssertionExample with assertions enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac MyAssertionExample.java

C:\Users\flower\Documents\javaprogs>java MyAssertionExample ea
Value of a is not equal to 2 and assertion is enabled

------------------------------------------------------------------------
Output of AssertionExample with assertions not enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java MyAssertionExample

*/

### Simple Java Program to understand assertions

/*
------------------------------------------------------------------------
Simple Java Program to understand assertions
------------------------------------------------------------------------
*/

class AssertionExample{

public static void main(String args[]){

int a=1;
try{
assert(a==2);//value of 'a' should be 2, else throw an assertion exception error
}catch(AssertionError E){
System.out.println("Value of a is not equal to 2 and assertion is enabled");
}
}
}
/*
------------------------------------------------------------------------
Output of AssertionExample with assertions enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>javac AssertionExample.java

C:\Users\flower\Documents\javaprogs>java -ea AssertionExample
Value of a is not equal to 2 and assertion is enabled

------------------------------------------------------------------------
Output of AssertionExample with assertions not enabled
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java AssertionExample

*/