Pattern matching or sort of in python

I must admit that pattern matching is not really new to me. The first time I looked at haskell I was impressed by the idea a lot. It wasn’t until late that I found about new languages on the JVM that support the same idiom.

For this to work properly – the language should know how to “destruct” an already constructed element. A simple example in haskell is if you have a list of elements and you want to capture the first element in a variable and the remaining part of the list in another variable. In that case you would write something like this:

 
f (x:xs) =  -- do something with "x" as the head of the list and "xs" as the tail

This is a definition of f as a function on one argument – if you then call the function with a list like [1, 2, 3] you will have a x = 1 and xs = [2, 3] in the body of the function.

So given this knowledge today I started coding a python script at work. And I found myself trying this pattern in the python interactive shell – the result was that python supports this for lists at least:

>>> p = [1, 2]
>>> [a, b] = p
>>> a 
1
>>> b
2
>>>

But continuing further I was given an error message:

>>> p = [1, 2, 3]
>>> [a, b] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
>>>

So while this works for full pattern on lists it won’t work if you provide less elements.

It is strange how exotic languages like haskell can open your mind for idioms that you can use in more “accepted” languages like python.

Implement properties in C plus plus

Here is some tricky code in C++ that I was watching recently and decided to post here for future references. Sometime the usage of operator overloading in C++ amuses me so much. Apperently there is a way to implement properties that look the same as normal properties and behave almost the same. The only problem as always is that when you get a compile time error – the messages are pretty confusing if you don’t know what’s going on. Enough said here is the code for that “beautiful” feature.

/* vim: set sw=4 sts=4 et foldmethod=syntax : */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 
#include 
 
using std::cout;
 
template
class Property
{
private:
    PropertyType data;
 
public:
    /* Use the cast type operator here */
    operator PropertyType()
    {
        return Controller::get(data);
    }
 
    PropertyType operator=(PropertyType a)
    {
        Controller::set(data, a);
        return Controller::get(data);
    }
};
 
class IntController
{
public:
    static int get(int &a)
    {
        return a;
    }
 
    static void set(int &a, int &b)
    {
        a = b;
    }
};
 
class Man
{
public:
    Property<int, IntController> HP;
};
 
void PropertyTest()
{
    Man man;
    man.HP = 7;
    man.HP = 7 + man.HP;
    cout << man.HP << "\n";
}
 
int main (int argc, char const* argv[])
{
    PropertyTest();
    return 0;
}

Installing flash 64bit on Kubuntu jaunty

Maybe some of you know that kubuntu/ubuntu is providing 32 bit flash player and is using nspluginwrapper if you are using an 64 OS. Here the nspluginwrapper is making problems, it is making my machine unresponsible if I am watching 3 flash sites at the time and so on. I am also suspecting that it is the reason firefox crashes sometimes on some flash movies.

So here is the workarround. On the official website of adobe there is no 64 option so we have to dig a little more. We push a search on google and here is what we get . It seems that there is some 64bit support so we scroll down the page and find a download link. Here is the whole procedure for installing the 64bit flash :) :

       wget -c http://download.macromedia.com/pub/labs/
       flashplayer10/libflashplayer-10.0.32.18.linux-x86_64.so.tar.gz
       tar zxvf libflashplayer-10.0.32.18.linux-x86_64.so.tar.gz
       mkdir -p ~/.mozilla/plugins
       mv libflashplayer.so ~/.mozilla/plugins

NB. Make sure that you uninstall any previous version of the flash player :)

Reloading jars at Runtime

I haven’t blogged in a while but now i have some time :) . This week I had to dynamically reload some jars from a directory and i searched the net about the problem. I will show the implementation that I finally came up with. The problem with the dynamically loading external jars is that they should not be in the CLASSPATH because the system classloader is making some optimizations(cache) of the currently loaded classes and doesn’t search again in the CLASSPATH if it has already instantiated the class. So to make the jars dynamically loadable we have to make our own ClassLoader or we can use the URLClassLoader which is part of the JavaSE. The idea is that every time we load the class we should use a new object of the URLClassLoader so we don’t use the cache. And also we should have an interface so we can cast our instantiated object or the alternative is to use reflection and the Method class. But enough words here is the implementation:
1. The Interface :

package org.nikolavp;
 
public interface Reloadable{
    public void method();
}

2. The Class which will reload our class by a given name:

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
 
import org.nikolavp.Reloadable;
 
public class ClassReloader{ 
    public static Reloadable reload(String className) {
        Reloadable obj = null;
        URL jar = null;
        try {
            jar = new File("jars/somejar.jar").toURI().toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        URLClassLoader loader = new URLClassLoader(new URL[] { jar },
                        ClassLoader.getSystemClassLoader());
        try {
            Class clazz = loader.loadClass(className);
            obj = (Reloadable) clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }  return obj;
    }
}

3. The Main class to test our work:

import org.nikolavp.Reloadable;
 
public class Main{
    public static void main(String[] args) {
        while (true) {
            Reloadable object = ClassReloader.reload("MyClassFromSomeJar");
            object.method();
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Assume that MyClassFromSomeJar exist in the jars/somejar.jar
you can now make changes to the
code in the external jar and see the results :)

Conclusion: This is one of the areas where java really shines. Try doing that with static languages like C/C++ :)

Sparse matrix multiply dummy algorithm

Today almost the half an hour I was trying to write that algorithm which multiplies two sparse matrix. At the end this is what I’ve got. The matrix is represented as a linkedlist of triples, because this is how they want it in our university. There were some mistakes in the code like Sparce is not with “s”, but those are pretty much syntax mistakes and i didn’t want to make changes for our teacher :) .

public NumericMatrix multWith(SparseMatrix mat) throws CannotMult, 
   OutOfMatrixRange {
   if (!canMult(mat)){
       throw new CannotMult();
   }
   SparseMatrix result = new SparseMatrix(this.rows, mat.columns);
   if (body.isEmpty() || mat.body.isEmpty()){
       return result;
   }
   Iterator<Triple> itForThis = this.body.iterator();
 
   while (itForThis.hasNext()) {
       Triple thisElement = itForThis.next();
       Iterator<Triple> itForMat = mat.body.iterator();
       while (itForMat.hasNext()) {
           Triple thatElement = itForMat.next();
           if (thatElement.i > thisElement.j){
               break;
           }
           if (thisElement.j == thatElement.i) {
               double value = result.elementAt(thisElement.i,
                       thatElement.j);
               result.setElement(thisElement.i, thatElement.j, value
                       + thisElement.element * thatElement.element);
           }
       }
   }
   return result;
}

Sorry for the bad code formatting but java is kind of verbose :( . All in all the code is not so nice but it was the only thing that came up and worked so I am posting it here if someone need it, because there wasn’t good simple code for that algorithm. I didn’t have the time to look at performance libraries and how they implement that, but I read some interesting stuff on wikipedia.com. I didn’t know that there was an algorthm that can multiply two Ordinary matrices in O(n^2.376). Take a look at the page. If you find some free materials about the algorithm please let me know I will be glad to look into it, because I might need it for some graphic stuff I will be doing next year :)

UPDATE: Fixed some stuff and chan the name to SparseMatrix to be really normal :)

C++ can have nasty syntax sometimes

Hmm today on IRC in the channel ##C++ @ Freenode someone posted the following code

/*In g++ this does not work*/
template
struct hello
{
 hello(){};
 ~hello(){};
 template
 int world()
 {
  return _b+_a;
 }
};

template
void try_hello()
{
hello h;
h.world();
}

so i tried to help the person telling him that he should use a typename before h.world(); because it can ambitious for the compiler. It turns out that the right solution was

h.typename world();

someone asked why is

world()

ambitious for the compiler and seldon said that the compiler can’t know the type of world in that context. Well but world is explicitly called with


. Hmm the problem is that when the compiler see that expression it assume that

<

after world is the operator less than. Oh that my brain started to hurt badly :D . Maybe the syntax of C++ is getting really complicated with the years. I think that the new standards won’t get rid of those, because they can’t. Too much code have been written already to work that way :(

Back from the vacation

Hmm yesterday i finally came back from the vacation in the mountain. I prefer it instead of the sea, because the sea is too dirty in the last years. As you maybe know i live in Bulgaria and it is near the Black sea which is pretty much aweful. Most of the time i was fishing swimming in a nice Pool near Ribarica. I also almost read Code complete second edition which is pretty old book but is still adequate for most of the tips. The author is one of those writers which make you think about every single word without making you bored of the book ;) . It is language independent – there are examples in VB(which i don’t know but you can understand the idea of the examples with no problem), C#, Java, C++, C. One thing is for sure – the mountain was damn better than the dirty sea :) .

More kbgoffice fun

Yesterday i finally managed to port kbgoffice completely to Qt4, so everyone with no qt3support can compile it. I am not happy with what i got however. The code is really bad and there are no testcases so i might write those for now. With no tests the development is really hard. I might use the test framework provided with Qt which really rocks. The program is also hard coded with a class named Properties which is really broken, because it seems that when they wrote the program there was no QSettings class which is times better :) .

Eclipse for c++

Hmm lately I started using eclipse more and more. It seems they made it to not crash so much with the new release. I am pretty happy with it for C++ development it seems to own. I am not sure but i think that I am even more productive with it now than with vim. I have used the 3.2 version but it was full crap back then ;) . Besides it is written in java it is worth looking in it.

Supress some warning in vim

Maybe you know that vim parses the output from the compiler so it can jump to the right line which cause the error(:h quickfix for more info). Well it seems that the default compiler options parse even warning which are sometimes pretty annoying. There were some warning for depracated conversion from the compiler because of xmp files. Well i am sure that i don’t want to see those. So here is what i have in my ~/.vim/ftplugin/cpp.vim for some time:

let &errorformat = "%-G%f\:%l\:\ warning\:\ deprecated\ conversion\ from\ string%.%#\,".&errorformat

I know that maybe this only works for gcc, but it is a start. You can get more info about the erroformat with :h errorformat in vim. Happy vimming :)