Multi-line String Literals in Java

30. October, 2008

You want multi-line string literals in Java which work in Java 1.4 and up? Can’t be done, you say?

Sven Efftinge found a way.


Compile VMware tools on openSUSE 10.3

27. October, 2008

I just tried to install the VMware tools on openSUSE 10.3 (Linux kernel 2.6.22.18) so the virtual machine would survive more than 10 days on an ESX server and failed. If you have the same problem, the solution is here.

Errors you’ll see during the installation otherwise:

The directory of kernel headers (version @@VMWARE@@ UTS_RELEASE) does not match your running kernel (version 2.6.22.18-0.2-default). Even if the module were to compile successfully, it would not load into the running kernel.


Failure is not an Option

22. October, 2008

Everyone loves war stories. Here is one of mine. I need a special diet, especially bread. So one Friday evening, I was taking the train home after buying a couple of custom made loafs of bread. In Dübendorf, I left the train and walked home.

About halfway home, I noticed that I had my head, my arms, my bag … but not my bread! ARGH! Stupid, stupid, stupid! I knew I should have stuffed them in my rucksack but didn’t because it was so full and … yeah … okay. My baker needs three days to make these breads so that meant about a week without any for me.

Arriving home, an idea struck me and I fired up the VBZ online service to find out where the train was and when the driver would make the next break. A few moments later, the SBB Train Police got a really strange call by me: “I need my bread. It’s in this train and can you please, please ask the driver to check if the white plastic bag with the bread is still there?”

The woman on the other end was surprised and promised to call me back.

Ten minutes can be sooo long.

From the timetable, I knew that my train would probably come through my town in about twenty minutes when I got the call. Yes, they found it and the driver would take the plastic bag into his cabin and she told me where to wait on the platform so he could hand it over.

Try train was on time (as usual), the driver handed me my bag (and it really was mine and all the bread was still there) and I was really relieved. After thanking him, I went home to have my dinner. Thanks to the SBB train police, a train driver and an unknown person who put my bread in the overhead compartment when I left it behind, I didn’t go hungry that weekend.

Lesson: If all seems lost, take a step back, do something else and you might have the idea which will save the day.

Train related joke: The SBB (Schweizer Bundesbahn – Swiss federation train company) and the German Bundesbahn (the counterpart of the SBB in Germany) wanted to save some money and decided to buy the same information system to inform about arriving trains on the platform. After a longer evaluation, the plan was dropped. The SBB needed signs which said “Train is 1, 2, 3, 4, 5 minutes late” and the German Bundesbahn needed “Train is half an hour, 1 hour, 2 hours, 3 hours, 4 hours, Train Cancelled.”


So… You want your code to be maintainable.

14. October, 2008

A great post if you’re interested in TDD or testing in general: So… You want your code to be maintainable. by Uncle Bob. Thanks, Bob!


Good Games for the PS3

11. October, 2008

I’ve recently upgraded to a PlayStation 3. I kept my old PS2, though, since the new PS3 can’t emulate the PS2. I wonder why that is … maybe it’s because Sony is still selling so many PS2’s? Ah, rumors 🙂 Easy to create and hard to kill.

So what good games are there? Here is my list:

  • Burnout Paradise City
  • PixelJunk Eden
  • Ratchet & Clank – Tools of Destruction
  • Flow

Burnout Paradise City

Mindless street racing with a high adrenaline level. Ideal to waste a couple of minutes or an hour. Great graphics, no blood, no violence (it’s more like auto scooter) and nice ideas like smashing ads or the super jumps. If you don’t like some events (haven’t managed to win a single race, yet. I excel at kicking other cars off the street), you can simply ignore them and still complete enough of the game to have fun.

PixelJunk Eden

A definitive feel of Tarzan or Spiderman when you want to relax a bit. Simple, fitting graphics, no violence, no agression. All that and at the price it’s a steal.

Ratchet & Clank – Tools of Destruction

My favorite jump’n’run. Lots of insane weapons, Ratchet’s ears look great on the PS3, the story has more depth than usual; not sure I like the depressive realization at the end, though. Judge for yourself.

Flow

Like Eden, it’s a brand new kind of game. One of a kind. I play that when I want to come down from all the stress in my life. Go get it!

Bad games

I’ve got a couple of other games. First, we have the Orange Box with Half Life 2, two of the extra episodes, Portal and Team Fortress. I liked the puzzles in Portal. That games was much too short. I didn’t like Half Life 2 much and I hate the episodes. The story was great, the levels gigantic and intelligent. You could almost always find a way around without getting killed. But the handling … Freeman feels like a block of wood when you move him through the levels: You’ll get stuck all the time at hand rails and stuff like that. Sometimes, he’ll be able to jump on something, sometimes not. Sometimes, he’ll stay on top of a barrel, sometimes not. This sucks. And then those stupid zombie levels. Yeah, I’m stuck in the elevator scene in the first episode. Got killed five times in the dark and now, the games goes where it belongs: The trash.

Resistance – Fall of Man. I like the other games by Insomniac and I like this one, too. It’s just too violent for my taste. I like shooting pixels or push empty cars off the street or zoom down a highway at break-neck speed. I don’t like shooting at people. I finished the game but it left me asking: Is that all? Running around, shooting people, blow up stuff? Is that the result of many years of game evolution? Better graphics?

Uncharted: Drake’s Fortune. Oh well. Okay, the levels look great. When you scale the wall of the castle, there is a sense of vertigo. It’s breath taking. The jeep escape is a lot of fun. Smart story (mostly). The game character moves smart. You press a button and he takes cover. He’s smart, not a dead puppet like Freeman. He moves as if he was real. Again the violence cooled me off quickly. Too much killing, not enough puzzles.


Enthought Traits

9. October, 2008

I’m always looking for more simple ways to build applications. Let’s face it, it’s 2008 and after roughly 50 years, writing something that collects a few bits of data and presents them in a nice way is still several days of work. And that’s without Undo/Redo, a way to persist the data, a way to evolve the storage format, etc.

Python was always promising and with the tkinter module, they set a rather high watermark on how you easily could build UIs … alas Tk is not the most powerful UI framework out there and … well … let’s just leave it at that.

With Traits, we have a new contender and I have to admit that I like it … a lot. The traits framework solves a lot of the standard issues out of the box while leaving all the hooks and bolts available between a very thin polish so you can still get at them when you have to.

For example, you have a list of persons and you want to assign each person a gender. Here is the model:

class Gender(HasTraits):
    name = Str
    
    def __repr__(self):
        return 'Gender %s' % self.name

class Person(HasTraits):
    name = Str
    gender = Instance(Gender)
    
    def __repr__(self):
        return 'Person %s' % self.name

class Model(HasTraits):
    genderList = List(Gender)
    persons = List(Person)

Here is how you use this model:

female = Gender(name='Female')
male = Gender(name='Male')
undefined = Gender(name='Undefined')

aMale = Person(name='a male', gender=male)
aFemale = Person(name='a female', gender=female)

model = Model()
model.genderList.append(female)
model.genderList.append(male)
model.genderList.append(undefined)
model.persons.append(aFemale)
model.persons.append(aMale)

Nothing fancy so far. Unlike the rest of Python, with Traits, you can make sure that an attribute of an instance has the correct type. For example, “aMale.gender = aFemale” would throw an exception in the assignment.

The nice stuff is that the UI components honor the information you use to build your model. So if you want to show a tree with all persons and genders, you use code like this:

class Model(HasTraits):
    genderList = List(Gender)
    persons = List(Person)
    tree = Property
    
    def _get_tree(self):
        return self

class ModelView(View):
    def __init__(self):
        super(ModelView, self).__init__(
            Item('tree',
                editor=TreeEditor(
                    nodes = [
                       TreeNode(node_for = [ Model ],
                           children = 'persons',
                           label = '=Persons',
                           view = View(),
                       ),
                       TreeNode(node_for = [ Person ],
                           children = '',
                           label = 'name',
                           view = View(
                               Item('name'),
                               Item('gender',
                                  editor=EnumEditor(values=genderList,)
                               ),
                           ),
                       ),
                       TreeNode(node_for = [ Model ],
                           children = 'genderList',
                           label = '=Persons by Gender',
                           view = View(),
                       ),
                       TreeNode(node_for = [ Gender ],
                           children = '',
                           label = 'name',
                           view = View(),
                       ),
                    ],
                ),
            ),
            Item('genderList', style='custom'),
            title = 'Tree Test',
            resizable = True,
            width = .5,
            height = .5,
        )

model.configure_traits(view=ModelView())

First of all, I needed to add a property “tree” to my “Model” class. This is a calculated field which just returns “self” and I need this to be able to reference it in my tree editor. The tree editor defines nodes by defining their properties. So a “Model” node has “persons” and “genderList” as children. The tree view is smart enough to figure out that these are in fact lists of elements and it will try to turn each element into a node if it can find a definition for it.

That’s it. Everything else has already been defined in your model and what would be the point in doing that again?

But there is more. With just a few more lines of code, we can get a list of all persons from a Gender instance and with just a single change in the tree view, we can see them in the view. If you select a person and change its name, all nodes in the tree will update. Without any additional wiring. Sounds too good to be true?

First, we must be able to find all persons with a certain sex in Gender. To do that, we add a property which gives us access to the model and then query the model for all persons, filter this list by gender and that’s it. Sounds complex? Have a look:

class Gender(HasTraits):
    name = Str
    persons = Property
    
    def _get_persons(self):
        return [p for p in self.model.persons
                if p.gender == self]

But how do I define the attribute “model” in Gender? This is a hen-and-egg problem. Gender references Model and vice versa. Python to the rescue. Add this line after the definition of Model:

Gender.model = Instance(Model)

That’s it. Now we need to assign this new field in Gender. We could do this manually but Traits offers a much better way: You can listen for changes on genderList!

    def _genderList_items_changed(self, new):
        for child in new.added:
            child.model = self

This code will be executed for every change to the list. I walk over the list of new children and assign “model”.

Does that work? Let’s check: Append this line at the end of the file:

assert male.persons == [aMale], male.persons

And the icing of the cake: The tree. Just change the argument “children=”” to “children = ‘persons'” in the TreeNode for Gender. Run and enjoy!

One last polish: The editor for genders looks a bit ugly. To suppress the persons list, add this to the Gender class:

    traits_view = View(
        Item('name')
    )

There is one minor issue: You can’t assign a type to the property “persons” in Gender. If you do, you’ll get strange exceptions and bugs. Other than that, this is probably the most simple way to build a tree of objects in your model that I’ve seen so far.

To make things easier for you to try, here is the complete source again in one big block. You can download the Enthought Python Distribution which contains all and everything on the Enthought website.

from enthought.traits.api import 
        HasTraits, Str, Instance, List, Property, This

from enthought.traits.ui.api import 
        TreeEditor, TreeNode, View, Item, EnumEditor

class Gender(HasTraits):
    name = Str
    # Bug1: This works
    persons = Property
    # This corrupts the UI:
    # wx._core.PyDeadObjectError: The C++ part of the ScrolledPanel object has been 
    # deleted, attribute access no longer allowed.
    #persons = Property(List)
    
    traits_view = View(
        Item('name')
    )
    
    def _get_persons(self):
        return [p for p in self.model.persons if p.gender == self]
    
    def __repr__(self):
        return 'Gender %s' % self.name

class Person(HasTraits):
    name = Str
    gender = Instance(Gender)
    
    def __repr__(self):
        return 'Person %s' % self.name

# Bug1: This doesn't work; you'll get ForwardProperty instead of a list when
# you access the property "persons"!
#Gender.persons = Property(fget=Gender._get_persons, trait=List(Person),)
# Same
#Gender.persons = Property(trait=List(Person),)
# Same
#Gender.persons = Property()
# Same, except it's now a TraitFactory
#Gender.persons = Property

class Model(HasTraits):
    genderList = List(Gender)
    persons = List(Person)
    tree = Property
    
    def _get_tree(self):
        return self
    
    def _genderList_items_changed(self, new):
        for child in new.added:
            child.model = self

Person.model = Instance(Model)
Gender.model = Instance(Model)

female = Gender(name='Female')
male = Gender(name='Male')
undefined = Gender(name='Undefined')

aMale = Person(name='a male', gender=male)
aFemale = Person(name='a female', gender=female)

model = Model()
model.genderList.append(female)
model.genderList.append(male)
model.genderList.append(undefined)
model.persons.append(aFemale)
model.persons.append(aMale)

assert male.persons == [aMale], male.persons

# This must be extenal because it references "Model"
# Usually, you would define this in the class to edit
# as a class field called "traits_view".
class ModelView(View):
    def __init__(self):
        super(ModelView, self).__init__(
            Item('tree',
                editor=TreeEditor(
                    nodes = [
                       TreeNode(node_for = [ Model ],
                           children = 'persons',
                           label = '=Persons',
                           view = View(),
                       ),
                       TreeNode(node_for = [ Person ],
                           children = '',
                           label = 'name',
                           view = View(
                               Item('name'),
                               Item('gender',
                                  editor=EnumEditor(
                                      values=model.genderList,
                                  )
                               ),
                           ),
                       ),
                       TreeNode(node_for = [ Model ],
                           children = 'genderList',
                           label = '=Persons by Gender',
                           view = View(),
                       ),
                       TreeNode(node_for = [ Gender ],
                           children = 'persons',
                           label = 'name',
                           view = View(),
                       ),
                    ],
                ),
            ),
            Item('genderList', style='custom'),
            title = 'Tree Test',
            resizable = True,
            width = .5,
            height = .5,
        )

model.configure_traits(view=ModelView())

UPCScan 0.6: It’s Qt, Man!

8. October, 2008

Update: Version 0.7 released.

Getting drowned in your ever growing CD, DVD, book or comic collection? Then UPCScan might be for you.

UPCScan 0.6 is ready for download. There are many fixed and improvements. The biggest one is probably the live PyQt4 user interface (live means that the UI saves all your changes instantly, so no data loss if your computer crashes because of some other program ;-)).

The search field accepts barcodes (from a barcode laser scanner) and ISBN numbers. There is a nice cover image dialog where you can download and assign images if Amazon doesn’t have one. Note: Amazon sometimes has an image but it’s marked as “customer image”. Use the “Visit” button on the UI to check if an image is missing and click on the “No Cover” button to open the “Cover Image” dialog where you can download and assign images. I haven’t checked if the result of the search query contains anything useful in this case.

UPCScan 0.6 – 24,055 bytes, MD5 Checksum. Needs Python 2.5. PyQt4 4.4.3 is optional.

Security notice: You need an Amazon Web Service Account (get one here). When you run the program for the first time, it will tell you what to do. This means two things:

  1. Your queries will be logged. So if you don’t want Amazon to know what you own, this program is not very useful for you.
  2. Your account ID will be stored in the article database at various places. I’m working on an export function which filters all private data out. Until then, don’t give this file to your friends unless you know what that means (and frankly, I don’t). You have been warned.