May 11, 2012

OAuth 2.0 Library for ActionScript

Here at Adobe, we’ve been working really hard recently on our latest big project: Adobe Creative Cloud. For anyone that is unfamiliar or wasn’t able to attend our latest MAX conference, here is how we describe the project, straight from our press release

“Adobe Creative Cloud reinvents creative expression by enabling a new generation of services for
creativity and publishing, that embrace touch interaction to re-imagine how individuals interact with
creative tools and build deeper social connections between creatives around the world.”

-Kevin Lynch, CTO, Adobe Systems

In a nutshell, Creative Cloud is really an ecosystem that includes a multitude of applications for various devices that facilitate creative workflows, all backed by a cloud storage solution. Now that I’m done with the marketing, I can get to the good stuff :)

One of the major tasks that we’ve decided to undertake while doing this project was to switch from our current authentication system to a standards-based OAuth 2.0 authentication and authorization system. This was (is) a large undertaking and included building the likes of an OAuth 2.0 server, building and supporting new OAuth 2.0 compatible clients, as well as converting all existing systems to the new one. As part of this project, I ended up creating some OAuth 2.0 libraries that our touch-tooling applications use to interact with our system. While doing this, I realized that a lot of this work can easily be open-sourced and used with any OAuth 2.0 compliant service! And so, here we are!

 
Out in the Open
What I’ve created is exactly how it sounds: an OAuth 2.0 library for ActionScript. It abides by the OAuth 2.0 specification (version 2.15) and so is compatible with any OAuth 2.0 service! That includes services like Facebook Platform, Google APIs, Twitter APIs, and many many more.

 
What it Does
If you are unfamiliar with the OAuth 2.0 workflow, it is really quite simple…

  1. Your application makes a request to the server to get an access token.
    • An access token is what is used to access a protected resource, say, an API to post a status update.
  2. The user authenticates and authorizes the use of said protected resource by the application on behalf of the user.
    • For example, the user logs in and allows your application to post a status update on their behalf.
  3. An access token is granted and returned back to your application.
    • The access token will be restricted for use with only the specific permissions that were authorized in Step 2.
  4. You use the access token for whatever you want!
    • Using the same example, your application then uses this token to make a call to update your status.

The library is only in charge of steps 1-3. It will just get you your access token. What you do with it, and what API calls you make with it, are up to you.

 
How to Use It
This library is designed for use in mobile devices using AIR. Because of that, it makes use of the StageWebView object to display the user consent page (the form that the user must log into and authorize your application in Step 2). I’ve created a very simple mobile demo application that does exactly this. Here is the important part of the code…

// set up our StageWebView object to use our visible stage
stageWebView.stage = stage;
 
// set up the call
var oauth2:OAuth2 = new OAuth2("https://accounts.google.com/o/oauth2/auth", "https://accounts.google.com/o/oauth2/token", LogSetupLevel.ALL);
var grant:IGrantType = new AuthorizationCodeGrant(stageWebView, "INSERT_CLIENT_ID_HERE", "INSERT_CLIENT_SECRET_HERE", "http://www.mysite.com", "https://www.googleapis.com/auth/userinfo.profile");
 
// make the call
oauth2.addEventListener(GetAccessTokenEvent.TYPE, onGetAccessToken);
oauth2.getAccessToken(grant);
 
function onGetAccessToken(getAccessTokenEvent:GetAccessTokenEvent):void
{
	if (getAccessTokenEvent.errorCode == null && getAccessTokenEvent.errorMessage == null)
	{
		// success!
		trace("Your access token value is: " + getAccessTokenEvent.accessToken);
	}
	else
	{
		// fail :(
	}
}  // onGetAccessToken

You’ll see that the code is quite simple. First, we set up the StageWebView object. Then, we prepare the OAuth2 object by invoking its constructor with the appropriate values. In the third step, we attach an even-listener and make the call. Finally, in the event handler function, we handle the response. That’s it!

 
Demo
I’ve created a sample demo application that demonstrates the usage of this library. Using the same sample code as above (with the appropriate values filled in), connecting to Google’s OAuth 2.0 APIs, the sample app looks like this…

Take it for a spin and let me know what you think!

ActionScript OAuth 2.0 Mobile Demo Application

 
Code, please!
I’ve released the code under the Apache License, Version 2.0 and made it all available on GitHub! Please, fork and extend!

ActionScript OAuth 2.0 Library

That’s it! Hopefully some of you will find this project useful. And as always, I love hearing from you so let me know what you think! Happy coding =)

 
Update: As requested, I’ve removed the dependencies on the Flex framework so this library is now a pure AS3 library. Enjoy!

 
Charles

3:34 PM Comments (13) Permalink
February 20, 2012

ActionScript Notification Engine! Open-Sourced!

Last year, I posted about a side project that I was working on. Dubbed “Facebook Desktop“, it is essentially a notification engine that I built that would give you updates about your Facebook friends in real time! It became quite popular and I ended up building it out over the next year, pushing out 6 new releases in that time (0.80, 0.81, 0.82, 0.83, 0.84, and 0.85). Well, I’ve decided to contribute to the community and open-source the primary component in Facebook Desktop, the notification engine!

 
Project M6D Magnum Sidearm
That’s right, I codenamed my notification engine project “Project M6D Magnum Sidearm” (I have a weird naming convention for projects :p). Anyways, it is exactly how it sounds. It is a cross-platform, notification engine built on top of Adobe AIR. With a very simple interface, you can drop it into any AIR project and allow it to deliver messenger-style notifications to your users! Think Growl, but for all platforms :)

Mac:                                                                         Windows:

What can it do?
If you’re familiar with the Facebook Desktop project that this engine was built for, it supports all of the features that you see being used in that project, including…

  • Ability to display messenger-toast notifications as well as compact notifications.
  • Variable display length for notifications.
  • User-presence logic that detects when the user goes idle. If the user is away from the computer, notifications are held on-screen and queued for when the user returns.
  • Ability to replay the most five recent notifications.
  • Individual notification post settings, such as sticky, replayable, custom image, click URL, compact, etc.
  • Operating system detection to set logical default display locations for notifications for the various platforms (i.e. bottom-right on Windows, top-right on Mac).
  • Smart repositioning logic for extended length toasts.
  • Ability to see a summary notification when the user returns from idle after an extended period of time.
  • Support for changing notificaion images.
  • Custom styling which can be applied at run-time.
  • Optional notification sound.

These are just a few of the really cool features that we’ve built into this engine.

 
How can I use it?
Even though we’ve added a lot of powerful features to this library, using it is very easy! All you have to do is include the SWC (or source) into your project, and follow the patterns below…

// create engine with default settings
var notificationManager:NotificationManager =
	new NotificationManager("/assets/style/dark.swf",		   // default style
				"/assets/m6d-magnum-sidearm-50x50.png",	   // default notification image
				"/assets/m6d-magnum-sidearm-16x16.png",	   // default compact notification image
				"/assets/sounds/drop.mp3"		   // (optional) default notification sound
				NotificationConst.DISPLAY_LENGTH_DEFAULT,  // (optional) default display length
				NotificationConst.DISPLAY_LOCATION_AUTO);  // (optional) default display location
 
// now that we have an engine, let's create a notification and show it
var notification:Notification = new Notification();
notification.title = "Derek ► Jacobim";
notification.message = "What is this?  A center for ANTS?!";
notification.image = "/assets/images/profile/derek/avatar.png";
notification.link = "http://www.youtube.com/watch?v=_6GqqIvfSVQ";
notification.isCompact = false;
notification.isSticky = false;
notification.isReplayable = true;
notificationManager.showNotification(notification);
 
// we can also show notifications quickly using this API too
notificationManager.show("Derek Zoolander Foundation", "Now open!", "/assets/images/dzf-logo-50x50.png");

And that’s all it takes for you to add robust notifications to your application. You can even change many of the engines settings on the fly!

// let's change the default images, display length, and display location
notificationManager.defaultNotificationImage = "/assets/images/dzf-logo-50x50.png";
notificationManager.defaultCompactNotificationImage = "/assets/images/dzf-logo-16x16.png";
notificationManager.displayLength = NotificationConst.DISPLAY_LENGTH_SHORT;
notificationManager.displayLocation = NotificationConst.DISPLAY_LOCATION_TOP_RIGHT;
 
// we can even change the style and sound settings on the fly too!
notificationManager.loadStyle("/assets/style/light.swf");
notificationManager.loadSound("/assets/sounds/bing.mp3");

For those of you that want all the details, you can check out the ASDocs here.

 
Demo
I’ve also created a sample demo application that you can install and see the engine work in real time! It has an interface like this…

…where you can quickly test out all of the features of the engine! Take it for a spin and let me know what you think!

Download Notification Engine Test Console

 
Code, please!
I’ve released the code under the Apache License, Version 2.0 and made it all available on GitHub! Please, fork and extend!

ActionScript Notification Engine on GitHub

That’s it for now! Hopefully some of you will find this project useful. And as always, I love hearing from you so let me know what you think! Until next time, happy coding =)

Charles

1:56 PM Comments (9) Permalink
December 16, 2011

Diff Library for ActionScript

I was working on an interesting automation project here at Adobe recently. In short, we wanted to have a utility that shows a particular set of configurations and settings on our various servers and indicates to us if any of the servers are different from the rest, configuration-wise. Sounds simple, right? Sure! So, I thought it would be cool to enhance this a bit and instead of just indicating that yes, there is a difference, I would indicate exactly what that difference was.

Since I’m working predominately with text files, the first thing that came to mind was a diff algorithm. (D’uh!) The front-end for the tool that we use is built in Flex, and so I started looking for a diff algorithm implementation in ActionScript. No luck. Guess I’ll have to write my own :\ I started doing some research on the various approaches to diff algorithms and came to the consensus that the Myer’s diff algorithm[1] is widely accepted as the best general-purpose diff algorithm around. After about 6 pages into the research paper, though, I realized it would take too long to grok this all and implement it from scratch. So, instead, I found an implementation of the Myer’s diff algorithm and ported it to ActionScript. A few hours later, it was done!

As you can tell from the example above, text additions are green, and omissions are red. Any text that is the same remains black. And that’s it!

 
Usage:
The usage is quite straightforward, too. There is really only one API, diff(), and it takes two parameters, the before-text and after-text. Done!

var diffs:Array = new Diff().diff(beforeText.text, afterText.text);

The result that you get back is an Array of the different operations that it took to go from the original string to the modified string. You can easily use this to display the differences in whatever way you want!

 
Code:
The code is too long to post here, but you can find it in my GitHub project -> https://github.com/charlesbihis/actionscript-diff

 
Enjoy!

 
Charles

[1] “An O(ND) Difference Algorithm and Its Variations” by Eugene W. Myers

3:16 PM Comments (1) Permalink
May 18, 2011

Facebook Desktop – We’re international, baby!

Some of you might remember a side-project of mine that I announced here which I called Facebook Desktop.  In short, it was a small application that I initially wrote for myself to help me stay in touch with my friends and family through Facebook.  It would sit in my system tray or dock and quietly push messenger-style toast notifications to my screen whenever something happened in my Facebook stream.  Neat, huh?  I thought so.  So, I built it out and eventually released it as a free app for everyone to use!  Since then, it’s actually picked up quite a bit of steam and now enjoys thousands of users from all over the world!

Pleasantly Surprised
I’ve had a couple of releases since I first announced it, but this latest release is special and so I wanted to mention it here.  The popularity of the app, especially overseas, took me by surprise.  Considering this started out as a small utility I built for myself over a weekend, I didn’t anticipate it being used overseas.  But now, it’s actually used in over 20 countries all around the globe!  In fact, the bulk of our users are overseas!  After noticing this, I made the decision to devote the entire next release into adding language support for all of our international users.

Technically, localizing the application wasn’t a problem (I’ve had some experience in the area).  The bigger problem was actually getting all of the text I use in the app translated to all of the various languages I wanted to support.  Then, someone posted a beautiful message on our Facebook application page.

“Are you adding support for German?  If so, I volunteer to translate!”

Shortly after, a comment: “Me too, for Italian!”.  And another: “I can do Hindi”.  That’s when it hit me…crowdsourcing!

The Power of the Community
I’ve never done it before, and there are plenty of ways that it can blow up in my face, but it was obvious to me that our users wanted it, but more importantly, were willing to help make it happen!  So, I took advantage of it!  The next day, I posted a message to our page asking if there is anyone willing to help translate Facebook Desktop in their native language.  The response was amazing!  At the end of the day, we had over 30 responses with people volunteering to translate in over a dozen languages!

I couldn’t ignore this, and so I took everyone up on their offer and started getting all of the text translated.  A couple of months later, a bit of coding, and a lot testing, it’s released!  Facebook Desktop v0.84 went live last night at midnight with support for a whopping SIXTEEN languages.

Together is Better
This version of Facebook Desktop could not have been accomplished without the help of the community.  Plain and simple.  On top of that, engaging with the users in this way made this release that much more fun too!  In the future, I’ll definitely be looking to involve our users more.  It’s better for them, it’s better for me, and it’s better for the app!  To infinity, and beyond!

 

Charles

10:18 PM Comments (0) Permalink
May 3, 2011

Relative Time Library for ActionScript

While working on a side-project of mine, I came across the need to display dates and times as relative instead of absolute. You know, saying “two hours ago” instead of “Mon Jan 5 17:24:33 GMT-0700 2011″. Since the web is going real-time these days, it just makes sense. Besides, everyone’s doing it, so it must be good! Anyways, I wrote a library (really, just a simple class) that you can use to do this with ActionScript. It’s really quite simple, but since I couldn’t find it anywhere else, I thought I’d contribute it here for everyone to use too. Here it is in action…

 

If you’re wondering, I’ve tried to follow the convention that Facebook uses for what format to display and when. Twitter has a very similar format, but I decided to go with Facebook’s. Also, if you notice, my library can handle times in the future as well as times in the past. Here’s how to use it…

Usage:

Once you’ve added the library to your project, it’s really quite easy to use. Just call any of the two available APIs and pass in a date or two and you’ll get back the relative time string. Done!

var relativeTime:String = RelativeDate.getRelativeDate(firstDate, secondDate);
var relativeTime:String = RelativeDate.getRelativeDateFromNow(someDate);

Code:
Finally, here is the code in all it’s glory!

package com.adobe.date
{
	import com.adobe.utils.DateUtil;
 
	/**
	 * Utility class to help create human-readable Strings representing
	 * the difference in time from two different dates (e.g. "just now"
	 * or "2 hours ago" or "13 minutes from now").
	 *
	 * @langversion ActionScript 3.0
	 * @playerversion Flash 10.0
	 */
	public class RelativeDate
	{
		private static const SECONDS_PER_MINUTE:uint = 60;
		private static const SECONDS_PER_TWO_MINUTES:uint = 120;
		private static const SECONDS_PER_HOUR:uint = 3600;
		private static const SECONDS_PER_TWO_HOURS:uint = 7200;
		private static const SECONDS_PER_DAY:uint = 86400;
		private static const SECONDS_PER_TWO_DAYS:uint = 172800;
		private static const SECONDS_PER_THREE_DAYS:uint = 259200;
 
		/**
		 * Creates a human-readable String representing the difference
		 * in time from the date provided and now.  This method handles
		 * dates in both the past and the future (e.g. "2 hours ago"
		 * and "2 hours from now".  For any date beyond 3 days difference
		 * from now, then a standard format is returned.
		 *
		 * @param date The date for which to compare against.
		 *
		 * @return Human-readable String representing the time elapsed.
		 */
		public static function getRelativeDateFromNow(date:Date, capitalizeFirstLetter:Boolean = false):String
		{
			return getRelativeDate(date, new Date(), capitalizeFirstLetter);
		}
 
		/**
		 * Creates a human-readable String representing the difference
		 * in time from the first date provided with respect to the
		 * second date provided.  If no second date is provided, then
		 * the relative date will be calcluated with respect to "now".
		 * This method handles dates in both the past and the
		 * future (e.g. "2 hours ago" and "2 hours from now".  For
		 * any date beyond 3 days difference from now, then a
		 * standard format is returned.
		 *
		 * @param firstDate The date for which to compare against.
		 * @param secondDate The date to use as "present" when comparing against firstDate.
		 *
		 * @return Human-readable String representing the time elapsed.
		 */
		public static function getRelativeDate(firstDate:Date, secondDate:Date = null, capitalizeFirstLetter:Boolean = false):String
		{
			var relativeDate:String;
			var isFuture:Boolean = false;
 
			if (secondDate == null)
			{
				secondDate = new Date();
			}
 
			// the difference between the passed-in date and now, in seconds
			var secondsElapsed:Number = (secondDate.getTime() - firstDate.getTime()) / 1000;
 
			if (secondsElapsed < 0)
			{
				isFuture = true;
				secondsElapsed = Math.abs(secondsElapsed);
			}
 
			switch(true)
			{
				case secondsElapsed < SECONDS_PER_MINUTE:
					relativeDate = "just now";
					break;
				case secondsElapsed < SECONDS_PER_TWO_MINUTES:
					relativeDate = "1 minute " + ((isFuture) ? "from now" : "ago");
					break;
				case secondsElapsed < SECONDS_PER_HOUR:
					relativeDate = int(secondsElapsed / SECONDS_PER_MINUTE) + " minutes " + ((isFuture) ? "from now" : "ago");
					break;
				case secondsElapsed < SECONDS_PER_TWO_HOURS:
					relativeDate = "about an hour " + ((isFuture) ? "from now" : "ago");
					break;
				case secondsElapsed < SECONDS_PER_DAY:
					relativeDate = int(secondsElapsed / SECONDS_PER_HOUR) + " hours " + ((isFuture) ? "from now" : "ago");
					break;
				case secondsElapsed < SECONDS_PER_TWO_DAYS:
					relativeDate = ((isFuture) ? "tomorrow" : "yesterday") + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase();
					break;
				case secondsElapsed < SECONDS_PER_THREE_DAYS:
					relativeDate = DateUtil.getFullDayName(firstDate) + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase();
					break;
				default:
					relativeDate = DateUtil.getFullMonthName(firstDate) + " " + firstDate.getDate() + " at " + DateUtil.getShortHour(firstDate) + ":" + getMinutesString(firstDate) + DateUtil.getAMPM(firstDate).toLowerCase()
					break;
			}
 
			return ((capitalizeFirstLetter) ? relativeDate.substring(0, 1).toUpperCase() + relativeDate.substring(1, relativeDate.length) : relativeDate);
		}
 
		/**
		 * @private
		 */
		private static function getMinutesString(date:Date):String
		{
			return ((date.minutes < 10) ? "0" : "") + date.minutes;
		}
	}
}

Hopefully, this can help someone out there looking to do the same! Also, see the code in my GitHub repo!

Until next time, happy coding!

Charles

*Note: Shout-out to Joel Hooks for creating and sharing his awesome date-picker component!

11:03 AM Comments (0) Permalink
March 24, 2011

ActionScript Puzzler – The Joy of Millisecs

Note: This is the same puzzler that was featured in the March issue of the Adobe Edge newsletter!

It’s about that time again…time for another Puzzler! I’ve written a few before, in a couple of languages too, but this will be my first in ActionScript! I know I have a lot of Flash readers, so hopefully this will be extra ‘puzzling’ for you (see what I did there?). For those that don’t know what a Puzzler is, it is essentially a short problem used to demonstrate special cases or “features” of a particular language. Here is the format:

  1. Code – I introduce the code
  2. Question – I pose a multiple-choice question and you guess what the outcome is…think hard!
  3. Walkthrough – I walk through a reasonable explanation
  4. Answer – I tell you the real outcome (it might surprise you), and explain why
  5. Moral – How can we avoid making mistakes like this in our own code

Now that we all know what a Puzzler is, here is a simple ActionScript Puzzler:

Code:

// declare key dates
var now:Date = new Date();
var birthday:Date = new Date(1940, 06, 27); // Bugs Bunny’s birthday!
 
// save them as milliseconds since epoch
var nowInMs:int = now.getTime();
var birthdayInMs:int = birthday.getTime();
 
// get the difference to calculate Bugs’ age in milliseconds
var millisecondsElapsed:int = nowInMs - birthdayInMs;
 
// sanity check
if (millisecondsElapsed == now.getTime() - birthday.getTime())
{
	trace("What’s up, Doc?");
}

What does this print?

  1. Nothing
  2. “What’s up, Doc?”
  3. Throws an exception
  4. None of the above

Walkthrough:

Alright, it looks like we are just trying to compute Bugs Bunny’s age in milliseconds, from the time he was “born” until now. First, we create the key dates. We have now initialized to the current date (as in the date this program is executed), and birthday initialized to Bug Bunny’s birthday. We then go and save those times as milliseconds since epoch so that we can easily do some date math with these two dates. Next, we calculate the difference of Bugs’ birthday (in ms) from now (also in ms) which should give us the total milliseconds elapsed since he was born. Finally, we do a sanity check. In the sanity check, we essentially duplicate the math we’ve done previously: calculate the difference from Bugs’ birthday until now, in milliseconds. This should obviously be true, and so we trace “What’s up, Doc?” to the debug console.

 

*SPOILER ALERT – ANSWER BELOW*


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Answer:

The answer is a – nothing! How does this happen? Well, we must be skipping over the trace statement. That would only occur if the sanity check fails. But the sanity check does exactly what is done earlier on in the code…almost! The key error in this code is that there is an implicit narrowing type-cast! Where is it? Let’s take a look at the description of the Date class in the ActionScript 3 LiveDocs. In the documentation for the Date.getTime() method, we get the following function prototype:

  Method Defined By
   
Returns the number of milliseconds since midnight January 1, 1970, universal time, for a Date object.
Date

Date.getTime() returns a Number! And we are storing that number in an int. In ActionScript, a Number uses the IEEE-754 double-precision floating-point specification, and therefore can use 53 bits to represent integer values. Comparing this to only 32 bits used by int and uint, we can see that Numbers can be used to represent values well beyond the range of the int and uint data types. Because of this implicit type-cast, our millisecond time gets narrowed and loses precision! Now, knowing this, it is easy to see why our sanity check fails. Our int variable millisecondsElapsed does not, in fact, store the total milliseconds elapsed since Bug Bunny was born, but rather, it stores the total milliseconds elapsed since he was born, truncated to 32 bits. Therefore, the sanity check fails, the if-statement falls through, and the trace statement never gets executed.

Moral:

Although in some other languages, implicit narrowing type-casts cause warnings or even compilation errors, in ActionScript, they do not. So, whenever you are storing or working with numbers, be aware of the size of the numbers as well as the data-types floating around. Implicit casts do occur (and often, in any language), but implicit narrowing casts will go unnoticed by the compiler, and likely by you as well…until now :)

That’s it for this Puzzler! Hope you enjoyed! Happy coding!

 

 
Charles

actionscript-puzzler-the-joy-of-millisecs.zip (source code)

1:47 PM Comments (0) Permalink
February 23, 2011

Want to Localize Your Flex/AIR Apps? It’s Easy! I’ll Show You How…Again!

For anyone who is interested in localizing their Flex or AIR applications, I’ve written a very simple series that I’ve contributed to the Adobe Developer Connection.  As I’ve mentioned before, localization may seem like an enormous task, for any application, but the Flex framework provides great utilities to make this process surprisingly easy!  The articles are part of a two-part series which focuses solely on the task of localizing Flex and AIR applications using the Flex framework.  I’ve previously talked about Part 1, but now Part 2 is published and the series is complete!

Localization in Flex – Part 1: Compiling resources into an application
Localization in Flex – Part 2: Loading resources at runtime

Here is the end-product of the tutorial, which you can emulate for yourself in your own applications!

The series covers a variety of ways to attack the task of localization.  Different approaches have different advantages as well as disadvantages, but with the complete series, you will hopefully have a better understanding of what approach will suit your needs and your customer’s needs.

Until next time, happy localizing!

5:10 PM Comments (4) Permalink
February 17, 2011

C Puzzler – Give Me A Float

Time for another Puzzler! This time, let’s do a C Puzzler :) For those that don’t know what a Puzzler is, it is essentially a short problem used to demonstrate special cases or “features” of a particular language. Here is the format:

  1. Code – I introduce the code
  2. Question – I pose a multiple-choice question and you guess what the outcome is…think hard!
  3. Walkthrough – I walk through a reasonable explanation
  4. Answer – I tell you the real outcome (it might surprise you), and explain why
  5. Moral – How can we avoid making mistakes like this in our own code

Now that we all know what a Puzzler is, here is a simple C Puzzler:

Code:

// c-puzzler-give-me-a-float.c
#include <stdio.h>
 
int main()
{
	int x = 0.5 + giveMeAFloat();
 
	return x;
}
// c-puzzler-give-me-a-float-please.c
float giveMeAFloat()
{
	return 0.5;
}

Question:

What does this print?

  1. 0
  2. 1
  3. 1056964608
  4. it varies

Walkthrough:

There is a local variable, x, and it is declared as an int. It is being initialized to the sum of 0.5 and the value returned by the function giveMeAFloat, which is implemented in another source file. The function giveMeAFloat returns the float value 0.5, and so the sum of these two values is the float value 1.0. The variable x is an int, and so it will cast the value from 1.0 to 1. So, my answer is b, main returns the int value 1.

 

*SPOILER ALERT – ANSWER BELOW*


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Answer:

The answer is actually d – it varies! But, in practice, you will likely get c – 1056964608. How does this happen? Well, the astute observer will notice that in the source file containing our main function, there is no function prototype declaring the function giveMeAFloat. Because of this, and the fact that giveMeAFloat is implemented in another source file, then giveMeAFloat is *assumed* to return an int and not a float! If the method were declared and defined within the same source file, the compiler would detect this error and not complete the compilation. However, due to separate compilation, this cast goes unnoticed. And so, because of this ambiguity, depending on the compiler and the platform, how this value is treated and stored will vary from machine to machine! To better understand this, let’s look at the practical case where the answer is 1056964608.

  • This assumes that the program is being executed on a typical machine setup, with an x86 architecture running a current version of gcc (v4.x+)
    When the program is executed, within main, an int variable, x, is declared and initialized with a simple assignment expression that invokes giveMeAFloat. When giveMeAFloat returns, it stores the value 0.5 into the return register, eax. Since we are on a little-endian machine, this value is 0x3F000000. However, since the compiler is expecting to read an integer value, it interprets 0x3F000000 as an int and not a float, effectively loading the value 1056964608 (this is the decimal interpretation of the floating point hex representation of 0x3F000000…yikes!). Back in main, the value 0.5 gets added to this, resulting in the float value 1056964608.5. This subsequently gets assigned to the variable x. Since x is an int, this value gets cast and therefore truncated to 1056964608. And so main returns 1056964608.
     

As you can see, there are many factors that can affect the return value. In particular, what value the compiler stores into the return register (if anything), how that value is stored internally (endian-ness of the host machine), and how that value is subsequently read from the register (interpreted as int, or float, or other) all play a part. Due to all of these factors, the return value from main is effectively unpredictable, and should be treated as such (regardless of what the practical case would yield)!

Moral:

Given an arbitrary name that has not yet been previously declared, if the name is followed by a left parenthesis, it is defined to be a function and it is assumed to return an int. To prevent this, explicitly declare the function, either as a function prototype at the top of the source file, like so…

#include <stdio.h>
 
float giveMeAFloat();
 
int main()
{
	int x = 0.5 + giveMeAFloat();
 
	return x;
}

…or within the calling routine, like so…

#include <stdio.h>
 
int main()
{
	float giveMeAFloat();
	int x = 0.5 + giveMeAFloat();
 
	return x;
}

Now, there is no confusion, to yourself or the compiler, about the return-type of the function giveMeAFloat().

That’s been another C Puzzler! Hope you enjoyed! Happy coding!

 

 
Charles

c-puzzler-give-me-a-float.zip (source code)

Update: This post was corrected based on some feedback in the comments by Mihai. Thanks for the feedback, Mihai!

3:49 PM Comments (4) Permalink
January 26, 2011

My Adventure Writing My First Quine in Java

Today, I tried to write my very first quine. What is a quine, you might ask? Well, for those that don’t know, a quine is simply a program that takes no input but whose only output is the program code itself. Easy, right? That’s what I thought. This post is going to document my adventure writing my first quine in Java.

 

Trial and error

So, I need to write a program that outputs a program…itself to be exact. I didn’t think much of it, so I dove right in. Let’s take a look at my first pass…

public class Quine {
	public static void main(String[] args) {
		System.out.println("public class Quine {\n\tpublic static void main(String[] args) {\n\t\tSystem.out.println(\"...fuck");
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main(String[] args) {
		System.out.println("...fuck
 
*/

Fuck. This won’t work. As you can see, the problem quickly reveals itself. Essentially, there comes a point where you must print the code that you are using to print! (Even that sentence is a little confusing) This can easily degrade into an infinite loop. So, how do you overcome this?

You must write some code that you use to both store the characters
to be printed, but can ALSO be used to print itself!

I believe this is the main problem to solve when writing quines. Once you can get over this hump, the rest is simple! If you can figure this out, you’ve done 90% of the work. Really! So I started to tackle this problem, head on.

 

A string that prints itself

First, I did away with the System.out.println() method. Instead, I opted for the printf() method. With functionality very similar to the ANSII C printf() method, it has some powerful string manipulation features that will make this quine much easier to write (and read). Second, I tried to think of a way to write some code that printed itself. More specifically, I decided that I needed to figure out a way to solve the following code segment…

String s = "?";
System.out.printf(?);

What could I replace the question marks with such that it would output the string declaration itself, exactly, and nothing else? I thought about this for a while before I came up with a solution. Since I think that this step is the most important and requires the most thinking, rather than ruin it for you, I’ll let you think about it for yourself.

 

*SPOILER ALERT – ANSWER BELOW*


 

 

 

 
Willard Van Orman Quine - A Harvard Professor of philosophy for which the self-reproducing code concept was named after

Willard Van Orman Quine - A Harvard professor of philosophy for which the self-reproducing code concept was named after



 

 

 

 

After some head-scratching, I came up with…

public class Quine {
	public static void main(String[] args) {
		String s = "String s = %c%s%c;";
		System.out.printf(s, '"', s, '"');
	}
}
 
/* OUTPUT:
String s = "String s = %c%s%c;";
*/

There are many other solutions for this, but this is what I came up with. Now that I’ve got this figured out, all that’s left is filling in the stuff before and after.

 

All that’s left is everything

The self-reproducing code that I wrote above is essentially the middle of the program, and I’ve figured out a way to print it. Now, on to printing the stuff that goes before. This is quite a bit simpler than the first step, but not quite trivial. Again, here is another failed attempt…

public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {\n\tpublic static void main(String[] args) {\n\t\tString s = %c%s%c;";
		System.out.printf(s, '"', s, '"');
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {
	public static void main(String[] args) {
		String s = %c%s%c;";
*/

You’ll notice that hardcoding the line-feeds and horizontal tabs into the string doesn’t give us the right result. They get evaluated by the printf() twice. The solution to this is to make use of the variable arguments in printf() and reference those characters instead.

public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {%c%cpublic static void main(String[] args) {%c%c%cString s = %c%s%c;";
		System.out.printf(s, '\n', '\t', '\n', '\t', '\t', '"', s, '"');
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {%c%cpublic static void main(String[] args) {%c%c%cString s = %c%s%c;";
*/

Nice! Things are coming along, but the code is getting uglier.

 

Spring cleaning!

As you can see, we’re starting to get a lot of redundancy in the printf() call. My next step was to clean this up. Quine’s are all about reuse! The less code there is, the less code I have to worry about re-printing. So, I changed all of the arguments to printf() to be index-based instead, allowing me to reuse characters.

public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;";
		System.out.printf(s, s, '"', '\n', '\t');
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main (String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;";
*/

This is looking a lot cleaner now. Finally, let’s round this quine off by filling in the rest of the code.

 

Print the rest...easy! I think.

Again, this is quite a bit simpler than the previous steps, but not trivial. Another failed attempt…

public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;%3$c%4$c%4$cSystem.out.printf(s, s, ...fuck";
		System.out.printf(s, s, '"', '\n', '\t');
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main (String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;%3$c%4$c%4$cSystem.out.printf(s, s, ...fuck";
		System.out.printf(s, s, ...fuck
*/

We have hit the familiar problem of printing code that is used to print itself! This is slightly different, however. The difference is that we are trying to output characters that must be escaped in one output, but not in the other. There is a simple solution for this! Use the ASCII character codes instead! Replacing ‘”‘, ‘\n’, and ‘\t’ with their ASCII decimal equivalent codes, we are easily able to insert them into the string literal without them being interpreted by the printf() method, and without the need for escaping them. In the end, we get….

public class Quine {
	public static void main(String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;%3$c%4$c%4$cSystem.out.printf(s, s, 34, 10, 9);%3$c%4$c}%3$c}";
		System.out.printf(s, s, 34, 10, 9);
	}
}
 
/* OUTPUT:
public class Quine {
	public static void main (String[] args) {
		String s = "public class Quine {%3$c%4$cpublic static void main (String[] args) {%3$c%4$c%4$cString s = %2$c%1$s%2$c;%3$c%4$c%4$cSystem.out.printf(s, s, 34, 10, 9);%3$c%4$c}%3$c}";
		System.out.printf(s, s, 34, 10, 9);
	}
}
*/

Eureka! My very first quine! Try writing one for yourself! Feel free to share them with me in the comments, or through e-mail at charlesb[at]adobe[dot]com! I’d love to post them :)

Enjoy!

 
Charles

1:17 PM Comments (6) Permalink
January 13, 2011

Introducing “Facebook Desktop” – A Lightweight, Unobtrusive Notification Engine for Facebook Built on Adobe AIR

Disclaimer: Facebook Desktop is a personal project. It is not sponsored by or affiliated with either Adobe® or Facebook®.

Once upon a time, I was involved in a project here at Adobe called “Project San Dimas“. That project eventually grew into a full-fledged product called “eBay Desktop” which enjoyed some impressive success. I was lucky enough to be part of the protyping, designing, and launching of the very first version, and it was very exciting. More recently, I’ve thought about doing something similar. Introducing, “Facebook Desktop“!

So, what is Facebook Desktop?
Facebook Desktop is a notification engine that gives you updates about your Facebook friends in real-time! Whenever someone posts a story, comments on your photo, tags you in a status-update, whatever…Facebook Desktop will let you know. It gives unobtrusive messenger-style toast messages whenever you have a notification.

Why build Facebook Desktop?
I moved away from my home in Vancouver for work and so Facebook has been a great tool to help keep me in touch with everyone. I found, though, that the browser metaphor for the Facebook “stream” just wasn’t working for me. I didn’t like refreshing my home page constantly to see what people were up to. I also didn’t like keeping a browser open whenever I wanted to read some of my friends posts. So, I made a simple AIR app that hits the Facebook APIs, grabs the latest posts, and delivers them to me in an unobtrusive way. I ended up finding it so useful, I started adding more and more features, like the ability to pause/resume, replay missed notifications, update my status, etc. Eventually, I was encouraged by a friend to polish it up and release it for others to use, and so here we are!

Anyways, if you’re interested in trying it out, install it here:

http://www.facebookdesktop.com/

You can also keep up with the project and reach out to me on any of our community pages:

And definitely, let me know what you think! Your feedback helps me make Facebook Desktop better and better. Until next time, happy Facebook’ing ;)

 
Charles

3:52 PM Comments (22) Permalink