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
module DebugHelper
def self.append_features(controller) #:nodoc:
controller.ancestors.include?(ActionController::Base) ? controller.add_template_helper(self) : super
end
IGNORE = ["template_root", "template_class", "response", "template", "session", "url", "params", "subcategories", "ignore_missing_templates", "cookies", "request", "logger", "flash", "headers" ]
def debug_popup
popup_create do |script|
script << add( "<HTML><HEAD><TITLE>Smarty Debug Console_#{@controller.class.name}</TITLE></HEAD><BODY bgcolor=#ffffff>" )
script << add( "<table border=0 width=100%>" )
script << add( "<tr bgcolor=#cccccc><th colspan=2>Rails Debug Console</th></tr>" )
script << add( "<tr bgcolor=#cccccc><td colspan=2><b>assigned template variables:</b></td></tr>" )
@controller.assigns.each do |key, value|
script << add ("<tr bgcolor=#eeeeee><td valign=top><tt><font color=blue>#{h key}</font></tt></td><td><tt><font color=green>#{dump_obj(value)}</font></tt></td></tr>") unless IGNORE.include?(key)
end unless @controller.assigns.nil?
script << add( "<tr bgcolor=#cccccc><td colspan=2><b>request parameters:</b></td></tr>" )
@controller.params.each do |key, value|
script << add ("<tr bgcolor=#eeeeee><td valign=top><tt><font color=blue>#{h key}</font></tt></td><td><tt><font color=green>#{dump_obj(value)}</font></tt></td></tr>") unless IGNORE.include?(key)
end unless @controller.params.nil?
script << add( "<tr bgcolor=#cccccc><td colspan=2><b>session variables:</b></td></tr>" )
@controller.session.instance_variable_get("@data").each do |key, value|
script << add ("<tr bgcolor=#eeeeee><td valign=top><tt><font color=blue>#{h key}</font></tt></td><td><tt><font color=green>#{dump_obj(value)}</font></tt></td></tr>") unless IGNORE.include?(key)
end unless @controller.session.instance_variable_get("@data").nil?
script << add( "<tr bgcolor=#cccccc><td colspan=2><b>flash variables:</b></td></tr>" )
@controller.instance_variable_get("@flash").each do |key, value|
script << add ("<tr bgcolor=#eeeeee><td valign=top><tt><font color=blue>#{h key}</font></tt></td><td><tt><font color=green>#{dump_obj(value)}</font></tt></td></tr>") unless IGNORE.include?(key)
end unless @controller.instance_variable_get("@flash").nil?
end
end
private
def popup_create
script = "<SCRIPT language=javascript>\n<!--\n"
script << "_rails_console = window.open(\"\",\"#{@controller.class.name}\",\"width=680,height=600,resizable,scrollbars=yes\");\n"
yield script
script << "_rails_console.document.close();\n"
script << "-->\n</SCRIPT>"
end
def add(msg)
"_rails_console.document.write(\"#{msg}\")\n"
end
def dump_obj(object)
begin
Marshal::dump(object)
"<pre>#{h(object.to_yaml).gsub(" ", " ").gsub("\n", "<br/>\"+\n\"" )}</pre>"
rescue Object => e
# Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback
"<pre>#{h(object.inspect)}</pre>"
end
end
end
I got this from <a href="http://dev.epilogit.com/file/trunk/app/helpers/debug_helper.rb?rev=23">EpiLog</a> after seeing it mentioned on on the <a href="http://wiki.rubyonrails.com/rails/show/HowtoDebugViews">HowToDebugViews </a> wiki. It is a helper class which will raise a Smarty like popup dumping all assigns, sessions, parameter and flash. Install it into your helper directory and include DebugHelper in your application controller. In your view (perhaps the bottom of your generic layout) add <i><%= debug_popup %></i>. Make sure to disable your popup blocker. This is especially useful if you work together with designers who have no idea what kind of information are exported by the controllers in a given view.
Update: go for the simplest regex possible...
$HTTP["host"] =~ "awesomerailsapp.com" {
server.error-handler-404 = "/dispatch.fcgi"
server.document-root = "/awesomerailsapp/public/"
url.redirect = (
"^/feed/atom" => "http://awesomerailsapp.com/xml/atom/feed.xml",
"^/feed" => "http://awesomerailsapp.com/xml/rss/feed.xml",
"^/wp-rss2\.php" => "http://awesomerailsapp.com/xml/rss/feed.xml",
"^/wp-atom\.php" => "http://awesomerailsapp.com/xml/atom/feed.xml",
# my wp article format to typo's
"^/(\d{4})/(\d{2})/(\d{2})/([\w-_]+)" => "/articles/$1/$2/$3/$4"
)
# bring on the rest of the config
}
import sysinfo
import e32
import os
import os.path
import re
import time
import urllib
import contacts
import codecs
CODEC='utf-16'
CVSFILENAME='E:\\contactsdb.cvs'
def getFieldtypenames():
"Return the list of fields"
dic = contacts.fieldtypemap
num = [[v,k] for k,v in dic.items()]
num.sort()
if num[0][0]==0 and num[0][1]=='none':
del num[0]
return [v for k,v in num]
def exportContacts(filename):
messages = []
f = None
try:
f = codecs.open(filename,'w+',CODEC)
except:
print 'error creation file'
if not f:
return -1
fields = getFieldtypenames()
fieldformat = u''.join(['%('+v+')s,' for v in fields ])[0:-1]
fieldformat+= '\n'
fieldname = u''.join([''+v+',' for v in fields ])[0:-1]
f.write("%s\n"%fieldname)
try:
db = contacts.open()
idlist = db.keys()
for id in idlist:
newdict = dict([[k,''] for k in fields])
contact = db[id]
for field in contact:
newdict[field.type]=field.value
f.write(fieldformat%newdict)
except:
pass
f.close()
def main():
exportContacts(CVSFILENAME)
if __name__=='__main__':
main()
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>





