Code Review: Fixing Unexpected State

During code review I came across a function that could produce broken state for a component. I wrote up an example Gist to show how it could create an unexpected state and a way to adopt the functional programing concept of “not mutating external state” to avoid this broken state.

Now you might think this would never happen to you because you wouldn’t catch the exception like my example and it would be an easy bug to find and fix, but remember Promises behave like Try/Catch.

Talk Like a Senior JavaScript Developer: Race Condition

This is the first part in a series called “Talk Like a Senior JavaScript Developer” where common computer science concepts are applied to JavaScript, HTML, and CSS. In this article we talk about a bug known as the race condition.

Have you ever noticed different state or ui show up when refreshing the page that you didn’t expect? Does it seems like no matter how hard you try you can never get consistent steps to reproduce a bug? Then you may have a race condition.

Wikipedia’s definition:

A race condition or race hazard is the behavior of an electronic, software or other system where the output is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when events do not happen in the order the programmer intended.[1]

Hopefully this makes sense. Breaking it down to you have two or more time dependent tasks that depend on each other. The race condition happens when your expected “race” is won by an unexpected task. Let’s look at an example. All of these samples are written in ES2015 and can run in the latest version of FireFox.

This is a simplified example and I hope you never write code like this, but this is what is going on in your app.

Imagine if we didn’t have the setTimeouts in calculateZ. Step by step we would get the value of y, x, and then calculate z. No problem. The issue is when we introduce the async function setTimeout with random delay times. This makes the code to where we can’t just rely on the first setTimeout resolving first. Sometimes it will sometimes it won’t, so race condition! The value of z will depend on who wins the setTimeout race.

So how can we fix this? Since we can’t predict who will finish first we can chain the calls together to ensure we get y first before moving on to getting x and finally calculating z.

That works, but what happens if this was an ajax call that took a large amount of time? We have effectively doubled the time to calculate z because of the chained calls. This is where promises can run both calls in parallel improving our performance and removing the race condition.

Don’t worry if you haven’t see promises before. They are a great tool and now part of the language. I would suggest studying up on them.

Hopefully, this article clears up what a race condition is and how to solve them. In my personal experience race conditions never appear right away, they tend to sneak into the codebase when adding new features, modules, or data stores that rely on existing code for state. Once identified they can be solved by applying some form of chaining.

Good luck!

Flexbox bug Rotating Device with iOS Keyboard Up

Just discovered this bug today. It involves flexbox not rendering correctly when the user has the iOS keyboard up (they have focus on a text input or editable div) and then rotate the device. Here is a screenshot of what I am talking about.

flex box rendering issues

I am not sure where it comes from or how it is caused, but I do know how to fix it. Playing around in debug mode when you reset the window’s scroll:


flexbox snapped correctly into position.  Combining this with iOS’s orientation change event from the window:

window.addEventListener("orientationchange", function() {
        window.scrollTo(0, 0);
    }, 0);
}, false);

Gives you work around for the rendering issue. Hope this works for others.

Selenium User Extension: Unknown Command

So at work we are setting up a selenium RC 1 grid. We decided to use RC1 and not web drivers since we can setup user-extensions to create locations and custom actions for our QA team.

We’ve slowly got the grid running with our python test cases running the client drivers. Somewhere in the setup (we still don’t know the cause) our user extensions weren’t working anymore. We would receive the Unknown Command error from the selenium nodes. Testing on the ide confirmed we had the user extension correctly written because they would run in the ide.

After some research I came across Stuvel’s blog post about the same issue. For some reason this fix didn’t work for me. So after some digging around in the selenium source I came up with a slight modification to Stuvel’s fix, but the concept of what is happening is the same.

//This is a fix to get the user-extensions working for RC.  The check is to prevent a runtime error in the IDE
//since the IDE does not contain command factory.

Place the above code at the bottom of your user extension file. Hopefully this works for you as it did for me. Let me know how it goes in the comments.

Getting Rain Fall Inches in Python

Rain Study 2 © by amandabhslater

Currently my wife and I are working on the house and decided to redo the front and back yards; they are what we love most about our house. We hired someone who knows a lot more about plants to help pick out what to plant and where. She has come up with some fun and neat ideas including lots of ferns, which I love. Georgia gets lots of rain in the fall, winter, and spring but summers can be very hit or miss. So our landscape architect gave me a rule for watering.

If the rainfall has been less than 1 inch in the last three days then water the garden. Wait three more days and repeat the same logic.

As soon as she told me this algorithm lights went off that this would work as great as a simple script that email’s me to water my new garden. I am also a new owner of a raspyberry pi (details later), which will work perfectly to do the monitoring and notifying.

Here is what I am currently thinking for the setup:

Python 2.7 using the following library’s

Here is what I have coded so far:

Created on Sep 12, 2012
@author: csimpson
import urllib2
import sqlite3
import datetime
from bs4 import BeautifulSoup
from bs4 import SoupStrainer
def fetchRainfall(station):
    print 'Retrieving rainfall from ' + station
    weatherData = urllib2.urlopen(BASE_URL+station)
    html =
    onlyTables = SoupStrainer(class_="contentData") 
    soup = BeautifulSoup(html.encode("utf8"), "lxml", parse_only=onlyTables)
    contentTable = soup.find(text='Precipitation:')
    contentTable = contentTable.find_parent('tr')
    inchStr = contentTable.find(class_='b')
    rainfall = float(inchStr.contents[0].string)
def recordRainFall(inches):
    date =
    iso = date.isoformat()
    print 'Station reporting ' + str(inches) + ' inches on ' + iso
    sql = "INSERT INTO Rainfall(Inches, Date) VALUES('"+str(inches)+"','"+str(iso)+"');"
    db = sqlite3.connect('rainfall.db')
if __name__ == '__main__':

fetchRainfall uses the urllib to get the html page from I limit my soup parsing to one contentData div on the site since it contains the actual data I care about. From there I found the first “Percipitation:” text node (note the second text node is the months total which is not what I wanted.) From there it was pretty simple the get the parent row and then from the parent dig back down to the reported inch level.

recordRainfall puts the inch level and date into a simple sql database for analysis. Note I configured the db and tables outside this script and if you want to run this example so will you.

This is just the start of the script, but I figured I should post this to give people ideas on how to get daily rain fall levels using python.

Future task include:

  • Setup a github repo
  • Setting up the logic for sending emails
  • Making it generic for all weather stations
  • Install scripts

The above script is current running as a cron job on my macbook at 11:55pm to collect the most recent rainfall levels for that day. I will eventually make it to were I can run the script on the next day, but get the rainfall levels for the previous day. This would allow me to collect the full 24 hours 0-24 data instead of data from 0 – 11:55. In Georgia 5 minutes can really be a 1/4 inch, so it is important.

Let me know what you find out about this script when you play around with it.

Another use for ‘this’

So just as I was looking over the lase post about ‘this’. I realized that I skipped one of the best uses for the infamous property of ‘this’. Enough talk, more actionscript (sorry terrible pun).

So imagine this. Lets say that we have class A which creates an instance of class B. Now lets say when want to store an instance of class A in class B so that you can call class A methods. For smaller apps this is can be an acceptable code structure. So how do you pass an instance of a class in that same class? You guessed it. this!

class A 
	private var b:B;
	public function A()
		b = new B(); //Creates instance of B class
		b.a = this; //this passes a reference of class A
		//to class B.  Now class B can call class A's
	public function myCoolFunction():Void
		//Magic happens here. :)

If you have any other handy uses for this (I’m sure there are), please let me know in the comments.

This is a good time to use ‘this’

I know for a lot of actionscript coders out there, especially beginners, ‘this’ in can be rather confusing. This issue can spark some pretty heated debates about this proper use. So before diving in here is a short explanation of ‘this’. In actionscript the object the code is currently running in is referred to as ‘this’. So lets say a class has a property myVar, putting this.myVar tells actionscript to look in the current object for the property myVar. Why do we need this? This doesn’t make any sense! Well look at the code below:

public var age:Number;
public function myClass(age:Number)
   if(age > 0)
      this.age = age;

So lets say this is a class (myClass) with a public variable age. In actionscript you can declare local variables and parameters that only exist for the duration of the function. These local variables have the smallest scope, but have the highest preference, meaning if another variable is named the same the local variable, the local variable will be used instead of the class variable. In the above example we have a constructor the class myClass. Can you see were I am going with this? In the above constructor we have two age variables! The parameter is defined in the function. So to set the class variable we need to use ‘this’ to specify between the local variable and the class variable.

This example is the only the real time that you need to use ‘this’, of course this is only my opinion. What do you think? Coding vets how do you feel about ‘this’?

What makes you a good Developer? Part 1.

Ya, coding conventions!

(for the OCD developer)

  1. Follow coding conventions in your projects. That way you write clear and concise code. The problem is there are many conventions. In reality “conventions” is really a code word for someones arbitrary opinion on how to write neat code. So…which one do you follow? It doesn’t really matter; just follow one. Adobe recently lays one out and I can agree with most of it.  It is not complete and just because it is by Adobe does not mean it is the end all be all.

    While reading the document, I couldn’t help but feel like I was being scolded by my parents. Take a look:

    Do this:

    public function set label(value:String):void

    Not this:

    public function set label(lab:String):void
  2. Stick to those conventions!  I have to admit it is hard but practice it all the time.  Remember this is not the fun part of Flash & Flex development and it never will be but make it a habit.
  3. Lastly, you will eventually run into someone who doesn’t agree with your conventions.  In that situation just think about my first point.

Now time for me to go back to my old code and see what mistakes I’ve made.

Interactive Forest

From my previous post, animation.Float, I had the basic example of the animation class that I wrote to simulate dandelion seeds floating in the wind.  Well I had some free time this weekend and decided to keep my AS3 skills sharped and went on to add interactivity!    Depending on the location of your mouse will vary on the speed of the wind blowing the seeds around.  Farther away you go from the middle the faster the wind gets.  The interactivity is also directional and when you click on one of the seeds they disappear.

The Float class was one of the very first classes that I wrote on my own. Pretty much after I got done reading a book about OOP in AS2, I started this class.  Looking back now, it was pretty rough.  To add in the interactivity and to port the class over to AS3, I pretty much gutted the whole thing and started new, but it is neat to see that I have come a long way in such a short time.

Now the seeds are in a new Dandelion class that extends Float. Float contains a wind object which is shared among the other instances of dandelion seeds (kind of like a singleton, not really fond of them personally, but that is a different post).  After that is was simple to add in the required mouse detection class and update the wind velocity based on the mouse position.


There are still a few bugs left, if you are in FireFox switch to another tab and then come back.  Also I want to enforce the wind velocities a little better in case the mouse position is too extreme.  To enhance it I want to make it 3D by splitting the picture into layers and having the seeds go between the tree.  The 3d would also have the smaller seeds be removed from the stage earlier to make it look like it landed in the background of the image.

[UPDATE]: Github Repository for the Interactive Forest

Licensed under Creative Commons, so feel free to use them in your project and if you do please let me know.