Hilarious Comment on Programming Stupidites Page

February 10th, 2017

I was reading a bunch of funny programming related stories on a page dedicated to programing stupidities, and came across this:

About four years ago, I was working on a project that, among other things, involved porting several million lines of code. While not technically real-time, the code needed to be reasonably fast. At one point, I found the following gem:

unsigned long reverse(unsigned long theWord)
    unsigned long result = 0;
    int i;
    for (i = 0; i < 32; ++i) {
        if (theWord & (unsigned long) pow(2.0, (double) i))
            result += (unsigned long) pow(2.0, (double) (31 – i));
    return result;

Obviously, the purpose was to reverse the bits in a word. Naturally, I called all of my colleagues over to see this, and we all marvelled[sic] at how someone would think that a conversion to floating-point, a function call, and a conversion to integer could be faster than one shift operation. To say nothing of the possibility of rounding errors completely screwing up the, um, algorithm.

Not wanting to leave an exercise for the reader, here’s the replacement:

unsigned long reverse(unsigned long theWord)
    unsigned long result = 0;
    int i;
    for (i = 0; i < 32; ++i) {
        if (theWord & (1 << i))
            result += 1 << (31 – i);
    return result;

I just wanted to point out the irony of it: I could say that “I marvelled[sic] at how someone would think that using an “if” test in this code is at all optimal.” But I won’t do that since my replacement might not be the pinnacle of performance either. I’m just pointing out that it’s funny to see someone write unoptimal code while condemning someone else’s unoptimal code. Here’s my better replacement, which may not be the best but is better than that person’s best:

unsigned long reverse(unsigned long theWord)
    unsigned long result = 0;
    int i;
    for (i = 31; i >= 0; ––i) {
         result |= ( theWord & 1) << i;
        theWord >>= 1;
    return result;

There is no “if” test in this. There seems to be one less math operation too, but I’m not sure if the loop counter is optimal. I could have left the loop as “for( i=0…” and then written slightly more complex code but I’m not sure if the more complex shifting counteracts a more efficient loop counter.

The lesson? Humility is important. Don’t condemn someone’s code unless you are 100% sure that yours is not also condemnable. Or at least admit that you are not sure yours is the best either.

Also, long values could be more than 32 bits in these modern times, so a bit count check at the beginning of the function, or a comment about assuming that “long” is 32 bits, would be appropriate in there.

New Linkage 3.4

January 13th, 2017

Linkage 3.4 is now available. I got rid of the Elements panel and button. You will now need to right click to insert elements into the mechanism.

There are other changes mentioned in the first section of the PDF documentation and in some previous blog posts.

Get it here.

RBS On/Off Switch Beta Test

December 31st, 2016

I made a makeshift part to hold the far end of the on/off switch pull rod. Here’s a few pictures:



Once I make the decorative part to hold the end of the rod, I’ll cut some threads in the end of the rod and screw on a steel ball. The switch pulls out to turn on the machine, making it easy to turn it off in a hurry.

Oh, and the base is going to be 3/4” round acrylic the size of that piece of wood.

Working On An RBS Again

December 18th, 2016

I cleaned my garage and I’m back to working on a Rolling Ball Sculpture again. My garage was figuratively knee deep in stuff and almost literally knee deep in some places. I wanted to make some room to work on projects while also uncover the climbing wall. Yes, I built a simulated rock climbing wall 15 years ago and it is the first place I start to lean things when I’ve got too much junk to store elsewhere.


Climbing Wall Mostly Uncovered

I built the climbing wall for my then five year old kid. That’s why there are hand and foot holds cut right through the plywood. Then I added climbing holds for more difficult climbing, and finally, added the parts that lean out from the wall. For my casual use, it’s fun and just hard enough to build a little climbing strength.

The opposite view shows what my work bench looks like when it’s clean. Amazingly, this is the clean version“


“Clean” Workbench

It’s actually a bit cleaner than this now. When I too the picture, I was still moving things around. But it’s not much cleaner. The Benchmaster milling machine had been sitting in front of the climbing wall for a year and I finally cut away an L shaped extension of the workbench and moved it. It weighs a lot and the cheap casters I got for under each leg bent a little when I moved it. but it worked and it’s now bolted to the workbench and the wall ( the table, not the mill itself).

On to the project…

This is what I was working on a long time ago:


Ball Lifter #2

The movie is more recent and shows it actually picking up and dropping off balls:

Ball Lifter #2 Running

Skip ahead to 1:01 to see a shot of the whole thing at once.

I decided to add an on/off switch to this sculpture because the power switch on the cord of the previous sculpture seems cheap and is at the back of the sculpture. This new one will have the switch next to the motor with a few links connecting it to a push/pull switch in front. To convert the push/pull action to up/down action for the switch, I built some new parts shown here:


The Big Lever


The Big Lever After Cleaning Up


The Big Lever and Small Connecting Link (And Switch)


The Big Lever and Small Connecting Link (And Switch)


Opposite Side of Lever, Link, and Switch

The lever that sticks down will have a rod connecting it to the front of the machine with a small steel ball on the end. Pushing in on the rod will turn off the sculpture. I think that this cool switch mechanism will be a nice addition to the machinery.

New Linkage Beta Test

December 2nd, 2016

Get the Beta Linkage here!

If you need this Beta program for Windows XP, send me an email and I’ll send it to you…

There’s a new beta test version of the Linkage program. This new version has some bug fixes for things like the crash that sometimes happens when a fastened link is deleted. There was also a crash sometimes happening when a connector is deleted that is a slider on a curved slider path.


Press Alt and Left Mouse Button
to Drag Selection Box On Top Of Elements

For new features, I added support for the Alt key so you can select objects by dragging a box around them even if you are pressing the left mouse button on top of another element. the Alt key stops the element selection that normally happens when the left button is pressed.


Selected Actuator Control Knob

I also changed the way the actuator throw/stroke distance is set using the mouse; in order to drag the end of the “cylinder”, you will need to first select the actuator element. Then the little black dot, the same size as the little black squares used to resize selected elements, will appear. And the same type of control knob is available for drawing circles. You will need to set an initial size for the circle by selecting a drawing point and opening the properties box, but once set, a selected drawing circle has a control knob too for setting its size. These changes are leading up to me adding cams. Cams will need control knobs for creating their shape and those knobs should not be visible unless the cam is selected.


Circle Size Control Knob

There are other smaller bugs that got fixed, like a weird problem with link outlines going through the wrong connectors when some of the internal connectors are in the exact same location. I also fixed the way connectors are automatically moved when their curved sliding path is moved.

And I mentioned in in another post but maybe never made the software available for it: when elements are selected, entering a number followed by the letter ‘D’ in the text box in the tool bar will result in the elements being rotated by that number of degrees. remember that 60D will rotate the elements counter-clockwise as is typical of polar coordinates in math and unlike the typical compass headings used in navigation. I have no idea why they are different in direction but they are!


Entry of Rotation Value

Get the Beta Linkage here!

Linkage Adjuster Knobs

November 9th, 2016

I’m not sure what to call them. On an actuator, there is a small circle that can be used to change the throw length. That little circle is an adjuster knob or adjustment controller or something like that. I’m working towards in-mechanism editing of cams and changing the code to support those on any element is part of that work.

The first big change that is visible to the user is the addition of an adjuster knob on the drawing circle. The drawing circle is a drawing point element that is set to include a drawing circle. When the point is selected, the little adjustment knob circle will appear and can be dragged around.

The second big change is that I am making the adjuster knob on the actuator only visible and selectable when the actuator is selected. from now on, adjuster knobs of any sort are only visible when the element is selected.


Circle and Actuator “Un” Selected


Circle and Actuator Selected

Notice in the first picture that the actuator doesn’t have the little circle at the end of the “cylinder” portion of the drawing. Also notice that when either or both elements, the circle and the actuator, are selected, the adjuster knobs are visible. Either of those adjuster knobs can be dragged with the mouse when they are visible and it will not unselect the elements.

This is important work because there will eventually be a few types of cams in the program and they will all be modifiable right in the mechanism window. Of course I will also have some types of cams provide special properties boxes that let users set some properties by entering numbers (especially needed for engine valve cams) so this won’t be the only way to modify a cam. But for a cam with a variable number of Bezier curves defining the shape, having these controls is the only way to design the cam shape.

I am still testing this work and it might change in the future. I might also add adjuster knobs to other elements if there is any reason to do so; maybe chain sprocket size should be settable this way.

Linkage Update

November 8th, 2016

A new version is available in the usual place. I was finally able to spend the hour needed to fix the crash that happened when deleting links that were fastened to gears (or vice-versa). Version 3.3.13 has this fix.

A few other changes and fixes:

You can now rotate the selected items by typing in a number into the text box in the tool bar (the only text box) and then adding the letter ‘D’ after the number. The number is the number of degrees to rotate. I use polar coordinates, not compass coordinates, so positive numbers rotate counter-clockwise.


Polar Coordinates
The center of rotation, which you can set by selecting elements to rotate and then dragging the center mark to where you want to center the rotation, is now remembered if you are using the rotation-by-text-entry feature mentioned above.
I fixed how the sliding connector on a curved path is adjusted when it and it’s limit connectors are moved and rotated. It was just broke before.
Fixed bug that let a simulation run if both ends of an actuator were anchored.
Sped up some code from Microsoft to load the tool bar more quickly on high resolution displays. Some of their code resizes the images in the tool bar and it was resizing the same images more than once. I can’t seem to fix it to use my own pre-sized images, but at least the current change makes it a little quicker to start up the program on pesky 4K displays.

That’s it. Get the latest version to get these cool new features!

Fastening Gears with Linkage

November 2nd, 2016

The whole “fastening” thing is a bit troublesome for me. I originally wanted to be able to move drawing elements with links and decided to allow “fastening.” This worked pretty well, though there is a bug where deleting a fastened element somehow causes a crash. But fastening isn’t quite right, bug or no bug. It is especially difficult to use now that I make links and gears move together by fastening them together.

To make the problem even more difficult, I had to make a way for gears to be fastened to the ground so they don’t rotate freely. And this is where I found myself mucking around in the Linkage code tonight.

A simple change to the code that allows and disallows actions let me fasten a gear to the connector at its center. Here’s the mechanism that made me want to make this change:


Gear 7 is fastened to anchor H making it not rotate freely.

But now what about gears that have an input anchor at their middle? I originally opted to make the gear rotate with the input even if they are not fastened together. It made sense because there is seldom a need to let a gear spin freely on a shaft that is rotating. I will keep it this way for now because no one really uses gears in the Linkage program anyhow.

Now on to finding the fastening bug!

AutoResponder Config File Parsing

October 19th, 2016

I found a bug in my PHP code that caused strings to match when parsing the AutoResponder config file for responses to submitted text messages. I was using old DOS style wildcards * and ? to make it easy to write the config file. But my comparison functions were just long and complicated and screwed up.

The solution to the problem was to switch to using regular expressions. But those asterisks are so handy for their simplicity. Here are some XML elements from the config file that are used for matching an incoming message with an appropriate response:

<response keyword="* hint *" answer="1">Hint 1</response>
<response keyword="help *">Your message […]</response>
<response keyword="register * team *" answer="#" action="register"></response>

The new code let’s me use multiple asterisks in the keyword attributes but only allows one of them to have data. So if someone sends a text message “hint1”, it will match that first XML element because only one asterisk represents data and whitespace is ignored (I hope ignoring it is a good choice for my application).

I will explain the CompareNumberString() function is in a moment. The WildCardStringMatch() function runs first and converts a keyword string from the config file with asterisks to a regular expression. Then it just compares/processes the regular expression with the input string. If there is data that matches one of those asterisks, a second comparison is done to see if that data matches the answer attribute. In the case of our “hint1” input, it matches because the “1” matches the “1” in the answer attribute. If the input had been “hint2”, it would not have matched and the code would look for some other match from a different response element. “1 hint” would also match but “1 hint 1” would not match because only one asterisk is allowed to have matching data.

The “help” XML element up there doesn’t care what message is sent, it accepts anything and some other PHP code handles getting help for the sender.

The last XML element up there in the sample config data has a hash tag (“pound sign” or “number sign” if you are more than 20 years old) in the answer attribute. Whenever an asterisk matches some data, the resulting data is then compared to the answer attribute. If there is no answer attribute, it is just considered a match. But when the answer has the hash tag, this is where the CompareNumberString() function is called. The CompareNumberString() function compares the input string to the answer attribute seeing if it is a number and if it matches an optional range of values in the answer attribute that are acceptable. Matching a range of values lets the config file specify how to handle numbers that are too large or too small.

This code is working much better than my previous version and is much more flexible.

Word Search Instead

September 22nd, 2016

I was going to write some posts about the latest version of the AutoResponder but I got side tracked on making a word search puzzle generator.


Word Search Generator

I was trying to make a puzzle by hand and it was clear that it’s hard to do. I then tried to use some free web-based software and it was clear that there was no way to create an overlay to more easily check answers. And finally, I needed to create a UWP app as practice for work – we might need to have this type of app sometime in the future.

I found one person online who described the algorithm that they used for their generator. After working on implementing it, I decided that it was overkill. Their algorithm, upon finding a word that can’t be placed anywhere, would remove and try to re-place the previous word in a different location. If that previous work cannot be placed somewhere new, the algorithm repeatedly backs out previous words until it can progress forwards and finish the puzzle. This isn’t so good if there isn’t enough space to place all of the words – the algorithm runs for a very long time. I found that it’s better to just start over with new random placements if any word cannot be placed. It essentially does the same thing but just backs out all words instead of just the previous word. The algorithm is simpler and also lets my app return partially completed puzzles.

Other than the cool feature of exporting PNG image files, I also let the user decide if they want just the ovals around the answers with no letters filled in. This might be good for creating a transparent overlay for checking other peoples work on the puzzle.

It’s not open-source but I would be happy to share with anyone who seem sincere about wanting to have this for their own personal projects.

So like I said it’s a UWP app written in C# so it runs on my laptop and on my phone, both running Windows 10.