Category: Programming

  • ODT to RTF converter

    Recently I discovered that OpenOffice can’t really generate RTF files, so I wrote my own converter. It’s rather basic, just handles italic, double space, paragaraphs, and centering. However, for what I need it for it works a lot better than the built-in OpenOffice export ability.

    The program is written in Java and you can get the jar file here: ODT2RTF.jar

    It’s completely self contained, and includes the source files. Go and have fun with it!

    If there is interest, I will expand its capabilities.

  • Learning Haskell

    If you do any programming, you may have heard of a strange language called Haskell. It’s gaining rapidly in popularity, and has many cool features.

    1. Implicit Strong Typing – It provides the compile time error checking that one gets with C++ or Java generics, but it deduces types on its own without explicit programmer input (of course, the programmer can over-ride this if needed).
    2. Functional – This is a limitation that results in a strength. Functional programming means once you assign a variable you can never change it. This restriction on the programmer frees the compiler to perform many optimizations.
    3. Shared Transactional Memory – Sometimes it is too inconvenient to program without mutable state, so Haskell provides you with an escape hatch from functional programming. With Shared Transactional Memory you can write sections of code that modify memory arbitrarily without fear of deadlocks or race conditions.

    Check out the tutorial: Learn Haskell now!.

  • Memory Conserving Regex Engine for Java

    Many regular expression engines, my own package pat included, suffer from a tendency to produce stack overflows in some circumstances. This seems to be a widespread problem, common to many java regular expression engines. To overcome this limitation I recently wrote a new regular expression library, completely from scratch, designed to avoid this problem. It conforms (mostly) to the java.util.regex interface, so changing your code to use my package is as simple as changing your import statement.

    Please try it out and let me know what you think. See the main site: http://stevenrbrandt.com.

  • Custom Dictionaries, Aspell, and LaTeX

    It took me a bit of hunting and twiddling to figure out exactly how to use aspell with a custom dictionary that supplements (not replaces) the master dictionary, so I thought I’d document it for posterity.


    aspell --lang en create master ./custom_dict.aspell < ./custom_word_list.txt aspell --add-extra-dicts=./custom_dict.aspell -t -c my_document.tex

    And that's it for the checking part. The only latex specific piece is the "-t" option which tells aspell to filter out latex nonsense. If you remove it, then you can use this recipe with a more generic text document.

    To create my initial word list I did this:


    aspell -t list -a < my_document.tex | sort -u > ./custom_word_list.txt

    This command just creates a list of unrecognized words from the document, and ensures that the are sorted and unique. After I created it I went through and carefully edited the word result. Enjoy.

  • Infinite Sunshine Computing

    I have been thinking about the struggle to build large computing systems. The major challenges of the current age of computing are power, cooling and scalability. The machine room and energy costs are dwarfing everything else. This concern has even spawned the creation of a new ranking of supercomputers, the Green 500, which ranks machines by compute power per watt rather than simple compute power.

    Imagine a single computing node that is self-contained and sealed. Each has its own storage and set of processing cores, a solar panel of some sort for power (many advances have been made in solar power recently), some kind of power storage (maybe even capacitors). For cooling, it could use the solid state heat pumps from Cool Chips and/or circulating fluids. Each of these nodes could be connected to its four nearest neighbors by some network — a 2D mesh is not the best network one can design, but it is infinitely growable. Alternatively, one could make a hexagonal mesh.

    Imagine this computer, allowed to grow in some wide flat country, stretching for miles in one all powerful matrix :). It would, in theory, be infiinitely scalable and require no machine room at all. You would probably mount it on some kind of rack a few feet above the ground so that people (or robots) could travel beneath it and fix or replace nodes. The system administrators would be like farmers, harvesting the compute cycles to feed the hungry scientists of the world.

  • Functional Programming

    Many people bemoan the difficulties of programming in the multi-core era. What many programmers do not realize is that a way out of deadlock/race condition hell is known — it’s name is “Functional Programming.” This term should not be contrasted to “Object-Oriented Programming,” rather it should be contrasted to “Imperative Programming.” The idea in functional programming is that variables cannot change value, they are set when defined and can never receive an update. Languages like C, Java, and Python are “Imperative” because the contents of variables can be modified.

    A method written in a functional program is said to be “Referentially Transparent” — in other words, if you call the method twice with the same arguments it will produce the same value. In fact, the second call can simply be optimized away by re-using the first value. Thus:

    x = sin(3.0)
    y = sin(3.0)

    Is the same as

    x = sin(3.0)
    y = x

    if the function “sin” is referentially transparent (and it is). If I have a functional program, then, I can take any two method calls that do not depend on each other and run them in the same thread

    x = call1(3,4,"x")
    y = call2(5,9,8)
    z = x + y

    It would be perfectly safe, in a functional world, for call1 and call2 to execute simultaneously as they could not possibly affect each other. The computation of z could block until both calls finished, and no deadlock or race condition could occur.

    But, as you have probably guessed, there are some difficulties programming in a functional language. We’ve come to count on loops, incrementing values, etc. How can we get things done if we don’t have them?

    The answer is that there’s a simple way to transform any imperative code to functional code — just introduce more functions and more recursion.

    func() {
    x = 3
    x = x + 4
    return x
    }

    could be re-written as

    func_1(x) {
    return x + 4
    }
    func() {
    x = 3
    return func_1(x)
    }

    Of course, these two methods cannot be called in parallel since one depends on the other. In some sense, however, that’s not the point. The point is that if we program in this fashion we can easily identify regions of code that can execute safely in parallel (i.e. without deadlock or race).

    One fly in the ointment is that methods which do IO (i.e. print to the screen, read or write a file, etc.) cannot safely be done in parallel with each other. If two threads are modifying the state of a single file then we have brought back race conditions. The simplest answer is to put all IO operations on a single thread. This is somewhat limiting, as many scientific applications rely on the speed they can get doing parallel reads or writes of large quantities of data.

    An alternative would be to segment IO operations into a parallel read phase and a parallel write phase on sets of distinct files. This would address the needs of certain scientific applications, but it might not be so great for applications like web servers which want to continuously read and write to many clients. A web server, however, might be able to launch numerous methods that read from a socket and write a response back. They could be viewed as autonomous small programs and could be run safely in parallel so long as they did not try to communicate data back to their parent thread.

    Between these few simple rules then, it should be possible to construct a functional language that would allow the “average programmer” to take great advantage of multi-core computers — without the pain of debugging race conditions and deadlocks. Many languages do exist that are functional, but what is lacking (as far as I can see) is a simple language with syntax similar to python or java to bring this discovery of computer science to the masses.

  • How to build a Universal Translator

    It occurred to me that something like the “Universal Translator” of Star Trek could be constructed without very advanced technology. I call my more primitive device a “Drongo.”

    If you have two technologically advanced races, and they meet, there is a need to construct a basic vocabulary quickly. One can sit in a room, point and say words — but this can get quite tedious and is not readily amenable to computer analysis.

    The device I am proposing makes the following assumptions about the aliens we contact:

    1. They are able to use some reasonable part of the electromagnetic spectrum for communications (i.e. radio, infra-red),
    2. They see things in images,
    3. They know what primary numbers are,
    4. They know what binary numbers are,
    5. They have the basic concept of nouns and verbs.

    An obvious code for an image would be to write it as an array of binary digits, using a primary number for the number of pixels on the x and y axes (similar to what Sagan proposed in “Contact”). Aliens receiving the signal would recognize they were seeing a product of binary numbers and might deduce an image was intended. To aid in this endeavor, the drongo should have one or more displays that show the image in various electromagnetic frequencies.

    Images and words could be sent on alternating frames, and by studying the sequence of words and images a number of names, nouns and verbs could be communicated (even basic mathematics concepts such as counting and arithmetic). This might form the basis of a very primitive communication, and if both parties have a drongo they might be able to get up to speed on a basic written language in short order. The device would send the foundational vocabulary out repeatedly in an infinite loop. If the foundational vocabulary is understood, the device could be queried to request a next lesson (This would reduce the amount of information that would need to be in the first loop/lesson).

    I could envision two alien races constructing an intermediate language (albeit a primitive one) after only a few hours of drongo communication.

    Key to the success of a drongo is the development of various recognition technologies, such as this. It will make it possible for us to classify images received from an alien’s drongo.

    There might be other kinds of reasonable assumptions that would enable deeper communication to progress, this is only the kernel of the idea.

    Obviously this device is vastly inferior to the device on Star Trek. It is very much dumbed down, but could be quite effective. I named the device “Drongo”, after a type of bird known for its effective mimicry of human speech. “Drongo” is also an Australian slang word for “idiot.”

  • Regular XML Expressions

    I have been toying with the idea of a specialized regular expression syntax for XML. Often, the regular expression questions that people email to me indicate that they are using them on XML and HTML. There is a very nice discussion of part of the problem here on Joe Gregorio’s blog. On that blog, he considers solving the problem by trying to limit XML, but I think the problem may be that the Regex needs to be adapted.

    Ideally, I’d like to write a pattern as simple as <a>(.*)</a> and match it against an XML document, retrieving the text inside an “a” tag.

    How should this work?

    1. CDATA sections: If we have a Regex parser that works on a stream, the stream reader can disentangle this bit for us
    2. Comments: We don’t want to match on a tag if it is in a comment. The pattern <a>.*</a> should know how to identify and ignore comments. Of course, we might want to match something inside a comment. If that’s the case, then our pattern should explicitly say so. It should look like this: <!--.*<a>.*</a>.-->.
    3. Matching nested blocks: <root><a>bar</a><a><b><a>foo<h;/a></b></a></root>. Obviously neither <a>.*</a> nor <a>.*?</a> is quite the right thing if we expand .* according to standard regex rules. Our xml regex could be taught to understand what tags are, and how they nest.
    4. If I write a regex to match <a>.*</a> I want it to match <a x='smile'>foo</a>. If we want to require that a certain argument be present we could specify as follows: <a x='.*'>.*</a>. If we want an element to not be present, we could write this: <a x != '.*'>.*</a>. If we want the tag to have no elements, we could write this <a '.*'!='.*'>.*</a>
    5. I should not need to specify the quote character. Matches should work regardless of whether single, double, or no quotes (HTML) are used. Escaped quotes could be used to identify the quote character if I do care: <a x=\"foo\">.*</a>
    6. Extra white space should not matter: <a> should be the same as <a >.
    7. Flags could be provided for ignoring prefixes, allowing <a>.*</a> to match on <root:a>narf</root:a>
    8. When searching text, it should be possible to ignore <b>, <i>, <em>, <font> tags that are mixed into the text. I want foo to match against <b>f</b>oo

    What else would a tool like this need?

    Is it necessary? Are existing tools like XQuery and Beautiful Soup sufficient?

  • Coding Conventions

    It is important to follow standard naming conventions when writing code. It increases clarity and readability. Thus, in the "Elements of Java Style," we are told to capitolize class names but not function names, etc. A recent elaboration on this basic idea was put forward by a colleague of mine (Adam French) and his associate (Andrew France).

    The suggestion is that, in addition to other style considerations, your object oriented code should operate as follows:

    1. All variables should be named after Star Wars characters.
    2. All function names should be named after Star Trek characters.
    3. All classes should be named after Lord of the Rings characters.

    Coding in this fashion will, obviously, require great discipline and nerdity, but in the end the resulting clarity will bring many rewards. And if you are planning to become ISO 9000 certified, remember to document this procedure.

  • Python’s “with” keyword

    Python recently introduced the “with” keyword. It is another way of automatically cleaning up something at the end of a block. It is a way to try and get some of the destructor functionality of C++ into a garbage collected language. Garbage collection, IMHO, continues to be a mixed blessing and I think the “with” keyword is an ugly (but useful) way to deal with one of its shortcomings.