PHP in_array equivalent for Javascript

Lately I have been doing a lot work with passing data back and forth between Javascript and PHP and I often am working on arrays on the Javascript side and there is no easy native method to test whether an array contains a certain value. So I wrote my own.

function in_array(needle, haystack, strict) {
    for(var i = 0; i < haystack.length; i++) {
        if(strict) {
            if(haystack[i] === needle) {
                return true;
            }
        } else {
            if(haystack[i] == needle) {
                return true;
            }
        }
    }

    return false;
}

You could also prototype it to be built in to the native Array object. You just have to tweak the code a little.

function in_array(needle, strict) {
    for(var i = 0; i < this.length; i++) {
        if(strict) {
            if(this[i] === needle) {
                return true;
            }
        } else {
            if(this[i] == needle) {
                return true;
            }
        }
    }

    return false;
}

Array.prototype.in_array = in_array;

// example usage

var test = new Array();
test.push('i');
test.push(1);

test.in_array('i'); // true
test.in_array('i', true); // true
test.in_array('b'); // false
test.in_array(1, true); // true
test.in_array('1', true); // false

Xen on Ubuntu 8.04 (Hardy Heron)

I have been setting up Xen based virtualization and I just wanted to post the useful links I have found. Unfortunately (at the time of this writing) there are couple of bugs in the Ubuntu repositories for Xen that can make installing and configuring Xen a bit of a headache.

This article on HowtoForge pretty much gives you everything your need to get going (even how to get around the current bugs).

http://www.howtoforge.com/ubuntu-8.04-server-install-xen-from-ubuntu-repositories

This is the user manual for Xen. Unfortunately it is not very descriptive in places, but it is still a good resource.

http://tx.downloads.xensource.com/downloads/docs/user

This is the manual page for xen-create-image. It has some really great examples to base your DomU creation commands from.

http://man.cx/xen-create-image

Below is the Ubuntu community documentation for Xen. They still need some time to update to Hardy.

https://help.ubuntu.com/community/Xen

Static IP Address in Linux (Ubuntu)

Sometimes it can be useful to give a computer a static IP address. I was working on a Xen cluster and kept having to setup each machine with a static IP. I am posting this here to help me remember.

Edit this file.

sudo vim /etc/network/interfaces

Look for the lines that should say something like the following.

auto eth0
iface eth0 inet auto

This is presuming you only have one ethernet device in you computer. If you have more than one you may need to change eth1 or eth2 (or whatever), depending on which one you are using.

Take those lines and make it look something like this.

auto eth0
iface eth0 inet static
    address 192.168.0.150
    netmask 255.255.255.0
    network 192.168.0.0
    broadcast 192.168.0.255
    gateway 192.168.0.1

The ‘address’ is the static IP address that you choose. The rest of those could also be different depending on your network configuration and the IP address of your router (’gateway’ is usually the IP of your router).

After you get that setup like you want you can restart networking to test it out.

sudo /etc/init.d/networking restart

Then you can check that everything is correct by looking at the output of ifconfig.

ifconfig

It should show your device and the static IP address.

I was doing this on Ubuntu, but it should work for other distros as well.

Here is the reference link that helped me figure this out.

http://codesnippets.joyent.com/posts/show/319

Find Out If You Are Paying Too Much For Rent

This is a simple website that I came across yesterday that aggregates rental information from across numerous rental searching sites. You tell it where you live, a little bit about the property and how much you are currently paying in rent each month and it will give you a report about the area and how your rate compares to comparable listings in the area.

I really like this site because it has a clear, simple and useful purpose and it is very easy to use.

Check it out and find out if you are paying too much in rent.

http://www.rentometer.com

New Projects Page

I am putting together a new page on my website to keep track of all the random projects I am working on or have worked on in the past. I am hoping this will help me get all the stuff I have built over the years organized and out to the community so it can be useful to the world instead of just collecting dust on my backup hard drives.

Check it out here.

Improved Smarty strip_tags Modifier Plugin

I wrote this because I wanted to incorporate normal php strip_tags functionality into the Smarty modifier. I structured it so it would retain backwards compatibility with the original Smarty strip_tags modifier. You should be able to drop it into your plugins folder and run with it (name the file modifier.strip_tags.php).

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty strip_tags modifier plugin
 *
 * Type:    modifier

 * Name:    strip_tags

 * Purpose: strip html tags from text
 * @link    http://www.smarty.net/manual/en/language.modifier.strip.tags.php
 *          strip_tags (Smarty online manual)
 *
 * @author  Monte Ohrt <monte at ohrt dot com>
 * @author  Jordon Mears <jordoncm at gmail dot com>
 *
 * @version 2.0
 *
 * @param   string
 * @param   boolean optional
 * @param   string optional
 * @return  string
 */
function smarty_modifier_strip_tags($string) {
    switch(func_num_args()) {
        case 1:
            $replace_with_space = true;
            break;
        case 2:
            $arg = func_get_arg(1);
            if($arg === 1 || $arg === true || $arg === '1' || $arg === 'true') {
                // for full legacy support || $arg === 'false' should be included
                $replace_with_space = true;
                $allowable_tags = '';
            } elseif($arg === 0 || $arg === false || $arg === '0' || $arg === 'false') {
                // for full legacy support || $arg === 'false' should be removed
                $replace_with_space = false;
                $allowable_tags = '';
            } else {
                $replace_with_space = true;
                $allowable_tags = $arg;
            }
            break;
        case 3:
            $replace_with_space = func_get_arg(1);
            $allowable_tags = func_get_arg(2);
            break;
    }

    if($replace_with_space) {
        $string = preg_replace('!(<[^>]*?>)!', '$1 ', $string);
    }

    $string = strip_tags($string, $allowable_tags);

    if($replace_with_space) {
        $string = preg_replace('!(<[^>]*?>) !', '$1', $string);
    }

    return $string;
}

/* vim: set expandtab: */

?>

Two examples of same as always:

{$var|strip_tags}

{$var|strip_tags:false}

An example of php style strip_tags (will leave b and p tags):

{$var|strip_tags:'<b><p>'}

An example of both old and new functionality together:

{$var|strip_tags:false:'<b><p>'}

The original plugin (and therefore this plugin) is licensed under the LGPL.

Here is the link to its place on the Smarty plugin wiki.
http://smarty.incutio.com/?page=StripTags

Validating a Multiple Select in Javascript

The other day someone asked me how to validate a multiple select on a form in Javascript. They needed to check that the person filling out the form at least chose one option. This is what I came up with off of the top of my head.

Here is a basic multiple select.

<select id="color" multiple="multiple" size="5">
  <option>Red</option>
  <option>Orange</option>
  <option>Yellow</option>
  <option>Green</option>
  <option>Blue</option>
</select>

Here is the Javascript function code that you can pass a reference to a select to and it will return true if one or more options are chosen, otherwise it will return false.

function multiselect_validate(select) {
    var valid = false;
    for(var i = 0; i < select.options.length; i++) {
        if(select.options[i].selected) {
            valid = true;
            break;
        }
    }

    return valid;
}

Here is an example of how you could call the above function on a select.

// referencing the select above by id
multiselect_validate(document.getElementById('color'));

The example above is a little limited in that it will only ensure that at least one option is chosen. It wont work if you need to check that at least two (or more) options are selected. This modified function can take an additional argument to specify how many options need to be selected.

function multiselect_validate(select, num) {
    if(!num) {
        num = 1;
    }

    var valid = false;
    var found = 0;
    for(var i = 0; i < select.options.length; i++) {
        if(select.options[i].selected) {
            found++;
            if(found == num) {
                valid = true;
                break;
            }
        }
    }

    return valid;
}

Be a Patriot When it Comes to SPAM

I was perusing around the website of the Federal Trade Commission brushing up on my rights as an american consumer (I was looking into policy related to telemarketing and cell phones). I noticed that they actually have a database for email spam, they ask you to forward mail to spam@uce.gov. So as you get annoying (and illegal) email messages you can do you part to help fight spam.

http://www.ftc.gov/ftc/contact.shtm

Open Source Password Strength Meter

This is a Javascript based password strength tester. It works really well and the code is available under the GPL.

http://www.passwordmeter.com

Counting the Lines in a Set of Files

I find myself needing this command every once in a while and I can never remember exactly how it goes. It parses through a directory (and subs) to give you a report on how many lines are in each file. It is great for working with csv files.

wc -l `find ./ -name '*.csv'`

I got this from an old post on Dev Shed forums that I participated in. I posted it here so I don’t have to keep seeking out the post every time I am trying to remember this command.

http://forums.devshed.com/showthread.php?p=1857692#post1857692

...older
{
}