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
They should be default options of SciTE (good for python too)
just put them in your scite user properties (menu > options > open user properties)
# visual options of the gui tabbar.hide.one=0 toolbar.visible=1 tabbar.visible=1 statusbar.visible=1 line.margin.visible=1 line.margin.width=4 buffers=20 buffers.zorder.switching=1 # editing options braces.check=1 braces.sloppy=1 are.you.sure=1 load.on.activate=1 are.you.sure.on.reload=1 reload.preserves.undo=1 # source-respect options strip.trailing.spaces=1 tabsize=4 indent.size=4 use.tabs=0 indent.auto=1 indent.opening=1 indent.closing=1 tab.indents=1 backspace.unindents=1 eol.mode=LF eol.auto=1
I've finally figured out how to add thousands separators.
If there's a built in for this (like a `sprintf` parameters) I don't want to hear it. I just don't, ok?
def ts( st )
st = st.reverse
r = ""
max = if st[-1].chr == '-'
st.size - 1
else
st.size
end
if st.to_i == st.to_f
1.upto(st.size) {|i| r << st[i-1].chr ; r << ',' if i%3 == 0 and i < max}
else
start = nil
1.upto(st.size) {|i|
r << st[i-1].chr
start = 0 if r[-1].chr == '.' and not start
if start
r << ',' if start % 3 == 0 and start != 0 and i < max
start += 1
end
}
end
r.reverse
end
That's it.
puts ts('100')
puts ts('1')
puts ts('1000')
puts ts('1000000.01')
puts ts('100046546510000.022435451')
puts ts('-100')
puts ts('-1')
puts ts('-1000')
puts ts('-1000000.01')
puts ts('-100046546510000.022435451')
outputs:
100 1 1,000 1,000,000.01 100,046,546,510,000.022435451 -100 -1 -1,000 -1,000,000.01 -100,046,546,510,000.022435451
It's ugly, yeah, but it works.
if you got some path/enhancements, you can mail me at my pseudo at gmail.com, i'll update it.
(you should install the marvellous beautifulsoup module, http://www.crummy.com/software/BeautifulSoup/documentation.html)
the snippets.py file :
from BeautifulSoup import BeautifulSoup
import urllib
class Keyword: # top tags
def __init__(self,tag,nb):
self.tag=tag
self.nb=int(nb)
def __repr__(self):
return "<Keyword '%s' : %d>" % (self.tag,self.nb)
class Snippet:
def __init__(self,title,code,tags):
self.title=title
self.code=code
self.tags = tags
def __repr__(self):
return "<Snippet '%s' : tags %s>" % (self.title,str(self.tags))
class Snippets:
urlForTags = "http://www.bigbold.com/snippets/tags"
def __init__(self,l=[]):
url = self.__getUrlForTags(l)
#load the url
fu = urllib.urlopen(url)
content = fu.read()
fu.close()
self.tags = l
self.keywords,self.snippets = self.__extractContent(content)
def __repr__(self):
return "<Snippets for tags:%s>" % (str(self.tags))
def __getUrlForTags(self, l ):
assert type(l)==list
l = [Snippets.urlForTags] + l
return "/".join(l)
def __extractContent(self,content):
soup = BeautifulSoup( content )
# get the keywords
tagTable=soup('div', {'id' : "sidebar"})[0].table
keywords=[]
for i in tagTable("tr"):
td = i("td")
# add this keyword
try:
# extract from the empty selection page "/tags"
keywords.append( Keyword(td[1].span.a.string , td[0].string) )
except TypeError:
# extract from a selected selection page "/tag/something"
keywords.append( Keyword(td[2].span.a.string , td[1].string) )
# get the snippets
postList=soup('div', {'class' : "post"})
snippets=[]
for i in postList:
divs = i("div")
# get title and tags
title = divs[0].h3.a.string # title
tags = [j.string for j in divs[1]("a")][:-1] #don't get the user ;-)
# get code of the snippet
list = [j for j in divs[0]][1:]# zap the first (h3)
code=""
for i in list:
try:
if i.name == "pre":
try:
code+=i.string
except TypeError:
pass
except AttributeError:
# transform "out-pre-text" in comment
out = str(i).strip()
if out:
code+="#| "+out+"\n"
# add this snippet
snippets.append( Snippet(title,code,tags) )
return keywords,snippets
and an example (all returned "strings" are in utf-8):
from snippets import Snippets
s = Snippets(["python","xml"])
print s
print s.keywords # the "top tags" column
for i in s.snippets:
print i
print s.snippets[6].title # the title of the 6th
print s.snippets[6].code # the code of the 6th
RewriteEngine On
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://www.domain.de/folder/$1 [L,R]
require 'open-uri'
require 'rss/0.9'
require 'rss/1.0'
require 'rss/2.0'
require 'rss/parser'
url = 'http://some.host/rss.xml'
rss = RSS::Parser.parse(open(url){|fd|fd.read})
puts rss.items.collect{|item|item.title}.join("\n")
See also <a href='http://simple-rss.rubyforge.org/'>simple-rss</a> at rubyforge.
you must install qemu first ... run this :
sudo apt-get install qemu
then create a virtual filesystem (to simulate a hdd) (1000000 = 10go), under your home directory
dd of=hd.img bs=1024 seek=1000000 count=0
put a bootable cd (or an "iso-file") in your cd drive (win2k, xp, linux live-cd, ...), and run
qemu -hda /home/[your_name]/hd.img -cdrom /dev/hdd -boot d -m 512 -user-net
option -hda = the virtual disk to use (~/hd.img)
option -m = memory to use (512 mo).
option -cdrom = cd-drive (/dev/hdd for me) (or an iso file)
option -boot = which drive to boot (d as the cdrom)
option -user-net : net user mode (see http://fabrice.bellard.free.fr/qemu/qemu-doc.html#SEC21)
and it's run like a charm ...impressive
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 />" ) );




