PLAYING WITH FLOT

This is not the first time I've felt the need to visualize some sort of data with the help of basic line-graphs. Last time I didn't even try doing it in javascript but went directly at pythons matplotlib which in all fairness is really nice. Another alternative has been Googles Charts, but that's relying on a third part, and even if we are talking a company as reliable as Google it still leaves me with a slightly sour taste. So enter Flot, a jQuery (yes, I know.) based plotting library that is very simple to use and produces pretty decent results.

var plot = $.plot($("#placeholder"), [d1,d2,d3]);

Where d1,d2,d3 being arrays on the form [[x,y],[x,y], ...]. For your basic plot that's about all you need to do, not much hassle at all. But what if you want to do something more advanced? Such as add legen labels, decide on showing lines, fill, points. And what about axis-enumerations? Well, it's still pretty simple, here's an example from the DoF calculator below.

var plot = $.plot($("#placeholder"), [
        { data: d1},
        { label: "In focus", data: d2, color:'green', lines : {show:true, fill:true,lineWidth: 0}},
        { label: "Focus Limit",  data: d3, color:'red', lines : {show:true}},
	],	
	{
		xaxis: {
			ticks: 10,
			min: plotStart/1000,
			max: plotEnd/1000,
		},
		yaxis: {
			ticks: 6,
			min: 0,
			max: plotMaxCoc,
		}
	}
);

So what are we doing? Yes, xaxis and yaxis specifies the respective axis enumeration, you can specify transform functions for the enumeration if you need it in some special format (it's all in the API if you don't mind digging some). Label defines the legend, and well. I guess it really explains itself. Check out the examples the Flot page, they are a great foundation (the API is however a bit messier).

Here's what I felt the need to use it for, Depth of Field calculator. A depth of Focus Calculator. Yes, photo being one of my hobbies and for shooting street on film keeping a reasonable track of your zone-focus is a good idea. Though don't look to closely at the code, it's quite a mess. And no, it won't work in Internet Explorer because I was to lazy to add the canvas-fix (Flot comes with one of those so no problem if you need compatibility).

VERIFY YOUR DATA. CHECK

It all started out when I wanted to play a little bit with mootools Move.Drag. The original plan was to make a javascript version of magnetic poetry – why not? – it sort of got a little out of hand and turned into chess, and consequently the drag/drop implementation for good old tested left-click.

But what does this has to do with anything. Well to start there's the very simple (quickly hacked) two player javascript version of the game, really quite uninteresting, but as my little project continues onward getting it to look a little better and implementing an actual server in php. So far it looks something like this. It's quite basic at the moment, no feedback whatsoever, text-graphics, doesn't care about check-mate (and probably never will because it is a little more computationally expensive than the rest), and only covers basic legal moves (ie. Castling and En Passante is out of the picture). Check it out if you want to but the code is a mess of UI handling and logic in one small bowl of spaghetti-o, more to come later.

So what? you should probably ask by now. Except for sharing that fugly hack of a chess-implementation, what is the point I'm trying to make? Well it's this: Javascript is a convenient way to validate input data on the client side. Big whoop, you could say, but it does add to the responsiveness of the application and it does save a smidgen of band-width, not to mention processing power since most of the request (assuming that end-users actually use your client) will be more or less valid. By not having to check all input against the server latency becomes much less of an issue (javascript performance could however show it's ugly face in extreme or badly coded cases).

Practical one could say, just getting validated data to mash into your application. But not so fast, javascript being easily changed from the console (or from skimming to the source to get the format of those pesky GETs/POSTs) and that way skip the verifying scripts all together you still run the risk of getting malicious data. Cheating being an issue for chess – (you are using prepared SQL statements to help combat SQL-injection right?), not to mention data that will simply break your carefully crafted app.

So boys and girls, no matter how much client-sided work you do, always always always treat data as poison and verify it on server side as well. Always.

DESIGN PATTERN – SINGLETON

This will be a part of a series of posts about some design patterns that I have found more or less useful, when developing this small page, or just in general programming. So to start it all off – what is a design pattern? To put it briefly – a design pattern is a general (abstract) solution to common situations encountered in software design. It's not a finished implementation but a template for solving problems without specifying the implementation.

What is it?

The first one we'll cover is the Singleton Pattern, which is probably the simplest design pattern to understand and implement. It is used to restrict the initialization of a class to only one object and provide a global point of access for that object. The implementation of the singleton pattern requires a method that returns the singleton object if it's already created or a reference to the singleton object created earlier.

A simple implementation (not thread-safe) could look something like this, in an unnamed object oriented programming language:

class Singleton {
	static Singleton instance;
	
	//Private constructor.
	private Singleton()
	
	public getInstance(){
		if(instance)
			return this.instance;
		else{
			this.instance = new Singleton();
			return this.instance;
		}
	}
}

And why not?

Unit testing

Singeltons are in essence not very different from a global variable and as such it carries around a state, a state that will change depending on how the program is being executed. This might not seem like a problem under normal use but for unit testing it's a big no no. Unit testing is effective because the tests are independent of each-other and since this is not true with global states the order in which the tests are performed will change their outcome. Another problem is that singletons are by nature tightly coupled to the classes that depends on them meaning that mocking or injecting a subclass of the singleton is non-trivial.

Hidden dependencies

Singletons also have the somewhat annoying tendency to hide dependencies in the API. When a class instantiates or gets a class via a singleton it's really just silently accessing a global variable that influences it's behavior. It means that you can't just examine a classes interface to understand it's dependencies, you have to wade through the actual source. Singletons are easily abused as a means of not having to pass around references to services.

Single responsibility

While you can limit the instantiation of a singleton to only one object. But why should this be the responsibility of the singleton itself? If an application only needs one instance of an object it should make sure to enforce that requirement itself, having the singleton do it breaks the Single Responsibility Principle and makes the class less general – what happens if you suddenly find out that you need two or more instances of a class in the program?

Memory Handling

A singleton has the advantage it can be lazily instantiated it also carries the big disadvantage that there is no simple way of garbage collecting the object if it's not going to be used for a while, or again. And since you don't really know for sure if it will be used or not it will be hanging around until the end of the application.

It can seem like a good way to make sure that it's resources are properly terminated when the program closes this can't be guaranteed either if the program exits in a non-controlled way. Not to mention the fact that the resource will be open all the time.

Extensibility

Extending singletons is not a trivial matter either since static methods aren't very flexible at all. So the day that you wake up to find out that you actually need subclasses of the singleton you just made yourself a bigger problem than you had too. This might however be a smaller issue if the singleton is actually a class created by a factory.

Conclusion

The singleton is a quite common pattern and why is that really? Well, because they feel warm and fuzzy to use. Let's face it, using design patterns actually feels somewhat good, you are doing something that's supposed to be more or less right, like following a recipe, and this one in particular is very use to understand and implement. Not to mention it can make your code look cleaner. Hell, I use them for quick and dirty little things I do for myself, things that I know no-one else will ever need to test or maintain.

So to finish it all off – Singletons are global variables and as such they carry with them some problems that might or not be an issue for you. In general they are simply an excuse not to pass around dependents. If you really need a singleton object then creating it at the top of your application and passing it down is probably a better solution. Add in a factory and you can get the exact same behavior without much of the drawback.

So why did I really go through all this just to tell you that the singleton pattern is crap, well because there really can be situations where they are usable. If passing around a lot of services isn't feasible (though restructuring your code can be an option), if you will need one and only one instance of the class – or rather when instancing the class multiple times can actually be harmful.

SPINNERS – WHY YOU SHOULD USE THEM

In the last post I talk briefly about how breaking the back button can be an annoying thing. Today it's the next browser element that AJAX has an eye out for – the loading bar. Sure waiting for a slow page to move can make the meekest surfer steam off techno-stress but even while impatiently staring at the loading bar there's a sense of something actually happening. Something is moving, that means something is happening and even though the keyboard is since long out the window the user is still somewhat waiting in front of the screen for it to finish

Now imagine the same scenario but this time nothing is moving, the form, or button, or link just seems unresponsive, broken. It's no longer techo-stress but techno-rage that takes over. Sure a fast page is one way to go but even the best service providers hits a bump or two once in a while and since the problem is so easily remedied not giving the user some sort of feedback is inexcusable. So just use a loading bar, or a spinner, or other simple way of telling the user that yes – something is happening.

don't know where to get one? Just google AJAX spinner, or try this

2.5/5/1/5

GRIPES, GRIEVANCES AND BREADCRUMBS

AJAX, once a fancy schmancy buzz-word that was going to revolutionize hwo interactivity was handled on the web, is now a major part of the modern webscape. And while it brings many needed facelifts to the old girl it also has a tendency to break one of the most basic tools for browsing the web – the 'back' button. Clicking it on pages that asynchronously fetch new data and inject them into pages can have some more or less annoying results (depending on the mood of the user). Not only can he/she end up on a unintended page, it also makes the dynamically loaded content go bye-bye when the user tries to navigate forward to the same page again. A good example of this would be pages that add more content as the user scrolls down a page. Going back and then forward would on a normal page render you back at the same place in the page but will in the AJAX case force the user to scroll through all the content again.1

One simply way to at least alleviate the problem with the back button (if not the problem with scrolling) is by adding breadcrumbs to a page. You've all seen them, they are more or less an ubiquitous part of multi-stage forms. They can be everything from something like this:

Blog >> Post >> Hello World

...too as fancy as you could possibly imagine (though keeping a usability feature usable can still be recommended).

While breadcrumbs have been criticized when used in a browser for duplicating the browsers back-button this is no longer an issue when the back button doesn't do what it once used to. If you are concerned about this then generating (or just showing) breadcrumbs with javascript will degrade gracefully, personally I don't find breadcrumbs a bad thing even on non AJAX pages as it gives a spatial sense of where on a website I am currently located.

Conclusion

Breaking the browsing paradigm can be a bad thing, if you let it, so just remember that while flash is all nice and good, it's more important to keep a site usable. Breadcrumbs can be one of these feature, especially on client-generated pages.

And on another note

There's actually one more benefit to be gained from using breadcrumbs – SEO (Or search engine optimization for you acronym handicapped people). Since they provide a straightforward way for a web-crawler to navigate from the deeper parts of your page back up to higher levels for further Crawling

1) I'm not saying that it can't be a effective and user-friendly method of presentation, just that it shouldn't be used with reckless abandon.

LOGO OF DOOM

I've had some people asking: Oh great author, how did you do the cool and very awesome effect on the logotype at the top of this page? Okay okay, I still only have two readers, both of them are friends and none of them cares, but here we go anyways.

In essence it's very simple, three images and about 60 lines of mootools powered code.

It starts with your basic logo, just as you'd expect on any page that has one of them, though it does help if it starts out as a transparent png. From this we cut out the parts we want to fade and animate. Any good old image-editing software can do this as long as it supports transparency. Note that the left and right margins on the corresponding cutout is left intact, this is to simplify positioning the overlays on top of the original image.

So to sum up, about now you are supposed to be sitting with something like this on your hard-drive:

logologoleftlogoright

Any questions? No? Good, just remember that the overlays need to have a transparent background or the fading in/out won't really work, even though you can still move them back and forth 'til your heart's content.

Go ahead and insert the logo in a div with your favourite text-editor and then we go over to the code.

I inject the overlays with javascript, mostly because I think it's annoying to have them on a page that doesn't support javascript to start with. Since we are using mootols. Go ahead and create the img divs and inject them into the div that you put the logo in. Remember that we saved the left and right margins in the images so that we can position them to the right and left by just using left:0 right:0. Over these I put an empty div to use for the mouse-enters event, I had some issues when it wasn't there but your mileage may wary.

To actually fade and animate the different elements we have created the mootools transition of your liking, personally I think that a second is a nice time but you are free to do whatever you feel like.

	
logo.set('morph',{duration:1000,transition:Fx.Transitions.Quad.easeOut});
logo_left.set('morph',{duration:1000,transition:Fx.Transitions.Quad.easeOut});
logo_right.set('morph',{duration:1000,transition:Fx.Transitions.Quad.easeOut});
logo_morph = logo.get('morph'); logo_left_morph = logo_left.get('morph'); logo_right_morph = logo_right.get('morph');

Now that we have the Morph objects available it's time to actually do something useful. Take the mouse-over element I mentioned previously and add mootools mouseenters and mouseleaves events to it.

	
mouse_over.addEvents({
	mouseenter : function() {
		logo_morph.cancel; 
		logo_left_morph.cancel(); 
		logo_right_morph.cancel();
		
		logo_morph.start({opacity:0}).chain(function(){
		logo.setStyle('visibility', 'hidden');
		});
		
		logo_left.setStyle('visibility','visible');
		logo_right.setStyle('visibility','visible');
		
		if(logo.getStyle('visibility') != 'hidden'){
			logo_left_morph.start({opacity:1}).chain(function(){
				logo_left_morph.start({left:65});
			});
			logo_right_morph.start({opacity:1}).chain(function()
				{logo_right_morph.start({right:66});
			});
		}
		else{
			logo_left_morph.start({left:65});
			logo_right_morph.start({right:66});
		}
	},
});

A little more code to sink your teeth in. In essence it's actually really simple using Chains The Morph object will simple step through the chain on function after finishing the call to Morph.start(); So to break it down. On mouse over we start by canceling any ongoing Morph action and then starting with fading the logo out and the overlays out. Note that set visibility to hidden respectively visible on the elements faded, just to make sure that even if a browser doesn't play well with opacity it won't look horrible.

	
logo_morph.start({opacity:0}).chain(function(){
	logo.setStyle('visibility', 'hidden');
});
logo_left.setStyle('visibility','visible');
logo_right.setStyle('visibility','visible');

That said and done we check if the logo image is visible or not, this is to prevent getting a delay of the animation while the hidden logo is faded out from 0 to 0 again since that's what we would have asked for.

	
if(logo.getStyle('visibility') != 'hidden'){
	logo_left_morph.start({ opacity:1} ).chain(function(){
		logo_left_morph.start({left:65});});
	logo_right_morph.start({opacity:1}).chain(function(){
		logo_right_morph.start({right:66});
	});
}

So chain opacity->movement on the images and presto the effect is more or less complete. The other way around should be quite self-explanatory (if you managed to follow so far. If you didn't, don't fret – I'm horrible at explaining what the hell I'm doing), mouseleaves is just the same thing, but backwards.

That about it for today. If you want to play around with the code, it's not pretty nor is it properly objectified then take a gander over here Feel free to do whatever you want with it as long as you don't blame if it doesn't work or if it breaks anything

FIRST (SECOND) POST

I've been thinking long about what subject to actually start this blog off with. Something to actually set a good precedent for what's hopefully years (or at least months) of fun to come. Well, what are the subjects to chose from then? I guess that's what you'd call a major question. Being the easily distracted person I am it would be easy to range from the absurd to the political to the nerdy but to make this sort of work I know that I have to decide on a narrow range of subjects and the one that comes to mind is web-development, in one form of another (depending on what currently caught my whims). Mind you, It's my own personal little sandbox so I will definitely stray from time to time.

Logically that's where I'd start off then, maybe by write something about the design and development of this blog (that's held together with duct-tape and a lots and lots of happy thoughts), 3NF, PHP, Javascript, Humanly-Readable URLs, or something on that line. (Some of it I'd have to do some actual brushing up on – god forbid – but I guess that they say that learning is half the fun).

But in the end it's really quite simple, there's only one subject that I can – in good conscience – start with, or rather continue with because it's been the first post in this blog for a couple of days now (and in a couple of other iterations, both back- and front-end revisions, before that) and it's the old venerable design-tool Lorem Ipsum. So what is this magical creature I hear my endless hordes of subscribers (I wish) asking (okay, I know that the two of you didn't). But I've started rambling so I might as well continue. Yes, I'd say, it's complete and utter gibberish but that's only half true Lorem Ipsum Dolor[...] is a more or less nonsensical place-holder text to demonstrate (or test depending on how good you feel that you are) typography or layout.

It's nonsensical nature actually fills a purpose because according to hearsay (I'm sure that they've made they've studies but I am far to lazy to look one up) human people have a tendency to focus on the actual textual content of a page rather than the typography/layout. One thing to watch out for however when using Lorem Ipsum that design-handicapped people like me (I claim to have a diagnosis!) need to watch out for is that it's a very symmetric text that will make a layout look far better than your (or mine, or your/my users) own inane scribbles ever will.

So here's my homage to Just Another Lorem on Just Another Blog. A wonderful mess of semi-gibberish (that you can easily procure yourself here), that has been in this world, in one form or antohter for 500>x>20 (with badly formed error margins) years longer than I have and hopefull will around when I am long since gone.

Lo(rem/ve), out.

JUST ANOTHER LOREM

Lorem ipsum dolor sit amet, tellus feugiat dictum fermentum rhoncus a mauris, orci wisi duis in mauris cursus quam, ut nam cursus pellentesque dui, ut massa lacus, dui ipsum nec montes. Ut vivamus amet natoque, quis est et id vestibulum nec, aut varius et, ac maecenas etiam mollis. Fringilla non ut at rutrum ultrices, auctor mi, enim sapien consectetuer vehicula ac, vivamus sed lorem ut maecenas aliquam, quasi senectus ac vitae consectetuer natoque. Morbi lorem donec adipiscing lacus id sem, sequi cursus libero orci pharetra felis, mi massa, at bibendum, condimentum eros dolor vitae eget nunc. Pretium sit sed vitae suscipit integer dolor. Erat neque nullam sit duis mauris, congue lectus, et dapibus etiam mi imperdiet sem, blandit torquent ligula posuere purus aliquet. Eleifend ridiculus, sed magna dictum euismod suscipit erat turpis, mauris etiam suspendisse adipiscing nonummy rutrum, magna nam, ante lorem amet mauris esse a. Dui at pharetra accumsan nonummy a tristique, et eget ut in. Quidem erat.