Perfect example of whats wrong with JS

This is from the Require.js library which is very useful, and solves a lot of find when using JS.

    //Alias for caja compliance internally -
    //specifically: "Dynamically computed names should use require.async()"
    //even though this spec isn't really decided on.
    //Since it is here, use this alias to make typing shorter.
    req = require;

…Really?

Use this alias to make your development time noticeably shorter by doing that? Are you really clocking out earlier? Calling it a half day most of the time after that huge time saver?

No it’s just a pointless and at worst confusing inconsistent modification to the code from only that point forward to anyone looking at it.

Another Example

This also irks me. I’m getting some error, and im trying to dive into the multi-thousand line (literally) file, and figure out whats going wrong / learn the module better. When I go to the line in question, i scroll up to find this:

 main = function (name, deps, callback, config, contextName, relModuleName) {
        //Grab the context, or create a new one for the given context name.
        var context, newContext, loaded, pluginPrefix,
            canSetContext, prop, newLength, outDeps, mods, paths, index, i,
            deferMods, deferModArgs, lastModArg, waitingName, packages,
            packagePaths;
 
        contextName = contextName ? contextName : (config && config.context ? config.context : s.ctxName);
 
 
/*********************/        
/*********************/        
/*********************/  
// What the freaking hell is s?       
context = s.contexts[contextName];
/*********************/        
/*********************/        
/*********************/        
 
        if (name) {
                        // Pull off any plugin prefix.
            index = name.indexOf("!");
            if (index !== -1) {
                pluginPrefix = name.substring(0, index);
                name = name.substring(index + 1, name.length);
            } else {
                //Could be that the plugin name should be auto-applied.
                //Used by i18n plugin to enable anonymous i18n modules, but
                //still associating the auto-generated name with the i18n plugin.
 
//				console.log(" context.defPlugin[name]", this);
                pluginPrefix = context.defPlugin[name];
            }
 
 
            //If module already defined for context, or already waiting to be
            //evaluated, leave.
            waitingName = context.waiting[name];
            if (context && (context.defined[name] || (waitingName && waitingName !== ap[name]))) {
                return;
            }
        }

What the hell is ‘s’? !! This left my struggling to find it by doing ctrl+f, for the most popular letter in the alphabet.

Seriously i waste so much time on this kind of junk when I code in javascript – it really takes the fun of it.

“Using JS.Class” or “Sharing a Class Between Node.JS and the Browser Part 2”

Just a quick snippet, but this is a much better way of sharing a class between Node.js and the browser. I also like this psuedo Class implementation much better than the Class.js thing, it always seemed a bit ghetto how you had to say.

The ugly way (i was using this before but it felt wrong)

var ServerGame = require('./ServerGame.js').Class;
 
var myInstance = new ServerGame();

There’s a better way!

/**
 * Animal.js
 * This is an example I created for us JS.Class
 * Mario Gonzalez | http://onedayitwillmake.com
 */
var init = function()
{
	return new JS.Class(
	{
		initialize: function(name) {
			this.name = name;
			console.log( 'Animal::initialize - ', name);
		},
 
		/**
		 * Cause the Animal to tell you what it likes (Testing JavaDoc)
		 * @param things What the animal likes
		 */
		speak: function(things) {
			return 'My name is ' + this.name + ' and I like ' + things;
		}
	});
};
 
// Handle Node.JS and browser
if (typeof window === 'undefined') {
	require('../lib/jsclass/core.js');
	Animal = init();
} else {
	define(['lib/jsclass/core'], init);
}

Ok, but now to use it in another file!

// Testing JS.Class
 
// bring it in
require('../client/js/scratchpad/Animal.js');
 
// use it
var animal = new Animal('Rex');
console.log('Animal', animal.speak("YELLING!!!") ); // Should output: Animal My name is Max and I like BARKING!!!

There you have it – so simple and soooo much cleaner!!

Cheap NYC Whiteboard

Whiteboards are pretty great. They save you a lot of time, you draw the connections between something or how it might work – whatever the flow is and right away you can usually many flaws in your logic or gaps to fill. If you’re like me, then you’ll still have many more once you implement it 🙂 – however, at least i can catch a few early mistakes.

More importantly they make whatever task you’re working on seem very important. After all it’s on a written on the board isn’t it?

Whiteboard NYC-Style

Living in NYC you learn to cobble together various things and make something out of it because space here is so limited. So this is a “whiteboard” I created using an acrylic picture frame I bought from Muji. It isn’t the cheapest but it comes with some nice hanging hooks, and two sides. (I’m not using the second side, or the hooks since I used that half for something else aleady).

I’m going to buy another one, and double the whiteboard space. It will be like buying a new harddrive, whenever you get one you, “think ok now i have ALL the space i’ll ever need.”

If you notice the walls, you can tell I live in NYC East Village where landlord’s live by the motto:
“Why fix, when you can apply more paint!”

I also bought some dry-erase makers with an eraser from CVS for 8 dollars. So total is ~25 dollars.

Basic Training in Mathematics: A Fitness Program For Science Students

I stumbled upon the Yale 2006 Physics 201 course on iTunes U. It’s very very good. The professor himself is actually quite a character. After watching about half of the first one, I looked him up on google to see what he was about. There’s no doubt about it, he’s the real deal. One of the first things he said in his physics course was – This is going to be hard. We can’t gloss over the math, there will be a lot of it. Sorry.

I liked him so much, per his recommendation as a study guide I bought his book on amazon.

The Book

Basic Training in Mathematics: A Fitness program For Science Students

It aims to go thru teaching the student (that’s us!) – the “maths” they’ll need to undertake a course in science.
In this case, the professor’s own physics course.

Chapter 1, Page 2

Don’t be impressed, or afraid by that page. It looks scary, but what is going on there is very simple. Thanks to the professors talent in explaining.
Of course you will be googling some math symbols, but again no need to fear “teh scary maff lawlz.”

In order to help me retain more of the knowledge.
I aim to write an example per every section (I would define section as individual significant pieces of knowledge, that make up a chapter. Where a new idea is presented, or previous idea elaborated on in depth).

This is the first one i’ve created. It’s actually laughably simple, but i wanted to make sure I made one before I went to bed. Also it is the FIRST section in the book so I wanted to stay true to that.

Here is ‘a function of x’, where f(x) is continuous, that is – a line can be drawn through it without lifting the pen from the paper:

f(x) = x^2+x/2;

A modest start. Tomorrow I will show the derivative of that function, which should be kind of cool. The classic example is that given the location of a particle P at a time T the derivative of that function is the instantaneous velocity of that particle.

Thoughts on Intelli-J IDEA

Wow. This is the single best code-editor I have EVER used in my life.

  • It is fast.
  • More importantly, It FEELS fast.
  • It gets syntax coloring correct (Can there ever be TOO much syntax-coloring? No. There can be too many colors used, but there cannot be too much syntax-coloring).
  • It has a debugger.
  • It has a very low memory footprint.
  • I can use it for my AS3 / Javascript / PHP / Python / Pearl / Java (I still prefer xcode for c/c++/obj-c)
  • It’s one of the few javascript editors that is not a glorified text editor. In other words it is aware of my properties and their methods!
  • Ctrl+J to quick-view Javadoc for selected method.
  • Ctrl+i to quick-view method implementation.
  • I can export ALL my settings with 3 clicks, and import them into my laptop!
  • It has so many options and things to play with – it recreates that – ooo look what you can do if you press this, feel that makes learning a new IDE fun.

It’s really awesome, and i’ve copied my xcode color settings that Apple probably spent millions of dollars tweaking and now im in coding heaven.

Most importantly, in terms of relative to editor IDE’s it’s “dirt cheap”. FDT is like 500 bucks? WITHOUT debugger? FlashBuilder is like 600 bucks, and it just plain sucks (Everything looks like default text, what are you providing me again? Oh right i forget, annoyance *cough* html-template errors *cough* compiling project keeps producing swf with old code *cough* )

The most basic away3d scene

Time to get cracking getting back to doing 3D in AS3. I’m very excited for molehill, and i’m excited that at work I am just starting a new project in which we need to use one of the existing 3D packages. Previously i’ve always used Papervision3D, and i felt very comfortable with it and how it works and the ins-and-outs so I was able to get my hands dirty with it whenever I needed and not feel lost.

Well that time is over, Papervision3D has long since been dead.

With Away3D already working with adobe on their future release of their API that supports Molehill, and a new project at work that will require using one of the 3D packages, I can’t think of a better time to start using/learning Away3D. Especially with the aid of my fellow co worker, ‘wu media‘ – who’s a bit of a wizkid when it comes to 3D

Below is a very basic stub. It contains a barebones document class with barebones 3D scene, including one light source.

I find these useful when you need to just have something on the screen and then go from there. So this is also kind of a reference for myself as well.

package 
{
	import away3d.cameras.Camera3D;
	import away3d.containers.Scene3D;
	import away3d.containers.View3D;
	import away3d.lights.DirectionalLight3D;
	import away3d.primitives.Cube;
 
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.geom.Vector3D;
 
	[SWF(width="800", height="800", backgroundColor="0x000000", frameRate="60")]
	public class MostBasicAwayDocumentClass extends Sprite
	{
		// Away3D 
		private var camera	:Camera3D;
		private var view 	:View3D;
		private var scene	:Scene3D;
		// Constants
		private const WORLD_SIZE	:Number = 800;
 
 
		public function MostBasicAwayDocumentClass()
		{
			if(stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
 
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
 
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
 
			initEngine();
			initObjects();
			addEventListener(Event.ENTER_FRAME, run);			
		}
 
		private function initEngine():void
		{
			camera = new Camera3D();
			view = new View3D();
			view.camera.moveTo(0, 0, -2000);
			view.camera.lookAt(new Vector3D(0, 0, 0));
			view.camera.zoom = 10;
			view.camera.focus = 50;
			view.x = stage.stageWidth/2;
			view.y = stage.stageHeight/2;
 
			addChild(view);
			scene = view.scene;	
		}
 
		private function initObjects():void
		{
			var light	:DirectionalLight3D = new DirectionalLight3D();
			light.color = 0xFFFFFF;
			light.ambient = 0.45;
			light.diffuse = 0.55;
			light.specular = 0.9;
			light.direction = new Vector3D(-1, -1, -1);
 
			scene.addLight(light);
 
 
			//
			var cube	:Cube = new Cube();
			scene.addChild(cube);
		}
 
		private function run(e:Event):void
		{
			view.render();
		}
	}
}

Better Eclipse Icon

Eclipse is awesome
Update: Eclipse sucks, use IntelliJ IDEA

However you have to set it up right. I recommend downloading and using only the stripped platform binary (http://download.eclipse.org/eclipse/downloads/drops/R-3.6.1-201009090800/index.php) it should be about ~49M – if it’s much larger then double check you’re downloading the ‘platform runtime binary.’

But let’s face it. The icon sucks

So after looking around I found this.
However as it is, it is a little unusable so i opened up photoshop and modified it a bit to work better at small sizes and decrease the visible hard edges.

Finally i’ve made the .icns file which contains all the appropriate sizes with mask.

Here is the final result

Here’s the icns file for OSX
Eclipse.icns
(if you’re on a PC – post a request and if anyone someone is interested i’ll try to make a .ico file)

To Install

Browse to the Eclipse directory inside your Applicaitons directory. Right click it and select, ‘show package contents’, Go into Contents > Resources and paste the extracted Eclipse.icns file. Restart eclipse.

After that

After that make sure you set the memory and a few other launch arguments correctly, i’m using these:

-startup
../../../plugins/org.eclipse.equinox.launcher_1.1.0.v20100507.jar
--launcher.library
../../../plugins/org.eclipse.equinox.launcher.cocoa.macosx.x86_64_1.1.1.R36x_v20100810
-showsplash
-showlocation
org.eclipse.platform
--launcher.XXMaxPermSize
512M
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms512m
-Xmx1024m
-Xss2m
-XX:PermSize=1024m
-XX:MaxPermSize=1024m
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CompileThreshold=5
-Dcom.sun.management.jmxremote
-Xdock:icon=../Resources/Eclipse.icns
-XstartOnFirstThread
-Dorg.eclipse.swt.internal.carbon.smallFonts

Again, The real thanks goes to ‘*domox’ for the original imagery, i just modified it a tad to my liking and made the icons.

Sharing a Javascript base class between Node.js Server / Client-side Browser

I’ve been using Node.JS a lot lately, and Im really enjoying it.

What is it / How does it work?

I was very hazy about that a few weeks ago other than, “It’s some kind of server and also a buzz word”
Node.js is a very very fast event-based server. Also equally important, the server-side code you write is itself written in javascript.

One of the good things about Node.js is that It has a strong following already. People have created many modules for it already. One such module is a Websocket implementation.

What might I use it for?

We are using it here at work to create an HTML5+Websockets real-time multiplayer game.

In order to make this game work, I have the server running a version of the game – while each individual client is running in their browser a version of the game as well. The server is ultimately the one in charge of killing players / tracking projectiles.

The users merely see a facade of this game they play. Their own character sends information to the server, which they implement in themselves instantly. For example when you fire a projectile, you send that information to the server (what / how fast / what angle). Once the server receives that message, and adds that projectile to it’s running of the game. You see the projectile move, but really the server is now in charge of it and it will let you know when it has hit another player. Other users characters movements are predicted based on the last received information, but continuously checked as new information is received.

For this methodology to work, the server needs to have a version of the game running. This is only viable if the server and client side can share base classes between one another. For example the character/projectile classes are no different on the client or server. We share both between them.

However ClientGameController and ServerGameController differ from one another, yet both inherit from AbstractGameController.

This is the beauty of node, it is very easy to do this and keep the code looking nearly exactly the same on both sides if you use Require.js.

Let’s see it in action

This is a shared Character class implementation.

var init = function()
{
	// some defaults we use
	this.velocity = { x: 0, y: 0 }; // how fast i am going
 
	var CharacterController =  function(aClientID) {
		this.clientID = aClientID;
		console.log('Character ID:', this.clientID); // Node has a console.log so this works perfectly on both.
	};
 
	CharacterController.prototype.doSomething = function() {
		console.log('(CharacterController) doSomething()!');
		return 'hi';
	}
 
	return CharacterController;
};
 
if (typeof window === 'undefined') {
// We're in node!
	exports.CharacterController = init();
} else {
// We're on the browser. 
// Require.js will use this file's name (CharacterController.js)
// to export an object called - CharacterController
	define(init);
 
/*
      // You could use this to require modules before your class is created
      define(['ClassCharacterUses', 'WeaponClass'], 'CharacterController', init); 
*/
}

We are taking advantage of the fact that the browser has a global ‘window’ property. Another thing to note, is how similar Require.js is to Node’s own require syntax.