FightSkillz.com - Life, Code, & Idiocy
It's really irritating when you're searching for OGG Vorbis support in the iOS 4 version of WebKit and a tech reporter's last name is Ogg. 2 days ago

Code

Weird Flex Error #2006

Saturday, July 10th, 2010

I was getting this weird error whenever switching from a given state to it's parent state in a Flex 3.5 based project.

RangeError: Error #2006: The supplied index is out of bounds.
	at flash.display::DisplayObjectContainer/addChildAt()
	at mx.core::Container/addChildAt()
	at mx.effects::EffectManager$/removedEffectHandler()
	at Function/http://adobe.com/AS3/2006/builtin::apply()
	at mx.core::UIComponent/callLaterDispatcher2()
	at mx.core::UIComponent/callLaterDispatcher()

It threw me for a minute because I hadn't made any changes to effects since I last tested the application and I couldn't see any connection between the code I had just written and any effects in the app. But after hunting around I found the culprit. There's a set of components in a Canvas that gets removed when moving to the parent state. What I had done was separate those components into two Canvases(Canvi?). For whatever crazy reason the new second Canvas can't have a RemoveEffect. The code works fine if just the first Canvas has it, but if both or just the second Canvas has it then it throws that error.

side note: the reason it took me a while to find the source of the error was because I copy/pasted the canvas declaration only changing the id, and I forgot that there was a removedEffect associated with it.

But wait there's more. The reason I split the components into two distinct Canvases was so I could position one below and the other on top of a third major component in z-space. The solution was to add the first Canvas as a "firstChild" and the second Canvas as a "lastChild". That it seems was the problem. In mxml when changing states you apparently can't add a firstChild before adding a lastChild. so I copy and pasted the first Canvas below the second one, so that all the lastChild additions occurred before all the firstChild additions and voila, presto, it works.

The reason is that when you move from a state back to its parent state it follows the order in which you add components in the state declaration to remove them. If the first component you add is added as a firstChild then that get's removed first changing the indexes and number of children of the parent container. I guess the underlying state changing function already calculated what the lastChild index was, so when trying to remove a Child with the pre-calculated index of lastChild it triggered an index out of bounds error.

Flex Skins, Registration Points, and Illustrator CS5

Friday, May 14th, 2010

In Illustrator CS4 it was really easy to make Flex Skins. You just go to File -> Scripts -> Flex Skins -> Create Flex 3 Skin, choose the components you want to skin - optionally give it a style class name, style it, use the same menu to export for Flex, use the Flex Builder skin import feature which creates or adds to your CSS file and blah blah blah. If you want me to do a tutorial on that just comment and ask.


In Illustrator CS5 they've updated the way registration points work. Flex 3(halo) skins require that the registration points be in the top left of the symbol. Illustrator CS5 defaults to a center registration point, so when you open your CS4 Illustrator skin file in CS5, it updates the registration point mechanism and defaults all your registration points to the center. Don't hulk-smash your computer just yet.

Another key difference with CS5 is while you get finer registration point control, it takes more work to move the registration point after the symbol is created. Say you've opened your CS4 created Flex 3 skin in CS5 and your registration points have been centered. There are a bunch of ways to edit the symbol. You could double click on the the symbol instance, or the symbol in the symbol pane, or click Edit Symbol at the top. Once editing the symbol, you'd need to drag your symbol around - make sure you get all the layers - positioning it rather than the registration point and don't forget to move the 9-slice guides. This process get's messy fast, it's time consuming, and it'll be hard to get the registration point and guides exactly where you want/need them. It's aggravating that there isn't a faster way to do it, and that in converting the file to work with CS5 it doesn't keep the registration point locations. So if you know a better faster way let me know. Until then here's the fastest way I've found to move all your registration points back to the top left.

  1. First Save as your skin file, you can use the same filename but will get a dialog to save it as a CS5 compatible file
  2. Click on the symbol instance, ie: the Up skin for a button, make sure you've got it selected on the artboard
  3. Click on the Symbol Options button in the Symbol pane
  4. Copy the name to the clipboard (ctrl/option + c)
  5. Click Cancel
  6. Click the Break Link button in the Symbol pane
  7. Make sure the correct symbol is still selected in the Symbol pane, the selection may have jumped to the top left symbol in the list
  8. Click on the Delete Symbol button in the Symbol pane
  9. Delete the symbol, if it tells you there are other instances then take special care and double check that the correct symbol is selected; due to the nature of a flex 3 skin there should only be one instance of each symbol. It's not impossible to have multiple instances, but you would know if you created them.
  10. Click on the New Symbol button in the Symbol pane
  11. Paste the name you have in the clipboard (ctrl/option + v)
  12. Select the top left corner for the registration point
  13. Tick the box for Enable Guides for 9-Slice Scaling
  14. Click Ok, and repeat for every other symbol
  15. Now you can save, backup with DropBox, export as a Flex 3 skin, and finally it's time...
  16. Hulk-SMASH!!! SMASH! this really should have been automated in the import mechanism.. right?

 

click image to zoom

Adobe Flex/Air Bug – Serving Content via PHP

Monday, February 1st, 2010

I've been using a php script as a gateway to fetching certain content from a server, mainly mp3 files. There are a bunch of reasons for doing this, the main ones would be to be able to easily log which files are being accessed, when, and by who - and if you plan on creating widgets for your users to stream the content they upload to your site and they happen to put it on a heavily visited part of the web you can temporarily disable or limit that user's widget's access to content giving your other user's priority and preventing your server from crashing or being overworked.

So in the Flex/AIR app I've got a URLRequest that's used to load a Sound object. Instead of specifying the index.php it had been accessing http://domain.com?var1=blah&var2=blah. Usually this will redirect to the index.php sending it the post variables and letting it do it's thing and fetch the mp3. It works on Adobe AIR for Mac, it works in a browser on Mac/Windows. But in a URLRequest from Windows it doesn't work, confirmed for XP and 7. It doesn't just redirect to the /index.php file and drop the POST/GET variables, it actually just doesn't redirect anywhere, and you get an IOError. You'd think the redirect would be handled entirely by the server and transparent to the client, but it appears that for whatever reason, Adobe AIR on Windows just returns an IO Error.

Either way it's easy to fix, you just have to specify the index file in your URLRequest like so: http://domain.com/index.php?var1=blah&var2=blah.

Flex/Actionscript 3.0 Strip HTML Tags Function

Friday, January 22nd, 2010

I needed a function to strip out html tags from a text input, but still let me specify allowable tags.

Instead of spending time figuring out the regular expressions needed to pull it off and becoming a better programmer, I figured why repeat work someone else has probably already done.. I mean I could be a busy man. Anyway I found this great function on Flexer.info [link]. But after trying it out I noticed that the one tag I really really wanted to be parsed out iframe wasn't. It seems because I had specified i as an allowable tag it was also accepting iframe.

So with all due respect to Andrei, below is the revised function with the security hole patched.

All I changed was near the bottom where it determines if it's an allowable tag or not the reg exp was

<\/?" + tagsToKeep[j] + "[^<>]*?>

which allowed any character to follow the allowed tag as long as it wasn't a nested tag, which included frame following i. This will also support self closing tags.

 
// strips htmltags
// @param html - string to parse
// @param tags - tags to ignore
public static function stripHtmlTags(html:String, tags:String = ""):String
{
    var tagsToBeKept:Array = new Array();
    if (tags.length > 0)
        tagsToBeKept = tags.split(new RegExp("\\s*,\\s*"));
 
    var tagsToKeep:Array = new Array();
    for (var i:int = 0; i < tagsToBeKept.length; i++)
    {
        if (tagsToBeKept[i] != null && tagsToBeKept[i] != "")
            tagsToKeep.push(tagsToBeKept[i]);
    }
 
    var toBeRemoved:Array = new Array();
    var tagRegExp:RegExp = new RegExp("<([^>\\s]+)(\\s[^>]+)*>", "g");
 
    var foundedStrings:Array = html.match(tagRegExp);
    for (i = 0; i < foundedStrings.length; i++)
    {
        var tagFlag:Boolean = false;
        if (tagsToKeep != null)
        {
            for (var j:int = 0; j < tagsToKeep.length; j++)
            {
                var tmpRegExp:RegExp = new RegExp("<\/?" + tagsToKeep[j] + " ?/?>", "i");
                var tmpStr:String = foundedStrings[i] as String;
                if (tmpStr.search(tmpRegExp) != -1)
                    tagFlag = true;
            }
        }
        if (!tagFlag)
            toBeRemoved.push(foundedStrings[i]);
    }
    for (i = 0; i < toBeRemoved.length; i++)
    {
        var tmpRE:RegExp = new RegExp("([\+\*\$\/])","g");
        var tmpRemRE:RegExp = new RegExp((toBeRemoved[i] as String).replace(tmpRE, "\\$1"),"g");
        html = html.replace(tmpRemRE, "");
    }
    return html;
}
 

Length is Semi-Reserved

Monday, November 30th, 2009

I'm writing a Flex/AIR app that grabs stuff from a database and displays it in an mx.controls.list. Interacting with it you can switch the list mode, which changes the visibility of certain controls in the itemRenderer. There are currently 20 items in the dataProvider, about 8 are displayed at any given time. I noticed that switching modes - and by doing so waiting for validateList() to run, took incrementally larger amounts of time for each of the first 3 items that were in view. So if you scrolled down one item and switched modes it was a bit faster, and if you scrolled past the first 3 switching modes became instant as it should be.

After looking over the same possibly relevant lines of code several times, reading up in detail of how the validateList() cycle works and getting into the nitty gritty of list classes I realized the problem was on the database side. I had a column named length. At first I thought there was an issue where I'd set the column type as a floating point number and maybe actionscript was having a time converting it or dealing with it in an object - there's no actual reason why I thought this, but the performance issue was not noticeable if the floating point number was smaller than 10,000.

Fortunately after only a few hours time wasted I, the spaz writing this, realized that the length column was being interpreted in actionscript as the length(ie: number of children/values) of the object. So say length was set to 100,000, for every item in the list it would have to create and analyze 999,992 blank values - creating space in memory for each one, along with the 8 actual values pulled from the database.

Furthermore when I referenced the item.length value while technically the value pulled from the database, was really the number of children in the object. The small robots that live inside my computer and make it work must have though I was bananas.

I'd like this to be my formal application for the prestigious Leader of the Idiots, but since I'm obviously not equipped with the basic skill set to do anything(read: dressing oneself, remembering reserved names) I'll rely on some kind soul reading this to file the application for me and submit it to the proper authorities.. thanks.

Flex: Variables, Anonymous Functions, and For Loops

Wednesday, September 23rd, 2009

I just ran into some weird behaviour involving a for loop, some variables, and a bunch of anonymous functions. This is in Actionscript 3.0 using Flex SDK 3.4 and current Google Maps API(as of the date of this post&mdash I read somewhere they're rolling out a new version although it's not really relevant for this post)

So below I have a function that loops through the xml result of an http service, for each item in the result it creates a marker on a map and gives that marker a click event. When you click on a given marker I want a window to pop up with the name and description of that location, so the following is the code you'd expect to write. For simplicity sake you can keep an eye on the i:int variable which will help clarify the issue.

 
//trace(i) will always output total items in the xml result
private function processResult(event:ResultEvent):void {
 
  var total:int = event.result.data.item.length;
 
  for (var i:int = 0; i<total; i++) {
    var item:Object = event.result.data.item[i];
    //this will create the marker object
    var marker = new Marker(new LatLng(item.lat, item.lng), new MarkerOptions({fillStyle: {color: 0xEE9C21}, radius: 7, tooltip: item.name}));
 
    marker.addEventListener(MapMouseEvent.CLICK, function():void {
      //this will open an info window when the marker is clicked
      map.openInfoWindow(map.getCenter(), new InfoWindowOptions({hasTail: true, tailHeight: 5, hasShadow: true, title:item.name, contentHTML:item.description}));
      trace(i);
    	});
  map.addOverlay(marker);
  }
}
 

Now what you'll find with the above code is that no matter which placemark you click on, they will all show the same name and description. Say that there are 5 items in the xml result, tracing i will output the number 5.

If you're new to programming, yes i will be 0 during the for loop's first run. Yes having 5 items and starting at 0 means it should be 4 for the last run, but the value of i increments one last time to make the i<total condition false before it exits the loop, so essentially it uses the final value of i for all the placemarks which is 5.

I can't see any reason why this should be happening other than language or framework immaturity.

The solution; or I should say the easiest, quickest solution, is to create an external function for marker creation that is called by the for loop, which for clarity's sake will only contain the part that's required to explain the concept and make it work ie: adding an event listener to the marker, but in the real world should have all the code necessary for creating a marker - that way you'd have an independent marker creation function you could call from anywhere in the application. Below is the working code:

 
//trace(i) will output the correct index depending on the placemark clicked
private function processResult(event:ResultEvent):void {
 
  var total:int = event.result.data.item.length;
 
  for (var i:int = 0; i<total; i++) {
 
    var item:Object = event.result.data.item[i];
    var marker = new Marker(new LatLng(item.lat, item.lng), new MarkerOptions({fillStyle: {color: 0xEE9C21}, radius: 7, tooltip: item.name}));
 
    //call external function and pass variables to it
    placeMarkerAddClickEventListener(marker, item.name, item.description);
    map.addOverlay(marker);
  }
}
 
//external function
private function placeMarkerAddClickEventListener(marker:Marker, name:String, description:String):void {
 
  marker.addEventListener(MapMouseEvent.CLICK, function():void {
 
    map.openInfoWindow(map.getCenter(), new InfoWindowOptions({hasTail: true, tailHeight: 5, hasShadow: true, title:name, contentHTML:description}));
    });
}
 

Wordpress Automatic Upgrade

Tuesday, July 21st, 2009

For a few versions now Wordpress has let you automatically upgrade it and your plugins. Every time an update would come around I'd try figure out how to activate it and fail. As a last resort you can specify ftp/ftps details and have it upgrade that way, but who wants to setup an ftp server right?

Anyway, it turns out that aside from setting file permissions like everyone tells you to do to setup the automatic upgrade feature, the actual missing piece of the pie was to give ownership of the entire wordpress directory to the owner of the apache process.

So, step 1: open up terminal and ssh to your server(use your ip address instead of all those 9s)

# ssh root@99.99.999.999

# [password]

step 2: Now you're running a remote session to your server, open top

# top

step 3: Expand the window and look for processes name httpd or apache2, chances are they're owned by the user www-data. Say you have wordpress installed in /var/www/, enter in:

# chown -R www-data /var/www

The above command changes the ownership of /var/www, which is a folder, recursively so it goes through and changes ownership of all the files and folders below it, and it's changing ownership to the user www-data.

Now log into wordpress and try auto upgrade.

Adding Another Sidebar to Wordpress

Monday, January 5th, 2009

I'm using Wordpress 2.7 at the time of writing, but my theme is modified from the default theme from around version 2.5. My current sidebar uses the widgets feature with some manually added stuff, sort of a lazy way of customizing it. I keep adding to it and now I need a second one, which will inevitably require a wider site but my analytics shows most people these days have more than the formerly standard 1024x780 screen resolution and so it should be fine.

So if you're in the same boat as me, hand me that paddle, I'll show you what I did.

In your theme folder open your functions.php file, and find the following code:

 
if ( function_exists('register_sidebar') )
register_sidebar(array(
'before_widget' => '
<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>
 
',
'before_title' => '
<h2 class="widgettitle">',
'after_title' => '</h2>
 
',
));
 

You may not have the above code, instead look for:

 
if ( function_exists('register_sidebar') )
register_sidebar();
 

In either case we want to replace it with the following:

 
if ( function_exists('register_sidebars') )
register_sidebars(2);
 

Note: changed sidebar to sidebars, and the number 2 indicates the total sidebars we want.

In your theme folder open your index.php file, and find the following code:

 
<?php get_sidebar(); ?>
 

Or depending on your theme:

 
<?php include(TEMPLATEPATH."/sidebar.php");?>
 

Since I want to add another right sidebar, add the following code below:

 
<?php get_sidebar('2'); ?>
 

Note: Anything between the ' ' is representative of the new file you have to create called in this case sidebar-2.php

Or in the later case for consistency you can instead add:

 
<?php include(TEMPLATEPATH."/sidebar-2.php");?>
 

The call for your sidebars in your index.php file should now look something like the following:

 
<div id="sidebar">
<?php get_sidebar(); ?>
<?php get_sidebar('2'); ?>
</div>
 

In my case since I already had a sidebar, the "sidebar" div was inside sidebar.php. As you can see from the code above, it needs to be in the index.php file. Change the div id in sidebar.php to "sidebar1", and in sidebar-2.php to "sidebar2".

Note: At this point you should see the two sidebars, and be able to add widgets or custom php. But it will likely appear below the other sidebar.

Since I have css rules for sidebar, and not sidebar1 or 2, I can just re-assign some of the rules to sidebar 1, create a similar set for sidebar two and adjust the overall body and content width. This all depends on your theme and where you want your new sidebar.


Flex 3-RegExp: Find Urls In Text And Html

Thursday, December 18th, 2008

There are a number of situations where you'd want to grab the urls from a block of text. For example you may be loading in some external or dynamic data and want to make the links clickable, or change their colour. Regular expressions are used in a multitude of languages; they define patterns that can be matched against a string, thus certain key characters used in defining a RegExp have to be escaped so they are interpreted as special characters like \d matches any digit. In Actionscript, you can define a RegExp by either wrapping it in double quotes "", or forward slashes//. In each case you would have to escape any characters that match the wrapping in addition to the characters that need to be escaped in the actual pattern. Further more Actionscript requires you to separate out the last part of the regular expression, called flags, and insert it as the second argument when defining a new RegExp object.

Here's how you find a url in text or html:

var str:String = new String('This is a url www.fightskillz.com, and this is another one: <a href="http://chalk-it-out.com">Chalk It Out</a>');
var reg:RegExp = new RegExp("\\b(((https?)://)|(www.))([a-z0-9-_.&amp;=#/]+)", 'i');
var result:Object = reg.exec(str);
trace(result[0]);

First off if you're new to Flex/Actionscript you have to copy and paste this into a function and the variables created will only be accessable within that function while it's running as they are created and destroyed as it runs. If you wanted more permanence you'd just define the variables outside the function.

Now Let's break it down. The first \ is used as a character escape for Actionscript. In actionscript when defining a string within double quotes you'd escape a double that's part of the string like this "Look at this double quote \"". \b searches for a word boundary ie: a whitespace, or the beginning or end of a string.The next part ((https?)://)|(www.)) defines the first part of a 'word' that passes for a url. It's made up of two substrings, the first looks for http, the question mark deems the preceding character optional, so it'll match to https as well. It then looks to see if the protocol is followed by ://. The | character means OR, so if there is no protocol specified, it checks for (www.). Next we have [a-z0-9-_.&=#/] which is a list of characters a to z, 0 to 9, and various others commonly found in urls. This is followed by a + which instructs the pattern to match the preceding list of characters until it can't anymore. It can't anymore when it reaches whitespace, a single or double quote, brackets, or any other non-url character. Finally the RegExp flag i informs the pattern to be case insensitive.

reg.exec(str); executes the pattern on the specified string and returns the results as an array. Since the example is only designed to match the first url it encounters and then stop, the array will only have one result. The method reg.exec(str) is interchangable with str.match(reg)

Convert Milliseconds to Time (H:M:S)

Tuesday, December 9th, 2008

Converting milliseconds to a time string can be a pain, especially when you're measuring something dynamic. In most languages I've come accross the Date object is calculated by the number of milliseconds that have passed since Jan 1, 1970. Because the different parts of a date are based on different bases ie: 60 minutes in an hour, 24 hours in a day etc. It's a lot easier to get the milliseconds passed since Jan1, 1970 and work with that value. This only works if you want to get the difference between two dates. If you were to subtract two dates(expressed as milliseconds) and get 432000000 milliseconds(5 days), then convert that to a Date object, the code would interpret 432000000 as Jan 6, 1970.

In another scenario I was just writing a podcast player in Flex 3/AIR and wanted to convert the Sound.length and SoundChannel.position values, both of which are measured in milliseconds, and display the length and current position of the episode in formats that would make sense. So I wrote a generic function that accepts milliseconds as an argument and returns the formatted time string.

  /**    Milliseconds to Time String in Flex 3              **/
  /**    Author: Yoav Givati [http://fightskillz.com]       **/
 
public function fnMillisecondsToTimeCountUp(time:Number):String {
 
	//calculate playtime from milliseconds
	var h:Number = new Number(Math.floor(time/1000/60/60));
	//minutes left shows total minutes left plus hours, 1h5m = 65mins
	//so we subtract the amount of 60's added by the hours to get just minutes
	var m:Number = new Number(Math.floor(time/1000/60)-(h*60));
	//seconds left
	var s:Number = new Number(Math.floor(time/1000)-(m*60));
 
	//create string variables
	var hours:String;
	var minutes:String;
	var seconds:String
 
	//make sure minutes and seconds are always two digits
	if(m.toString().length == 1) {
		 minutes = "0"+m;
	} else {
		 minutes = m.toString();
	}
 
	if(s.toString().length == 1) {
		seconds = "0"+s;
	} else {
		seconds = s.toString();
	}
 
	//if hours or minutes are 0 we don't need to see them
	if(h == 0) {
		hours = '';
		if(m == 0) {
			minutes = '';
		} else {
			minutes = minutes+":";
		}
	} else {
		hours = h+":"
		minutes = minutes+":";
	}
 
	// after 1 hour passes the seconds become 4 digits long
	// the last two of those digits represent the actual seconds
	seconds = seconds.slice(seconds.length-2, seconds.length);
	return hours+minutes+seconds;
 
}

You'll notice that I'm using Math.floor(), it's crucial that you round down, because the way the hours are being calculated for example, rounding up would show one hour had passed after only a fraction of an hour, just rounding up the minutes or seconds would cause everything to be out of sync and the math would be concussed. For those of you who are confused I should clarify that Math.floor(1.8) would return a value of 1 and Math.ceil(1.3) would return a value of 2, the term 'round' is probably a misleading. If you were using this function to count down instead of up, you would use Math.ceil()(although still not for the hour value), you essentially want to stay on the 'other side' of the minute or second for as long as possible.