August 18, 2008 Ask the (JavaFX) Experts

August 21st, 2008

me: What is the long term future of javafx.ext.swing.* classes in JavaFX’s
technological roadmap? Are new Node-based ui classes in-the-works to supercede this?
Joshua Marinacci: We plan to keep the swing classes but they will only be in the desktop profile. New gui classes based on nodes are in the works. These new gui components will be available on all platforms.
me: Currently, there are only a handful of people who are able to skin Swing components, are there plans to make skinning accessible to web developers? I note that a prototype skin design tool exists for Nimbus.
Joshua Marinacci: We have plans for CSS support for skinning.
me: The DropShadow filter is very slow for large objects (e.g. 300×400px), especially for animations. Can we have a flag to switch over to a low-fi version [when] using animations?
Joshua Marinacci: That’s an interesting idea. We’ll look into it. thanks.
me: It is difficult to write serious web applications if JavaFX doesn’t support multiline formatted text. Anything planned in this respect?
Joshua Marinacci: We are working on that as well.
me: How many of these (node based ui components, css) are slated for 1.0? I’m assessing whether there’s a market for 3rd party components, and need to know what gaps would already be filled by Sun.
Joshua Marinacci: We don’t have a final list yet, but it’s going to be just the basics for the 1.0 release. Things like buttons and scrollbars. We won’t have more targeted components like you see from the various Swing component vendors. There is definitely a market for 3rd party components.
me: Memory use is still a problem. A JavaFX hello world with Client JVM takes 31Mb of private memory space (jre1.6u7). For comparison purposes, Meebo on DHTML reputedly takes 43Mb, while GMail takes 50Mb on my laptop. I haven’t tested any Flex apps. So I have my concerns that using Node-based UI instead of flyweight rendering (as in JTable) will tax the capability of most machines. Last weekend, I drew 65536 rectangles with JavaFX and the JVM ran out of heap space. Will 1.6u10 JavaFX applets load a smaller class library by default?
Joshua Marinacci: We are still doing lots of optimization work. Getting the memory usage down is one of our core concerns.
me: Is the JavaFX interpreter going to be shipped with 1.6u10? Most web hosters support PHP and not java compilers, and that means if the applets can consume JavaFX script, PHP could be used to generate UI. This can help adoption. For example, silverlight supports XAML inlined with HTML.
Joshua Marinacci: The old interpreted version of JavaFX is deprecated. The only way to build JavaFX applications now is to use the compiler. However, it shouldn’t matter what your hosting company has. You will compile the JavaFX application on your development desktop computer and only upload the binary jars and html to the website. From the webserver’s point of view they are just binary files which are served to the user, the same as images or media files.
me: May I post your response on my blog? http://teyc.tumblr.com/
Joshua Marinacci: absolutely. Thanks for your great questions.

Other interview Q&A can be found

Tumblr vs Wordpress

August 20th, 2008

Tumblr is refreshingly light compared to Wordpress. There’s no comment spam to worry about. It’s actually enjoyable to blog again. Here’s my test playground. http://teyc.tumblr.com/

JavaFX Questions

August 19th, 2008

Sun has released a JavaFX preview. Having played around with it, here are my questions:

  • Will using the scenegraph api consume less resources than a comparable app developed using DHTML? In Meebo is what’s wrong with the web (cached), Uncov writes that Meebo consumes 39Mb RAM over-and-above that of Firefox. Running a basic JavaFX app (JRE1.6u7) consumes about 33Mb “VM Size”, i.e. private process memory.
  • Why is interpreted JavaFX script slow, when interpreted javascript is fast enough for client-side work? Web apps don’t necessarily have to compute prime numbers.
  • Silverlight will consume markup generated from any web server. JavaFX requires a server-side compiler, or a precompiled script. Any client-side plugin ignores PHP at it’s own peril.

Get Mark Baker

August 19th, 2008

Looks like Mark Baker is available for projects. Mark’s the man who first called out on the complexity of SOAP and advocated simpler technology, despite there being little business case for a consultant to rubbish complicated technologies that rake in the money. I wish Mark success.

JavaFX API documentation

August 17th, 2008

Since JavaFX is still under active development, the JavaFX API docs could do with some serious link-love. Currently, version 0.2 of JavaFX docs ranks in Google.

JavaFX Type Casting

August 17th, 2008

I have been playing a little bit more with JavaFX. Unfortunately the language reference isn’t particularly complete, and it turns out that type casting in JavaFX is via the as keyword. (Thanks Andres Almiray for the tip!)

For example,

var myWidth = (e.node as Rectangle).width

Incidentally, the performance of the drop shadow effect leaves much to be desired, especially if the shape is sufficiently large. During animation, the effects should be cached and preference should be given to inaccurate but speedy rendering. For instance, during rendering, the effect should be timed and if it is too slow, then a cached bitmap should be used.

The drop shadow is a rather important visual effect, especially given that Windows XP has been decorating all their windows with a shadow for 6 years, I hope Sun doesn’t drop the ball on this in JavaFX 1.0.

import javafx.scene.image.*;
import javafx.application.*;
import javafx.animation.*;
import javafx.scene.effect.*;
import javafx.scene.paint.*;
import javafx.scene.geometry.*;
import javafx.scene.text.Text;
import javafx.input.*;

var imX:Number=0;
var WIDTH:Number=400;

Frame {
    closeAction:function() { java.lang.System.exit(1); }
    stage: Stage {
        fill:Color.web('#333333')
        content: [
            Text { content:"Click on rectangle to make it smaller and observe increased frame rate" x:10 y:10 fill:Color.ORANGE},
            Circle { cache:true centerX:400 centerY:100 radius:80 fill:Color.YELLOW },
            Rectangle {
                cache:true
                x:bind imX y:100 arcWidth:20 arcHeight:20
                width:WIDTH height:WIDTH*0.75
                fill:Color.web('#6699ff')
                effect: DropShadow { radius:20 color:Color.web('#111111') offsetX:10 offsetY:10 }
                onMouseClicked: function (e:MouseEvent) {
                    (e.node as Rectangle).width  = (e.node as Rectangle).width  * 0.70;
                    (e.node as Rectangle).height = (e.node as Rectangle).height * 0.70;
                }
            },
        ]
    }
    visible:true height:768 width:1024
    title:"DropShadow Test"
}
Timeline {
    repeatCount:Timeline.INDEFINITE autoReverse:true
    keyFrames: [
        KeyFrame {
            time: 3s
            values: { imX => 800 tween Interpolator.EASEBOTH }
        }
    ]
}.start();

Clairvoyant Interaction

August 12th, 2008

This page is where I keep track of interaction design patterns. It will be particularly useful to implement these behaviors in JavaFX/Flex base-classes for nodes so that UX designer don’t have to nitpick over details like these:

  1. Yorai discusses the effect of mouse clicks and shift click, control click on focus, selection, activating in-place editing, dragging
  2. Raymond Chen discusses how a sequence of two single clicks is converted into a double-click event, and how the designer should assume that single click has occurred even if the user has double-clicked because the user double-clicks on everything (I have watched my wife do that). This is known as debouncing
  3. Just for completeness, Raymond Chen discusses triple-clicks.
  4. When waiting for a potential double click, onDragBegin() should not fire unless the mouse has moved a certain minimum distance (this is known as drag tolerance).
  5. Draggable, Droppable, Sortable
  6. Once a mouse is captured during drag-and-drop, when the mouse hovers over other objects, it should fire onDragOver instead of onMouseEnter.
  7. Robert Biggs of Vertigo discusses the minutae of drag and drop parameters
  8. A pretty complete framework for mouse-dragging … we can probably implement this for JavaFX
  9. Dragging should also trigger scrolling in containers

Language Enthusiast

August 11th, 2008

If you have been reading my blogs for an length of time, you’d know that I’m a bit of a programming language wonk. If you enjoy learning about different kinds of programming languages, you’d be pleased to know there is another kind of language geekery known as “linguistic typology”.

For example, why is it that “spoon” and “fork” are feminine in Russian, but “fork” is masculine and “spoon” is feminine in Portugese? Native speakers can tell you because “it is just so”, but cannot tell you why. Linguistic typologists can.

It’s amazing what one can learn from public radio. More on it over here.

Even more amazing is language constructs like this:

In a number of languages, every statement must contain some marker of the kind of evidence on which it is based, such as whether the speaker saw it, heard it, inferred it from indirect evidence or learned about it from someone else. This grammatical category, indicating the information source, is called ‘evidentiality’.

Having a language like this is absolutely going to make pollies squirm. +1 from me.

JavaFX for Experienced Programmers

August 9th, 2008

What JavaFX is not

JavaFX is not Java. It is a brand new language that builds on top of the JVM and the runtime libraries.  There is a new syntax, and a lot of new syntactic sugar aimed that reducing the quantity of code needed to

  • create and animate user interfaces
  • update user interfaces as model data changes
  • update model data from the user interface

A Quick Taste of JavaFX for the Impatient

// hello.fx (.fx is the only allowed file extension, hello.jfx will not work)
//import javafx.ex.swing.*;
import javafx.ext.swing.SwingFrame;
import javafx.ext.swing.Label;
import javafx.scene.paint.Color;java.lang.System.out.println(”Step 1″);
SwingFrame {
  title: “Chui’s Counterpoint”
  visible: true
  content: Label {
    text: “Hello World!”
  }
}
java.lang.System.out.println(”Step 2″);

Building and running is straightforward

javafxc hello.fx
javafx hello

This yields a standard ugly Swing Frame with “Hello World” label.

The important take-away is

  1. There is no main loop
  2. Although the code looks declarative, it is actually run imperatively, statement by statement.
  3. Instantiation of classes does not require a “new” keyword
  4. There is no need to assign the newly instantiated class to a variable
  5. There is no messy getContentPane().add(myJLabel)

Syntax Nit-picking

It appears to me that spaces are optional in JavaFX. For instance:

content:Label{text:”Hello”width:50}

is valid syntax. There is usually some measure of benefit in enforcing readability in a language. Ignoring spaces also lead to some potential disambiguation issues. For instance, FORTRAN “for” loops are difficult to parse. do 10 i = 1, 5 could potentially mean assignment do10i=1.5 if the comma was mistyped, and replaced with a period.

I found the syntax makes it difficult to decide where to place the closing braces. For example, should we prefer the following - where the closing brace lines up with the content attribute:

  content: Label {
    text: “Hello World!”
  }

or should we prefer this - where the closing brace lines up with the constructor?

  content:
    Label {
      text: “Hello World!”
      color: Color.web(”#336699″)
    }

This leaves a hanging indent, similar to Python. There’s nothing wrong with hanging indents, but a language should make it easy for teams to just stick with one system.

I suspect the latter style is more useful, since it makes it easier to move elements around).  You will need to customize your editor to indent code upon carriage return following an attribute.

Java Problem #1: Too many statements are required to initialize a user interface

JavaFX solution: Declarative User Interfaces using Object Initializers

A common problem encountered developing user interfaces in Java, is the number of statements it takes to accomplish particular tasks. For instance, to add a JLabel in swing would require three statements:

JLabel myJLabel = new JLabel();
myJLabel.setText(”Hello”);
frame.getContentPane().add(myJLabel)

C# exponents would probably note the how JavaFX also uses Object Initializer syntax to reduce the amount of code written. The following is the C# equivalent (from msdn)

StudentName student = new StudentName { FirstName = “Craig”, LastName = “Playstead”, ID = 116 };

So the Java example above could be rewritten in JavaFX as a single expression:

  content: Label {
    text: “Hello World!”
  }

Java Problem #2: Binding user interface to data is not baked into the Java, but requires libraries to implement cooperating classes

User interface components like JTable require a cooperative class to implement a specific Model interface, in order for the user-interface to be able to consume the data. This makes the user-interface king, as it dictates how data is represented internally, otherwise, additional work would be required to write adapters so that data could be adapted to a particular model.

JavaFX solves this by automatically wiring up update handlers using the bind keyword. In the example below, a Text node is bound to myString. When the value of myString is changed by the background thread called timeline, the Text node’s content will be updated automatically.

// bind.fx
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.text.Text;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.lang.Duration;

var myString = “Hello World!”;
Frame {
    width: 150
    height: 50
    visible: true
    stage: Stage {
        content: [
            Text {
                content: bind myString
                x: 0
                y: 10
            }
        ]
    }
}
var timeline = Timeline {
    keyFrames: [
        KeyFrame {
            time: Duration { millis: 1000 }
            action: function() {
                myString = "Goodbye World";
            }
        },
        KeyFrame {
            time: Duration { millis: 2000 }
            action: function() {
               
myString = "Hello World";
            }
        },
    ]
    repeatCount: 3
}
timeline.start();Decompiling bind.class with jad java decompiler yields the following nuggets:

1. The timeline keyframe has a Function instance

new Function0() {
  public void lambda()
  {
     bind.myString.set(”Goodbye World”);
  }
}

2. myString is a static variable in the bind class and it is not strongly typed at all.

public class bind implements Intf, FXObject {
  public static final ObjectVariable myString;
}

The question arises then, how do we integrate ordinary POJOs into JavaFX to make them observable? Perhaps the easiest way is to marshall data as JSON, and then recreate the instances using JavaFX classes. The JavaFX classes could be created automatically via annotations on the original POJO class definitions.

Binding to expressions

JavaFX permits binding to expressions. For instance, we can replace the example above with the following:

// bind.fx
import javafx.application.Frame;
import javafx.application.Stage;
import javafx.scene.text.Text;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.lang.Duration;

var myString = “Hello World!”;
Frame {
    width: 150
    height: 50
    visible: true
    stage: Stage {
        content: [
            Text {
                content: bind "JavaFX says: ".concat(myString)
                x: 0
                y: 10
            }
        ]
    }
}
var timeline = Timeline {
    keyFrames: [
        KeyFrame {
            time: Duration { millis: 1000 }
            action: function() {
                myString = "Goodbye World";
            }
        },
        KeyFrame {
            time: Duration { millis: 2000 }
            action: function() {
               
myString = "Hello World";
            }
        },
    ]
    repeatCount: 3
}
timeline.start();

Running the compiled class file through the Jad decompiler yields this interesting method called getStaticDependents()

protected Location[] getStaticDependents()
{
    return (new Location[] {
        arg$0, bfx$0selector
        // arg$0 is myString, bfx$0selector is “JavaFX says: “

    });
}

public String computeValue()
{
    return bfx$0selector.get() == null ? null : ((String)bfx$0selector.get()).concat((String)arg$0.get());
}

Presumably, the purpose of getStaticDependents is to construct a giant dependency graph so that when one item updates, the dependent values will be recomputed.

 

Java Problem #3. Updating the underlying model from User Interface is not baked into the language

Writing code to update model is repetitive and adds little joy to a developers daily work. In Java, much of the drudgery can be taken out by using Binding frameworks. This usually involves calls to a binding library that converts user-interface values into model values. For instance, “1.25″ has to be parsed to 1.25 and followed by updating the underlying property on the model. There are several competing Binding frameworks, Swing Data Binding aka JGoodies Binding, Beans Binding, JBind, Castor. Some would say that too much effort is being devoted to something so fundamental.

JavaFX’s approach is to get rid of external libraries, and put it in the language instead via the keyword “bind … with inverse”.

// twoway.fx
// demonstrates two way binding
import javafx.ext.swing.SwingFrame;
import javafx.ext.swing.TextField;
class Person
{
    attribute name: String
        on replace oldVal = newVal { java.lang.System.out.println(oldVal.concat(” updated to “).concat(newVal)); }
}
var person = Person { name: “Chui Tey” }
SwingFrame {
    width: 400
    title: “Two way binding”
    visible: true
    content: TextField {
        editable: true
        width: 250
        text: bind person.name with inverse
    }
}

There are two new constructs introduced here.

Firstly, the declaration “with inverse” allows the TextField to update the underlying model. (omitting “with inverse” results in an illogical AssignToBoundException).

Secondly, we have created a trigger, which is an analog of setter() methods in Java. The syntax is a mix of SQL triggers and ruby blocks. It’s not particularly pretty, and I have a dislike of introducing new syntax when a good old lambda would have sufficed. e.g.

class Person
{
    attribute name: String
        function onReplace(oldVal, newVal) { java.lang.System.out.println(oldVal.concat(” updated to “).concat(newVal)); }
}

However, the new syntax allowed slice assignments to be expressed. I have not delved into this, but would have thought it is better to extend the function() syntax to take the slice assignments rather than having a new construct altogether. As an old BASIC programmer, the idea of OPEN FILE FOR READ is anathema to building good libraries, and makes code difficult to introspect.

Unaddressed Issues

While JavaFX is an improvement on Java for building RIA applications, I feel it has not completely addressed the issues of making it easy for designers to create interactive components. For instance, there is no clear path for a programmer to prototype using Swing components, and then a designer replaces the swing buttons, textboxes and listboxes with a totally custom UI, while retaining the original behaviors.

There is also no clear guidance for using custom renderers for plain-old-objects. For example, WPF has a concept of DataObjects, where plain-old-objects are embedded within a UI container, and specialized renderers are registered to render these objects when they are encountered. 

JavaFX is an improvement, but Java could adopt some of the changes too

As a language that is intended to solve some of Java’s deficiency in the construction of user interfaces, binding of data, and change notification, JavaFX has addressed these issues reasonably. However, there is no reason why Java couldn’t adopt Object Initializers as a way to simplify coding.

Another QANTAS incident

August 7th, 2008

A QANTAS jet was grounded in Melbourne, bringing up the number of newsworthy flight incidents to 4 in 11 days for the beleagured airline, The Australian reports.

The 737, registered as VH-TJU, is the same aircraft on which Qantas engineers found 95 defects that had been missed during contract maintenance work by Malaysian Airlines in Kuala Lumpur.

Are safety standards being lowered? The QANTAS chief pilot, Captain Manning, had this to say:

Australia’s high aviation safety standards are not being lowered to minimum world standards. But standards were being “harmonised” with the rest of the world

In other words, we are doomed.

Update 15-Aug-2008: Another small panel falls off a QANTAS plane.

Sales Patter

August 7th, 2008

This is an amazing sales patter about a somewhat illegal plant. (Note: I’ve no interest in these substances, but I was searching for something else and ended up at a myspace page that embedded this audio). The MySpace page had affiliate links to a vendor that sells these.

Terence begins by telling the audience the attributes of this legal plant, how it means you can store it, transport it, plant it, and consume it without fear of getting in trouble with the law. There’s an appealing emotional hook, I can imagine, for people who have been had a brush with the police for their drug habits. Then proceeds to describe how vividly one would use it. It’s the equivalent of a salesman putting the product in your hands - “There sir, feel how heavily built this pen is sir, the finest platinum, not like the cheap plastic material”. The overall pace was excellent.

If you are preparing a toastmasters speech, I’d recommend listening to it for instruction.

NAT Traversal Techniques

July 29th, 2008

The ability of applications like Ultravnc and Hamachi to operate behind firewalls through NAT traversal intrigued me. Newport Networks has a whitepaper detailing current NAT traversal solutions for SIP:

  • Universal Plug and Play (UPnP)
  • Problem: … relies on the NAT opening pinholes to the outside world under the dynamic control of the UPnP client - maybe a SoftPhone on a PC. This capability is most likely contrary to most security policies and therefore may not be accepted by communications managers of corporate customers.

  • Simple Traversal of UDP Through Network Address Translation devices (STUN)
  • Problem: Most NATs in use today are symmetric. This means that they create a mapping based on source IP address and port number as well as the destination IP address and port number. STUN will not work with symmetric NATs

  • TURN - Traversal Using Relay NAT
  • Refinement over STUN by using a proxy to relay packets

  • Application Layer Gateway
  • Enhanced NAT that can modify packets depending on whether protocol is SIP, or some other. However, it doesn’t really explain how a SIP phone behind a firewall can receive inbound calls. (UDP sessions are easier than TCP sessions?)

  • Manual Configuration
  • Tunnel Techniques
  • Automatic Channel Mapping

On the practical side of things, Heise Security has a light write-up on how Skype tries different methods, from direct UDP through to probing firewalls in order to tunnel a direct connection between two computers.

On Declarative Languages

July 28th, 2008

Domain specific languages (DSLs) are usually implemented as declarative languages, where the only data is expressed, and invariant rules are coded into the language interpreter itself.

Dave Herman has thought through some of the practicalities of using declarative languages, particular when a complex system has to be broken up into modules. This leads to problems like overriding, specificity of rules, recursion.

Other problems with DSLs include

1) difficulty in debugging. It is hard to debug data, add breakpoints

2) difficulty in showing derivation of results.

3) error handling is hard

System failure at the Malaysian Stock Exchange

July 10th, 2008

The Malaysian stock exchange (Bursa Malaysia) had to suspend trading on 3 July for an entire day due to system failure.

Sounds like all the planets were in alignment, two hard disk failures, one cpu failed, and connectivity issues. The secondary system couldn’t even start up in time. Uh uh, this would be costly.

Transcript:

I just want to go through the sequence of events of the trading system of the [Malaysian] stockmarket. There was one hard disk which was faulty. This was replaced as per standard procedure. About half and hour later, we found that the new disk was not able to recover data.

We have a system we have two disks running in parallel. This then triggered the failure of the second disk as well as one of the CPU. Half an hour later, we managed to restart the system and went about trying to reconnect with the brokers. We found that the brokers were unable to connect to our system. This normally takes about half an hour. By 8 am, more than half of the brokers were unable to connect to our system. We have a policy within Bursa Malaysia, where if more than one third of brokers were unable to connect to our system or to trade, we would suspend the market. This decision we took at 8:30am, and that point in time we took the decision to activate our backup site. This normally would take 3 hours. By 1 pm we noticed that the start up process at the back up site was taking longer than expected.

At that time, together with our vendors, we had resolved the problem at the primary site.

We tried to resume the afternoon session from the primary site, and this was targetted at 3 pm, and we were aiming for the market to resume at 3:15pm.

At 3:15 pm we noticed there were some preopening orders which were being keyed in. But we noticed there many brokers site which were unable to connect to our site. There were connectivity issues being encountered.

By 3:30pm, we were still unable to resolve the connectivity issues and we decided to suspend the market for the rest of the day.

However, because some pre-opening orders were keyed in at 3:15. We noticed there were some orders which have been matched. We subsequently cancelled these matched orders. …

Tom Rafferty on Web 2.0 Toolset

July 2nd, 2008

Ran into this interesting post by by Tom Rafferty with a run down of popular Web 2.0 tools a company can use to communicate with their audience.

The biggest takeaway from the talk is that Web 2.0 is democratizing the web, in a way beyond what 1.0 had to offer. One man one vote means that corporations are no longer in complete control of their message. They may have the money to spend on advertising, but this is always in competition with people who have the time to air their grievances and adulation publicly. Just as companies used to have media relations officer, and subscribe to media monitoring services, living in Web 2.0 means that companies need web monitoring services and a strategy to respond faster to key conversations that are happening about your company on the web.

First Encounter with Genshi

June 4th, 2008

I was playing around with code generation of some scaffolding-style code for CodeIgniter. Initially, python’s string interpolation operator % sufficed. As time progressed, it became clearer that resorting to a templating library buys me cleaner code.

Problem #1
The $ used by Genshi for string interpolation conflicts with PHP’s $variables.

Solution #1
After 10 minutes of source diving (by the way, Genshi source is a work of art - wish I could write like that).

import genshi.template.interpolation
genshi.template.interpolation.PREFIX = '^'

from genshi.template import TextTemplate
template = TextTemplate("$this->^{foo} = 'home';")
stream = template.generate(foo="customer")
print stream

Problem #2
The generated output quotes the > into >

Solution #2
The Stream render() method takes a parameter specifying the kind of escaping.

print stream.render('text')

Overall Solution

from genshi.template import TextTemplate
import genshi.template.interpolation
genshi.template.interpolation.PREFIX = '^'
for tablename, table in specs.items():
    fd = open('controllers/%s.php' % tablename, 'w')
    template = TextTemplate(open('controllers.php', 'r'), filename='controller.php')
    print template.generate(tablename=tablename, columns=table).render('text')

Python subclassing file types

June 3rd, 2008

I was hoping to write a simple tee class by subclassing file, but there must be further type magic getting in the way when print >> is used.

import sys

class tee(file):
   def write(self, text):
     sys.stdout.write(text)
     file.write(self, text)

fd = tee("output.txt", "w")
print >> fd, "Test 1"
fd.write("Test 2\n")
$ python test.py
Test 2

$ cat output.txt
Test 1
Test 2

Using the dis module, we can tell that print >> is compiled into PRINT_ITEM_TO.

>>> def t(): print >> fd, "foo"
...
>>> import dis; dis.dis(t)
  1           0 LOAD_GLOBAL              0 (fd)
              3 DUP_TOP
              4 LOAD_CONST               1 ('foo')
              7 ROT_TWO
              8 PRINT_ITEM_TO
              9 PRINT_NEWLINE_TO
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

and looking through ceval.c, searching for PRINT_ITEM_TO yields

 case PRINT_ITEM_TO:
    w = stream = POP();
    /* fall through to PRINT_ITEM */

case PRINT_ITEM:
    v = POP();
    if (stream == NULL || stream == Py_None) {
        w = PySys_GetObject("stdout");
        if (w == NULL) {
            PyErr_SetString(PyExc_RuntimeError,
                    "lost sys.stdout");
            err = -1;
        }
    }
    /* PyFile_SoftSpace() can exececute arbitrary code
       if sys.stdout is an instance with a __getattr__.
       If __getattr__ raises an exception, w will
       be freed, so we need to prevent that temporarily. */
    Py_XINCREF(w);
    if (w != NULL && PyFile_SoftSpace(w, 0))
        err = PyFile_WriteString(" ", w);
    if (err == 0)
        err = PyFile_WriteObject(v, w, Py_PRINT_RAW);


Any ideas why?

The Death of Indiana Jones

May 24th, 2008

The writers killed the Kingdom of the Crystal Skull by

1) Trying too hard to set the sidekick up for a future spin-off

2) Telling the audience that knowledge is gold, but then kills the villianess by filling her with knowledge

3) Turning an action show into a cheesy father-son reunion. Indiana had too much to prove to his son that he was a worthy father, and ended up being too sure-footed. The past shows had a cocky Indiana but he was often wrong. The most recent rendition of Indy had turned him into a super-human.

4) Not making the flying saucer play “re-mi-do-SO-so”

5) Action sequences not up to par with the previous ones. There were no huge rolling balls, nor roller coaster chases. Again, unnecessarily too much screen time was given to Shaun Bellouf. This show is more of a warm-up for Henry Jones III than a curtain call for Henry Jones II.

Comparing Owner Drawn in Winforms vs Swing

May 12th, 2008

I was having a play with custom renderers in Java Swing, and comparing them with the effort required in .NET. I find that in this case, the Swing approaches the problem at a higher level of abstraction (less effort), at the expense of a lot of new objects being created, while .NET goes for a straightforward custom paint.

Here’s an example in Swing, custom rendering JListbox control. Notice that we return a JLabel control here. This is what Swing does by default. We can also choose to return any controls, like combobox, et. c. There’s no additional painting required. In this sense, JListbox resembles a repeater control we see in WPF. The downside is a JLabel control is returned for every visible item in the listbox. Custom drawing can be done by creating an Anonymous inner class with an overridden onPaint handler.

                    jList1.setCellRenderer(new ListCellRenderer() {

                        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                                // By default, listbox renders using a label
                                JLabel display = new JLabel(value.toString());
                                display.setOpaque(true);
                                display.setBackground(isSelected ? Color.GRAY : Color.WHITE);
                                return display;
                        }
                    });

Contrast this with the J# implementation of custom painting in .NET (sourcecode nicked from MSDN), lots of low level painting, but no new objects being created or garbage collected. However, it’s not clear if you can reuse the paint() routine from an existing control.

private void listBox1_DrawItem(Object sender,
    System.Windows.Forms.DrawItemEventArgs e)
{
    // Set the DrawMode property to draw fixed sized items.
    listBox1.set_DrawMode(DrawMode.OwnerDrawFixed);
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    Brush myBrush = Brushes.get_Black();
    // Determine the color of the brush to draw each item based on the
    // index of the item to draw.
    switch (e.get_Index()) {
        case 0 :
            myBrush = Brushes.get_Red();
            break;
        case 1 :
            myBrush = Brushes.get_Orange();
            break;
        case 2 :
            myBrush = Brushes.get_Purple();
            break;
    }

    // Draw the current item text based on the current Font and the custom
    // brush settings.
    e.get_Graphics().DrawString(System.Convert.ToString(listBox1.
        get_Items().get_Item(e.get_Index())), e.get_Font(), myBrush,
        RectangleF.op_Implicit(e.get_Bounds()), StringFormat.
        get_GenericDefault());
    // If the ListBox has focus, draw a focus rectangle around the selected
    // item.
    e.DrawFocusRectangle();
} //listBox1_DrawItem

Australian Alphabet Names

May 5th, 2008

Having trouble reciting alphabet names over the phone? Here’s a truly Australian wordlist you can use.

Aratula
Brisbane
Chinchilla
Dalby
Eromanga
F - ?
Goondowindi
H - ?
Illawarra
Jindabyne
Kallangur
L - ?
Melbourne
Nebo
O - ?
Perth
Queensland
Roma
Sydney
Tasmania
Uluru
Victoria
Wogga Wogga
X -?
Yamba
Z - ?