Posts tagged ‘Programming’

Hey, just noticed that the next version of the book Dive into Python. It is a brilliant book and you can found it online free here. To be honest, I will surely buy my printed version also, i’m a little old fashioned.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

These days i’m finalising the FIRE regular expression compiler. To add a feature, the need arise to modify the classpath at runtime. It was a surprise for me when i discovered that there is no official way to modify this at runtime. I even created my own URLClassLoader (java.net), and set it as default classloader for my thread, but nothing.

I searched in google a little and found this post on a forum, which provided a class named ClassPathHacker that could add a path or file (jar) to a classpath at runtime. All this by a programmer named Antony Miguel. Well done :) .

The source code of the class follows:

import java.net.*;
import java.io.*;
import java.lang.reflect.*;
 
public class ClassPathHacker {
 
	private static final Class[] parameters = new Class[]{URL.class};
 
	public static void addFile(String s) throws IOException {
		File f = new File(s);
		addFile(f);
	}
 
	public static void addFile(File f) throws IOException {
		addURL(f.toURL());
	}	 
 
	public static void addURL(URL u) throws IOException {			
		URLClassLoader sysloader = (URLClassLoader)ClassLoader.getSystemClassLoader();
		Class sysclass = URLClassLoader.class;
 
		try {
			Method method = sysclass.getDeclaredMethod("addURL",parameters);
			method.setAccessible(true);
			method.invoke(sysloader,new Object[]{ u });
		} catch (Throwable t) {
			t.printStackTrace();
			throw new IOException("Error, could not add URL to system classloader");
		}		
	}	
}

and an example of usage ..

import java.io.*;
 
public class ClassPathAdder {
	public static void main(String[] args) {
		try {
			ClassPathHacker.add(new File("/home/user/newClassPath"));
		} catch (IOException e) {
			System.err.println("Error - " + e.toString());
		}
	}
}

Cool! :-D

VN:F [1.9.17_1161]
Rating: 4.0/10 (1 vote cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

Recently I decided to move on with my web programming skillset, and see (at last) a little more modern approach that include much client side coding, with Javascript. The first thing you learn when studying such approaches is the XMLHttpRequest, which is used to send/receive data with the web server.

To aid me, i purchased the Head First Ajax, a really nice book, focused in practical things, than in theory and specifications.

Imagine my suprise when in the first pages of the book i found this code?

function create_request(url) {
    var req = null;
 
    try {
        req = new XMLHttpRequest();
    } catch (tryMS) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                return null;
            }
        }
    }
 
    return req;
}

In my previous article, I stated that web programming is a little chaotic (the way it is), and the problem is the diverse technologies that are used, among with the ad-hocracy of the browsers.

And voila, one more snippet to my wall of fame, which shows the rubbish approaches that are used in some implementations. Internet Explorer decided that he should have another way to implement the http functionality object and with two different ways, making the programmers, trying to initialize 3 objects in total, with nested try/catch statements.

I really do not know, which great business policy is served with this implementation … maybe I lack the big picture management thing that exists in the head of some people, that take those superb decisions.

VN:F [1.9.17_1161]
Rating: 7.0/10 (1 vote cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

I always liked to play with static initializers in Java. I remember back in the summer of 2003 i accidentally discovered the empty main pattern. Later on, a very close friend of mine, Kostantinos Saidis also found the no main pattern.

I don’t know if its bug or feature. but i sure know its fun! :)

Following the examples of …

Normal Class

public class Main {
	public static void main(String[] args) {
		System.out.println("Boom");
	}
}

Empty Main Class

public class Main {
	static {
		System.out.println("Boom!!");
	}
 
	public static void main(String[] args) {
		//do nothing
	}
}

No Main Pattern

public class Main {
	static {
		System.out.println("Boom!!");
	}
}
VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

Today, i decided to search a little the latest j2sdk sources. My initial search began with the usage of final modifier in the signature of a method. What is its exact usage, etc.

I wrote some sample programs and decompiled them, finding nothing of interest. Then i tried to investigate auto-boxing. I wrote a sample program that calls a method that has an Integer class as parameter. Something like that:

public void bar(Integer i) { ... }
 
int i = 1;
System.out.println(i);

When i used auto-boxing, the compiler used the Integer.valueOf(int) method. So i started searching if it is more optimized to use auto-boxing, or not.

When i changed the i variable to Integer type, and called normally the constructor of the Integer class, i realized that the constructor was invoked normally, with int as parameter.

The mystery solved when i read the original Integer class sources.

The contructor simply instantiates a new Integer object. On the other hand, the Integer.valueOf(int) does the following:

public static Integer valueOf(int i) {pre
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
		return IntegerCache.cache[i + offset];
	}
 
	return new Integer(i);
}

The valueOf method uses an cache object and keeps 256 integers cached all the time. The pre for the integer cache follows:

private static class IntegerCache {
	private IntegerCache(){}
 
	static final Integer cache[] = new Integer[-(-128) + 127 + 1];
 
	static {
		for(int i = 0; i < cache.length; i++)
			cache[i] = new Integer(i - 128);
	}
}

So, if you use auto-boxing (or simply use the Integer.valueOf() method) instead of the normal constructor, you get a cached integer reference instead of a new object. This is an documented feature (see the Integer.valueOf(int) javadoc entry), and is demostrated by the following code.

public class Foo {
	public static void main(String[] args) {
		Integer i = new Integer(10);
		Integer ii = new Integer(10);
		Integer iii = Integer.valueOf(10);
		Integer iiii = Integer.valueOf(10);
 
		System.out.println("i == ii - " + (i == ii));
		System.out.println("ii == iii - " + (ii == iii));
		System.out.println("iii = i - " +  (i == iii));
		System.out.println("iiii = iii - " + (iiii == iii));
	}
}

Sample executiion output follows:

nefarian:~/devel/ew bkarak$ java Foo
i == ii - false
ii == iii - false
iii = i - false
iiii = iii - true

But the caching works only with the Integer.valueOf(int) method. See the implementation of the Integer.valueOf(String,int) for example:

public static Integer valueOf(String s, int radix) 
	throws NumberFormatException {
		return new Integer(parseInt(s,radix));
}

This method always returns a new Integer object. Doh!

VN:F [1.9.17_1161]
Rating: 7.0/10 (1 vote cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

Recently, after lots of demonstation (kindly provided by my friend Christos KK Loverdos) I am evaluating Intellij. I am a regular user of eclipse.

I installed a trial version, and began to configure my projects (yeah, i have many, which are a few thousands lines each, and i do not mean one thousand :-p), configure additional plugins etc.

On the process i noticed the following paradox … eclipse seem to think that is correct to use the annotation @override in a function, when you provide an implementation for an interface,

Annotation usage is considered correct by eclipse.

Annotation usage is considered correct by eclipse.

and intellij thinks that it is wrong.

Intellij thinks completely the opposite. Notice the red line under the @override keyword that indicates an error.

Intellij thinks completely the opposite. Notice the red line under the @override usage is erroneous.

So … which is the correct one? And as a second thought, how many of these assumptions are embedded into our IDEs and shape the way we program?

By the way, javac never complained for the annotation usage.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

Lets have a look at the following example:

bkarak@linux-uho3:~&gt; python
Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[1:].extend(a[:2])
>>> a[1:] + a[:2]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2]

I am trying to concatenate two slices from a python list, using the extend method.

“| extend(…)
| L.extend(iterable) — extend list by appending elements from the iterable”

Why this does not work? … the list concatenation works fine with the “+” operator.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

5,1 GB and 23625 Files …. to be exact ….

HTML, 2525 / 23625
GIF Images, 2168 / 23625
JPEG Images, 1977 / 23625
Java, 1238 / 23625
XML, 928 / 23625
C/C++ Headers, 704 / 23625
C, 662 / 23625
C++, 650 / 23625
PDF Documents, 620 / 23625
Pascal, 619 / 23625
ASCII Text Files, 507 / 23625
MS Word Documents, 411 / 23625
ZIP Archives, 276 / 23625
JAR, 197 / 23625
PNG Images, 194 / 23625
TIFF Images, 132 / 23625
Excel Files, 132 / 23625
TeX/LaTeX, 109 / 23625
MS-Dos/Windows Batch Files, 109 / 23625
Powerpoint Files, 88 / 23625
RAR Archives, 80 / 23625
BiBTeX, 76 / 23625
X-Schema Files, 75 / 23625
GZIP Archives, 69 / 23625
make, 67 / 23625
Perl, 54 / 23625
C#, 48 / 23625
RTF, 31 / 23625
Windows HELP Files, 31 / 23625
PHP, 24 / 23625
Bourne Shell, 21 / 23625
SQL, 19 / 23625
PSD Photoshop Images, 16 / 23625
Javascript, 14 / 23625
Document Type Definition Files, 14 / 23625
Mac OS X Install Files, 6 / 23625
XSL/XSLT, 5 / 23625
BZIP Archives, 3 / 23625
Visual Studio C# Project File, 3 / 23625
SED, 3 / 23625
TAR Archives, 1 / 23625
Other, 8719 / 23625

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

I always liked python. It is a rather gentle language with many functional and Object-Oriented characteristics. I was always complaining about python’s Object-Oriented support, and i have a principle as a developer: “If you cannot implement something, do not offer it as a feature”.

Python violates this principle, because it allows developers to use multiple inheritance on a class but does not implement it correctly. Consider the following example:

class ParentOne:
	def __init__(self):
		print "Parent One says: Hello my child!"
		self.i = 1
 
	def methodOne(self):
		print self.i
 
class ParentTwo:
	def __init__(self):
		print "Parent Two says: Hello my child"
 
class Child(ParentOne, ParentTwo):
	def __init__(self):
		print "Child Says: hello"

We have three classes, ParentOne, ParentTwo, and Child. The class Child inherits ParentOne and ParentTwo.

Normally each parent class should be initialised when the child class is initialised through a specified initialisation scheme. Python just do not initialise the parent classes. For example, if we create an instance of the class Child

c = Child()

… we will see in our screen the following output:

bkarak$ python example.py
Child Says: hello

As we can see the __init__ method (aka the constructor) for each parent class is never executed. OOppss.

So, if the ParentOne init method declares a field named “i” (instance field) and the child tries to execute the method, we will end up with the following result:

bkarak$ python example.py
Child Says: hello
Traceback (most recent call last):
  File "example.py", line 20, in 
    c.methodOne()
  File "example.py", line 9, in methodOne
    print self.i
AttributeError: Child instance has no attribute 'i'

Ouch. This fact narrows down the usability of multiple inheritance to simple concatenation of methods with static methods. Really nicely done.

My advice is: “Avoid it, because you are not going to enjoy it”.

I do not really know if something is better implemented in Python 3.0. I will check it and write about it in the distant future.

VN:F [1.9.17_1161]
Rating: 10.0/10 (2 votes cast)
VN:F [1.9.17_1161]
Rating: +1 (from 3 votes)

I really hate GUI programming. Lucky me, i develop mostly command-line applications.

The problem is always the same. Command-line applications take arguments, and that arguments need to be parsed. I used various methods to do the job; i tried to use getopt (which i found BAD) and some other libraries.

During the development of biblio.py, i devised the following solution to create a very simplistic command-line parser.

The actual command-line scheme of biblio.py is:

biblio.py [command] [args]

An example:

biblio.py search software

To parse such simple arguments you typically need an if-else if pattern:

1
2
3
4
5
6
if sys.argv[1] == 'arg1':
	# do something here
elif sys.argv[1] == 'arg2':
	# do something there
elif sys.arg[1] == 'arg3':
	# etc ...

Hm … that is not very good piece of code, and not very scalable either. To avoid all these, i proposed the following solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ArgsDispatcher:
       def __init__(self, args):
                self.__args = args
 
       def doHelp(self):
                # print the online help
 
       def doFoo(self):
                # is the 'foo' argument actual implementation
 
# the program starts here
def main():
	# initialise the dispatcher and execute
	cdisp = ArgsDispatcher(sys.argv[2:])
	try:
		getattr(adisp,"do" + sys.argv[1].title())()
	except (AttributeError, IndexError):
		adisp.doHelp()
 
# call the main function
if __name__ == '__main__':
	main()

The solution is simple; reflectively the main function calls the implementation of each argument (after initialising ArgsDispatcher). The implemented method follows the pattern do[argument] e.g. help is implemented by doHelp.

VN:F [1.9.17_1161]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)