Shiftin', Unshiftin', Pushin' n Poppin'

I would like to show a neat trick on looping through arrays, not using one value every time but sometimes one, sometimes two and so on.

I found this while doing the Bowling Game Code Kata. A kata is like a code practice, you try to solve a problem in many different ways to see what you find. I find this very interesting, cause I'm learning test driven development at the moment, and it's perfect to try different implementations once you got your tests set up.

A guy named Zach Leat has set up a very nice repository of javascript katas, and I will show you part of his Bowling Game, very true to the original Java implementation:

What you see above is the "score" function, the way the bowling scores are summed up. As you see, when you hit a strike, you use one value from the array, and then you add up the following two but not passing by them. When you hit a spare, you use two values from the array, and then adding one following value, without passing by it. 

A nicer way of doing this, without having to deal with a counter variable, is simply shifting the array. That way you don't have to count, because you always use the latest values, like this:

The shift, unshift, push and pop functions are really great for working with arrays, though i have to admit it took me long to memorize. I think most people know push and pop. Here's an overview:

Hope that helps with something! Anyway if you sit on any good code katas, i would really appreciate if you post them in the comments! Looking forward to it!

PS. Here's my entire bowling score kata, if you find it useful!

Some of javascript's more esoteric operators:

Bitwise NOT: ~

The bitwise "not"-operator has some pretty weird but interesting side effects. Its basic functions on numbers can be described as:

~N = -(N+1)

Now, the way you see this operator used is more often than not for flooring numbers:

~~10.23342 // returns 10

The reason this works is because all bitwise operations are performed on 32-bit integers in javascript:

~10.23342 // => -11 (Rounded when converted to integer)
~-11 // => 10 (-(-11+1) = 10)

Taking this one step further, this can be used to convert -1 to false. Functions like Array.indexOf, String.indexOf and String.search returns -1 on "not found".

var facon = "sundriedtomatoesisvegetarianbacon";
if(~facon.search("bacon")) eat(facon); 
// HAHA! tricking meat eaters into eating vegetarian

@webreflection Has written much better about the javascript tilde trick, and it's also mentioned by Dreaming Javascript

Bit-shifting ( >>, >>>, << )

One possible use-case for bitshifting in javascript is when working with hex colors, for example can we use bit-shifting to filter out Red, Green and Blue values:

Filtering out hex values:

111111111111111111111111

32-bit (16 777 215 in Base 10)

R        G        B
11111111 11111111 11111111

Mask for filtering G-value:
00000000 11111111 00000000

Combine with bitwise & (Only saving the spots where BOTH numbers are 1)
Example: Base-10 color-value: 16737792 – the orange color in the "Hacker News"-logo

00000000 11111111 00000000 // Mask
             &
11111111 01100110 00000000 // Color value
                         =
00000000 01100110 00000000 // result => 26112

Bit shift it to get only the "green"-value:
26112 >> 8 => 102 // removing the lowest (rightmost) 8 bits

Raphael.js uses bitshifting for the reverse operation, converting an object like { R: 10, G: 20, B: 255 } into a hex value:

rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1);
(Line 855, Raphael.js)

The bit-operator part is: (16777216 | blue | (green << 8) | (red << 16))

Dimitry is using the | (and/or) operator to add up a hex number:

So let look at this:
First we create a mask, that we add the numbers to: in base(2) 1000000000000000000000000. This is one number bigger than the highest RGB-color value on Base(10). We'll soon see why.

The "blue" value is a normal color-value, for example 255:

16777216 | 255 means:

1 00000000 00000000 00000000
                        | (inclusive or)
0 00000000 00000000 11111111
                        =
1 00000000 00000000 11111111

The green value needs to be shifted 8 bits to the left: 66

66 << 8 => 16896

1 00000000 00000000 11111111 // number after adding blue value:
                        |
0 00000000 01000010 00000000                        
                        =
1 00000000 01000010 11111111

(And the same thing repeated with the red color, that needs to be shifted 16 bits.)

  Red      Green    Blue        
1 01100100 01000010 11111111                        

This number is now converted to Hex with (number).toString(16):
(parseInt("1011001000100001011111111", 2)).toString(16) 
// we need to convert out binary number to Base 10 first, hence parseInt

Now we'll delete out initially added "1 time bigger" number:
(parseInt("1011001000100001011111111", 2)).toString(16).slice(1)

And add a # to the start, then we'll have a hex number.

Bit-shifting is extensively used in Mozilla's pdf.js and also appears in Mr Doob's Three.js. I'm sure it's relevant in those extremely performance-heavy use-cases, because when you start creeping up towards tens of millions of loops per second, the difference between shift-right 2 bits and divide by four (which is the same operation on integers) starts to make sense

Should you use wordpress? (Beginners guide.)

Most people i have a professional relationship with know that i nurture an almost passionate hate for Wordpress. Sometimes even other people ask me for my opinion, hence this blog post.

So, the answer to "Can I use wordpress?", seems to be other questions:

You run your won company, wanna create a quick site yourself, and don't wanna pay a consultant/agency?

YESSS!!! Actually you SHOULD use wordpress. And you should use a *.wordpress.com-hosted blog, and have a friend setting up a custom domain name for you. It will be limited, but it will always be better and more hassle-free than any self-hosted wordpress installation with all the fancy functionality you can dream of. In fact, wordpress.com is the ONLY "create-your-own-website"-service i can recommend.

You want to accept payments on your site?

NO. To accept payments from a wordpress site, it will need to be self-hosted. Getting the security right on a self-hosted Wordpress blog is very hard. Get help. From someone else. I'm not an expert on internet payment systems, unfortunately.

You're looking for an extendable, lightweight, CMS?

NO. Wordpress is very extendable, but the problem is that the plugins are often very low quality, and when you need to upgrade a system, you're likely to end up having a broken website with 15/20 plugins broken because of Wordpress changes, or because they were badly written from the beginning. 

You're looking to have more than 1000 visits/day?

NO. Well i know there's a plugin called WP-Super Cache. Still, every day i see wordpress blogs crumbles under the load of 5-10 000 Hacker News visitors. It's just not easy to get it right. And if you do, you're very likely to break your site's security. The problem, must be admitted though, is also often in Apache settings rather than Wordpress. Did you have better load tolerance with other servers? Please comment!

You already know Wordpress, and want to get started now?

YES. See first question. Use a wordpress.com site and buy a custom domain. When it's time to add payments, bookings and other things, Wordpress has excellent export tools for getting your content out and move it to another system. 

Your question not here? Ask it in the comments! If i have a good answer, i'll add it!

Options to check out:

  • Jekyll: Generating static pages from Markdown. For extremely lightweight, fast blogging that can take a hit from reddit, digg or whatever. For self-hosted sites.
  • MojoMotor: Small, extendable, lightweight CMS based on the CodeIgniter PHP framework, for self-hosted sites.
  • ExpressionEngine: Also based on CodeIgniter. Full blown stuff, extendable for e-commerce, booking, applications etc. Self-hosted.
  • BigCartel: E-Commerce as a service. Good templates, they host it = take care of the hassle :)
  • Shopify: Same as above. Note that i haven't tried any of these two myself, but that'd be the first place i'd look if i needed to

 

 

Nokia N9 and an incomplete list of browser features

Faith gave me the chance to lay my filthy hands on a Nokia N9 this weekend. Not very long, but at least it gave me some impressions:

First of all the UI as smooth and snappy as in the videos

It looks really great to use! Trying to push it, the only time i saw a hiccup was the first time i got the notifications drawer out. I'm not enough of an iOS user to be able to compare, but my impression was that speed and animations were better than on my Nexus S running Android 2.3.4

Swipe to switch apps rocks

Swipe to switch apps is like the Dude's carpet. It really ties the phone together. It works like this: when you swipe on the screen, it is a normal swipe that for example browses photos in a gallery. When you swipe from the edge of the screen, it switches apps. The difference felt very distinct and far easier to perform than the 4-finger-swipe-to-switch-apps in iPad on iOS 5. 

Browser: 3D CSS Transforms, CSS Animations, Homescreen apps 

So during the few minutes i had i had the chance to run a html5test.com test. I don't remember the exact score, but it was something around 300. Accordning to the site, iOS 5 scores 303, so i guess they're around the same. The features are quite different though. Let's do some comparison:

According to the Nokia engineer i spoke to, the phone supports CSS3 3D transforms and CSS3 transitions and animations. I can't applaud this enough. He also claimed the phone to have good support for the application cache manifest, as well as Local Storage + WebSQL. This means that Nokia goes down the Apple path, and don't support the IndexedDB type of local database used by Google and Mozilla. According to the engineer i spoke to, they also included javascript touch-events and gesture-events, detecting up to 5 fingers on the screen.

One peculiar thing is that you can't actually bookmark a web-page. Only place it as a home-screen app. In the category "no's" we'll also find Websockets and WebGL. I honestly forgot to check whether it supported the DeviceMotion and DeviceOrientation javascript APIs for the accelerometer. So if you get the chance to check that out, please let me know!

On the video side, the browser supports the MPEG4, H.264 and Ogg Theora codecs. That means no WebM.

The browser priorities are right 

Whether this makes the phone and its' browser good or not is too early to say. But as a web developer i say that i have the impression that Nokia got their priorities right. CSS3 transitions and 3D animations might be eye-candy, but it's really important for creating user-friendly, touch-enabled websites that even comes close to the feel of native apps. While i pity the exclusion of websockets, I wouldn't prioritize WebGL for mobile on this point. Don't get me wrong, i think WebGL is one of the most interesting technologies to show up lately, but it still has to prove its' user value beyond cool demos and videos.

Internet Explorer 10 – Columns, Box-model and Gradients. No webGL or websockets yet.

So, yesterday microsoft released the first platform preview of IE10. I'm happy to see they seem to adopt shorter release cycles. Let's see what they put in there for now!

I was a little bit lazy, so i basically jsut went to modernizr.com and checked the new feature list. Microsoft seem to keep their habit of adding proprietary prefixes and stuff, but on the other hand, so does webkit and firefox too. Let me just say it sucks.

Well. This is just the very very first platform preview, so i hope there's more to come. At the moment it still looks pretty lame I'd say.

Feature table, according to modernizr:

FeatureIE10IE9Chrome 10
@font-face OK OK OK
Canvas OK OK OK
Canvas Text OK OK OK
HTML5 Audio OK OK OK
HTML5 Video OK OK OK
rgba() OK OK OK
hsla() OK OK OK
border-image: NO NO OK
border-radius: OK OK OK
box-shadow: OK OK OK
text-shadow: NO NO OK
opacity: OK OK OK
Multiple backgrounds OK OK OK
Flexible Box Model OK NO OK
CSS Animations NO NO OK
CSS Columns OK NO OK
CSS Gradients OK NO OK
CSS Reflections NO NO OK
CSS 2D Transforms OK OK OK
CSS 3D Transforms NO NO OK
CSS Transitions NO NO OK
Geolocation API OK OK OK
localStorage OK OK OK
sessionStorage OK OK OK
SVG OK OK OK
SMIL OK OK OK
SVG Clipping OK OK OK
Inline SVG OK OK OK
Drag and Drop OK OK OK
hashchange OK OK OK
X-window Messaging OK OK OK
History Management NO NO OK
applicationCache NO NO OK
Touch events NO NO OK
Web Sockets NO NO OK
Web Workers NO NO OK
Web SQL Database NO NO OK
WebGL NO NO OK
IndexedDB NO NO NO

JavaScript Accelerometer on iOS & Android (via firefox)!

Since iOS 4.2, Mobile Safari supports accelerometer events. The native browser on Android doesnt do that yet. (I've heard that it does accelerometer in WebViews, ex via phonegap, but i couldn't confirm this now) Firefox 4 (currently in Beta 13, 28 March 2011) does support accelerometer events! Of course, this is awesome, not least for building games on websites!

So, this is how you do it:

 

You can view the demo here: http://nerdcommunications.com/demos/accelerometer/

 

You can download the demo source here: http://nerdcommunications.com/demos/accelerometer/demo.zip

 

Tracking lost users w/ Google Analytics

Step 1: Set up your custom 404-page, put this in .htaccess:
ErrorDocument 404 /404.html

Step 2: Put this Google Analytics code on your 404.html:

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-19487197-1']);
  _gaq.push(['_trackPageview', '/404'+ '?page=' + document.location.pathname + document.location.search + '&from=' + document.referrer]);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

That way, you catch both that you had an error, what path they tried to access and where the bad link is.

The facebook scam "101 hottest women" and why you clicked it

have you seen any of you're facebook friends clicking something like this lately?

Bild_3

Hmm... maybe not something you wanna show off to your friends. But how come?

It comes in various size and colors, Chinese Videos that makes you fall asleep (you MUST see it!), cutest pets, whatever. But what is it, and what do the people behind this want?

Since this one seems to be pretty common, plus that it's working in a lot of different versions currently. I wanted to look through it a little!

0. What is it?

Basically, some people want to fool you into filling out a survey, to see some old crappy content. The content is usually not even theirs.

The scam doesnt seem to attempt to steal anything from you PLEASE LOOK THIS UP, PEOPLE WITH THE RIGHT KNOWLEDGE.

Btw that porn-site you were looking for is here: http://www.maxim.com/girls/girls-of-maxim/92660/2010-hot-100.html

Here's what happens!

1. The moving "like button"

Wonder when you ever clicked "Like" on that link? You just clicked the normal link? No, you clicked the "like" button, which moves around with javascript:

    function lololol(e){

    if (window.event) 

    { // for IE

        aaaa.style.top = (window.event.y-5)+standardbody.scrollTop+'px';

        aaaa.style.left = (window.event.x-5)+standardbody.scrollLeft+'px';

    } 

    else 

    {

        aaaa.style.top = (e.pageY-5)+'px';

        aaaa.style.left = (e.pageX-5)+'px';

    }

    }

       document.onmousemove = function(e) {

        if (xxx == 0) {lololol(e);}

    }

Moves the button around. Then it redirects you:

function updateActiveElement()

{

    if ( $(document.activeElement).attr('id')=="xxx" ) 

    {

        clearInterval(interval);

        xxx=1;

window.location = "gallery.html";

    }    

}

 

2. The "tamper-proof" survey page

Is just an iframe with the link above. But there's some interesting JavaScript going on. It checks the following things:

  • That you haven't got an adblocker
  • If you're using mozilla firebug or other javascript console
  • If you're moving around the elements using this console or css editor

3. WTF is "surveys for charity?"

 

 

It's a website set up by the CPA leads (the company behind this). CPA Leads doesn't seem to be a serious company in any way. Registrar info for "surveys for charity": (whois.domaintools.com)

Domain Name:SURVEYSFORCHARITY.ORG
Created On:22-Jan-2010 20:19:29 UTC
Last Updated On:24-Mar-2010 03:48:04 UTC
Expiration Date:22-Jan-2012 20:19:29 UTC
Sponsoring Registrar:GoDaddy.com, Inc. (R91-LROR)
Status:CLIENT DELETE PROHIBITED
Status:CLIENT RENEW PROHIBITED
Status:CLIENT TRANSFER PROHIBITED
Status:CLIENT UPDATE PROHIBITED
Registrant ID:CR40825751
Registrant Name:CPAlead LLC
Registrant Organization:CPAlead.com
Registrant Street1:6845 Escondido Street
Registrant Street2:#107
Registrant Street3:
Registrant City:Las Vegas
Registrant State/Province:Nevada
Registrant Postal Code:89119
Registrant Country:US
Registrant Phone:+1.8669964666
Registrant Phone Ext.:
Registrant FAX:+1.2629224231
Registrant FAX Ext.:
Registrant Email:

 

4. Why the fuck are they doing this?

 

 

I don't know if there is any money in this. The company, CPA Lead, has at least fooled some people into believing that they can make money by serving up others peoples websites through a CPA Lead script. How much CPA themselves get from this, i don't know... Seems like they only wanna waste your time. By spreading it through facebook, using your friends as referalls, they can quickly get a lot of clicks. Its hard to find any information on how much each of these surveys pay, but it seems to be a couple of dollars, or some cents. 

The site 101hottestwomen.com is registered using a name protection service. That seems to be the case with these kind of things.

All the files i've found can be downloaded on: karlwestin.dienstleistungen.ws/scam_decon.zip

 


 

 

HTML5 in internet explorer 6

Wow!
You couldn't believe that!
When doing the final checks on the site for Malmö Stad Sommarscen (http://www.sommarscen2010.se) in Internet Explorer 6, it worked almost perfectly at the first attempt! And it's written using a lot of HTML5 tags, like <header> <nav> <section> and <article> !!
Who would have thought that??

OK, here's how we roll:

1. Register tags

Ok, IE6 won't recognize the tags without hassle. You'll need to "register" the tags by running a document.createElement(); on each of the tags you're gonna use before you can use them:

example:
         <script>
                  document.createElement("header");
         </script>

Of course, someone has already done this for us, so i used:

         <!--[if lt IE 9]>
                    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" ></script>
         <![endif]-->

instead. Yes this code is CDN-hosted and you can hotlink it!

Optimizers!! Yessir we want our JS at the bottom, but this one you'll need to keep in the <head> section, else it won't work!

2. Some "safe" css

Then, in order to make sure the elements behaved as i wanted, i used some CSS:

article, header, section, nav, footer {
         display: block;
         position: relative
}

3. The double margin float bug:

To make your floats work in internet explorer 6, you'll have to give them half the margin in the direction the elements are floated. For example, if your original css is:

section {
         float: left;
         margin: 10px 16px 20px 16px;
}

you'll have to follow that up with:

* html section {
         margin-left: 8px;
}

Yes the star (*) is THE way to target internet explorer in your css files. First you write for everyone else, then you follow that by * html (tag) – forget about adding an extra stylesheet, adding extra HTTP-requests. This is how we roll!

We'll that's about it!
If you're site is well coded in general, things should work now!

Comments? Better ideas? Tips? Cool! Comment, please!

Facebook, pyFacebook and the infamous IntegrityError

Currently developing the WalkTheTalk facebook app – i encountered a REALLY annoying error. When i tried to access the application, i got a 500 internal server error. When my friends accessed it, they got in. Why?

Integers and databases
Turns out pyFacebook uses a IntegerField to storing the user id. However, mid 2009 facebook got to many users to store in such a field. My user id had too many figures.

How to solve:
1. Changing the python:
Go to your application folder, and open the models.py file.

• Change all the table fields that uses the user id from models.IntegerField to models.CharField(max_length=64);
example:
        user_id = models.IntegerField
will be:
        user_id = models.CharField(max_length=64)

Then go to the fbcon folder of your web root.
Find the line that says:
        id = models.IntegerField
into
        id = models.CharField(max_length=64, primary_key=True)

2. Altering the mySQL database:
Log on to your mysql database:
        mysql -u username -p
        use
databasename;

First, you'll have to change to pyFacebook user table:
      ALTER TABLE fbcon_use MODIFY id char(64);

Then change the other fields needed in your app with the same command.

That's it, Cheers!