Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 11-15 of 15 total

Masked Input //Javascript Object


Simple and generic mask routine.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



@REQUIRES Event-Listener

// REQUIRES: http://jsfromhell.com/geral/event-listener

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

MaskInput = function(f, m){ //v1.0
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[À-ÿ]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
        addEvent(f, i, mask);
};

//]]>
</script>



Usage (sorry, i'm lazy to write a help hahaha)

<form action="">
telephone "(99)9999-9999"

<input type="text" />

date "99/99/9999"

<input type="text" />


máscara = letter + letter withou accent + 2 numbers + "-" + anything + letter "Cc99-*C"

<input type="text" />


everything, but a, b or c "E^abc"

<input type="text" />


only a, b or c "O^abc"

<input type="text" />


just letters "C^"

<input type="text" />


just letters and also white-space "C^ "

<input type="text" />


just numbers and also the letters a, b e c "9^abc"

<input type="text" />

</form>

<script>
with( document.forms[0] ){
MaskedInput.apply( elements[0], '(99)9999-9999' );
MaskedInput.apply( elements[1], '99/99/9999' );
MaskedInput.apply( elements[2], 'Cc99-*C' );
MaskedInput.apply( elements[3], 'E^abc' );
MaskedInput.apply( elements[4], 'O^abc' );
MaskedInput.apply( elements[5], 'C^' );
MaskedInput.apply( elements[6], 'C^ ' );
MaskedInput.apply( elements[7], '9^abc' );
}
</script>

Motion detection as input

Inspired from the PIL version here
http://gumuz.looze.net/wordpress/index.php/archives/2005/06/06/python-webcam-fun-motion-detection/

First with typical import and Canvas, exit setup
from appuifw import *
from graphics import Image
import camera, e32
#import miso    # don't dim the light

app.body = c = Canvas()

running = 1
def quit():
    global running
    running = 0
app.exit_key_handler=quit

Then the getdata function that reads pixel data
from image by saving/reading PNG.
def getdata(im, bpp=24):
    import struct, zlib
    im.save('D:\\pixels.png', bpp=bpp, compression='no')
    f = open('D:\\pixels.png', 'rb')
    f.seek(8 +8+13+4)
    chunk = []
    while 1:
        n = struct.unpack('>L', f.read(4))[0]
        if n==0: break  # 'IEND' chunk
        f.read(4) # 'IDAT'
        chunk.append(f.read(n))
        f.read(4)   # CRC
    f.close()
    return zlib.decompress(''.join(chunk))  # '\x00' prefix each line

Lastly, the real code follows.
last1 = '\x00' * 930    # can be anything
while running:
    im = camera.take_photo('RGB', (160,120))
    im.rectangle([(10,10),(40,40)], 0xff0000)   # red outline
    im.rectangle([(120,10),(150,40)], 0xff0000) # no code for this square
    # check hot spot whether active
    box = Image.new((30,30), 'L')  # gray scale
    box.blit(im, (10,10,40,40))
    data = getdata(box, 8)
    # check difference for motion
    pixdiff = 0
    for i in range(len(data)):
        if abs(ord(data[i])-ord(last1[i])) > 15:  # pix threshold 15/256
            pixdiff += 1
            if pixdiff > 90:    # img threshold 90/900
                im.rectangle([(10,10),(40,40)], fill=0xff0000)  # fill
                break           # motion detected
    last1 = data
    c.blit(im, (0,0), (8,12))   # show camera
    #miso.reset_inactivity_time()

When measured, it takes around 1.1 sec for each loop.
Compared this with 0.9 sec without image processing,
out code is quite efficient.

Inputing non-ascii characters

My mobile phone (6600) doesn't have a Thai input method.
(You can buy a special software to do it)
After a lot of my thought experiments, I got an easy
example from my friend on this. You do a 2-level popup menu
to let people choose from the character table.
from appuifw import *

def thai_input():
    first_list = ['  '.join(thai_char[i:i+11]) for i in range(0,77,11)]
    y = popup_menu(first_list, u'select Thai char')
    if y is not None:
        x = popup_menu(thai_char[11*y:11*(y+1)], u'select Thai char')
        if x is not None:
            t.add(thai_char[11*y + x])

thai_char = [unichr(0x0e01+i) for i in range(77)]   # 77 thai characters

app.body = t = Text()
app.menu = [(u'thai', thai_input), (u'clear screen', t.clear)] 

# wait for user to exit program
import e32      
lock = e32.Ao_lock() 
app.exit_key_handler=lock.signal
lock.wait()


For other language, you can change the unicode offset (0x0e01)
and number of characters (77) to that of your language.
One requirement for this method is that the phone must be
able to display font in your language already.
(I have previously install Thai font on my 6600)
An alternative method to implement this will be manually drawing
your text (combile character from image font file).
I may do that some day.

Enter as tab //Javascript Function


Tabulation on fields through the enter key, i didnt allowed it to work on <select> and <textarea> since the enter is required to use this fields, so find a nice place to use it :]

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]


@REQUIRES Event-Listener

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

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

enterAsTab = function(){
	for( var f, i = ( f = document.forms ).length; i; addEventListener( f[--i], "keypress", function( evt ){
		var el, l, k = evt.key == 13, e = evt.target;
		if( k && !/textarea|select/i.test( e.type ) && !evt.preventDefault() ){
			for( l = k = ( el = e.form.elements ).length; el[--k] != e; );
			while( !(e = el[ k = ++k * ( k < l ) ]).type || e.disabled );
			e.focus();
		}
	} ) );
};



Example:

<form action="">
	<p>
	<input type="text" />
	<br /><input type="text" />
	<br /> <input type="radio" name="aaa" /> opção 1
	<input type="radio" name="aaa" checked="checked" /> opção 2
	<br /><textarea rows="3" cols="15">aaaaaa pode dar enter q ele naum pula hahah</textarea>
	<br /><select><option>opção blablablabla</option><option>opção bleblebleble</option></select>
	<br /><input type="text" />
	</p>
</form>


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

enterAsTab();

//]]>
</script>

Input and textarea preview

Preview what you type in an input or a textarea out of them (in a html tag, like a p, hx...)

Seen here: http://amuchamu.bitacoras.com/archivos/2005/02/17/previsualizacion_de_comentarios (spanish explain).

javascript code:

function preview(id1, id2){
	  		var NewText = document.getElementById(id1).value;
	  		splitText = NewText.split(/\n/).join("<br />");
	  		var DivElement = document.getElementById(id2);
	  		DivElement.innerHTML = splitText;
}



html code:

<form action="#">
<label>Name:</label>
<input type="text" id="nombre" onkeyup="preview('name', 'preview-name');" />

<label>Phone:</label>
<input type="text" id="phone" onkeyup="preview('phone', 'preview-phone');" />
</form>

<h2>Preview</h2>
<dl>
	<dt>Name:</dt>
	<dd id="preview-name"></dd>
	<dt>Phone:</dt>
	<dd id="preview-phone"></dd>

</dl>
« Newer Snippets
Older Snippets »
Showing 11-15 of 15 total