jQuery this selector

http://www.javascript-coder.com/jquery/jquery-selector-this.phtml

 

When you handle events for a particular element, it is often required to make a change only within children of the element. Here is how to do it.

Suppose this is the HTML code

<h2>Select the services you want:</h2>
<ul id='services'>
<li><img src='tick.gif'>Build a Website</li>
<li><img src='tick.gif'>Page design</li>
<li><img src='tick.gif'>Flash banners</li>
<li><img src='tick.gif'>SEO</li></ul>
</ul>

When someone clicks on each of the service, the image is to toggle.
Here is the jQuery code to do that

$(function()
{
    //handle the click for each of 'li'
    $('ul#services li').click(function()
    {
        //toggle the image
        var newimg =
            $('img',this).attr('src') == 'tick.png' 'cross.png' 'tick.png';
        /*
        notice the second parameter to $() is the context.
         'this' is the 'li' that was clicked.*/
        $('img'this).attr('src',newimg);
    });
});

jQuery draggable and resizable images

http://jsbin.com/ipoxe5/edit#javascript,html,live

 

$(document).ready(function(){

  $(“img”).resizable({ handles:’n,e,s,w,ne,se,nw,sw’ , maxHeight: 300, aspectRatio: true }).parent().draggable({containment: “#droppable”, snap:false});  

  $( “#droppable” ).droppable({

      drop: function( event, ui ) {

        $( this )

          .find( “p” ).hide();

      }

    });

});

Input field label alignment wrap float wrapping

http://ryanflorence.com/sandbox/aligned-labels.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

	<title>untitled</title>
	<style type="text/css">
	ol{
		padding-left: 0;
		margin-left:0;
	}

	ol>li {
		list-style-type: none;
		margin-bottom: .5em;
	}

	ol>li input[type=radio] {
		display: -moz-inline-box;
		display: inline-block;
		vertical-align: middle;
	}

	ol>li label {
		display: -moz-inline-box;
		display: inline-block;
		vertical-align: middle;
	}
	</style>
</head>

<body>
	<fieldset>
	    <legend>Radio Buttons</legend>
	    <ol>
	        <li>
	            <input type="radio" name="radio" id="x">
	            <label for="x">blah blah<br/>blah blah<br/>blah</label>
	        </li>
	        <li>
	            <input type="radio" name="radio" id="y">
	            <label for="y">blah blah<br/>blah blah<br/>blah</label>
	        </li>
	    </ol>
	</fieldset>

</body>
</html>

jQuery Hover DIV pop-up slide up

http://buildinternet.com/2009/03/sliding-boxes-and-captions-with-jquery/

 

$(‘.container’).hover(function(){

var position = $(this).children().position();

$(“.detail”, this).stop().animate({bottom: 0},{queue:false,duration:600});

}, function() {

var position = $(this).children().position();

$(“. detail”, this).stop().animate({bottom : -70},{queue:false,duration:600});

});

});

Promise Smartstor 4300n hack hacking

  1. Go to http://www.16paws.com/projects/NS4300N/dropbear.html
  2. Download the http://www.16paws.com/projects/NS4300N/dropbear_ppg/dropbear_005200.ppg
  3. Copy ppg file to your Promise drive
  4. Go to your web admin for your 4300n drive
  5. Go to Application Plug-ins and enable the new ppg file
  6. SSH into your promise drive using ssh admin@IP address using your admin password

Once you are inside SmartStor SSH:

  • The sudoers file is at /etc/sudoers
  • Type uname -mrs to see the operating system. Should be Linux 2.6.11SR3_1_2 ppc
  • You can copy and move files using cp and mv commands
  • Commands are: alias bg break cd chdir command continue eval exec exit export  false fg getopts hash help jobs kill let local pwd read readonly  return set shift times trap true type ulimit umask unalias unset  wait [ ash basename bunzip2 busybox bzcat cat chgrp chmod chroot  chvt clear cmp cp cut dd deallocvt df dirname dmesg du echo egrep  env expr false fgrep free getty grep gunzip gzip head hostname  id ifconfig insmod install kill killall ln loadkmap logger login  ls lsmod mkdir mknod mkswap more mv netstat nslookup openvt passwd  pidof ping ps pwd reset rm rmdir rmmod route run-parts sed sh  sleep sort start-stop-daemon strings stty sulogin swapoff swapon  sync tail tar tee test time top touch tr true tty uname uniq  unzip uptime usleep vi vlock wc whoami xargs yes zcat 

 

Latest DLNA drivers

this is the new ftp address for the DLNA plugin 01.02.0000.05 A6
thanks to Promise on Twitter

ftp://oem.promise.com
username: promisenas
password: dlna

Go here to learn more http://www.avsforum.com/avs-vb/showthread.php?t=859675&page=19

http://mizupc8.bio.mie-u.ac.jp/pukiwiki/?Promise%20NS4300N#hf420c97

Know any more hacks? I want to increase the speed of copies. 4300n is so damn slow over network.

Useful UNIX commands to remember

history
get history of commands

history | grep “sudo”
find all history of commands that has sudo in it

history > commands.txt
output the history to a text file

increase scrollback buffer in OS X

  1. Edit .bash_profile 
  2. Add HISTFILESIZE=2000

 

Copy files recursively keeping directories
cp . -b –parent /usbdrive

Find files by certain size and copy them
find . -size -4gb -exec cp -b –parent ‘{}’ /downloads \;

restart shell

  • . .bash_profile
  • sh .bash_profile

 

Rsync only certain file size
rsync -rv –max-size=1.5m root@tss01:/tmp/dm

Prevent SSH disconnect
edit /etc/ssh/ssh_config
ServerAliveInterval 100

Copy files without overwrite and typing Y over and over again
yes n | cp -R -h -i /dirone/* /dirtwo 

Creating alias shortcuts
alias browse=’nautilus’
alias gohere=’cd /gohere’

You can save shorts to your .bash_profile file. 

Convert unix timestamp to facebook style date format using javascript

http://forrst.com/posts/Facebook_style_live_dates_in_JavaScript-hro

 

 

/**
 * date_suffix()
 * returns the date suffix (st,nd,rd,th) for a given day in a month
 *
 * @author: Andy Thomas (forrst@antom.co.uk)
 * @date: 27/09/2010
 */

function date_suffix(date) {
        if (date == 1 ||  date == 21 || date == 31) {
                return 'st';
        } else if (date == 2 || date == 22) {
                return 'nd';
        } else if (date == 3 || date == 23) {
                return 'rd';
        } else {
                return 'th';
        }
}

/**
 * time_since()
 * returns the time passed since a given unix_timestamp.
 * eg. 10 seconds ago, 1 hour ago, 10th Sep etc
 *
 * @author: Andy Thomas (forrst@antom.co.uk)
 * @date: 27/09/2010
 */
function time_since(original) {
        original = new Date(original * 1000);
        
        var str = '';
        
        var months = [
                'Jan',
                'Feb',
                'Mar',
                'Apr',
                'May',
                'Jun',
                'Jul',
                'Aug',
                'Sep',
                'Oct',
                'Nov',
                'Dec'
        ];
        
        var chunks = [
                [31536000000, 'year'],
                [2592000000, 'month'],
                [604800000, 'week'],
                [86400000, 'day'],
                [3600000, 'hour'],
                [60000, 'minute'],
                [1000, 'second'],
        ];
        
        var today = new Date();
        var since = new Date(today.getTime() - original.getTime());
        
        if (since.getTime() > 604800000) {
                str = months[original.getMonth()] + ' ' + original.getDate() + date_suffix(original.getDate());
                
                if (since.getTime() > 31536000000) {
                        str = str + ', ' + original.getFullYear();
                }
                
                return str;
        }
        
        var ms = 0;
        var name = 0;
        var i = 0;
        var ic = chunks.length;
        var count = 0;
        
        for (i=0;i<ic;i++) {
                ms = chunks[i][0];
                name = chunks[i][1];
                
                count = Math.floor(since.getTime() / ms);
                
                if (count != 0) {
                        break;
                }
        }
        
        return count + ' ' + name + ((count == 1) ? '' : 's') + ' ago';
}

 

Good tutorial on AJAX requests using jQuery

http://kyleschaeffer.com/best-practices/the-perfect-jquery-ajax-request/

 

The Perfect AJAX Request

I’m fairly positive that by using the term perfect, I’m going to get a good amount of nay-sayers telling me why jQuery AJAX sucks, but that’s not what I’m getting at. This jQuery function is perfect in the sense that it handles 99% of all the AJAX requests you’ll ever need to make, it includes a success and failure function to ensure that users get the proper feedback they need, and you’ll get a spinning loading image while the request is being processed to boot. Throw on top of that the fact that it’s extremely easy to use, and I’d say you have something that’s pretty damned close to perfect, at least in my book. Here is the template:

$.ajax({
  type: 'POST',
  url: 'http://kyleschaeffer.com/feed/',
  data: { postVar1: 'theValue1', postVar2: 'theValue2' },
  beforeSend:function(){
    // this is where we append a loading image
    $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
  },
  success:function(data){
    // successful request; do something with the data
    $('#ajax-panel').empty();
    $(data).find('item').each(function(i){
      $('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
    });
  },
  error:function(){
    // failed request; give feedback to user
    $('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
  }
});

In this case, I’m loading my site’s RSS feed into a <div/> with an ID of ajax-panel. What does it look like exactly, you ask? Let’s try it out.

Nice PHP file diff code

http://scrivna.com/blog/php-file-diff/

 

<?php
/*
	Ross Scrivener http://scrivna.com
	PHP file diff implementation
	
	Much credit goes to...
	
	Paul's Simple Diff Algorithm v 0.1
	(C) Paul Butler 2007 <http://www.paulbutler.org/>
	May be used and distributed under the zlib/libpng license.
	
	... for the actual diff code, i changed a few things and implemented a pretty interface to it.
*/
class diff {

	var $changes = array();
	var $diff = array();
	var $linepadding = null;
	
	function doDiff($old, $new){
		if (!is_array($old)) $old = file($old);
		if (!is_array($new)) $new = file($new);
	
		foreach($old as $oindex => $ovalue){
			$nkeys = array_keys($new, $ovalue);
			foreach($nkeys as $nindex){
				$matrix[$oindex][$nindex] = isset($matrix[$oindex - 1][$nindex - 1]) ? $matrix[$oindex - 1][$nindex - 1] + 1 : 1;
				if($matrix[$oindex][$nindex] > $maxlen){
					$maxlen = $matrix[$oindex][$nindex];
					$omax = $oindex + 1 - $maxlen;
					$nmax = $nindex + 1 - $maxlen;
				}
			}       
		}
		if($maxlen == 0) return array(array('d'=>$old, 'i'=>$new));
		
		return array_merge(
						$this->doDiff(array_slice($old, 0, $omax), array_slice($new, 0, $nmax)),
						array_slice($new, $nmax, $maxlen),
						$this->doDiff(array_slice($old, $omax + $maxlen), array_slice($new, $nmax + $maxlen)));
						
	}
	
	function diffWrap($old, $new){
		$this->diff = $this->doDiff($old, $new);
		$this->changes = array();
		$ndiff = array();
		foreach ($this->diff as $line => $k){
			if(is_array($k)){
				if (isset($k['d'][0]) || isset($k['i'][0])){
					$this->changes[] = $line;
					$ndiff[$line] = $k;
				}
			} else {
				$ndiff[$line] = $k;
			}
		}
		$this->diff = $ndiff;
		return $this->diff;
	}
	
	function formatcode($code){
		$code = htmlentities($code);
		$code = str_replace(" ",'&nbsp;',$code);
		$code = str_replace("\t",'&nbsp;&nbsp;&nbsp;&nbsp;',$code);
		return $code;
	}
	
	function showline($line){
		if ($this->linepadding === 0){
			if (in_array($line,$this->changes)) return true;
			return false;
		}
		if(is_null($this->linepadding)) return true;

		$start = (($line - $this->linepadding) > 0) ? ($line - $this->linepadding) : 0;
		$end = ($line + $this->linepadding);
		//echo '<br />'.$line.': '.$start.': '.$end;
		$search = range($start,$end);
		//pr($search);
		foreach($search as $k){
			if (in_array($k,$this->changes)) return true;
		}
		return false;

	}
	
	function inline($old, $new, $linepadding=null){
		$this->linepadding = $linepadding;
		
		$ret = '<pre><table width="100%" border="0" cellspacing="0" cellpadding="0" class="code">';
		$ret.= '<tr><td>Old</td><td>New</td><td></td></tr>';
		$count_old = 1;
		$count_new = 1;
		
		$insert = false;
		$delete = false;
		$truncate = false;
		
		$diff = $this->diffWrap($old, $new);

		foreach($diff as $line => $k){
			if ($this->showline($line)){
				$truncate = false;
				if(is_array($k)){
					foreach ($k['d'] as $val){
						$class = '';
						if (!$delete){
							$delete = true;
							$class = 'first';
							if ($insert) $class = '';
							$insert = false;
						}
						$ret.= '<tr><th>'.$count_old.'</th>';
						$ret.= '<th>&nbsp;</th>';
						$ret.= '<td class="del '.$class.'">'.$this->formatcode($val).'</td>';
						$ret.= '</tr>';
						$count_old++;
					}
					foreach ($k['i'] as $val){
						$class = '';
						if (!$insert){
							$insert = true;
							$class = 'first';
							if ($delete) $class = '';
							$delete = false;
						}
						$ret.= '<tr><th>&nbsp;</th>';
						$ret.= '<th>'.$count_new.'</th>';
						$ret.= '<td class="ins '.$class.'">'.$this->formatcode($val).'</td>';
						$ret.= '</tr>';
						$count_new++;
					}
				} else {
					$class = ($delete) ? 'del_end' : '';
					$class = ($insert) ? 'ins_end' : $class;
					$delete = false;
					$insert = false;
					$ret.= '<tr><th>'.$count_old.'</th>';
					$ret.= '<th>'.$count_new.'</th>';
					$ret.= '<td class="'.$class.'">'.$this->formatcode($k).'</td>';
					$ret.= '</tr>';
					$count_old++;
					$count_new++;
				}
			} else {
				$class = ($delete) ? 'del_end' : '';
				$class = ($insert) ? 'ins_end' : $class;
				$delete = false;
				$insert = false;
				
				if (!$truncate){
					$truncate = true;
					$ret.= '<tr><th>...</th>';
					$ret.= '<th>...</th>';
					$ret.= '<td class="truncated '.$class.'">&nbsp;</td>';
					$ret.= '</tr>';
				}
				$count_old++;
				$count_new++;

			}
		}
		$ret.= '</table></pre>';
		return $ret;
	}
}
?>
<style type="text/css">

table.code {
	border: 1px solid #ddd;
	border-spacing: 0;
	border-top: 0;
	empty-cells: show;
	font-size: 12px;
	line-height: 110%;
	padding: 0;
	margin: 0;
	width: 100%;
}

table.code th {
	background: #eed;
	color: #886;
	font-weight: normal;
	padding: 0 .5em;
	text-align: right;
	border-right: 1px solid #d7d7d7;
	border-top: 1px solid #998;
	font-size: 11px;
	width: 35px;
}

table.code td {
	background: #fff;
	font: normal 11px monospace;
	overflow: auto;
	padding: 1px 2px;
}

table.code td.del {
	background-color: #FDD;
	border-left: 1px solid #C00;
	border-right: 1px solid #C00;
}
table.code td.del.first {
	border-top: 1px solid #C00;
}
table.code td.ins {
	background-color: #DFD;
	border-left: 1px solid #0A0;
	border-right: 1px solid #0A0;
}
table.code td.ins.first {
	border-top: 1px solid #0A0;
}
table.code td.del_end {
	border-top: 1px solid #C00;
}
table.code td.ins_end {
	border-top: 1px solid #0A0;
}
table.code td.truncated {
	background-color: #f7f7f7;
}
</style>
<?php
$diff = new diff;
$text = $diff->inline('users_controller.42.php','users_controller.45.php',2);
echo count($diff->changes).' changes';
echo $text;
?>