StopWatch MIDlet

To get a better handle on MIDP programming, I’m writing a quick and dirty stopwatch for my phone (the Nokia 3650, which didn’t come with a stopwatch, unlike the T68i I had before).

Basically, I’ve got a MIDlet class (container for the app), a Canvas class (displays the stopwatch) and a Thread class (updates the canvas every second). I’ve run into a couple interesting tidbits while trying to use the repaint() method of the Canvas class. At first I was having the Thread class update a public String object in the Canvas and then calling repaint() on the canvas, which according to this article on java.sun.com, should then clear the previous canvas and display the new canvas. Curiously, this resulted in each canvas repainting the display with the previous canvas showing through, which I’m guessing is what the above article was saying might happen when it said:

“… If you mark two or more areas for repainting within a short span of time, the system may combine the paint requests into a single request to paint the union of the two areas (the smallest rectangle containing both).”

For example, in my thread class, I’d update a property of the canvas:

canvas.setText(“this is the new time”);

and then call the repaint method:

canvas.repaint();

This resulted in “this is the new time” being written over whatever previously existed in the canvas. Do I have the wrong idea about how to update text in a canvas? Shouldn’t I just be able to update the text and call repaint()?

Anyways, I’ve ended up updating a public Image object in the Canvas from the Thread and then calling repaint(), which seems to work. Love to hear any suggestions about a better way!

Links:

Creating Low-Level GUI Components [onjava.com]

MIDP Canvas Repainting [java.sun.com]

Nokia Java Graphics Forum [discussion.forum.nokia.com]

Emergence: From Chaos to Order

I finished Emergence: From Chaos to Order a couple weeks ago, snippets that I want to remember include:

On model building: “For most of us model building starts at an early age. As children we use building blocks to generate concrete realizations of our imagination — castles and space stations. This facility for recombining standard objects to make new items carries over into late occupations. A watchmaker uses familiar mechanisms — gear wheels, spring, pinions and so on — to generate marvels of timekeeping, and a scientist does the same thing at a more abstract level, generating complex objects, such as molecules, from simpler objects, atoms. By selecting the building blocks and the ways of recombining them, we set up the rules that make rule-governed systems comprehensible. A well conceived model will exhibit the complexity and emergent phenonmena, of the system being modeled, but with much of the detail sheared away.” [pg 12]

In relation to the checker playing model, the emergent consequences of weight changing: “Subgoals: Though it seems that the evaluation function makes no provisions for subgoals, in fact it does, providing subtle direction when there is no clear path to a win or an obvious advantage. Anticipating the opponent: The checkersplayer must impute a strategy to the opponent if it is to anticipate the opponent’s actions; the valuation function can serve as a guide to the opponent’s likely response. Toward minimax: The valuation function only indirectly minimizes the maximum damage the opponent can inflict (minimax), yet it captures important elements of this idea. Bootstrapping: The checkersplayer can improve its performance by playing against itself. Lookahead: Knowing the rules of the game, the checkersplayer can look ahead several moves using its model of the other player, changing weights on the basis of the anticipated outcomes.” [pg 68-69]

On anticipating the opponent: “An undesirable outcome can only occur because a) the checkersplayer has made a bad play, or b) the opponent has made a good play. In either case, the checkersplayer is well advised to assign a low (possibly negative) value to configurations that lie in that direction. On the other hand, a desirable outcome presents an ambiguous situation. The desirable outcome may occur because of good play on the part of the checkersplayer, but it can also occur because of poor play on the part of the opponent. If the outcome is the result of an opponent’s poor play, then it is unwise to make any adjustments. That line of play is unlikely to recur, either because the opponent has learned or because a different player plays a better game.” [pg 70-71]

On neural nets and transmitter molecules: “Transmitter molecules diffuse across the synaptic gap to the surface of the receiving neuron; if enough transmitter molecules from enough synapses accumulate at the surface of a neuron, that neuron fires. In doing so, if effectively removes the molecules from the synaptic gap. If this happens repeatedly, the synapse increases its ability to produce the transmitter molecule…. The synapse has increased its effectiveness (weight)…” [pg 95]

On the mechanisms of a neural net: “Variable threshold. A neuron’s threshold decreases as the time since it last fired increases. This decreasing threshold makes the neuron increasingly sensitive to incoming pulses when it remains quiescent over an extended period. The variable threshold allows the neuron to act as a frequency modulator, firing at a rate that reflects the average synapse-weighted strength of the impulses firing on its surface. Fatigue. A neuron that fires at a high rate over an extended period has its threshold steadily incremented — in effect the whole variable threshold curve is translated upward. Contrariwise, a neuron that fires at a low rate over an extended period of time has its threshold steadily decremented. Fatigue eventually forces a neuron’s firing rate back to a ‘normal’ or ‘set-point’ level: no neuron can continue to fire at a rate above or below this set-point. Hebb’s rule. If neuron x fires at time t and neuron y fires at time t+1, then any synapses that x’s axon make at y are strengthened. Contrariwise, if x fires at time t and y does not fire at time t+1, the same synapses are weakened.” [pg 108]

On emergence: “… The behavior of an ant colony is not the simple sum of the behaviors of a group of average ants. The coupled interactions of the ants provide a coherence to the nest that far exceeds anything predictable in terms of simple summations. Emergence is above all a product of coupled, context-dependent interactions. Technically these interactions, and the resulting system, are nonlinear. The behavior of the overall system cannot be obtained by summing the behavior of its constituent parts. We can no more truly understand strategies in a board game by compiling statistics of the movements of its pieces than we can understand the behavior of any ant colony in terms of averages.” [pg 121-122]

On cultivating innovation: “Practice. A part of the answer to all who strive within a discipline, be it tennis, piano playing, writing poetry, or building a scientific model. The answer lies within the word itself: discipline. Only when you are so familiar with the elements (building blocks) of your discipline that you no longer have to think about how they are combined, do you enter the creative phase. If you are a tennis player and you have to concentrate on the elements of each stroke, you will have little appreciation of the flow of the game — your opponent’s strengths, weaknesses and strategy. If you play the piano and have to concentrate on fingering, you will not hear the flow of the music, the ‘long line’. Local concerns drive out global perceptions, and so it is with other disciplines.” [pg 211-212]

More on innovation: “Once a set of building blocks has been chosen, innovation depends on selection from among the plethora of potential combinations. The possibilities are so numerous that the same building blocks can be used over and over again without seriously impairing the chances for original discoveries. Think of the standard building blocks provided by words in a language, or folk themes in music. The key to handling this complexity is the discovery of salient patterns in the tree of combinations. Creative individuals exhibit talent for such selection, but the mechanisms they employ are largely unknown.” [pg 217-218]

Java Collection Types & ColdFusion

At work one of our developers is programming an ecommerce store against a Java API written by a third party. Said Java API returns a TreeMap object from a method and when you try to access that TreeMap object in any fashion, you’ll get an error, specifically:

“Error casting an object of type java.lang.Integer to an incompatible type. This usually indicates a programming error in Java, although it could also mean you have tried to use a foreign object in a different way than it was designed.”

What we’ve concluded is that ColdFusion attempts to cast any and all Java classes that implement the Map interface to:

coldfusion.runtime.Struct

which is of type java.util.Hashtable. Unfortunately, a TreeMap uses an Object (in this case an Integer) as the key. ColdFusion structures can only use strings as the key. The takeaway is that this is a ‘feature’ of ColdFusion, it’s nice that it attempts to transform collection type objects into the native ColdFusion structure type. In this specific case, it’s more of a hindrance. The workaround is to create your own Java wrapper that takes the TreeMap, loops over all the keys, inserting each into a Vector and then return the Vector to ColdFusion, which turns that into a structure.

In case you don’t feel comfortable going to sleep at night without seeing the code, here’s an example Java class that returns a simple TreeMap:

import java.util.*;
public class TreeMapTest {
   public static TreeMap getTree() {
      TreeMap t = new TreeMap();
      t.put(new Integer(131000), “product”);
      return t;
   }
}

Compile that and then drop it into your [cfusionmx]\wwwroot\WEB-INF\lib\ directory. You can use this script to test it:

<cfscript>
   tmt = createObject(“java”, “TreeMapTest”);
   WriteOutput(“tmt is of type ” & tmt.getClass());
   treeMap = tmt.getTree();
   WriteOutput(“treeMap is of type ” & treeMap.toString()); // you get an error here
</cfscript>

I’d be very very interested in hearing about any ways that you know of to get around something like this without having to write a wrapper class. And for you Macromedia ColdFusion guys, it might be a nice (albeit probably rarely used) feature to be able to maintain the Java type of an object by using some function, ( ie: maintainType() or some such).

By the way, if you’re interested in knowing more about using Java and ColdFusion together, Terry Ford has written a great article here entitled “Using Java and J2EE Elements in ColdFusion MX Applications”.

ColdFusion Whois client using Jakarta Commons/Net lib

Doug posted a query on the cfguru list asking how he might retrieve whois information using ColdFusion. I mentioned that there are numerous tags (search on google if you want to see them), but that it’s pretty easy to do within ColdFusion if you drop the Jakarta Commons/Net jar into your ColdFusion lib directory (cfusionmx/wwwroot/WEB-INF/lib/):

<cfscript>
  whois = createObject(“java”, “org.apache.commons.net.WhoisClient”);
  whois.init();
  whois.connect(“192.149.252.43”); // whois.arin.net
  WriteOutput(whois.query(“204.212.42.4”)); // your random ip address here
  whois.disconnect();
</cfscript>

Note that the whois service works over port 43, so your server must have outbound access to port 43 (if you’re accessing a server outside your own network, performance would presumably be much better if you ran your own whois server internally).

.NET code generation

Short article on .NET code generators: .NET code generators enable rapid application development. Only one tool is covered, “DeKlarit”, which you can view a nifty Flash demo on here.

I used the wsdl tool yesterday to generate a C# web service client stub, how handy is that tool? The command line switches allow you to customize the namespace, the generated file name, the name of the key to retrieve from the config file for the webservice endpoint, and the language (C#, VB.NET)… etc…

> wsdl /urlkey:name_of_my_key /n:com.mypackage /o:FileName.cs /l:CS http://hostname/path/mywebservice.asmx

You can then start using the generated class in your code immediately. Very cool.

Lucene Index Browser

From the lucene-user list today: Lucene Index Browser: Luke is a handy development and diagnostic tool, which accesses already existing Lucene indexes and allows you to display their contents in several ways:
· browse by document number, or by term
· view documents / copy to clipboard
· retrieve a ranked list of most frequent terms
· execute a search, and browse the results
· selectively delete documents from the index
and more…