All posts by Clément Pinchedez

My name is Clément Pinchedez. I am a software engineer and with this blog, I would like to share some of my thoughts about programming and computer science. Have a look at my presentation page if you want to know more about me.

A funny numeration system

When I swim at the pool of Antibes, I usually count the laps I do. It is just an obsession, I just feel good when I know how many laps I did.

At first I was using the regular decimal system, but after a while I found it a bit boring. So I progressively shifted to other kinds of counting methods, just to conjugate the water I was swallowing with some mathematical brain-twisting fun.

That’s how I ended up counting in other languages (German, Chinese or Swedish) and in other numeral system: Roman, binary, octal, duodecimal, hexadecimal.
Since I often try to do 40 laps, that makes me count up to vierzig, 四十, fyrtio, XL, 101000, 050, 34, x28.

But lately, I had the idea to count in a new interesting numeral system, and I would like to share it in this post. I have not found a lot of posts dealing with this kind of counting system (at least I think Kurt Gödel used it somehow) and I even do not really know if it has practical applications (let’s keep these reflexions for the conclusion). But at least it find it is quite funny to count with it.

The numeration system

The fundamental theorem of arithmetic states that every integer can be written as a unique product of prime numbers.

That’s why and .

So I thought: why cannot we use this uniqueness to write numbers? We could take primes as the base of the system and for each, we assign a number, the exponent.
In that system 240 would be written something like a list of tuples: (2,4),(3,1),(5,1). Or better, we could use a positional system where the position will be the prime number position in the list of prime numbers, and the number assigned to the position will be the exponent.
For example, the number 240 would be written 411 since 2, 3 and 5 are the 1st, 2nd and 3rd prime numbers. And for 1170, it is: 121001.

But since the exponent is itself a number, you cannot write it in base 10. So let’s write it in the same prime-number-decomposition system. I will put bracket around the position. In that system it seems you end up only needing brackets, 0 and 1…
In that system, the number becomes , and that is why the number 240 should then be written .

So let’s count from 1 to 10!

Counting to 10000

Back from the swimming pool, I was wondering: that would be great to count even higher. Let’s program a little. That’s how I ended up writing some Python script to count up to 10000 with that method.
It is not really complicated admittedly, and if we assume having a function fac(n) to get the decomposition of an integer in prime numbers, this is the program you can use to count numbers1:

num = 10000
result = {1: '0'}
primes = []
maxlength = 0
for n in range(2,num+1):
    f = fac(n)
    if len(f) == 1:
        primes.insert(0,f[0])
        s = '1'+'0'*maxlength
        maxlength += 1
    else:
        s = ''
        b = False
        for p in primes:
            c = f.count(p)
            if c==0:
                if(b):
                s += '0'
            elif c==1:
                s += '1'
                b = True
            else:
                s += ('['+result1+']')
                b = True
                result[n] = s
    print(repr(n).ljust(6),s)

The result: the complete numeration from 1 to 10000 can be found here

For the factorization in prime numbers I used the pyecm script, which uses the Elliptic curve method for the factorization. Since the script is not adapted for a version of Python higher than 3, I did adapt it a little. The complete source code is here (note that this source code is licensed under GNU GPL).

Is it useful?

My answer is NO. Don’t use it at home!
I have several reason to think this numeral system is far from being useful in everyday’s life (at least when you are not swimming laps):

  • Small number can be very long to write. For example 2012 is written 10000000000000000000000110, which is also very hard to understand!
  • To write a number, you need to know how the number before were written. And you also need to know the list of prime number by heart.
  • To write a given number you need to decompose numbers in primes, which is far from being an easy exercise!

Besides, I do not see any practical use of this notation. If it is easy to multiply and get the GCD/LCM of two numbers, there is no obvious way to divide and add them to each other…

  1. Note that I did not pay a lot of attention concerning the memory consumption of this method. Storing the list of primes and most of all the complete numeration in a dictionary is not the cleverest idea! []

Transient and final instance variables in Java

In Java, transient and final are two important keywords and it is legal to put them as modifier of instance variables.

But how does it behave when it comes to object serialization? Since it is transient, we can guess such variable are not serialized and therefore, when the object is deserialized, they are initialized to their default values, like for regular non final instance variable.

But in fact, it depends! See the code below:

public class Diplodocus implements Serializable {

	private final transient String s1 = "test";
	private final transient String s2;
	private final transient String s3 = new String("hello");
	private final transient String s4 = s1 + s1 + 1;
	private final transient int i1 = 7;
	private final transient int i2 = 7 * 3;
	private final transient int i3 = Integer.MIN_VALUE;
	private final transient int[] a1 = {1,2,3};

	public Diplodocus() {
		s2 = "s2";
	}

	public static void main(String[] args) {

		File f = new File("diplo");
		try {
			FileOutputStream fos = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(new Diplodocus());
			oos.flush();
			oos.close();

			FileInputStream fis = new FileInputStream(f);
			ObjectInputStream ois = new ObjectInputStream(fis);
			Diplodocus diplo = (Diplodocus) ois.readObject();
			ois.close();
			System.out.println("s1 = "+diplo.s1);
			System.out.println("s2 = "+diplo.s2);
			System.out.println("s3 = "+diplo.s3);
			System.out.println("s4 = "+diplo.s4);
			System.out.println("i1 = "+diplo.i1);
			System.out.println("i2 = "+diplo.i2);
			System.out.println("i3 = "+diplo.i3);
			System.out.println("a1 = "+diplo.a1);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

What we expect here is that the instance variables after the deserialization will be equals to the default initialization values : null for objects like Strings and 0 for the integers.

But, in fact the code has the following output:

s1 = test
s2 = null
s3 = null
s4 = testtest1
i1 = 7
i2 = 21
i3 = -2147483648
a1 = null

What happened?

During deserialization, the constructor of the object is not called. This is a special object instantiation process handled by the JVM. For regular non-final transient instance variable, they are assigned with their default values.

But what happened for final variables? There is a little trick.

If the final variable is blank, meaning that it is first initialized in the object constructor(s) (like on line 13), the deserialization will put the default value. That is why s2 = null.

On the contrary, for a final variable explicitly initialized, the value is reaffected, but only if this initializations is done in a certain manner, in fact, only if the initialization is done with what the Java specification calls a compile-time constant expression (§15.28).

Constant expressions are the ones you are allowed to use in the case labels of a switch statement. A constant expression is an expression, which can be resolved at compile-time with no ambiguity: somehow, it gives the guarantee that the resulting value will never change during the execution.

In our case, these are considered constant expressions and that is why the values are reaffected to the final variables (even if they are transient).

  • literals (like a String on line 3, or an integer on line 7)
  • + operation between literals and reference to a constant final variables (like on line 6)
  • * operation between integers (like on line 8)
  • reference to constants (like on line 9)

There are other types of constant expressions (e.g. cast operation to a primitive or a String). I suggest you to have a look at the specifications for more details1.

However, object instantiations are not considered to be constant expressions and that is why these are assigned to the default values (like on lines 5 and 10).

Conclusion

Be careful when you use transient final instance variable! You may expect to get attributes initialized or not according to the context. And the worst part is that, since they are final you cannot modify them directly afterwards.

  1. or simply check this: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28 []

Origami and Egyptian triangles (the Haga theorem)

I think most of us have only been taught Euclidian geometry at school. A ruler and a compass, the solid axioms of the Elements, and here we go!…

But as you probably know, even if it is pretty good to describe quite a lot of things, the Euclidian geometry suffers from some limitations. The famous Greek examples are doubling the cube (or the delian problem), the angle trisection and squaring the circle. We had to wait for the 19th century to show these problems where impossible to solve with the Euclidian geometry (i.e. with a ruler and compass only).

That is why other people invented other types of geometry. Thus, I lately came across some Web articles about origami geometry and I was quite surprised how powerful it is: it is indeed possible to solve some of the impossible problems above with origamis1. It was quite a revolution in my mind ! And where I am the most impressed is that you can achieve a lot with very limited materials: paper and folding…

The thing I did not know is that it exists many publications and theorems about origamis, although this field of research gained most of its popularity in the 20th centry. In this post, I will just give you an example (and a demonstration) of a famous theorem one can find about origami : the Haga theorem.

I like this theorem because it is very easy to understand and shows how you can have interesting geometrical reasonning from origamis. The demonstration is also not very complicated: you do not need more than highschool student geometrical notions to understand it.

The Haga Theorem

The Haga theorem comes from Kazuo Haga, a Japanese retired professor of biology from the University of Tsukuba.

To see what this theorem is, you first need a square piece of paper2. I really encourage you to do it at home because it is very visual.

Fold this square in two. Here is what you get:

So, the next step is simply to fold the paper so that the corner C goes to the point S, the place where the paper was folded in half. You should end up with something like this::

That’s all! The Haga theorem simply says:

But actually, I prefer to rephrase it like this:

The triangles SAV, SBT and TDU are all Egyptian triangles.

What are Egyptian triangles? Maybe we need some explanations…

Egyptian triangles

You should be familiar with the famous Pythagorean theorem stating that in a right triangle, the square of the length of the hypothenuse (the longest side) is equal to the sum of the squares of the length of the two other sides.

You may also know that the converse of this statement is true: if you have a triangle so that the square of the longest side is equal to the sum of the squares of the other sides, then you have a right triangle.

If the theorem have the name of the famous Greek mathematician of Samos, it seems that more ancient civilizations already know this laws, e.g. the Egyptians.
They indeed used a quite powerful tool: a rope with 13 knots evenly distributed. With this rope, they were able to draw right triangle very easily.
Here is how it works:

You take the rope so that you create a triangle with the length 3, 4 and 5. This is a pythagorician triplet, because and that shows that the triangle is a right triangle. You can then used the rope to do draw right angles and build pyramids!

This is where we have our definition: an Egyptian triangle is a right triangle which is similar to this rope-made triangle. Similar means that one triangle has the same shape but maybe with a different scaling. For example, the right triangle with the sides of length 6, 8 and 10 is an Egyptian triangle (because the length are the double of the rope triangle).

Go back to the origami

Let’s go back to the Haga theorem, we say we have SAV, SBT and TDU as Egyptian triangles, which means that they are all similar to the (3,4,5) triangle made of rope.

First, we demonstrate that these triangles are similar. We demonstrate this by showing that they all have the same angles. It is a property of similar shapes to have the same angles.
Since the sum of the angles in a triangle is always equal to 180° (or if you prefer). We can show with no difficulties that the angles of the triangles ASV and SBT are the same (as show on the figure).
Concerning angles and they are the same because they are vertically opposite. We can therefore conclude to the similarity between triangles SBT and TDU (and therefore SAV).

Let’s show now that the triangle SAV is Egyptian. For that we will assume the length of the side of the initial square piece of paper is 8. That means the length of AS is 4.

We will now try to find the value of AV.

We have
And Pythagoras says:
Then:

So we have , , and . Hey, that’s an Egyptian triangle!
And since SAV is similar to SBT and TDU, we have show that all these triangles are Egyptian! Q.E.D.

(Origami crane photography author: Andreas Bauer (Origami-Kunst)

  1. at least doubling the cube and the angle trisection problems []
  2. I let you figure out how you can get a square from a A4 piece of paper []

Java EE startup and shutdown callbacks

Hurray, this is the first post of this blog!
As a first subject, I would like to discuss a problem where it was quite hard to find a solution on the Web. Let me share this with you.

The problem

Given a standard Java EE 5 application (with EJBs, Servlets…), how to develop some code which will be started when the application startup/shutdown?

In other words, how to execute something when you start or stop your application?
Indeed, when you start the server you may need to initialize some stuff like initializing your cache, and when you stop the server, wouldn’t it be great to do some data cleanup?

In my case, our application was a pure back-end application (only EJBs) which embedded a remote service interface and we wanted to register it (resp. unregister it) to a service locator at the application startup (resp. shutdown).

Unsatisfactory solutions

Application server and framework tricks

In fact, most of the application servers already come with their own solutions. In Weblogic, for example, we have the notion of startup/shutdown classes (but admittedly, I have not tested it).

But in our case, we had to deploy on a JBoss 6 server! And moreover, wouldn’t it be preferable to have a pure Java EE way, so that it could be deployed anywhere with minimal configuration?

If we were using some Java development framework like Seam, there are also some tricks, like using an observer on the org.jboss.seam.postInitializatio event like this:

@Name("initializer")
public class Initializer {

   @Observer("org.jboss.seam.postInitialization")
   public void init() {
      // startup code here
   }
}

But once again, this is a specific solution and if you are not using Seam then you should find something else (besides, I haven’t looked for the implementation of the shutdown callback with Seam).

Static blocks in EJBs

So what if we just put static block in EJBs and let’s just hope that when the EJB class will be loaded, the static code will be executed?
Well, this is a bad idea. By definition, you have no control on how the EJBs are loaded by the application server. It may even not be called before the first invocation of the EJB.
So this is obviously not a good solution.

EJB 3.1

It is true that we are speaking only about Java EE 5 in this post, but I just want to mention that in Java EE 6 with EJB 3.1, we can use the pretty code below:

@Singleton
@Startup
public class StartupShutdownBean {

	@PostConstruct
	private void startup() {
		// your startup code here
	}

	@PreDestroy
	private void shutdown() {
		// your shutdown code here
	}

}

The solutions

So, the only solution found was to use the servlet API. But the good news is that you have two choices:

Using Servlet init and destroy methods

The idea here is to have the startup and shutdown code in the init() and destroy() methods of a servlet embedded in your application. So if you do not have any servlet in your application, you will have to create one like this with these methods.

public class InitServlet extends HttpServlet {

	@Override
	public void init() throws ServletException {
		// startup code here
	}

	@Override
	public void destroy() {
		// shutdown code here
	}
}

You should guarantee that this servlet is loaded on start-up, (and potentially before the other servlets). This is guaranteed by the following statement in the web.xml.

<servlet>
        <servlet-name>Init</servlet-name>
        <servlet-class>com.clempinch.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
</servlet>

The number between the load-on-startup tag indicates the order in which servlet are loaded on startup (the lowest are first).
This solution is ok admittedly, especially if you have already servlets in your application. But what if you have none? Isn’t it a bit costly to create a servlet listening to coming requests just for two methods to call during the application life?
For that reason, I prefer therefore the second solution, which is…

Using Servlet context listeners (the one I prefer)

The other solution is still in the servlet API, and it is to use a servlet context listener.
This comes as a Java interface ServletContextListener. Classes implementing this interface will be loaded before (resp. after) the instantiation (resp. the destruction) of all servlets, therefore, it is a good place to put your application startup/shutdown code.
Here is how it is done:

public class InitContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent ce) {
        // startup code here
    }

    @Override
    public void contextDestroyed(ServletContextEvent ce) {
        // shutdown code here
    }
}

You will also need to declare the context listener in the web.xml with the following statement:

<listener>
	<listener-class>com.clempinch.InitContextListener</listener-class>
</listener>

That’s all…

Conclusion

So, to sum up, it seems that to have some startup/shutdown code in your application there is no other clean solution than to use the servlet API, either with the init()/destroy() methods or with a servlet context listener.

The other best/long-term/cleanest solution is of course to migrate to Java EE 6, but not everyone is ready to do it, right?

Welcome to my blog!

Hello traveler from the World Wide Web!

Welcome to my blog! Here you can rest after your long journey full of clicks from hyperlinks to hyperlinks.

But yes, I see you blinking and I guess you are asking yourself: “Yet another blog! On which damned hyperlink did I click to end up there?”. So let me answer your questions straight to the point…

Where you are

You are visiting my personal blog. Welcome! (hmm… am I repeating myself?)

What is this blog about?

In this blog, I will write about programming, mostly about Java which is the language I use almost everyday. But I will also speak about other programming languages I use on my spare time (and even at work, believe me), and I may also blog about more general computer science subjects and even about maths. So be prepared!
Don’t worry, there are quite many other things I like in my life. But I will keep this blog focused on these subjects.

Why such a blog?

I have been programming for quite a long time, solving puzzles and surfing on the technology… And if you are a programmer you also face this thing: quite a big part of our time is to end up browsing Google results to find answers to problems with hard-to-understand deployment error stack traces, dark-and-hard-to-debug framework issues or pretty-complicated-problematic libraries… Often, the Web has the answer: a forum, a blog, and even the official documentation!
But sometimes, in spite of the zillions storage units connected together on the Internet, I find no answer at all! So I hack, getting my hand dirty, fighting with the technology and sometimes I find something useful. So why not sharing with the world and contributing to the Web and maybe help programmers like me in the future?

Who I am

My name is Clément Pinchedez, I am a human being from planet Earth and I am a software engineer. I am currently working for Amadeus, a worldwide company developing software for the travel industry. I live in the South of France, quite a nice area admittedly.

When?

I have started this blog in April 2012. This is my second blog (I did one in my youth about my student life in Sweden).
I will try to keep a relative regular pace for posting.

How?

I will post in English because I think it is the best language to target the largest audience. I am a French native speaker and I hope my English will not be too bad.

To conclude

Hope I have answered your questions or maybe you have already clicked on an hyperlink and just left this website… “Live long and prosper!”

(image from MassassiUK)