Saturday, February 11, 2012

method_missing, C style

Given: We need to interface to communication in S-expressions. In C. We are given a library that does the communication and S-expr representation in some C data structure. We expect commands like

(get "file" 2500 250)

that is, read from a given file at given position and length, and return the data.


Now, doing this based on elementary functions like sexprIsCons() and sexprGetCar () is pretty unwieldy. It would be much nicer to simply do


const char *file;
int pos, len;
if (fs_ps_get_SII (sx, file, pos, len)) {
unsigned char *bp;
int blen;
get_data (file, pos, len, &bp, &blen); // TODO: error handling
return fs_mk_SBy (file, bp, blen);
}

We'd like to have one function that parses the incoming S-expression into some variables, and another to compose the reply. (The fs_ prefix is used since this is C and its usual method of namespacing.)


Now, we could go along and implement those functions by hand. But, since we even encoded the exact data types we expect into the function names, we could just as well generate them. The namespace prefix and the _mk_ (make) and _ps_ (parse) prefixes suffice as a discriminator against catching other names, and thus we can just scan the whole source file(s) for these patterns and generate the according functions. VoilĂ , auto-generation of missing functions.


Note: The _ps_ functions are actually macros; otherwise we'd need to pass in the addresses instead of the variables themselves.


Exercise for the reader: Also implement command collection so that all functions named fs_cmd_get_XXX are directly put into a command table. Then a server would need only the command implementations itself and the global setup code.

Sunday, March 06, 2011

Skewed distribution

Distributing items (IP packets, phone calls, http requests) randomly onto a set of machines (say, four) is easy (in C here):

int slot = random_nonnegative () % 4;


The number space returned by the random number generator is big enough that the items are essentially evenly distributed even if the number of slots wasn't a divider of the size of the random number space.


I want a skewed distribution, however. The slots shall be loaded unevenly. Thus:


int slot = random_nonnegative () % 4;
slot = random_nonnegative () % (slot + 1);


That is, if slot is 3 after the first line, then we have an even change to get to any of the slots in the second line. If it is 0 we can only end up there. In essence there are four ways to get to slot 0, three to slot 1, two to slot 2, and one to slot 3. Zeroth-order intuition would thus say that four out of ten (1+2+3+4) items would end up in slot zero.


Except that the experimental results don't match. And for a reason. For slot being 3 in the first line, a fourth of the item go to each slot; for slot being 2, a third goes to each of the three first slots, and so on. Thus slot 3 receives a quarter of a quarter, or 1/16th of all items (and not one tenth); slot 2 receives a quarter of a quarter likewise, plus a third of a quarter via slot being 2 on first line; slot 0 finally gets 1/16+1/12+1/8+1/4, which is 3/48+4/48+6/48+12/84, which is 25/48, or about 52%. Which is a bit more than the 40% of our first guess.

(PS:


char *target = targetarray [
random_nonneg () % (
random_nonneg () % (sizeof (targetarray) /
sizeof (targetarray [0]))
+ 1)];


for the golfing old-style C hacker.)

Wednesday, December 23, 2009

svn needs IDE integration

It's funny; all the world craves for svn integration for their IDE and doesn't want git because of lack of such integration. On the other hand I am quite happy without the integration, but then I was raised on a command line.

And then I noticed that, for the usual IDEs (java dev, that is), you need IDE integration for svn for a very simple reason: refactoring. If you rename or repackage a class, the source file changes location, and svn needs to record that as a file rename, and you need to tell it so. Now, if the IDE has moved the file, you can't do again with svn, and that would be the only way to make svn to know the move. (You could stop the IE, move the file back and then with svn move it forth again, but...shudder.)

Thus the IDE must be able to talk directly with svn. It's not just a question of avoiding a suboptimal command line, it's a necessity. With git, on the other hand, there is no such need as it does not directly track renames anyway and is much smarter about them and merging.

Sunday, November 15, 2009

svn: more bad

Ranting about tortoisesvn and it committing new files with CR/LF in them, I finally found that there is apparently no way to make svn behave the right way (in our sense) of doing svn:eol-style=native automatically. You need to do a setup like this. Yet another misdesign. (And if you work on two projects where these defaults differ, then you are out of luck.)

By the way, somehow nobody did think that a by-line diff of svn:externals would be a good thing. We usually have one directory with six or so externals, and when you change one of them svn diff just shows the whole property text as changed, and not individual lines. Tortoisesvn is smarter here (as in other places), reinforcing my claim that with svn you need GUI support because the command line interface isn't exactly pretty.

Sunday, November 08, 2009

svn: BAD

svn is just broken.

Google for git commit. First link points to the current documentation. Dito for svn commit. First hits point to outdated versions of the manual (usually 1.0, maximum 1.5).

Checkout a module. Unfortunately, the URL to check out usually ends on trunk so the default sandbox directory name isn't really helpful. Likewise, it took 'til 1.6 that they found out that typing the repository URL in many commands is a waste, and allowed ^/repo-relative paths not only in svn:externals but also in commands.

Just for kicks try an svn ls http://... operation over GPRS. Will take on the order of half a minute because GPRS round trip time is about a second, and svn ls does a good dozen http requests to the server, all serialized, but not reusing the connection. It is actually a good idea to prefix commands with ssh elsewhere; the ssh login is faster, and the svn command is then done on fast links. (Doesn't work for commands involving a sandbox, of course.)

svn import can only import a given tree into a new location within the svn repo; it can't do updates, like they are needed to import newer versions of vendor software and keep the file identity that will be needed to keep future merges smooth. There is a script in contrib that can do that, but it never got integrated into the import command proper.

Likewise, don't even expect a command that can create an archive (tar/zip) from the versioned files in the current directory (git archive), or that can delete all unversioned files in the sandbox (git clean). Or that tells you a human-readable name for the current revision based on the last tag (git describe).

And, of course, there is the big thing: the hyped merge support of svn 1.5 is broken by design. Isn't fixed in 1.6, and probably can't be fixed without changing the repository format. (I suspect the whole mergeinfo property stuff is just wrong.) In the meanwhile, and in a much shorter timespan than from the announcement of svm merge support to its eventual functional delivery, git appeared, and just did it right.

I don't like that. We've been waiting for svn 1.5 because of the merge support, and then started to switch. At the same time git appeared on my radar; I could use git cvsimport and git filter-branch to do our conversion from cvs to svn, in a way that allows to pull future changes from cvs to svn as well, and without manual intervention. Unfortunately I lost all liking for svn in the process, because git turned out to be just much better tooled, capable, and flexible. And faster in its development, its version number is bound to pass that of svn soon.

Thursday, October 22, 2009

The awesomeness of no rename

git does not store renames. All it does is store each version of the whole tree of the managed project. The diff and merge tools are those that look at the trees and file contents and notice that a file has been renamed.

For example, I had a project where a program was converted to C++, piecewise. One file was originally foo.c, then foo.cpp was created by copying and fixing the original C source. foo.c was not removed until later, so for a few commits both existed simultaneously. Indeed this was in CVS, and I just imported the stuff to git, to work on newer stuff there.

Now it was time to merge the line originating in CVS into the work branch. git merge just looked at the changes that needed to be merged all at once, and saw that foo.c was gone and foo.cpp was new over that stretch, and that they were 95% similar, so it assumed this was a rename, and properly merged the rename into the work branch.

That is the power of not doing or saving renames.

Monday, September 28, 2009

git and cvs: Coexistence

There is a relatively trivial way to use git on trees managed by cvs which I use often to carry around cvs projects for new work and enjoy the distributed nature (which comes quite handy when on a train). Recipe: Check out the target tree with cvs, go into the root, git init, and cvs-files | xargs git add. One git commit -m initial and you are ready to go.

Now you can clone around as you like, and do cvs updates in the gitted sandbox, and commit those into git, and back. Only thing is that on the way back to cvs you manually need to track file additions/deletions.

The script cvs-files looks like:

#!/bin/sh
find * -name CVS -type d | while read cdir
do
dir=`dirname $cdir`
if test X$dir = X. ; then
dir=""
else
dir="$dir/"
fi
sed -ne 's:^/\([^/][^/]*\)/.*$:\1:p' /dev/null ${dir}CVS/Entries* | \
sort -u | while read name
do
if test -r $dir$name; then
echo $dir$name
fi
done
done

It just goes through the CVS/Entries files to find out what's under CVS control to initially put those into git.

Tuesday, April 07, 2009

There isn't enough coffee in the universe

EVS is me going "Screw it, I'm not playing any more" and writing a
system that can talk to anything, given enough time and coffee.


And this mail came after a loooong day filled with nothing actually, unless you count trying in vain to get some GeForce running with openSuSE as work. (Which would have been fun if the driver would not only support portrait mode but also draw correctly and use the panel's natural resolution. eclipse look quite good on a portrait screen.)

Anyway, how can one get the idea that all version control systems are basically created equal, and that that is enough to write an universal server that can talk each protocol equally and fully? Even with cvs you can trivially create a repository than can't be converted to, say, git, and vice versa create a repository in git that can't be represented in cvs. In the latter case the revisions would all be there, but the merge information would be missing.

If you take out all the edge cases, that is, sufficiently many of them, then it may be made to work. But neither would many existing repositories match those requirement, nor would the resulting functionality be very interesting.

Wednesday, February 25, 2009

MacOS surprise: ssh-agent

I'm new on my macbook. Anyway, since leopard ssh asks for passphrases using a dialog instead of on the command line. This is not necessarily a bad idea, for example a git push from within git gui has no good place to ask.

On the other hand, using ssh-agent for that is even more convenient, and since this dialog allows you to store the password on the keyring I assumed that that is the preferred way and no one would bother to start an ssh agent under the whole of the leopard gui session. Turn out I was wrong. And my workaround of using xterms started from another xterm with an agent in there was quite unnecessary.

Thursday, January 01, 2009

ant: BAD

Who doesn't know history is condemned to repeat it. Or not even that, as ant managed. In my option, ant started with a bad idea and then made it worse. In other words, it is Broken As Designed.

The quotes are form the aforementioned page, section 'Apache Ant'.

Apache Ant is a Java-based build tool. In theory, it is kind of like Make, but without Make's wrinkles.

Yeah, the wrinkles have been replaced by pointy brackets, and all the deep problems haven't even been addressed at all.

Why another build tool when there is already make, gnumake, nmake, jam, and others? Because all those tools have limitations that Ant's original author couldn't live with when developing software across multiple platforms.

Well, at least I don't want to live with ant. As little as possible. Granted, make isn't usable for building java projects either, but then neither is ant, without working around the buggy javac task.

Make-like tools are inherently shell-based -- they evaluate a set of dependencies, then execute commands not unlike what you would issue in a shell.

That's the point! Why invent another scripting language when you can have one for free? Instead ant goes along inventing a new scripting language (which may not even be turing complete), and it takes them years to come to a point where ant can at least do what the good old shell always could.

And still, to do a simple grep Whatever | sed -e s/XX/YY/ you need to write java programs, compile them, feed the jars to ant, and after a few hour get it actually working. Not to menting the fact that those classes can't easily be part of your project because you need them before starting ant. (Ok, that's not actually true, but in an ugly way.)

This means that you can easily extend these tools by using or writing any program for the OS that you are working on. However, this also means that you limit yourself to the OS, or at least the OS type such as Unix, that you are working on.

Gladly so. Nowadays you can easily get VMs oder cygwin if you should really need to work elsewhere.

At least it's much better than making everything complicated, everywhere. The average trivial build.xml contains about 60 lines, of which three do actually vary with the project, and the rest is always the same. Don't repeat yourself, huh? At least we hope it's the same, and there aren't any copy&paste bugs lurking.

Makefiles are inherently evil as well. Anybody who has worked on them for any time has run into the dreaded tab problem. "Is my command not executing because I have a space in front of my tab!!!" said the original author of Ant way too many times.

The original author of ant obviously had the wrong editor, or was missing a little script to check for that. I've written my share of makefiles, and I can't remember ever running into that problem.

If only the original author of ant ran into the real problems that make poses; then ant wouldn't have been such a terrible misdesign.

Ant is different. Instead of a model where it is extended with shell-based commands, Ant is extended using Java classes. Instead of writing shell commands, the configuration files are XML-based, calling out a target tree where various tasks get executed. Each task is run by an object that implements a particular Task interface.

So, instead of writing little one-liners I need to write code in a programming language that itself is known as verbose, write additional build targets to get those compiled, and finally knit it all together in XML, yet another source of bloat to the whole end. (And for the nitpickers, ant uses two extra syntactic elements: comma-separated lists and property value replacements. Guess why they don't do that as XML elements.) ant has a serious Dr. No syndrome.

Granted, this removes some of the expressive power that is inherent by being able to construct a shell command such as `find . -name foo -exec rm {}`, but it gives you the ability to be cross platform -- to work anywhere and everywhere.

...and making that a lot of work. Ant really does not fall into the category 'make the easy things easy and the hard things possible'.

And hey, if you really need to execute a shell command, Ant has an <exec> task that allows different commands to be executed based on the OS that it is executing on.

Now that't a cop-out. If our uber-tool happens to not support what we want we can still go platform-specific. Thanks; due to general disgust with XML I wrote a little shell script (of all things) that does everything I need to do in the projects I need to manage, including compiling and collecting used libraries of my own. /bin/sh isn't exactly the best way to do, but the whole thing is just five times larger than the (broken) build.xml I got for those projects (and shorter than this blog entry), and the actual build script for one of those condenses to

#!/bin/sh
. "`dirname "$0"`"/../proj-a/tools/buildtool.sh
depdir ../proj-a
javacomp
mkjar proj-b

and is also a shell script.

Now what?



Ok, more details on how ant is misdesigned. The javac task is broken:
It only compiles java files that have no corresponding class file or
whose class file is older than the java file. It does not erase class
files for which there is no longer a source file, nor does it
recompile dependencies between the classes. Especially the latter
makes for interesting bugs. Workaround: Always clean before compiling,
either manually or by the 'dependencies'.

And these 'dependencies'. They aren't, really. The individual tasks sometimes execute conditionally depending on whether the destination is newer than the source, but you need to state dependencies explicitly, no matter whether ant could deduce the dependency itself. For example, when a javac task produces what a jar task consumes ant won't make them dependent automatically. Otherwise, when you put a target into the dependencies list of another, it is executed, no matter what. As opposed to the following make fragment

prog : main.c gen.c
cc -o prog main.c gen.c
tool : tool.c
cc -o tool tool.c
gen.c : tool gen.in
./tool gen.c

which tells that gen.c needs to be generated by tool which in turn needs to be compiled from tool.c. The point here is that when you call make, the tool won't be recompiled unless you modified its source, and gen.c won't be generated unless you modified either the generator or its input file.

Ant stays blissfully unaware of any of this dependency management, and thusly degenerates to the fixed execution of a number of scripts (called targets) with a number of commands (called tasks) each. If you want your task not to do work when none is needed, don't expect support from ant. Ant is not really a build tool, it is a simple script executor, however their creators talk about declarative operations and the ant way which seems pretty long-winded to me.

The 'declarative way' does not keep people from relying on the fact that the dependencies of a target are executed in the order they are specified. A dependencies="clean, compile" to work around the javac problem is all but uncommon, and clearly will break when ant decides to run the dependencies in inverse oerder.

To be fair, the dependency problem isn't exactly trivial, especially without support from the actual compiler. make doesn't do a good job for java, either. But on the other hand side we'd expect an industrial-strength build system to have invested not just a little thought?

Then ant completely ignored the lesson of the X windowing system. Those guys actually improved on make by using the C preprocessor. Their Imakefile system inspired another (proprietary) system that could just say

CProgramFromSources (prog) {
CSource (gen)
CSource (main)
}
CProgram (tool)
gen.c : tool gen.in
./tool gen.c

with one important difference: The macros expand so that not only make prog does the expected thing, but also that make clean removed all the temporaries, except for gen.c which was done with a plain make rule. We need to add

clean ::
rm -f gen.c

to make that work, too. This also shows another overlooked make feature: You can actually combine a target from multiple separate commands and dependencies. It's just not possible to have multiple clean targets in ant, making it even more error-prone to do the right cleanout.

Ant simply aims too low by one or two levels of abstraction.

Then what?



Unfortunately ant has gotten a lot of traction in the java community. Proves again that you need to be the first, not the best. Compounded by the fact that most programmers don't care about the build system any more than needed to make it apparently work. And everything and the kitchen sink is available as an ant task, so it's not just programmers to turn around.

And I'm not exactly in a position to get a lot of traction for a change. The most promising way is to fight the system from within; perhaps by actually having some preprocessor (again) generating a tmp/build.xml to then be included.

The most depressing thing is that ant will make the majority of people think that this is the state of the art in build system design. Far from it.

Wednesday, December 31, 2008

Factoring out helper classes

The job is to get a source and a destination path for a java compile. Because it's mostly the same, we want defaults for source and class directory. Because we occasionally have more than one separate hierarchy to compile, we want to provide a base path on which the defaults are applied. Thus this is the wet (aka non-dry) code:

AttrList al = new AttrList (l.getParam ());

String base = al.pull ("dir");
if (base == null) base = "";
else base += "/";

String src = al.pull ("src");
if (src == null) src = "src";
src = base + src;

String cls = al.pull ("classes");
if (cls == null) cls = "classes";
cls = base + cls;

We first get the base path and fiddle it a bit, especially when not given. Then we obtain source and destination, set it to default when not there, and prepend the base (which we fiddled so we can always do so even when it does not change the path).

The repetition looks ugly. So: Factor it out. We can't purely do it with a helper function, so we need a class (this is java, everything needs to be done in a class):

class Basifier {
String base;
public Basifier (String param) {
if (param == null) base = "";
else base = param + "/";
}
public String basify (String arg, String def) {
return base + (arg != null ? arg : def)
}

and use it:

AttrList al = new AttrList (l.getParam ());
final Basifier base = new Basifier (al.pull ("dir"));
final String src = base.basify (al.pull ("src"), "src");
final String cls = base.basify (al.pull ("classes"), "classes");

Not too bad, except that we need to define a helper class and instantiate it for each invocation of ours; and we note that the useful lifetime of the object is tied exactly to the lifetime of the invocation of our funktion. In my optinion the latter is a sign that we are doing something wrong: If two things always have the same lifetime, they should really be parts of one thing.

If java had local functions and closures, we could spare the separate class:

String base = al.pull ("dir");
if (base == null) base = "";
else base += "/";

public String basify (String arg, String def) {
return base + (arg != null ? arg : def)
}

final String src = basify (al.pull ("src"), "src");
final String cls = basify (al.pull ("classes"), "classes");

We save the need for the extra object, and the need to reference it. Arguably the helper class has the advantage that the basification is encapsulated there, but it is not just that but also the default value handling for the other parameters that is done in there. Besides, the basification may also be usable in other locations.

One interesting sidepoint is that the basifier is almost, but not quite, implementable as an anonmous class:
    
final Whatever base = new Object () {
String base;
{
base = al.pull ("dir");
if (base == null) base = "";
else base += "/";
}
public String basify (String arg, String def) {
return base + (arg != null ? arg : def)
}
};
final String src = base.basify (al.pull ("src"), "src");
final String cls = base.basify (al.pull ("classes"), "classes");

The only thing that does not work is that we cannot name the type of the anonymous class for declaring base, and we need that type to be able to invoke basify on that object. In scala that actually works by type inference; the variable is just declared as a variable, and the type is assumed to be the type of the initializing expression.

Is the class Basify something that is worthy of a separate existence, or is just a little bit of code that gets factored out, and because of the needed scope of the data it works with, it is forced to become a separate class. It may also be done as a static inner class; only the option of a local function is out.

Basically in the latter case the function invocation serves as a kind of object; we could view the local function as a member function of the invocation. If that is so, we might also view the function invocation as some kind of a class, and then we might actually make it to extend another class (or implement an interface):

public void methodAsObject (String p, String q) extends Basifier {
super (p);
final String here = basify (q, "def");
..
}

It only does not work because we don't have the constructor parameter at that time.

Over the fence



By the way, other languages just do it differently. In C++ you decide whether a local variable is just a reference to an object

Basifier *base = new Basifier (param);

or whether you actually want the object itself to be a local variable:

Basifier base (param);

In the latter case the lifetime of the object is directly tied to the function invocation. This can't work in safe garbage-collected languages because you can't remove the object before you know there are no more pointers to it, and this is incompatible with with stack allocation.

Oops



So, this was planned to be a rant against excessive objectification and turns out to motivate me to actually use the basifier class. Will eventually show up here; look for "javac".

Tuesday, December 30, 2008

svn: BAD

Executive summary: Read about svn merge --reintegrate and weep.

We waited long for subversion 1.5 to come out. It was hyped to have proper merge support and thus be a real step forward for cvs users. Actually we were using cvsnt which already had some merge support until they broke part of it, and we kept using a patched version.

Anyway, 1.5 finally came out this summer, and since we did not only want to keep having merge support but the history-preserving renaming of subversion as well, the step was done. (We were not migrating but only using svn for new projects.)

Then I started reading the updated svnbook, and wondered: Why on earth is there an option --reintegrate? It turns out that you can only open a feature branch and merge repeatedly into it, to keep it in sync with new stuff on the trunk. But you can only once merge back into the trunk or wherever you came, and then the feature branch must be killed because further merging won't work.
And then it turns out that svn 1.5 was released with this half-working merge support on purpose because it was overdue already and they managed to represent the merge info in the repository in a way that makes a correct implementation impossible, and thusly, it won't happen before 1.6 or so.

And in nearly the same time frame, another star appeared and ran circles around svn in terms of ease of use (just count the number of times you need to type absolute urls in svn command), possible workflows, breadth of utilites. And it's a nice svn client, too.

Tuesday, December 23, 2008

git svn without root

git svn is my favorite way of working with svn. Uses less space than a native svn sandbox, still contains the complete bloody history, and doesn't fool grep-find with the pristine copies.

Installing both the right way isn't quite easy. For git you just need the standard install, but you need to install svn including its perl bindings. And you can control the installation location of svn with the usual --prefix=$HOME/local to configure, but this does not change the place where make install-swig-pl wants to place the shared libraries and other perl binding code. You can only change that by doing some steps manually:


tar xzf subversion-deps-1.5.4.tar.gz
cd subversion-1.5.4
CFLAGS=-fPIC ./configure --prefix=$HOME/local
make
make install
make swig-pl-lib
make install-swig-pl-lib
cd subversion/bindings/swig/perl/native
perl Makefile.PL PREFIX=$HOME/local
make install


Basic point: You need to invoke the perl make separately, and tell it where to install. Seems not to be so easy to include an option for that into the toplevel configure?

Also note the need to manually say CFLAGS=-fPIC even though the target system (Novell SuSE) isn't exactly unusual, and configure should figure this out.

Anyway, the perl library path (PERL5LIB) seems to already include $HOME/local, so after above commands, git svn works. If you use a different location you need to fix PERL5LIB.

Saturday, December 20, 2008

git on svn

git can push onto webdav-enabled http servers.

svn is a webdav-enabled http server.

Unfortunately, it does not quite work. Cloning via http://svnhost/whatever.git/ works, but I can't push back there. It says error: Error: no DAV locking support, and I tend to believe that. svn can lock, but apparently not over http and svn urls, and equally apparently locking is not enabled on our server. And I can't change that, and setting up my own svn server just to test that is out of the question.

Not to mention the usefulness of this exercise. Operating a git repository versioned in svn is...strange. It just would enable one to really use git and still claim to work with svn.

Tuesday, December 16, 2008

Under attack

I have a DSL link home, and by now I operate a regular unix system for the router, and it's the first system I have with an internet-facing sshd. Now, every once in a while some bot comes along and seems to try out a lot of account/password combinations, not withstanding the fact that I only enabled public key authentication.

Idea: Whenever massive login attempts are detected, just reflect further incoming connection attempts from the same address back to that address. Thus the bot just attacks its own machine.

Question: How to do this without hacking the sshd itself? Possibly temporary static nat rules?

Saturday, November 08, 2008

git usage

cvs was easy to take on, even though I didn't know any version control system beforehand.

git was harder, even though I did know some systems by then.

The difference: cvs has basically one way to work with it, while with git you are much freeer in how you want to work. With freedom comes the problem of choice and the need of experience. For example git practically doesn't let you destroy any history, but sometimes it can be tough to find out how to recover from a particular mistake.

Also in the mix: When I started cvs, I had nothing. When I started with git, I had quite some history to import and to deal with.

As long as you don't do branches (and with plain cvs, you better shouldn't), cvs is just a way of sharing a common tree without risking accidential overwrites. With git there is a wealth of things you can do, and of those you can do nearly right. I don't think that I am yet in a position to foist git over a bunch of developers and to give them enough training so that they can get along without big mishaps or frustration. Especially not for windows guys.

So mostly I still use git-svn, live with the company decision to use svn, and sometimes use git hackery for special effects that nobody else needs to know about that git was even involved.

Friday, November 07, 2008

Comment notification

Blogger bites too. I just noticed that there are some comments here, and I remember turning on email notifications for comments, and relied on these.

Consequence: Only today did I even notice the existence of any comments on this blog, for which I do want to thank you, dear readers!

(Note to self: Rework the post labels.)

Priorities and signs

This was almost going to be titled 'signs are hard'. I hat a problem that a simple timer queue implementation did not quite work. Problem: Some timers seemed to vanish from the java.util.PriorityQueue, or were in the wrong order. I tried, for lack of other ideas to change the sign of the compare method, to see if I got that wrong. Letting the handler thread wait for and pick the latest timer is not a good idea. But alas, that wasn't it, and there goes the title.

Google ("java PriorityQueue remove"): Somewhat unexpectedly, the first result is not the documentation of the queue but rather exactly the report for the bug that is biting me: remove does remove the first element it finds that compares equal to its argument, not that exact object: Voila: wrong element removed; that timer never fires, I'm not getting #ticks.

Good. So now I know what's wrong and can finally implement a strategy to do fewer removes in the first place. Many timers here serve as a timeout and leave the queue not at the front but by remove. And the timeout is constant. So if a timer is set to a later time I can just leave it in the queue and reposition it when it finally appears up front.

Also there is a decision to be made whether I leave the workaround in. It's fixed somewhere in 1.6 (b51?), and I can't rely on the JVM always being that new.

Wednesday, September 24, 2008

cvs to svn via git

It actually works. The problem: I wanted to take the history of a partial cvs repository into svn. Directly using the tools was out for two points: First, one needs access to the svn repository itself (at least I think so and didn't bother to check because of) second I wanted to patch the paths of the java packages contained therein. Apparently eclipse doesn't quite want to deal with company_name.com, so it needs to converted to companyname.com even though the company only owns the former domain.

Anyway, I did not figure out yet how to use git-cvsimport and git-svn both on the same repository sensibly; and I think git-svn rewriting of the commits doesn't quite make that feasible. But the problem already starts with getting both histories to have a common ancestor. Unfortunately git does not have a null commit as the universal base.

Ok, final approach: Create project base directories (the ttb) in svn, do an git svn clone on that. Separately, use git-cvsimport to get the history from cvs into git. (Caveat: The approach does only handle a single linear history well.) Use git format-patch --root commit to get a series of patches, run those through sed -e s:company_name.com:companyname.com:g (which patches directory names as well as imports and package declarations). Then apply (git-am) the resulting commits in the git-svn repository, and git-svn dcommit them. Done.

Except that my link to the svn repository isn't exacly fast at the moment (roundtrip at about a second), and the 60 commits took two hours. svn does not seem to like slow links; a simple tag operation (svn cp trunk tag/some) on a small thingy took me more than a minute over GPRS once.

Here's the complete commands:
mkdir myproj-cvs
cd myproj-cvs
git-cvsimport -p x -v -k -a -d :pserver:krey@localhost:/opt/cvs mystuff/myproj
git-format-patch -o out --root `cat .git/refs/heads/master`
mkdir mod
cd out
for i in *.patch; do sed -e s:company_name:companyname:g $i >../mod/$i; done
cd ../..
svn mkdir http://localhost:4080/repos/mystuff/myproj -m 'base dir'
svn mkdir http://localhost:4080/repos/mystuff/myproj/trunk -m 'trunk dir'
git-svn clone -s http://localhost:4080/repos/mystuff/myproj
cd myproj
git am ~/myproj-cvs/mod/*
git svn dcommit

Monday, September 22, 2008

Inband signalling is evil

In telephone inband signalling is, or rather, was to control circuit setup and teardown by tone signals within the speech band that is also transmitted from speaker to listener. Had the unfortunate effect that you use a specific whistle on the phone and lose the connection. Soon got exploited in more creative ways.

Anyway, in C++'s std::string often the same thing happens. When in C, you have a char*, and you can null it to mark the no value case. Not so in C++. You need a special value, and usually this is the empty string "". Fine and dandy as long as you can be sure that that value will never actually occur. Once this happens all the code will already be riddled with if (val != "") and you never find them all. Bad luck, just like with Y2K.

Neither do you have Maybe, the Haskell way of avoiding null pointer exceptions completely.