Collection of jQuery plug-ins for front-end design and development

Just found out this great site to find jQuery plugins. Worth to check it out.

Unheap was assembled in 2010 as an internal team resource. We found other repositories underwhelming and wanted to build a better experience for browsing & staying on top of the latest jQuery plugins. We made the site public on November 2012.

We’ve put a lot of effort into organizing, categorizing, thumbnailing and tagging plugins on our site and making sure things are as consistent as possible. There is plenty of room for improvement though, and we’d love your help to make things better. Send in feedback, suggestions or report bugs via the feedback form or by using Twittersubmit the freshest jQuery plugins and share the site if you find it useful.

Url: http://www.unheap.com/

Search on Amazon based on what others buy

Really cool project that allows one to visualize what other people have bought based on a search query.

 

 

This is particulary good to find book about a topic, for example lets say you’re trying to find some book about php performance as you can see it sugests heaps of interesting books based on hive-mind tastes.

Urlhttp://www.yasiv.com/amazon#/Search

Run parallel (threaded) bash commands with a job limit from file

I wanted to change mysql databases to use innodb_file_per_table problem is even if you add this to your my.cnf it will only affect newly created tables.

In order to alter existing ones I needed to run a bunch of alter tables with ENGINE=InnoDB. Because I have heaps of database and even more tables this was proving to be a huge time sink and my system was only using 1/16 of its resources since mysql only uses one thread per query.

To use multi thread power I needed to be able to run multiple queries at the same time but not too many otherwise I’ll hit the max amount of connection limit or max allowed number of forks.

Here’s the small script I wrote to overcome this problem:

# Read line in ~/tmp/convert_tables.txt
while read command; do
    # Echo with command are we running (I love stdout)
    echo $command;

    # Run the command in backgroud
    `bash -c "$command"`&

    # This is the where magic happens,
    # we don't want to have more than 10 jobs running
    # so with a simple while counting the jobs running we 
    # can put the script "on hold" until other jobs finish
    while [ `jobs | wc -l` -gt 10 ]; do
        sleep 1;
    done

done < ~/tmp/convert_tables.txt

Inside convert_tables.txt I just have the commands I want to run, here a example set:

mysql -u root -e "alter table db1.keyvalue ENGINE=InnoDB;"
mysql -u root -e "alter table db2.acl_role ENGINE=InnoDB;"
mysql -u root -e "alter table db2.acl_role_has_privilege ENGINE=InnoDB;"
...

Althout this post is about the threaded “jobs” if you’re wondering how to generate the table alter commands I follow this example:  innodb_file_per_table – Converting to Per Table Data for InnoDB

PHP strtotime WTF!

So I just spent almost a day chasing a (what I thought it was) a bug in my code regarding dates.

I needed to add a month to a specific date  so I can bill ongoing contracts, but the returned date sometimes where full “calendar” months other times it was 31 days.

Let me show:

echo date("Y-m-d", strtotime("+1 month 2011-11-21"));
returns: 2011-12-21 // appears to be right

echo date("Y-m-d", strtotime("+1 month 2011-11-30"));
returns: 2011-12-30 // wtf? but I wanted 2011-12-31

echo date("Y-m-d", strtotime("+1 month 2011-12-15"));
returns:  2012-01-15 // hum? that is right

echo date("Y-m-d", strtotime("+1 month 2012-01-31"));
returns: 2012-03-02 // wtf? I wanted 2012-02-29

echo date("Y-m-d", strtotime("+1 month 2012-01-01"));
returns: 2012-02-01 // oh! that's right

echo date("Y-m-d", strtotime("+1 month 2012-02-01"));
returns: 2012-03-01 // sigh... That's right to what's going on here?

As you can see above sometimes PHP return full calendar months other 31 days. Fortunately there’s a pattern:

The way I see it if the day is not in the end of the month PHP will add a calendar month if it’s in the end of the month PHP will add the number of days that the current month has.

So if you want to make sure PHP always adds a calendar month to your date this is how I did it:

$tmp_date1 = strtotime("+1 day", strtotime("2012-01-31"));
$tmp_date2 = strtotime("+1 month", $tmp_date1);
$final_date = date('Y-m-d', strtotime("-1 day", $tmp_date2));

This ensures that if your date is in the end of the month strtotime will make calculation with the beginning of the month that way full calendar months will be added instead of number of days that current month has.

Reddit discussion about this

FuelPHP Input arrays validation

After pulling some hair and digging a lot in FuelPHP core I finally discovered a litle hack that allows validation of input arrays and its re-population using FuelPHP Validation Class.

Here’s how I did it:

View simplified for the sake of the example:

<?php echo \Form::label("Price", "options[0][price]"); ?>
<?php echo \Form::input("options[0][price]", \Validation::instance()->input("options.0.price"); ?>

<?php echo \Form::label("Name", "options[0][name]"); ?>
<?php echo \Form::input("options[0][name]", \Validation::instance()->input("options.0.name"); ?>

<?php echo \Form::label("Price", "options[1][price]"); ?>
<?php echo \Form::input("options[1][price]", \Validation::instance()->input("options.1.price"); ?>

<?php echo \Form::label("Name", "options[1][name]"); ?>
<?php echo \Form::input("options[1][name]", \Validation::instance()->input("options.1.name"); ?>

Mind the options.0.name instead of options[0]name inside the Validation Input.

In my controller I did this:

$val = \Validation::factory();

if ( \Input::post("options") )
{
    $form_options = \Input::post("options");

    foreach ( $form_options as $form_id => $option )
    {
        $val->add("options.{$form_id}.price", "{$option["name"]} price")
                ->add_rule("required")
                ->add_rule("match_pattern", '/[0-9]*(\.|,)?[0-9]+/');

        $val->add("options.{$form_id}.name", "{$option["name"]} name")
                ->add_rule("required");

    }
}

 

And that’s it, this should validate the fields and repopulating them in case of errors. It’s a bit stupid that it only works like this.

FuelPHP should provide a friendlier way and a documented one to validate array input fields, it’s a common feature when dealing with dynamic built forms that have one-to-many objects in it.

 

Tested with FuelPHP 1.0.1

FuelPHP BreadCrumb Class/Library

Morning,

Just finish building a breadcrumb Class for FUELPHP.

This Class has persistent crumbs, meaning that visited crumbs will be saved in session.

GitHub link for FuelPHP-BreadCrumb

Read more »

Jump Tables Explained

A jump table is an array of function pointers or even machine instructions, each of which actually performs the jump. The latter is commonly used in assembly language and can be produced by compilers, but the former is something you’re likely to write yourself, often to help simplify some code.

Read more »

Check if all function arguments are equal in PHP

Question: Could this be written better?

private function compareThree($val_1, $val_2, $val_3)
{
    return (($val_1 == $val_2) && ($val_1 == $val_3) && ($val_2 == $val_1) && ($val_2 == $val_3) && ($val_3 == $val_2) && ($val_3 == $val_1));
}

Short Answer: Yes! That’s horrible and makes my eyes bleed.

Long Answer: Why compare only three? Why not build a function that compares a infitine number of arguments and check if they are all equal. Here’s my solution:

function compareAllTheArguments()
{
    return count(array_unique(func_get_args())) === 1;
}

Explanation:

func_get_args() // Get all function arguments in array list

 array_unique() // Removes duplicate values from an array

count() // Well, yeah, returns the number of elements in a array

Knowing this first we get all the arguments in the function then remove all the duplicates and if it’s only one left that means all elements are equal.

Get last key from array in PHP

The fastest and the correct way to get the last key from an array is:

$lastkey = array_pop(array_keys($arr));

Example:

$arr[] = array("red" => "apple", "yellow" => "banana");

Let’s say you want to add another element to the previous created array, for that you need to know the last created index so:

$lastkey = array_pop(array_keys($arr));
$arr[$lastkey]["brown"] = "kiwi";

And there you have it.

Prevent hotlinking with apache

To allow all domain except one:

RewriteCond %{HTTP_REFERER} ^http://(www\.)?offendinddomain\.com/$ [NC]
RewriteRule \.(gif|jpg|png)$ http://example.com/hotlink.png [R,L]

This will prevent holinking from the domain offendingdomain.com and serve the image from example.com instead.

Prevent more than one domain:

RewriteCond %{HTTP_REFERER} ^http://(www\.)?offendinddomain\.com/$ [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://(www\.)?offendinddomain2\.com/ [NC]
RewriteRule \.(gif|jpg|png)$ http://example.com/hotlink.png [R,L]

This will prevent hotlinking from the 2 offendind domains, if you need more just duplicate the second line.

Block all:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/.*$ [NC]
RewriteRule .*\.(gif|jpe?g|png)$ http://example.com/hotlink.png [R,NC,L]

This will block all hotlinking and and serve the image from example.com instead.

 

NOTE: Be carefull not to rewrite to a image in the same domain as yours or you could create a redirect loop.