Ryan Rampersad
Thoughts, opinions, ideas and now links
  • About
  • Podcast
  • Links

Archives

Crockford’s Top Down Parser∝

Because I’m a sick person sitting in the computer science building’s lounge, I took the time to read (and sorta-understand) Douglas Crockford’s Top Down Operator Precedence.

It’s basically writing a parser with operator precedence built in. It’s written in JavaScript, so some familiarity there helps, but for the most part, it’s pretty simple. And it’s quite fascinating.

Circular JavaScript Fractal∝

Here’s a really neat JavaScript fractal that’s interactive. If you have nested circles, and a point on the inner most circle draws while the circles rotate, you get an interesting fractal-like pattern.

The Chicken-Egg Problem with Javascript Cryptography∝

If you don’t trust the network to deliver a password, or, worse, don’t trust the server not to keep user secrets, you can’t trust them to deliver security code. The same attacker who was sniffing passwords or reading diaries before you introduce crypto is simply hijacking crypto code after you do.

JS: C-loop unrolling∝

I was working on some heavy duty loop unrolling and Sam wanted me to share my paltry JavaScript code to automate the task. It’s just a loop printing some lines, but the fact that I’m doing it with other code means literally, the compiler is probably doing it too.

var n = 32;
function mk(x) {
    var e = new Element("p");
    e.set('text', ("dst[RIDX(cache, i+"+x+",   dim)]  = src[RIDX(i+"+x+",   j, dim)];"));
    $("c").grab(e);
}

n.times(function(i){
    mk(i);
});
​

Quick Comparison: Browsers, Hardware & the HP TouchPad

There is no perfect benchmark or absolute comparison tool, but I like SunSpider to get a good feel. In the way I’m using it, I’m comparing browser speed on each respective device, but also overall performance because better processors obviously mean better performance in general. Usually.

These results merely report the browser and the total time it took to run the SunSpider tests. It’s not at all scientific, accurate, or precise. It’s nothing more than a quick’n'dirty way to compare lightly.

First, let’s start out with a two year old desktop that my mother uses daily for work and play. It’s fast enough for her and I wouldn’t say it’s slow for regular needs either. It’s packing a AMD Phenom 9650 Quad-core clocked at 2.30Ghz with 4GB of DDR3 clocked at 1333Mhz. So it’s a little older but it obviously gets the job done. It’s respective SunSpider results in Chrome 13: 411.3 ± 3.4% milliseconds. So that’s pretty good, right?

Comparing that computer to my month old Lion-MacBook Air with an Intel i5 clocked at 1.7Ghz and 4GB clocked at 1333Mhz, well, it’s twice as fast. The results in Chrome 14: 277.8 ± 1.5% milliseconds.

The HP TouchPad should be fairly decent right? It should be fast enough to complete the SunSpider tests in maybe twice the time of the desktop, or maybe five times the notebook? Well, everyone said its hardware was a bit lacking and that’s true. SunSpider results on the HP TouchPad 3.0.2 Browser: 4340.9 ± 2.5% milliseconds. That’s pretty slow. I don’t have an iPod touch anymore or even a iPad nearby, but one could guess they perform better than that.

But here’s a more suitable comparison. The TouchPad versus my Optimus V from February. It has two processors, one for main calculations and the other for graphics, but one must remember it’s clocked at a mere 600Mhz which is like a throw back to twenty years ago. It’s running Android 2.2.2 and its browser’s results were: 39951.7 ± 1.5% milliseconds. That means it took around 40 seconds for the tests to finish on the phone.

So there you have it. An HP TouchPad isn’t that slow compared to my Android phone, but surely if I compare it to an actual computer, it’s slower than a [insert slow animal here]. The one device that might be slower than the Android phone could be my mother’s BlackBery Curve 8300. Now that thing’s slow.

Replace Line Endings in JavaScript

I was bringing text in via XHR and I needed to replace the natural \n line endings with a true <br /> break line so that it would be legitimate HTML when injected into the DOM. It’s pretty easy, but you just need to remember: replace returns!

Since there are multiple versions of line endings, like Unix \n but also Windows \r\n and Mac’s old \r, you need to replace them all just to keep your bases covered. It’s all pretty easy.

var string = 'this is a sentence.\r\n and this is another sentence about nothing!';

// notice that is reassigned? .replace returns!
string = string.replace(/(\r\n|\n|\r)/gm, "<br />");

console.log(string);

This code is simple. Just a string with a line ending followed by a replace statement. I make an explicit note that replace will return the new string, not simply mutate it in place. This caused me a bit of confusion. Also note that the gm at the end of the regular expression means that it will match globally and over different lines, just in case.

You can read the MDC documentation about String.replace too.

My First MooTools Presentation

On Thursday, May 27th, I gave my very first MooTools presentation to an eagerly awaiting AP Computer Science class. The presentation was in three parts, the first a general overview of javascript itself, the second a micro-guide to MooTools glowing finesse with elements, events and effects, and finally a complete section on MooTools classes to compared to those in Java.

An introduction slide for my first mootools presentation

The MooTools website, the MooTorial and the mooWalkthrough all made appearances, giving extra credit to the third as my own project.

The presentation in all was 54 slides and lasted about 52 minutes with a Q&A segment. The content in the presentation was in fact enough to get the class to work on a not-too-rudimentary project involving MooTools the next day.

The Presentation

AP Computer Science MooTools Presentation
View more presentations from Ryan Rampersad.

You can also download the PDF or the PPTX. (If I wasn’t poor, I would have used Keynote.)

Enjoy!

Google Chrome 5 Media Global Variable

Axel posted some great information in the MooTools User google group a while ago, sharing his expierence with Chrome 5. Recently, I ran into this very problem.

The problem was that a global variable defined by chrome itself. It was a global read-only variable, it was special. My plugin could not override it, so my plugin broke. It was the media variable. Chrome sent back this error:

TypeError: Object #<a Media> has no method ‘play’

Google went completely against the mantra of reducing global variables and functions. I seriously hope this doesn’t happen increasingly as more browsers update their feature sets.

Good luck.

Facebook’s Javascript

Here’s the script.

“Hey Ry, Firefox crashed again!”

“What were you on?”

“I was on Farmville…”

“So you’re on Facebook using Flash. You’re asking for trouble…”

That’s how it goes with my parents every so often. They love Facebook and the games, but they hate when Firefox crashes on them. I’ve attempted to explain the problem. The excellent post on ajaxian about Facebook’s javascript speed up spurred this post.

I admit, it wasn’t as bad as it used to be. In the past, I would show my parents every time that Facebook is absolutely ridiculous by loading anywhere between 15 and 30 external resources. There is no speed when loading that much junk. When inspecting via firebug now, I don’t have an issue with only an initial load of a single file. CSS requests still number at 5 on the homepage though.

Millions of people use both Firefox and Facebook. How come they never had any of these problems? Did they all have 8gb of memory and quad-core processors? I doubt it. Maybe they weren’t as intensive users as my parents were? I doubt that too. I just don’t know. Maybe they did experience those problems but they lived with them and never really knew any other way to describe the problem, becuase that’s just how computers are? Probably.

The biggest problem with Facebook is the speed overall. The facebook parts, like the homepage and profiles do load faster than they used to. But the apps don’t. I understand that facebook doesn’t have anything to do with the apps. But do my parents know that? Do most people? I doubt it. Remember when AOL used to be the internet? It’s the same now, a limited scope, a narrowed preception, a vision of everything inside of the Facebook frame and domain is Facebook.

Can you imagine a world where Apple apps on the iPhone are blazing fast and third party apps aren’t? Most people, I can only believe, know the difference between the 9 Apple apps and the thousands of third party apps. If the case were made that third party apps are slower, like they are Facebook, people wouldn’t like it. They’d hate it. Apps are the point of the iPhone. For most people too, they are the point of Facebook.

This microrant is finished. Don’t get me started on Flash!

Invalid Object Initialization

Firebug will scream and shout about Invalid Object Initialization if you mess just a little something up. Firebug does this a lot. It is an unhelpful error because Firebug will direct you to the first line of your object, not where the problem is.

Firebug gave me this, more or less. That wasn’t helpful. (Why did Firebug get full, anyway?)

Firebug’s log limit has been reached. 0 entries not shown. Preferences invalid object initializer[Break on this error]

Let’s say you have some code, and it looks like this.

 var TranslationStrings = {
  onAdd: "Do you want to add this?",
  onDelete, "Do you want to delete this?"
 };

If you don’t notice the mistake in the object, Firebug will. It’s just a little something. It is a comma.

The onDelete, "Do...." should have a colon between the key-value pair. Not a comma, those go after a pair. It should be formed like so, onDelete: "Do...".

So remember, watch out for those javascript object literals with commas and colons.

Javascript let

Mozilla offers a let in javascript 1.7. The let keyword isn’t support by other browsers yet so using it isn’t generally recomended but it nice to catch up on the latest javascript constructs.

A Parallel

First, a parallel. I’ve coded in Java the last couple of months because of school. During said time, I discovered scoped blocks in Java. A scoped block might be like this:

public void myMethod() {
  int i = 100, j = 10;
  {
    int k = i * j;
    i = 10;
    j = 10;
  }
  // cannot reference k from here
}

If you’re a java programmer, you might never have seen this happen before. Basically, putting floating brackets, as long as they match up, around arbitrary code, it will be in a different scope. k won’t be accessible from the outside of those brackets. I call these structures scoped blocks.

Now back to javascript

let in javascript acts similarly to the scoped blocks mentioned above.

Using let as a block is similar to the scoped block in java. The let-block won’t allow g to be accessed from the outside, x and m are newly bound values, they will only be around in the block scope.

 var i = 100, j = 10;
 let (x = 10+i, m = j + 5) {
   var g = x + m;
 }

let might make it easy to bind this to another variable in a certain scope, which could prove useful.

For more information about let, checkout the MDC page.

Stop console.log errors without deleting each call

Have you ever added a couple of console.log calls to your javascript, test it in Firefox, then go into Internet Explorer and see tons of mysterious errors popup? I sure have, I always forget about those console.logs that are interwoven in my code. While it isn’t hard to do a replace on them all, I usually want to keep them where they are.

Firebug

Firebug

I recently came up with a solution to this problem, different from the one I wrote about before. I wrote a little function called log. As you can see, it is the simplest thing in the world.

function log(arg) {
 console.log(arg);
}

So what’s the big deal? Let me explain. If you’re testing in Firefox with Firebug, you won’t notice much difference. But if you need to test in Internet Explorer now, you can just comment one line, that internal console.log which is faster and easier than commenting out all of them by hand.

GoodCarousel – A Carousel with Mootools

Hey there. I’m trying to get this plugin into the Mootools Forge but I’ve been having a hard time getting it to work. So in the mean time, checkout the repository on github.

GoodCarousel is a plugin made with Mootools 1.2.3. It is made to slide over to, not fade to, the next slide and uses inline elements to draw data for the slide titles, descriptions and images.

GoodCarousel Demo

GoodCarousel Demo

What it does

It creates a carousel like those found on cNet but instead of fading, it will slide over. The carousel draws its data from inline elements: h3, p and img within in a div with a specific class. This allows you to use the carousel but also keep the data indexable.

Usage

You can see a fully working demo page here. There are a few steps you’ll need to follow in order to get it to work.

  1. You need to determine the space you have for your slides. The space cannot change so fluid layouts probably won’t work. The demo page uses 495×300 pixel images for slides because that is the space alloted to it by the layout. I found the space by using the layout tab in firebug.
  2. When you make your images, keep in mind that the title and description text will be displayed on the left side of the image so putting in the right-top corner is probably the best bet. Experiment with it.
  3. Once you have your slides, you can easily build your html structure so GoodCarousel can draw data from it.
    <div class="carousel-data">
    <h3>Slide Title</h3>
    <p><a href="http://what.the.slide.links.to/">Slide description or subtext</a></p>
    <img src="path/to/slide-image.png" title="image title" rel="rel - for lightbox support" />
    </div>
    

    Each div with carousel data will make a slide in the carousel.

  4. The carousel nav is automatically sized based on options you set when initialize GoodCarousel.
    	window.addEvent("domready", function() {
    		gc = new GoodCarousel("good-carousel", {width: 495, height: 300});
    	});
    

    Make sure you set the width and height you used for your images. GoodCarousel will take of how big to make the container and how small each nav should be.

You have to include the GoodCorners javascript file and css file in the head of your page, as always.

<link rel="stylesheet" href="path/to/good-carousel.css" type="text/css" />
<script src="path/to/mootools-1.2.3.js" type="text/javascript"></script>
<script type="text/javascript" src="path/to/good-carousel.js"></script>
<script type="text/javascript">
	window.addEvent("domready", function() {
		var gc = new GoodCarousel("good-carousel", {width: 495, height: 300});
	});
</script>

Remember to set the width and height that your slides will be.

Downloads

You can pick up GoodCarousel with the stylesheet, transparent background and double arrows on the demo page as a zip. The zip contains a compressed and uncompressed version for both the css and javascript. You can use the demo page for setup reference.

Notes

You may need to edit the stylesheet that accompanies GoodCarousel. You can easily customize the height of the nav, text color, hover color and so on by editing the uncompressed good-carousel.css file.

This post was written for GoodCarousel 1.1 but will probably make sense with subsequent versions. It will also work just fine with Mootools 1.2.4.

Pluralize In Java, Javascript and PHP

I was just reading David Walsh’s post about Possessives. It was a very clever use of PHP. I remembered a helper method I wrote last year that was somewhat similar in use, another form of coding English. It was Pluralization.

At first I just added s if the first argument was not 1 and that won’t always work. For instance, while blog will pluralize with just an s but box will not. Is there a solution to this horrible problem? Yes.

The solution is a three argument function, although exhausting, it does get the job done. So I provide these functions in Java, the original language, javascript and PHP.

Java

This method accepts a double and two strings. The first argument is a double for a technical reason. Do you say, “I have .57 apples?” or “I have .57 of an apple?” My conclusion was that decimals were plural. It sounds right. Is it linguistically correct? Somebody should tell me.

public static String pluralize(double howMany, String singular, String plural) {
 return ( howMany == 1.00 ? singular : plural  );
}

Javascript

function pluralize(howMany, singular, plural) {
 return ( howMany == 1.00 ? singular : plural  );
}

PHP

function pluralize($howMany,$ singular, $plural) {
 return ( $howMany == 1.00 ? $singular : $plural  );
}

The code for this method is based off of the Java version and because they all have similar syntax, they all look the same. Using something like this won’t be useful in a internationalization-localization context but it can help for tiny projects.

A little example and that should do it.

$itemsInCart = 1;
echo( "There " . pluralize($itemsInCart, "is one item", "are items" ));

Two Javascript Testing Utilities

PasteBin, Pastie and of course, Gist. There are tons of pasting services. Lately however, we’ve started to ask more of our neighborly paste service, we need it to run and demonstrate our javascript, basically, we need a javascript playground. I have found two such playgrounds, they both looks great and work well.

JSBin

JSBin

JSBin


JSBin is the more polished of the two testing utilities. JSBin allows you to create custom css,html and of course javascript and in conjunction with Google Ajax Library APIs, serve you with a live testing ground. The reason JSBin is more polished in my opinion is that it has some syntax highlighting and it uses those Google Libraries. This gives it an edge. I highly recommend that you check this out.

MooShell

MooShell

MooShell


This is dedicated to Mootools right now but it shows huge promise. It has four panes, HTML, CSS, JS and the result. Unlike in JSBin, the result isn’t accessible outside of the editing space so the Ajax mimicry isn’t quite as advanced yet. MooShell though is pretty cool and I’d love to see it put on GitHub, I’d love to help add features. You really need to try MooShell sometime, with your favorite Mootools code.

Share similar testing utilities you’ve seen or even made. I actually one similar to these a year ago for personal use.

Next>

© 2013 Ryan Rampersad.