Warning: include() [function.include]: Unable to access /var/www/html/rogue-development/blog2/wp-content/advanced-cache.php in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Warning: include(/var/www/html/rogue-development/blog2/wp-content/advanced-cache.php) [function.include]: failed to open stream: No such file or directory in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Warning: include() [function.include]: Failed opening '/var/www/html/rogue-development/blog2/wp-content/advanced-cache.php' for inclusion (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/rogue-development/blog2/wp-settings.php on line 62

Notice: add_option was called with an argument that is deprecated since version 2.3 with no alternative available. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3468

Notice: register_sidebar_widget is deprecated since version 2.8! Use wp_register_sidebar_widget() instead. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3382

Notice: register_widget_control is deprecated since version 2.8! Use wp_register_widget_control() instead. in /var/www/html/rogue-development/blog2/wp-includes/functions.php on line 3382
May « 2009 « Marc’s Musings

Monthly Archive for May, 2009

My Flash CS4 favorite new feature

I’ve only been using Flash CS4 for a couple weeks now. The 3d stuff, the reverse kinematics, even the new text stuff hasn’t been all that interesting. But this little baby rocks my socks:

CS4 Library Search Field

CS4 Library Search Field

ObjectHandles V2, sneak peek

Today I’ve been working on the next major release of ObjectHandles. Below is an example showing off some of the new features. I’m most excited about the enhanced rotation support.   This new version is focused on making a version that will easily work with MVC frameworks like Moccasin. Some of the changes include:

  • You no longer have to re-parent your components.
  • What and where handles appear is now completely configurable
  • ObjectHandles modifies your data object instead of moving a component around (there’s 3 example visual components / data models in the source)
  • Optionally, object handles won’t swallow all of your mouse events.
  • Will now work with non-flex components (still requires Flex SDK to compile, I have to look into that)
  • Rotation support is completely smooth
  • Configurable constraints/rules system
  • Smaller, cleaner code base!

Scroll down for demo.

Click to see the early proof of concept of it working within Mocassin.

ObjectHandles is a library to easily add graphical move/resize user gestures to a Flex based application.

[kml_flashembed fversion="8.0.0" movie="/uploads/ohv2/ObjectHandles2Example.swf" targetclass="flashmovie" publishmethod="static" width="700" height="700" fvars="undefined"]

Get Adobe Flash player

[/kml_flashembed]


Flicker related to modules and custom components

In a Flex application I’m working on we’ve been plagued with some flickering problems that have been very tough to pin down. I think I’ve finally figured out (at least one) source of the problem. We have a bunch of custom components developed. Those components have static intializers that set up the default styles for them like this:

  1. private static var classConstructed:Boolean = classConstruct();
  2. private static function classConstruct():Boolean {
  3.    if (!StyleManager.getStyleDeclaration("NumericDisplay"))
  4.    {
  5.       var myStyles:CSSStyleDeclaration = new CSSStyleDeclaration();
  6.        myStyles.defaultFactory = function():void
  7.                 {
  8.                     this.fractionLabelStyleName = "";
  9.                     this.wholeLabelStyleName = "";
  10.                     this.topGap = 0;
  11.                     this.barStrokeColor = 0;
  12.                     this.barColor  = 0;
  13.                     this.barWeight = 2;
  14.                 }
  15.         StyleManager.setStyleDeclaration("NumericDisplay", myStyles, true);
  16.  
  17.    }
  18.    return true;
  19.  }
  20.  

Now, usually, that works A-OK. It runs before there’s anything on screen so no flicker.

But, what happens if the class that contains that isn’t in your main application swf and is instead a loaded module? Well, that initializer doesn’t run until the module loads. And the call to StyleManager.setStyleDeclaration causes the entire application to update it’s display which causes a visual flicker.

I was considering some solutions like:
Making sure the class gets compiled into your main application swf.
Add the default CSS to a .css file that gets loaded at startup instead of doing it in code.

But then I realized that the last param to the setStyle call determines whether or not to update styles, setting that to false fixes the flicker. Since the static initializer has to run before any of that component are constructed, we don’t actually need to be doing an update anyways.

  1.  
  2.  StyleManager.setStyleDeclaration("NumericDisplay", myStyles, false);
  3.  

After googling a bit, I found “best practice” examples that did it both ways. I’d suggest sticking with “false” due to this type of problem.

Reminder: Floats are not precise

I was chatting with a couple friends the other day about an odd bug that was due to floating point precision.  Neither of them got it at first, and it reminded me that not everyone realizes how imprecise floating point math can be.  I know this, you know this, even the friends I was talking to knew it after they thought about it.  But it’s so easy to ignore it since floating point math usually does what we want.  Here’s three amazingly simple examples:

Actionscript:

  1. var val:Number = 0.0;
  2. for( var i:int = 0 ; i < 10 ; i++ )
  3. {
  4.         val += 0.1;
  5. }
  6. trace(val);

Java:

  1. public class FloatTest {
  2.         public static void main(String[] args) {
  3.                 float val = 0;
  4.                 for( int i = 0 ; i < 10 ; i++)
  5.                 {
  6.                         val += 0.1;
  7.                 }
  8.                 System.out.println( val );
  9.         }
  10. }

Ruby (I had to go a bit higher on the loop since it rounds differently):

  1. val = 0
  2. (1..100).each do
  3.   val += 0.1
  4. end
  5. print val

What would you expect the output of those to be? Probably 1, 1, and 10 right?

Wrong.

The actionscript example comes out to 0.9999999999999999, java has 1.0000001, and ruby gets 9.99999999999998

Here’s another actionscript example:

  1. trace( (0.1 + 0.1 ) == (2/10) );
  2. trace( (0.1 + 0.1 + 0.1) == (3/10) );

That traces out:
true
false

Baffling huh? A float should easily have the precision to represent a tenth, right? It should easily be able to add up ten tenths to get one, right?

Here’s the problem. Floats really operate in binary (duh). In binary, you can’t represent a lot of simple decimal values, such as 0.10 without a repeating pattern. 0.10 decimal works out to 0.000110011 in binary, with the last 4 digits repeating forever. So the 0.1 you see when you trace out 0.1 is really just a rounded off binary value. If you do math with those values, the error can accumulate until it’s big enough to be seen despite the rounding.

So you should never use floats for anything like:

  • Money
  • “Real mathematics” (for instance, I work on educational math software where the numbers have to always actually add up)
  • Anything requiring a certain precision, like sending a probe to mars or calculating medication dosage

You should use floats for things where precision doesn’t really matter.  Things, that if you’re off by a little nobody will ever notice.  Games, animations, audio compression, etc.   Otherwise, the easiest solution is to stick to integer based math.  You can pick a unit of measure magnitudes higher than you need.  Example: for money use cents (or thenths of cents?) instead of dollars as your UoM.  Then when you display the value you divide by 100 to show dollars.  Or you could use a richer class that handles precise numbers like Java’s BigDecimal, or ruby’s Rational type.

But like I said, we already knew this, right?

Creating nested objects with JSON in Rails


Notice: Undefined index: STRICT_MODE_APPLIES in /var/www/html/rogue-development/blog2/wp-content/plugins/deans_code_highlighter/geshi.php on line 1036

Did you know it’s possible to send a single JSON based request to a stanard rails controller and have it create an object, plus an entire tree of children records?  I knew it was possible, but I was wracking my brain trying to figure out how to do it for several days. Imagine you have a data model something like this:

  1. class Commute < ActiveRecord::Base
  2.   has_many :locations
  3. end
  4.  
  5. class Location < ActiveRecord::Base
  6.   belongs_to :commute
  7. end

That’s a pretty simple many-to-one relationship.  Now, if you have a regular old Rails controller, how do you pass that single JSON request to create both the commute object, as well as several location children?

The first step is to add the accepts_nested_attributes_for attribute to the commute model object.

  1. class Commute < ActiveRecord::Base
  2.   has_many :locations
  3.   accepts_nested_attributes_for :locations, :allow_destroy => true
  4. end

And… that’s it on the server side!

To use this functionality, your client should send a PUT request with the following JSON in the body:

  1. {
  2.     "commute": {
  3.         "minutes": 0,
  4.         "startTime": "Wed May 06 22:14:12 EDT 2009",
  5.         "locations_attributes": [
  6.             {
  7.                 "latitude": "40.4220061",
  8.                 "longitude": "127.4220061"
  9.             },
  10.             {
  11.                 "latitude": "42.4220061",
  12.                 "longitude": "41.4220061"
  13.             }
  14.         ]
  15.     }
  16. }

minutes and starttime are two properties of the commute object. And likewise latitude and longitude are two properties of the location objects.
The only thing strange there is instead of passing a locations array, you have to pass a locations_attributes array. The “_attributes” is the magic piece that I couldn’t figure out.  This lets Rails know you want it to figure out how to create the children, and you’re not simply passing those children in.

If you don’t put the _attributes suffix in, you’ll get errors like the following because Rails is creating a generic hash and trying to shove that into where a Location object should go.

ActiveRecord::AssociationTypeMismatch (Location(#18269790) expected, got HashWithIndifferentAccess(#2654720)):

This general approach should work with XML or HTTP params based requests as well.

Bookpool update

In the beginning of April I had blogged about the apparent disappearance of Bookpool.   It’s since been by-far my most commented on post ever.  I got in touch with my former boss there and got this update from him, so I thought I’d share it here:

I was the person in charge of IT in Bookpool from 1998 to 2008, which means I’m not an employee any more, but I know the site disappeared on March 23 around noon. They called me to shut down all the servers properly in case they revived the company later. The owners moved all the equipment to a location close to Boston, I don’t know the details but it seems to me unlikely that it comes back.

Although it wasn’t my business, I feel very touched by your comments, it’s great to hear that you liked our service so much. Richard said it was like “losing a relative”, and Koko was willing to promise to buy a certain number of books. This is better than hearing our boss saying that we made a good job, thank you!

I had the luck to work with great engineers, like Marc Hughes and others, also the office and warehouse employees (I won’t mention names in case they want to keep anonymity), everyone was awesome and we made a terrific team. We put a lot of hard work to provide the service you got used to. This is why today I feel as sad as you with Bookpool gone.

I agree with you, there should have been some type of notice explaining what happened,
unfortunately there was nothing I could do about it, the owners must have a good reason to do things this way.

But not everything is bad news, I was also a fan of the famous Bookpool bookmarks, and I have saved some that I’d be happy to share with you. They’re somewhere in my basement, when I find them I’ll post a note here to distribute them to the people interested.

Regards,
Braulio Carreno.

Long commute? Optimize it!

I’ve got a long commute into work on a daily basis. That commute gives me a lot of time to sit alone in my car and contemplate the fact that I have a long commute.

In the middle of the night I can drive it in 45 minutes, but with traffic it’s never under an hour, often 1.5 or more.  I’ve noticed that very small variations in when I leave, even just 10 or 15 minutes one way or another, can really make a huge impact.  But it’s not a sure thing.  Some days leaving at 7:45 is the best, some days it’s 8:00.  I don’t know why it differs.

It’s my belief there are certain patterns that might take into account things like weather, day of the week, departure time, school vacations, and a bunch of other variables.  But I don’t have a good way to that figure that out since I’m lacking the data.

Which brings me to my latest mini-project.  I’m writing some mobile software for my phone, plus a website that will help to record my daily commute and visualize what’s happening.  Eventually, I hope to bring in some statisitical models to help predict my average commute time based on when I leave the house.

  • Phase 1: Start collecting data on my phone
  • Phase 2: Collect the data on a website.
  • Phase 3: Visualize the data.
  • Phase 4: Make predictions based on a single user’s data.
  • Phase 5: Collate multiple users who commute in the same area to improve #3 and #4

It’s my hope that someday I’ll be able to answer questions like:

  • Tomorrow, what reasonable time should I get out of the house for the shortest commute?
  • I’m running late, should I work from home for an hour or head straight in to avoid some traffic?
  • What week is the worst traffic-wise of the year?  (And hence, what week should I favor for planning a vacation)
  • What’s my fastest commute time?  Did I break that record today?

Today, I recorded my first commute to my Android powered G1.  I wrote an application that allows me to press a button to start/stop recording my commute.  It notes the start and end time, plus saves GPS data about waypoints along the way.  A future version of that app will upload the data to a web server, but for now it just collects it into a database.

Any other commuters out there be interested in something like this?

P.S. “Long commute” is a very relative term.  A half hour might be long for some people, and a 3 hour commute might be long for others.