Underscore.js 101 – _.filter and _.contains

Underscore.js one of the powerful utility JS libraries out there. In this post am goin to explain some of the functions and how they can be mixed and matched to get our required functionality.

_.filter:

_.filter it looks through the list we pass and returns all the values that are truthy as per the iterator.

var odds = _.filter([1,2,3,4,5,6], function(num){ return num % 2 !== 0})
// [1, 3, 5]

returns all the odd number on the list.

Lets take an example you have a list of strings.

var langs = ['Ruby', 'RoR', 'Python', 'Django', 'Java', 'Javascript', 'Node.js'];

You want to extract the items based on the starting letter in a word

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R'}) // ["Ruby", "RoR"]

for searching between more than one letter you may have to do something like this

_.filter(arr, function(i){var startLetter = i.slice(); return startLetter[0] === 'R' || startLetter[0] === 'P'}) // ["Ruby", "RoR", "Python"]

It will become more complex if we are goin to add more letters to support in this, we can minimize the complexity with one more function Underscore provides us.

_.contains:

_.contains returns true if the passed value is present in array.

_.contains([1, 2, 3], 3); // true

this can be used in our existing filter function to reduce the long list of OR conditions

_.filter(arr, function(i){var startLetter = i.slice(); return _.contains(['R', 'P'],startLetter[0])}) // ["Ruby", "RoR", "Python"]

this is easy to maintain and scalable.

Image Compression and CSS Sprites – Web Developer Tools

So here are some of the links. I found useful while developing, for image compression and in making sprites

SpritePad


SpritePad is the best tool I have seen so far to create CSS Sprites. You can simply drag and drop the images and download the sprite. Fit document is a nice feature. Also it gives the style accordingly for individual pngs with their name as classname.

Sprite Cow


Using sprites needs some experience as it is hard to find the perfect CSS position. SpriteCow helps in it. Open an image in this web app and point your mouse to the image on the sprite to get the exact CSS position and code. If you already have a sprite this is what you should be using for gettin positions.

TinyPNG


In cases were you can’t use sprites, and have to use individual pngs. The best thing you can do is reduce the size of the png so that you can improve performance of your site. TinyPNG is the best i have seen so far in doin that. I have seen a good amount of reduction in size. I highly suggest you use this in your project, you can reduce the size of the sprite as well in this, to get better results.

JPEGmini

It does the same thing as TinyPNG, but for JPEG files. I like the way they show the original and the minimized version.

cropp.me

Easier way to crop your image files.

Conversions in Javascript

Using Javascript has an ease, you can achieve the same result by doing it in different ways. Here am going to discuss about the performance implications of the same. Lets start with string to number conversion. The usual way of string to number conversion is done using parseInt. However there are someother ways it can be done as well

var n1 = parseInt("12");
var n2 = Number("12");
var n3 = +"12";
var n4 = ~~(1*"12");

All of the above does the same job and n1==n2==n3==n4. So, of all the ways we have to see which one is the ideal way to do that. This is where performance is a big consideration. In this jsperf test we can see which one performs well. Of four of them the last wicked way performs well in all browsers except chrome and safari webkit browsers(I don’t know why). At the end the best way is to use the parseInt, somebody might prefer using +”Value” for ease of typing. However should know the performance benefits of the other ways. Similarly, string conversion

var date = new Date();
var ds = date.toString();
var dr = date+"";

In this case ds==dr, the way toString works is faster in most cases.

Brain Effing Javascript

Javascript has always been fascinating to me in so many ways, because it packs in so many things for a language that has been developed in 2 weeks (there were improvements after that). Look at this

JavaScript

  var truthy = true;
  if(truthy === !+[]){
    console.log("It's Truthy");
  }

Put this in the console and it prints the value. It’s ’cause

!+[] === true

javascript interprets the combination of these special characters into actual values. Similary

!!+[] === false

And also you can get numbers like this

+[] === 0
+!+[] === 1
!+[]+!+[] === 2
....

We can create all the numbers by adding !+[] like that. Using this, if you want your fellow programmer to go mad you can do something like this

JavaScript

 
var l = +!+[];
for (var i = +[]; i <= !+[] + !+[]; i++) {
    l = l + (+!+[]);
    console.log(l);
}

with these special character combinations, a complete program can be written in javascript.

Further reading:

http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html

jQuery AnimationEnd Plugin – Provides a callback when a CSS3 animation is complete on an element

There will be some instances where in we have to do something after a CSS3 animation is complete on a particular element. This plugin will come in handy on those cases.

Plugin attaches to the animationEnd and transitionEnd events, fired when an animation is complete and provides a callback.

Javascript

$.fn.animationEnd = function(callback) {
        return this.each(function(){
          var $this = $(this);
              $this.bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd transitionend webkitTransitionEAnind oTransitionEnd MSTransitionEnd", function() {
                if (typeof callback == 'function') {
                    callback.call(this); // brings the scope to the callback
                };
            });
        })
        
    };

In the demo, I have a case where we want to remove the class which provides the css3 styles, at the animation end so that we can add the class again to trigger the animation.

Demo

Suggestions are welcome to improve this plugin.Please, point out mistakes as well.

Twitter feed on Python using YQL and BeautifulSoup

Uses YQL’s Rest query (select * from twitter.user.timeline where id=’vetri02′)

import urllib2

from BeautifulSoup import BeautifulStoneSoup

var = raw_input("Enter your Twitter id: ")

print "Tweets of", var

er = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20twitter.user.timeline%20where%20id%3D'"

fg = "'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"

zx = er+var+fg

page = urllib2.urlopen(zx)

soup = BeautifulStoneSoup(page)

tweet = soup.findAll('text')

for twt in tweet:

    print twt.string

On Github

https://github.com/vetri02/Twitter-feed-on-Python-using-YQL-and-BeautifulSoup

 

 

Retreive data from google spreadsheet using python and beautiful soup

Create a spreadsheet on google doc share it and publish as web page ,take the url and put it instead of the URL pasted here on the code.You can retrieve the column values accordingly by changing the class name on soup.findAll (eg.:’class’ : ‘s1′)

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("https://spreadsheets.google.com/pub?key=0AujzeBNXnyI-dDNBRFJZaTZyRnZnMzdnQlFzSkRsd2c&hl=en&output=html")

soup = BeautifulSoup(page)
ted = soup.findAll('td',{ 'class' : 's1'})
for td in ted:
print td.string