Pages

Thursday, April 21, 2011

Notes to Myself about Coding

When coding html/xul, use consistent "id"s.
If you are given a skeleton code having some of the functionality, from someone without a technical background, don't rely on that code. If it's not a lot of work, don't build upon that code. Don't even consider about the skeleton code. Just build from the bottom.
If you are given part of a user interface, and told that is how the client wants it, don't be constrained by that interface. Think from the bottom and decide on your own interface and tell that to the client.
Always ask the client what he needs at the END. Sometimes clients think part of the solution and tell that to you without telling what they need in the END. In the end, the solution that the client has thought is wrong.
When bidding for a job, and you can't decide on the amount and can only think of a range, place a bid near the upper margin and not the lower.
Have some logging mechanism from the beginning with a method to turn logging on/off easily.
Use version control.
Use CONSTANTS where applicable.

Wednesday, February 23, 2011

Java Threads Example

This is a small example of how to use Threads in Java. The code will check if a number is prime or not. You can configure the number of threads that will run. Each thread will try to divide the number to be tested  by a different number. If the number to be tested gets divided by another number, the program will print that it is not prime and also print the number that it can be divided by. This example also demonstrates the use of the "AtomicIntger" class in the "java.util.concurrent" package. If you are looking for a simpler example you can take a look at this example first and then come back and take a look at this.

public class Divisor extends Thread {

  //Will hold the number to be tested
  private int testNumber;

  //Will hold the number we will try to divide by
  private AtomicInteger nextNumber;
 
  private int sqrtOfTestNumber;

  public Divisor(AtomicInteger nextNumber, int testNumber) {   
    this.nextNumber = nextNumber;
    this.testNumber = testNumber;
    sqrtOfTestNumber = (int) Math.ceil(Math.sqrt(testNumber));
  }

  @Override
  public void run() {
    while (nextNumber.intValue() < sqrtOfTestNumber
              &&
            PrimeTester.IS_PRIME.get()) {
      if (testNumber % nextNumber.incrementAndGet() == 0) {
        PrimeTester.IS_PRIME.set(false);
        System.out.println(testNumber + " is not a prime!");
        System.out.println("It can be divided by "
                             + nextNumber.intValue() + ".");
        return;
      }
    }   
  } 
}
public class PrimeTester {

  public static AtomicBoolean IS_PRIME =
                                  new AtomicBoolean(true); 
  private AtomicInteger nextNumber = new AtomicInteger(1);
  private int numberOfThreads;
  private int testNumber;

  public PrimeTester(int numberOfThreads, int testNumber) {
    this.numberOfThreads = numberOfThreads;
    this.testNumber = testNumber;
  }

  public void test() {
    for (int i = 0; i < numberOfThreads; i++) {
      new Divisor(nextNumber, testNumber).start();
    }
  }
 
  public static void main(String[] args) {
    PrimeTester primeTester = new PrimeTester(5, 370248452);
    primeTester.test();
  }
}

Note that the program will not output anything if the number is prime. This is because additional checks have to be performed in order to do this and it will complicate the code. Since this is meant to be a simple example, it has not been included here. Maybe it can be explained in a future post.

Sunday, February 20, 2011

PHP Logging Libraries

Recently while doing a project, I came across the need of a PHP logging library. The search for a php logging framework found me a few interesting results. The following are the libraries that I came across.

1) log4php
This logging library seems to be the most feature-rich library available. The RollingFile and DailyFile logging systems in this library can come in quite useful. Mail and Database logging are also available. This library can be configured using xml, properties file or through code, just like log4j. The log message format can be configured using layouts. This library is ideal for someone who is experienced with using log4j. The file compression functionality does not seem to be present in log4php at this time.

2) Zend_Log
This the Zend library component for logging. Other than logging to a file you can log to a database or email as well. Similar to log4php with Zend_Log you can configure the logged message's format.

3) Pear Logging Framework
This is the pear library for logging. This library supports logging to file,database and mail. You also have the option of setting the format of the log message.

4) KLogger
This library can log to file only. So for a lightweight application that does not require logging to database and email, this library can be used.

Hope this helped you to find the logging library that best suits your needs. You can follow the above links to find out more.

Wednesday, February 16, 2011

Maven Profiles Example

This is an example on a simple use-case for Maven profiles. It will be useful for someone who wants to implement one in their build or for someone who wants to know what is the use of having profiles.
Let us imagine that you need to have two builds. The difference in the two builds is the version of a single jar. For example, let us say that you need to have a build named profile-A with the version 1.0.0 of a jar and profile-B with the version 2.0.0 of a jar. The following is the pom.xml which shows how to do this.

<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>profiles-example</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>profiles-example</name>
  <url>http://maven.apache.org</url>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <profiles>
      <profile>
          <id>profile-A</id>
          <dependencies>
              <dependency>
                <groupId>com.example</groupId>
                <artifactId>dependency</artifactId>
                <version>1.0.0</version>
              </dependency>
          </dependencies>
      </profile>
      <profile>
          <id>profile-B</id>
          <dependencies>
              <dependency>
                <groupId>com.example</groupId>
                <artifactId>dependency</artifactId>
                <version>2.0.0</version>
              </dependency>
          </dependencies>
      </profile>
  </profiles>
</project>

Now you can invoke profile-A using the command
mvn -Pprofile-A install
which will build the project with the dependency version 1.0.0.

Why would someone want to do this? This is a good example where  profiles can be used. To learn more about profiles, take a look at introduction to profiles in the maven documentation. You can specify other build specific parameters such as "plugins"," dependency management" etc. via profiles.

Tuesday, February 15, 2011

Copying Files in Maven

The need to copy files/directories is something that we come across when we use maven as the build tool. The maven resources plugin can be used to achieve this functionality. This example shows how to do this using the plugin. This link talks about some other methods that can be used to achieve this.

Debugging Firefox Add-Ons Using Chromebug

When writing add-ons for Firefox, the ability to debug the add-on makes the development process quite easier and faster as well. Chromebug is a Firefox add-on which provides this capability. The Chromebug user guide has instructions on how to install and start Chromebug. You can inspect the XUL elements of the add-on and debug JavaScript code using this tool. The following are some screenshots of the add-on in action.







Saturday, February 12, 2011

Sorting a HashMap in Java

First of all I have to point out that a HashMap can not be in a "sorted" state. This is because a HashMap does not have an order. On the other hand a TreeMap does have an order (it implements the interface SortedMap). So to sort a HashMap by key, you can use the code below.

Map sortedMap = new TreeMap(yourOriginalMap);

This will sort the map according to the keys' natural order.


In order to sort the HashMap based on the values, we have to pass a Comparator to the constructor of TreeMap. For this example let us assume that the values of the HashMap that you need to sort are Integers. Then the comparator would look like the following.


public class MyComparator implements Comparator<Object> {

    Map theMapToSort;

    public MyComparator(Map theMapToSort) {
        this.theMapToSort = theMapToSort;
    }

    public int compare(Object key1, Object key2) {
        Integer val1 = (Integer) theMapToSort.get(key1);
        Integer val2 = (Integer) theMapToSort.get(key2);
        if (val1 < val2) {
            return -1;
        } else {
            return 1;
        }
    }
}

Then you can sort the map using the following code

MyComparator comp = new MyComparator(originalMap);
TreeMap treeMap = new TreeMap(comp);
treeMap.putAll(originalMap);


Now the treeMap object will contain the values in the orginalMap, sorted by the values.