DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
  • submit to reddit
        Converting from base 2 to int is easy
>>> int('1010', 2)
10
The opposite is a bit involved.
>>> number = 1000
>>> hex2bin = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "A":"1010", "B":"1011",
            "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
>>> "".join([hex2bin[h] for h in '%X'%number]).lstrip('0')
'1111101000'
See the def of toBase2(number) <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528>here</a>
    
        This is a helper that will add class="current" to an anchor, if the actions it is linking to is the current page. Here is the implementation:

def link_to_with_current_class_if_current(name, 
                                          options = {}, 
                                          html_options = {}, 
                                          *parameters_for_method_reference)
  html_options[:class] = "current" if current_page?(options)
  link_to(name, options, html_options, *parameters_for_method_reference)
end

<a href="http://mikezornek.com/archives/2005/09/09/rails_helper_that_adds_classcurrent_to_links.php">More info</a> at on my blog.    
        <% if @lesson_pages.current.previous -%>
  <%= link_to_remote 'Previous page', 
    :url  => { :page => @lesson_pages.current.previous },
    :update  => 'my_div',
    :loading => "Toggle.display('spinner');"
  %>
<% end -%>

This assumes that your paging links are inside the DIV that is being replaced by the Ajax call.

I'll leave 'next' as an exercise for the reader.    
        <a href="http://www.jsfromhell.com/classes/binary-parser">

This is a prototyped class written to serialize and unserialize binary data, so you can read and write binary data files to exchange with programs written in languages like C and Pascal.

Currently the class is able to handle just the following types: signed integers (small 8 bits, short 16 bits, int 32 bits), unsigned integers (byte 8 bits, word 16 bits, dword 32 bits) and floating point (IEEE754 float 32 bits and double 64 bits).

The endianess of the binary values representation can also be configured with the class.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

There's a php version right <a href="http://www.phpclasses.org/browse/package/2454.html">here</a>.

Code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/binary-parser [v1.0]

BinaryParser = function( bigEndian, allowExceptions ){
	this.bigEndian = bigEndian;
	this.allowExceptions = allowExceptions;
};
with( { p: BinaryParser.prototype } ){
	with( {p: ( p.Buffer = function( bigEndian, buffer ){ this.bigEndian = bigEndian || 0; this.buffer = []; this.setBuffer( buffer ); } ).prototype } ){
		p.setBuffer = function( data ){
			if( data ){
				for( var l, i = l = data.length, b = this.buffer = new Array( l ); i; b[l - i] = data.charCodeAt( --i ) );
				this.bigEndian && b.reverse();
			}
		};
		p.hasNeededBits = function( neededBits ){
			return this.buffer.length >= -( -neededBits >> 3 );
		};
		p.checkBuffer = function( neededBits ){
			if( !this.hasNeededBits( neededBits ) )
				throw new Error( "checkBuffer::missing bytes" );
		};
		p.readBits = function( start, length ){
			//shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
			function shl( a, b ){
				for( ; b--; a = ( ( a %= 0x7fffffff + 1 ) & 0x40000000 ) == 0x40000000 ? a * 2 : ( a - 0x40000000 ) * 2 + 0x7fffffff + 1 );
				return a;
			}
			if( start < 0 || length <= 0 )
				return 0;
			this.checkBuffer( start + length );
			for( var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - ( start >> 3 ) - 1, lastByte = this.buffer.length + ( -( start + length ) >> 3 ), diff = curByte - lastByte, sum = ( ( this.buffer[ curByte ] >> offsetRight ) & ( ( 1 << ( diff ? 8 - offsetRight : length ) ) - 1 ) ) + ( diff && ( offsetLeft = ( start + length ) % 8 ) ? ( this.buffer[ lastByte++ ] & ( ( 1 << offsetLeft ) - 1 ) ) << ( diff-- << 3 ) - offsetRight : 0 ); diff; sum += shl( this.buffer[ lastByte++ ], ( diff-- << 3 ) - offsetRight ) );
			return sum;
		};
	}
	p.warn = function( msg ){
		if( this.allowExceptions )
			throw new Error( msg );
		return 1;
	};
	p.decodeFloat = function( data, precisionBits, exponentBits ){
		var b = new this.Buffer( this.bigEndian, data );
		b.checkBuffer( precisionBits + exponentBits + 1 );
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
		divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
		do
			for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
		while( precisionBits -= startBit );
		return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
	};
	p.decodeInt = function( data, bits, signed ){
		var b = new this.Buffer( this.bigEndian, data ), x = b.readBits( 0, bits ), max = Math.pow( 2, bits );
		return signed && x >= max / 2 ? x - max : x;
	};
	p.encodeFloat = function( data, precisionBits, exponentBits ){
		var bias = Math.pow( 2, exponentBits - 1 ) - 1, minExp = -bias + 1, maxExp = bias, minUnnormExp = minExp - precisionBits,
		status = isNaN( n = parseFloat( data ) ) || n == -Infinity || n == +Infinity ? n : 0,
		exp = 0, len = 2 * bias + 1 + precisionBits + 3, bin = new Array( len ),
		signal = ( n = status !== 0 ? 0 : n ) < 0, n = Math.abs( n ), intPart = Math.floor( n ), floatPart = n - intPart,
		i, lastBit, rounded, j, result;
		for( i = len; i; bin[--i] = 0 );
		for( i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor( intPart / 2 ) );
		for( i = bias + 1; floatPart > 0 && i; ( bin[++i] = ( ( floatPart *= 2 ) >= 1 ) - 0 ) && --floatPart );
		for( i = -1; ++i < len && !bin[i]; );
		if( bin[( lastBit = precisionBits - 1 + ( i = ( exp = bias + 1 - i ) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - ( exp = minExp - 1 ) ) ) + 1] ){
			if( !( rounded = bin[lastBit] ) )
				for( j = lastBit + 2; !rounded && j < len; rounded = bin[j++] );
			for( j = lastBit + 1; rounded && --j >= 0; ( bin[j] = !bin[j] - 0 ) && ( rounded = 0 ) );
		}
		for( i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i]; );
		if( ( exp = bias + 1 - i ) >= minExp && exp <= maxExp )
			++i;
		else if( exp < minExp ){
			exp != bias + 1 - len && exp < minUnnormExp && this.warn( "encodeFloat::float underflow" );
			i = bias + 1 - ( exp = minExp - 1 );
		}
		if( intPart || status !== 0 ){
			this.warn( intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status );
			exp = maxExp + 1;
			i = bias + 2;
			if( status == -Infinity )
				signal = 1;
			else if( isNaN( status ) )
				bin[i] = 1;
		}
		for( n = Math.abs( exp + bias ), j = exponentBits + 1, result = ""; --j; result = ( n % 2 ) + result, n = n >>= 1 );
		for( n = 0, j = 0, i = ( result = ( signal ? "1" : "0" ) + result + bin.slice( i, i + precisionBits ).join( "" ) ).length, r = []; i; j = ( j + 1 ) % 8 ){
			n += ( 1 << j ) * result.charAt( --i );
			if( j == 7 ){
				r[r.length] = String.fromCharCode( n );
				n = 0;
			}
		}
		r[r.length] = n ? String.fromCharCode( n ) : "";
		return ( this.bigEndian ? r.reverse() : r ).join( "" );
	};
	p.encodeInt = function( data, bits, signed ){
		var max = Math.pow( 2, bits );
		( data >= max || data < -( max >> 1 ) ) && this.warn( "encodeInt::overflow" ) && ( data = 0 );
		data < 0 && ( data += max );
		for( var r = []; data; r[r.length] = String.fromCharCode( data % 256 ), data = Math.floor( data / 256 ) );
		for( bits = -( -bits >> 3 ) - r.length; bits--; r[r.length] = "\0" );
		return ( this.bigEndian ? r.reverse() : r ).join( "" );
	};
	p.toSmall    = function( data ){ return this.decodeInt( data,  8, true  ); };
	p.fromSmall  = function( data ){ return this.encodeInt( data,  8, true  ); };
	p.toByte     = function( data ){ return this.decodeInt( data,  8, false ); };
	p.fromByte   = function( data ){ return this.encodeInt( data,  8, false ); };
	p.toShort    = function( data ){ return this.decodeInt( data, 16, true  ); };
	p.fromShort  = function( data ){ return this.encodeInt( data, 16, true  ); };
	p.toWord     = function( data ){ return this.decodeInt( data, 16, false ); };
	p.fromWord   = function( data ){ return this.encodeInt( data, 16, false ); };
	p.toInt      = function( data ){ return this.decodeInt( data, 32, true  ); };
	p.fromInt    = function( data ){ return this.encodeInt( data, 32, true  ); };
	p.toDWord    = function( data ){ return this.decodeInt( data, 32, false ); };
	p.fromDWord  = function( data ){ return this.encodeInt( data, 32, false ); };
	p.toFloat    = function( data ){ return this.decodeFloat( data, 23, 8   ); };
	p.fromFloat  = function( data ){ return this.encodeFloat( data, 23, 8   ); };
	p.toDouble   = function( data ){ return this.decodeFloat( data, 52, 11  ); };
	p.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11  ); };
}
    
        <a href="http://www.jsfromhell.com/dhtml/incremental-search">
Implements a GMail-like auto-complete.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

@REQUIRES <a href="http://www.jsfromhell.com/geral/event-listener">Event-Listener</a>

//Requires http://www.jsfromhell.com/geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/incremental-search [v1.0]

IncrementalSearch = function( input, callback, className ){
	var i, o = ( o = this, o.l = [], o.i = input, o.c = null, o.s = { e: null, i: -1 }, o.f = callback || function(){}, o.n = className || "", o );
	for( i in { keydown: 0, focus: 0, blur: 0, keyup: 0, keypress: 0 } )
		addEventListener( o.i, i, function( e ){ o.handler.call( o, e ); } );
};
with( { p: IncrementalSearch.prototype } ){
	(p.constructor.fadeAway = function( o ){
		o instanceof Object ? ( this.trash = this.trash || [] ).push( o ) && setTimeout( this.fadeAway, 200 ) : arguments.callee.c.trash.pop().hide();
	}).c = p.constructor;
	p.callEvent = function( e ){ this[e] && this[e].apply( this, [].slice.call( arguments, 1 ) ); };
	p.highlite = function( e ){ ( this.s.e && ( this.s.e.className = "normal" ), ( this.s = { e: e, i: e.listindex } ).e.className += " highlited", this.callEvent( "onhighlite", this.l[ this.s.i ], this.s.e.d ) ); };
	p.select = function(){ this.s.i + 1 && ( this.i.value = this.l[ this.s.i ], this.callEvent( "onselect", this.i.value, this.s.e.d ), this.hide() ); };
	p.hide = function(){ ( this.c && this.c.parentNode.removeChild( this.c ), this.c = null, this.l = [], this.s = { e: null, i: -1 }, this.callEvent( "onhide" ) ); };
	p.next = function(){ var e = ( e = this.s.e ) ? e.nextSibling || e.parentNode.firstChild : null; e && this.highlite( e ); };
	p.previous = function(){ var e = ( e = this.s.e ) ? e.previousSibling || e.parentNode.lastChild : null; e && this.highlite( e ); };
	p.handler = function( evt ){
		var o = this, t = evt.type, k = evt.key, e = /span/i.test( ( e = evt.target ).tagName ) ? e.parentNode : e;
		t == "keyup" ? k != 40 && k != 38 && k != 13 && o.show()
		: t == "keydown" ? ( k == 40 && o.next() ) || ( k == 38 && o.previous() )
		: t == "keypress" ? k == 13 && !evt.preventDefault() && o.select()
		: t == "blur" ? o.constructor.fadeAway( o )
		: t == "click" ? o.select()
		: t == "focus" ? o.show()
		: o.highlite( e );
	};
	p.show = function(){
		var cS, found = 0, o = this, i = o.i, iV = i.value, d = document, c = ( o.hide(), o.c = d.body.appendChild( d.createElement( "div" ) ) );
		( c.className = o.n, cS = c.style, cS.display = "none", cS.position = "absolute", o.callEvent( "onshow" ) );
		o.f.call( function( s, x, data ){
			if( !( x.length == undefined ? ( x = [x] ) : x ).length )
				return;
			var j, l = 0, i = o.l.length, e = c.appendChild( d.createElement( "div" ) );
			for( j in ( o.l[i] = s, e.className = "normal", e.d = data, e.listindex = i, !found && i == o.s.i && ++found && o.highlite( e ), x ) )
				e.appendChild( d.createTextNode( s.substring( l, x[j] ) ) ).parentNode.appendChild( d.createElement( "span" ) ).appendChild( d.createTextNode( s.substring( x[j], l = x[j] + iV.length ) ) ).parentNode.className = "selectedText";
			for( x in ( e.appendChild( d.createTextNode( s.substr( l ) ) ), { click: 0, mouseover: 0 } ) )
				addEventListener( e, x, function( e ){ o.handler.call( o, e ); } );
		}, iV );
		if( !c.childNodes.length )
			return o.hide();
		for( var x = i.offsetLeft, y = i.offsetTop + i.offsetHeight; i = i.offsetParent; x += i.offsetLeft, y += i.offsetTop );
		( cS.display = "block", cS.left = x + "px", cS.top = y + "px", !found && o.highlite( c.firstChild ) );
	};
}


Example

<style type="text/css">
/*container da lista*/
.autocomplete{
	cursor: pointer;
	border: 1px solid #999;
	border-top: none;
	background: #eee;
}
/*caracteres que combinaram*/
.autocomplete .selectedText{ font-weight: bold; color: #008; }
/*items não selecionados*/
.autocomplete .normal{ border-top: 1px solid #999; overflow: hidden; white-space: pre; }
/*item selecionado*/
.autocomplete .highlited{ background: #ddf; }
</style>

<form action="">
	<fieldset>
		<legend>Preenchimento dinâmico</legend>
		<label for="list" >Emails</label>
		<input autocomplete="0" type="text" name="list" id="list" />
		<br />
		<label for="ip" >Lista de IPs</label>
		<textarea name="ip" rows="3" cols="20" id="ip"></textarea>
		<br />
	</fieldset>
</form>

<script type="text/javascript">
//<![CDATA[

var list = [ "192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.1.1", "192.168.1.2", "192.168.1.3", "200.168.0.1", "200.168.0.2", "200.168.0.3", "200.168.1.1", "200.168.1.2", "200.168.1.3" ];
new IncrementalSearch( document.forms[0].ip, function( search ){
	for( var i in list )
		if( !list[i].indexOf( search ) )
			this( list[i], 0 );
}, "autocomplete" );


var names = [ "João Alves <joao@123.com>", "Jonas Raoni Soares Silva <jonas@abc.com>", "Roberto <rob@net.net>", "Maria Fernanda <mariaf@i.tu>" ];

function retrieveNames( search ){
	search = search.toLowerCase();
	for( var i in names ){
		if( search ){
			for( var j = 0, indices = []; j = names[i].toLowerCase().indexOf( search, j ) + 1; indices[indices.length] = j - 1 );
			this( names[i], indices, i );
		}
		else
			this( names[i], 0, i );

	}
}

x = new IncrementalSearch( document.forms[0].list, retrieveNames, "autocomplete" );


//]]>
</script>

    
        <a href="http://www.jsfromhell.com/dhtml/drag-library">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

@REQUIRES <a href="http://www.jsfromhell.com/geral/event-listener">Event-Listener</a>


Code

<script type="text/javascript">
//Requires http://www.jsfromhell.com/geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/drag-library [v1.0]

DragLibrary = {
	e: null,
	diff: { x: 0, y: 0 },
	lineLength: function( x, y, x0, y0 ){
		return Math.sqrt( ( x -= x0 ) * x + ( y -= y0 ) * y );
	},
	dotLineLength: function( x, y, x0, y0, x1, y1, o ){
		if( o && !( o = function( x, y, x0, y0, x1, y1 ){
			if( !( x1 - x0 ) ) return { x: x0, y: y };
			else if( !( y1 - y0 ) ) return { x: x, y: y0 };
			var left, tg = -1 / ( ( y1 - y0 ) / ( x1 - x0 ) );
			return { x: left = ( x1 * ( x * tg - y + y0 ) + x0 * ( x * - tg + y - y1 ) ) / ( tg * ( x1 - x0 ) + y0 - y1 ), y: tg * left - tg * x + y };
		}( x, y, x0, y0, x1, y1 ), o.x >= Math.min( x0, x1 ) && o.x <= Math.max( x0, x1 ) && o.y >= Math.min( y0, y1 ) && o.y <= Math.max( y0, y1 ) ) ){
			var l1 = this.lineLength( x, y, x0, y0 ), l2 = this.lineLength( x, y, x1, y1 );
			return l1 > l2 ? l2 : l1;
		}
		else {
			var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
			return Math.abs( a * x + b * y + c ) / Math.sqrt( a * a + b * b );
		}
	},
	beginDrag: function ( e ){
		var dL = DragLibrary, o = dL.e = e.target;
		dL.diff = { x: o.offsetLeft - e.clientX, y: o.offsetTop - e.clientY };
		addEventListener( document, "mousemove", dL.drag );
		addEventListener( document, "mouseup", dL.endDrag );
	},
	drag: function( e ){
		var dL = DragLibrary, pt = dL.e.dragHandler.call( dL.e.dragHandler.data, e.clientX, e.clientY );
		dL.e.style.left = ( pt.x += dL.diff.x ) + "px";
		dL.e.style.top = ( pt.y += dL.diff.y ) + "px";
		dL.e.ondrag instanceof Function && dL.e.ondrag( e, pt.x, pt.y );
	},
	endDrag: function(){
		removeEventListener( document, "mouseup", DragLibrary.endDrag );
		removeEventListener( document, "mousemove", DragLibrary.drag );
	},
	setHandler: function( e, data, handler ){
		( e.dragHandler = handler ).data = data;
		e.style.position = "absolute";
		addEventListener( e, "mousedown", this.beginDrag );
	},
	freeDrag: function( e ){
		this.setHandler( e, null, function( x, y ){
			return { x: x, y: y };
		} );
	},
	squareDrag: function( e, x, y, width, height ){
		this.setHandler( e, { x: x, y: y, w: width, h: height }, function( x, y ){
			var o = this;
			return { x: x < o.x ? o.x : x > o.x + o.w ? o.x + o.w : x, y: y < o.y ? o.y : y > o.y + o.h ? o.y + o.h : y };
		});
	},
	circleDrag: function( e, x, y, ray ){
		this.setHandler( e, { x: x + ray, y: y + ray, ray: ray }, function( x, y ){
			var o = this, tg;
			return DragLibrary.lineLength( x, y, o.x, o.y ) > o.ray ?
				{ x: Math.cos( tg = Math.atan2( y - o.y, x - o.x ) ) * o.ray + o.x, y: Math.sin( tg ) * o.ray + o.y }
				: { x: x, y: y };
		} );
	},
	freeLineDrag: function( e, x, y, angle ){
		this.setHandler( e, { x: x, y: y, angle: angle }, function( x, y ){
			var o = this, tg = ( ( o.angle %= 360 ) < 0 && ( o.angle += 180 ), Math.tan( -o.angle * Math.PI / 180 ) );
			return o.angle < 45 || o.angle > 135 ? { x: x, y: ( x - o.x ) * tg + o.y } : { x: ( y - o.y ) / tg + o.x, y: y };
		} );
	},
	polylineDrag: function( e, x0, y0, x1, y1, etc, etc, etc ){
		for( var args = [].slice.call( arguments, 0 ), lines = []; args.length > 4; lines[lines.length] = { y1: args.pop(), x1: args.pop(), y0: args.pop(), x0: args.pop() } );
		this.setHandler( e, lines, function( x, y ){
			if( !this.length )
				return { x: x, y: y };
			var l, dL = DragLibrary, o = this[0], lower = { i: 0, l: dL.dotLineLength( x, y, o.x0, o.y0, o.x1, o.y1, 1 ) };
			for( var i in this )
				lower.l > ( l = dL.dotLineLength( x, y, ( o = this[i] ).x0, o.y0, o.x1, o.y1, 1 ) ) && ( lower = { i: i, l: l } );
			y = y < Math.min( ( o = this[lower.i] ).y0, o.y1 ) ? Math.min( o.y0, o.y1 ) : y > Math.max( o.y0, o.y1 ) ? Math.max( o.y0, o.y1 ) : y;
			x = x < Math.min( o.x0, o.x1 ) ? Math.min( o.x0, o.x1 ) : x > Math.max( o.x0, o.x1 ) ? Math.max( o.x0, o.x1 ) : x;
			return Math.abs( o.x0 - o.x1 ) < Math.abs( o.y0 - o.y1 ) ? { x: ( y * ( o.x0 - o.x1 ) - o.x0 * o.y1 + o.y0 * o.x1 ) / ( o.y0 - o.y1 ), y: y }
			: { x: x, y: ( x * ( o.y0 - o.y1 ) - o.y0 * o.x1 + o.x0 * o.y1 ) / ( o.x0 - o.x1 ) };
		} );
	}
};


Example

<style type="text/css">
.box{
	position: absolute;
	border: 1px solid #000;
	width: 50px;
	height: 50px;
	font: 12px monospace;
	font-weight: bold;
}
#circle{ background-color: #fee; }
#square{ background-color: #ccc; left: 50px; }
#freeLine{ background-color: #eff; left: 100px; }
#polyLine{ background-color: #efe; left: 150px; }
#free{ background-color: #eef; left: 200px; }
</style>


<script type="text/javascript">
//<![CDATA[

function newBox( id ){
	var r = document.body.appendChild( document.createElement( "div" ) ).appendChild( document.createTextNode( "kind: " + id ) ).parentNode;
	return ( r.setAttribute( "id", id ), r.setAttribute( "class", "box" ),	r.className = "box", r );
}

DragLibrary.freeDrag( newBox( "free" ) );
DragLibrary.polylineDrag( newBox( "polyLine" ), 0, 0, 200, 200, 200, 200, 400, 200, 400, 200, 600, 0 );
DragLibrary.freeLineDrag( newBox( "freeLine" ), 200, 400, 60 );
DragLibrary.squareDrag( newBox( "square" ), 200, 200, 400, 200 );
DragLibrary.circleDrag( newBox( "circle" ), 100, 100, 100 );

//]]>
</script>
    
        <a href="http://www.jsfromhell.com/dhtml/graphical-plotter">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>


An unuseful thing to draw using javascript, it's slow as hell :)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/graphical-plotter [v1.0]

Canvas = function(){
	var o = this;
	( o.penPos = { x: 0, y: 0 }, o.pixelSize = 10, o.pen = { style: "solid", size: 1, color: "#000" }, o.brush = { style: "solid", color: "#000" } );
};
with( { p: Canvas.prototype } ){
	p.pixel = function( x, y, color ) {
		var o = this, s = document.body.appendChild( document.createElement( "div" ) ).style;
		return ( s.position = "absolute", s.width = ( o.pen.size * o.pixelSize ) + "px", s.height = ( o.pen.size * o.pixelSize ) + "px", s.fontSize = "1px", s.left = ( x * o.pixelSize ) + "px", s.top = ( y * o.pixelSize ) + "px", s.backgroundColor = color || o.pen.color, o );
	};
	p.line = function( x1, y1, x2, y2 ){
		if( Math.abs( x1 - x2 ) < Math.abs( y1 - y2 ) )
			for( y = Math.min( y1, y2 ) - 1, x = Math.max( y1, y2 ); ++y <= x; canvas.pixel( ( y * ( x1 - x2 ) - x1 * y2 + y1 * x2 ) / ( y1 - y2 ), y ) );
		else
			for( x = Math.min( x1, x2 ) - 1, y = Math.max( x1, x2 ); ++x <= y; canvas.pixel( x, ( x * ( y1 - y2 ) - y1 * x2 + x1 * y2 ) / ( x1 - x2 ) ) );
		return this;
	};
	p.arc = function( x, y, raio, startAngle, degrees ) {
		for( degrees += startAngle; degrees --> startAngle; this.pixel( Math.cos( degrees * Math.PI / 180 ) * raio + x, Math.sin( degrees * Math.PI / 180 ) * raio + y ) ); return this;
	};
	p.rectangle = function( x, y, width, height, rotation ){
		return this.moveTo( x, y ).lineBy( 0, height ).lineBy( width, 0 ).lineBy( 0, -height ).lineBy( -width, 0 );
	};
	p.moveTo = function( x, y ){ var o = this; return ( o.penPos.x = x, o.penPos.y = y, o ); };
	p.moveBy = function( x, y ){ var o = this; return o.moveTo( o.penPos.x + x, o.penPos.y + y ); };
	p.lineTo = function( x, y ){ var o = this; return o.line( o.penPos.x, o.penPos.y, x, y ).moveTo( x, y ); };
	p.lineBy = function( x, y ){ var o = this; return o.lineTo( o.penPos.x + x, o.penPos.y + y ); };
	p.curveTo = function( cx, cy, x, y ){};
	p.polyBezier = function( points ){};
	p.path = function( points ){};
}


Example:

canvas = new Canvas;

canvas.pen.color = "#f00";
canvas.rectangle( 30, 20, 20, 20 );
canvas.pen.color = "#080";
canvas.rectangle( 35, 25, 10, 10 );
canvas.pen.color = "#008";
canvas.arc( 50, 30, 10, 180, 270 );
canvas.arc( 30, 30, 10, 0, 270 );
canvas.pen.color = "#ff0";
    
        <a href="http://www.jsfromhell.com/array/arrange">
It arranges elements in an array, the "n" parameter determines the amount of elements in each combination and the "m" one is a boolean which says if the function should return an array with an "index map" or real values.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/arrange [v1.0]

arrange = function( v, n, m ){
 	for( var i, j, k, sep = sep || "", l = v.length, r = new Array( i = Math.pow( l, n ) ), c = ( new Array( n + 1 ) ).join( 0 ).split( "" ); i; )
		for( r[--i] = new Array( j = n ), k = 1; j--; r[i][j] = m ? c[j] : v[c[j]], k && ( ++c[j] != l && --k, c[j] %= l ) );
	return r;
};


Example

document.write( arrange( ["A", "B", "C" ], 3, 1 ).join( "<br />" ), "<hr />" );
document.write( arrange( ["A", "B", "C" ], 3, 0 ).join( "<br />" ) );
    
        <a href="http://www.jsfromhell.com/array/permute">
It permutes elements in an array, the "m" parameter is a boolean which determines if the function should return an array with an "index map" or the real value.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/permute [v1.0]

permute = function( v, m ){
	for( var j, l = v.length, i = ( 1 << l ) - 1, r = new Array( i ); i; )
		for( r[--i] = [], j = l; j; i + 1 & 1 << --j && ( r[i].push( m ? j : v[j] ) ) );
	return r;
};



Example

document.write( permute( ["A", "B", "C" ], 1 ).join( "<br />" ), "<hr />" );
document.write( permute( ["A", "B", "C" ], 0 ).join( "<br />" ) );
    
        
Simply do this:

$string = implode('',file($pathToFileOrUrl));
    
        Use a helper function/class as such:

<%- row_class = cycle("even", "odd") -%>
<%- for item in @items do -%>
  <tr class="<%= row_class %>">
    ... use item ...
  </tr>
<%- end -%>

Put this in your application_helper.rb:

  def cycle(first_value, *values)
    values.unshift(first_value)
    return Cycle.new(*values)
  end

  class Cycle
    def initialize(first_value, *values)
      @values = values.unshift(first_value)
      @index = 0
    end

    def to_s
      value = @values[@index].to_s
      @index = (@index + 1) % @values.size
      return value
    end
  end
    
        <a href="http://www.jsfromhell.com/dhtml/tooltip">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

@REQUIRES <a href="http://www.jsfromhell.com/geral/event-listener">Event-Listener</a>

//Requires http://www.jsfromhell.com/Geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/dhtml/tooltip [v1.0]

ToolTip = function( toolTipClass, attributeName, followMouse ){
	var i, o = this;
	o.s = ( o.t = document.body.appendChild( document.createElement( "div" ) ) ).style;
	( o.s.display = "none", o.s.position = "absolute", o.t.className = toolTipClass, o.a = attributeName, o.f = followMouse );
	for( i in { mouseout: 0, mouseover: 0, mousemove: 0 } )
		addEventListener( document, i, function( e ){ o[e.type].call( o, e ); } );
};
with( { p: ToolTip.prototype } ){
	p.mouseout = function(){
		this.s.display = "none";
	};
	p.mouseover = function( e ){
		for( var d = document, x = e.target; !x.getAttribute( this.a ) && ( x = x.parentNode ) != d; );
		if( x == d )
			return;
		( this.s.display = "block", this.s.top = e.clientY + "px", this.s.left = e.clientX + "px", e.stopPropagation() );
		this.t.innerHTML = x.getAttribute( this.a );
	};
	p.mousemove = function( e ){
		if( !this.f )
			return;
		this.s.top = e.clientY + "px";
		this.s.left = e.clientX + "px";
	};
}


Example


<span style="color:red;" help="aaaaaaaaaaa :)<br /><br /><b>uuuuuuuuuu :(</b>">OIIIIIIIIIIII, PASSA A MÃOZINHA EM MIM XD</span>
<span style="color:green;" help="nooossa !!!!<br /><br /><b>affffffff iiii</b>">LALAAAAAAAAAAAAAAAA</span>

<script type="text/javascript">
//<![CDATA[

new ToolTip( "tooltip", "help", true );

//]]>
</script>
    
        <a href="http://www.jsfromhell.com/forms/auto-tab">
Auto tabulation of text inputs with maxlength setted

Usage: just add the code on the end of your page or call it on the onload event (worse solution) and "the enter tabulation" will be added for all fields enclosed by the <form> tag.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

@REQUIRES <a href="http://www.jsfromhell.com/geral/event-listener">Event-Listener</a>


//Requires http://www.jsfromhell.com/Geral/event-listener

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/auto-tab [v1.0]

autoTab = function(){
	for( var d, f = ( d = document ).forms, i = f.length; i; addEventListener( f[--i], "keyup", function( e ){
		var el, k = String.fromCharCode( e.key ), l = ( e = e.target ).value.length;
		if ( l >= ( e.getAttribute( "maxlength" ) || l + 1 ) && /[\wÀ-ÿ ]/.test( k ) ){
			for( l = k = ( el = e.form.elements ).length; el[--k] != e; );
			while( !(e = el[ k = ++k * ( k < l ) ]).type || e.disabled );
			e.focus();
		}
	} ) );
};
    
        <a href="http://jsfromhell.com/classes/data-slider">

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/data-slider [v1.0]

( DataSlider = function( onchange, interval, args ){
	var i = DataSlider.instances = DataSlider.instances || [], o = this;
	( o.c = 0, o.timer = null, o.interval = ( o.onchange = ( o.data = [].slice.call( arguments, 0 ) ).shift(), o.data.shift() ), i[o.index = i.length] = o );
} ).prototype = {
	stop: function(){ clearTimeout( this.timer ); },
	play: function(){ this.timer = setInterval( "DataSlider.instances[" + this.index + "].next()", this.interval ); },
	show: function( x ){ this.c = x; this.onchange( this.data[ x ] ); },
	previous: function(){ this.show( this.c > 0 ? --this.c : this.data.length-1 ); },
	next: function(){ this.show( ( this.c + 1 ) % this.data.length ); }
};


Example

<form action="">
	<fieldset>
	<legend>Rotacionador de objetos</legend>
	<div id="dados">:]</div>
	<input type="button" name="stop" onclick="" value="parar" />
	<input type="button" name="previous" value="anterior" />
	<input type="button" name="next" value="próximo" />
	<input type="button" name="play" value="play" />
	</fieldset>
</form>

<script type="text/javascript" src="event.js"></script>

<script type="text/javascript">
//<![CDATA[

addEventListener = function( o, e, h ){ var x='addEventListener'; o[x] ? o[x]( e, h, false ) : o[x='attachEvent'] ? o[x]( 'on' + e, h ) : o[ 'on' + e ] = h; }

var x = new DataSlider(
	function( data ){
		var x = document.getElementById( "dados" );
		x.innerHTML = '<a href="' + data[1] + '">'+ data[0] +"</a>";
	},
	1000,
	["ABCDE", "http://www.abcde.com"], ["FGHIJ", "http://www.fghij.com.br"], ["KLMNO", "http://www.klmno.com"]
);
x.play();

var f = document.forms[0];
//http://www.jsfromhell.com/Geral/event-listener
addEventListener( f.play, "click", function(){ x.play(); });
addEventListener( f.stop, "click", function(){ x.stop(); });
addEventListener( f.next, "click", function(){ x.stop(); x.next(); });
addEventListener( f.previous, "click", function(){ x.stop(); x.previous(); });

//]]>
</script>
    
        <a href="http://jsfromhell.com/math/dot-line-length">
Given a dot and a line, it returns the distance between them, the last parameter tells if the line should be considered infinite or if the function should respect its limits.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/dot-line-length [v1.0]

dotLineLength = function( x, y, x0, y0, x1, y1, o ){
	function lineLength( x, y, x0, y0 ){
		return Math.sqrt( ( x -= x0 ) * x + ( y -= y0 ) * y );
	}
	if( o && !( o = function( x, y, x0, y0, x1, y1 ){
		if( !( x1 - x0 ) ) return { x: x0, y: y };
		else if( !( y1 - y0 ) ) return { x: x, y: y0 };
		var left, tg = -1 / ( ( y1 - y0 ) / ( x1 - x0 ) );
		return { x: left = ( x1 * ( x * tg - y + y0 ) + x0 * ( x * - tg + y - y1 ) ) / ( tg * ( x1 - x0 ) + y0 - y1 ), y: tg * left - tg * x + y };
	}( x, y, x0, y0, x1, y1 ), o.x >= Math.min( x0, x1 ) && o.x <= Math.max( x0, x1 ) && o.y >= Math.min( y0, y1 ) && o.y <= Math.max( y0, y1 ) ) ){
		var l1 = lineLength( x, y, x0, y0 ), l2 = lineLength( x, y, x1, y1 );
		return l1 > l2 ? l2 : l1;
	}
	else {
		var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
		return Math.abs( a * x + b * y + c ) / Math.sqrt( a * a + b * b );
	}
};