Thursday, March 11, 2010

March Madness Challenge - Day 11

Hello kwargs

#test the default args

def test2args(arg1="default1", arg2="default2"):
print "arg1: " + arg1
print "arg2: " + arg2

def test2argskwargs(arg1="default1", arg2="default2", **kwargs):
print "arg1: " + arg1
print "arg2: " + arg2
for k, v in kwargs:
print "%s=%s" % (k, v)



test2args()
test2args("1","2")
args = ("3","4")

test2args(*args)
#test2args(a="5", b="6")
test2argskwargs("3","4", a="5", b="6")

Wednesday, March 10, 2010

March Madness Challenge - Day 10

Ok. Fighting back from last minute code, and then trying to fix it the next day. My little fixes managed to break barely working code. So, let's look at a a testing framework for Javascript called Qunit. QUnit is a jQuery based testing framework. Once you've got the basic html in place just include the necessary css and Javascript and you are up and running. Since my previous code had some issues with cookies I figured I would use QUnit to do a couple of test of how cookies work. I'll probably do more variations on this theme, but until then. Here's the code need to quickly test if cookies exist, cookies are created, etc.

Live Page


<!DOCTYPE html>
<html>
<head>
<title>QUnit Cookie test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAyOcYQmrUZiRTkZD33sBhThSYG2nKbTfLUqOyuY0R-KaU9CNsSxQHWg8je-XfTEMamlZKbXxG4Z752A">
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true">
</script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script>
<script type="text/javascript" src="jquery.cookies.2.2.0.min.js">
</script>

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {

test("a basic test example", function() {
ok( true, "this test is fine" );
var value = "hello";
equals( "hello", value, "We expect value to be hello" );
});

test("Are cookies available?", function() {
ok(true, $.cookies.test());
});

//Are there existing cookies
test("Is there an existing cookie?", function() {
equals(true, $.cookies.get('newcookie')[0].test, "Cookie exists from last time.");
});

//Load cookie values nd check

//Create a new cookie test
test("Created new cookie.", function () {
var markers = [];
var marker = {test: true, date: new Date() } ;
markers.push(marker);
$.cookies.set('newcookie', markers);
var cookiedata = $.cookies.get('newcookie');
equals(true, cookiedata[0].test, "Cookie data is true");
});
//if not created create cookie data

//find and display existing markers
});
</script>
<style type="text/css">
div.c1 {width:100%; height:100%}
</style>
</head>
<body>
<h1 id="qunit-header">QUnit Cookie Tests</h1>
<h2 id="qunit-banner"></h2>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>

Tuesday, March 09, 2010

March Madness Challenge - Day 9

Another last minute post. Attempting to save marker data as JSON array in a Cookie in a jQuery friendly way. I ran out of time to test the code. In theory it should work.

Preview URL

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Where in the world is my dog pooin!</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAyOcYQmrUZiRTkZD33sBhThSYG2nKbTfLUqOyuY0R-KaU9CNsSxQHWg8je-XfTEMamlZKbXxG4Z752A"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>

<script type="text/javascript" src="jquery.cookies.2.2.0.min.js"></script>

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var markers = [];
function setPosition(position) {
console.log("setPosition: lat: " + position.coords.latitude + " lng: " + position.coords.longitude );
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Map: " + map);
map.setCenter(location, 13);
addMarker(location, "Quality: " + $("input[name='quality']:checked").val() + "Date: " + new Date());
}

function addMarker(location, msg) {
var marker = new google.maps.Marker({
position: location,
map: map,
title: msg
});
markers.push(marker);
$.cookies.set('dogdata', markers);
}

function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");

if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}

if( !$.cookies.test() )
{
alert("Please enable cookies for this program to track very important information");
}

//if not created create cookie data

//find and display existing markers

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

$("#setcenter").bind("click", function(e){
console.log("bind click");
navigator.geolocation.getCurrentPosition(setPosition);
});

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
} else {
alert("navigator.geolocation not available.");

}
// detectBrowser();
navigator.geolocation.getCurrentPosition(setPosition);
});
</script>
</head>
<body >
<h1>Warning the SQLite poo storage db is not installed yet.</h1>
<h2>This means you have to never reload the page to record all the necessary poo data.</h2>
<div>Where in the world does my dog poo?</div>

<div>Use the geolocation information to mark the spots your dog marks, with optional quality indicator.</div>

<form name="controls">
<div>Quality: </div>
<input type="radio" name="quality" value="1">1</input>
<input type="radio" name="quality" value="2">2</input>
<input type="radio" name="quality" value="3" checked="checked">3</input>

<input type="radio" name="quality" value="4">4</input>
<input type="radio" name="quality" value="5">5</input>
<button name="setcenter" id="setcenter">Mark!</button>
</form>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Monday, March 08, 2010

March Madness Challenge - Day 8

This is the beginning of something special for all the dog lovers in the world. Using Google Maps API version 3, and jQuery you can now mark on a map where and the quality of your dogs poo. Unfortunately, this program is a two parter. Today's portion allows you to mark the location of the poo, and track it as long as you never reload the web page. The next update will use the SQLite option in HTML to store and retrieve poo data.

Compatibiltiy note: Marking poo locations works in Firefox 3.5 and higher, iPhone, and maybe Droid. When SQLite is added it will end up being only iPhone or Droid.

One thing that took way too much time to debug was how get the code recognized as HTML5. One way is to strip out all the things indicating that it's not HTML 5 and include only an html tag by itself. This let's the browser choose.

And here's the code:


<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Where in the world is my dog pooin!</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAyOcYQmrUZiRTkZD33sBhThSYG2nKbTfLUqOyuY0R-KaU9CNsSxQHWg8je-XfTEMamlZKbXxG4Z752A"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
function setPosition(position) {
console.log("setPosition: lat: " + position.coords.latitude + " lng: " + position.coords.longitude );
var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log("Map: " + map);
map.setCenter(location, 13);
addMarker(location, "msg");
}

function addMarker(location, msg) {
var marker = new google.maps.Marker({
position: location,
map: map,
title: msg
});
}

function detectBrowser() {
var useragent = navigator.userAgent;
var mapdiv = document.getElementById("map_canvas");

if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {
mapdiv.style.width = '100%';
mapdiv.style.height = '100%';
} else {
mapdiv.style.width = '600px';
mapdiv.style.height = '800px';
}
}

var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

$("#setcenter").bind("click", function(e){
console.log("bind click");
navigator.geolocation.getCurrentPosition(setPosition);
});

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
} else {
alert("navigator.geolocation not available.");

}
// detectBrowser();
navigator.geolocation.getCurrentPosition(setPosition);
});
</script>
</head>
<body >
<h1>Warning the SQLite poo storage db is not installed yet.</h1>
<h2>This means you have to never reload the page to record all the necessary poo data.</h2>
<div>Where in the world does my dog poo?</div>
<div>Use the geolocation information to mark the spots your dog marks, with optional quality indicator.</div>

<form name="controls">
<div>Quality: </div>
<input type="radio" name="quality" value="1">1</input>
<input type="radio" name="quality" value="2">2</input>
<input type="radio" name="quality" value="3">3</input>
<input type="radio" name="quality" value="4">4</input>
<input type="radio" name="quality" value="5">5</input>
<button name="setcenter" id="setcenter">Mark!</button>
</form>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>

Sunday, March 07, 2010

March Madness Challenge - Day 7

Thumb joystick controlled RGB LED!!!

Yesterdays entry was way unsatisfying. I wanted to enumerate all the possible RGB combinations, but was impatient, and made errors. Today's project took on the issue of determining what exact PWM values were set on this RGB led, and getting a starting point to calibrate the brightness between leds so get a decent color mix. Well, I didn't get to the issue of calibration, but I did get connect 2 thumb joysticks to the led and adjust the brightness values by reading the joystick data. Hook up 3 potentiometers and you can dial the exact combination RGB values you want.




/*
* 3 Potentiometers or Joystick controled rgb led
*/


int redPin = 9; // LED connected to digital pin 9
int greenPin = 10;
int bluePin = 11;
int potR = 0;
int potG = 1;
int potB = 2;
int r,g,b = 0;

void rgb (int r, int g, int b)
{
analogWrite(redPin, r);
analogWrite(greenPin, g);
analogWrite(bluePin, b);

}

void setup() {
Serial.begin(9600);
Serial.println("Setup done");
}


void loop() {

r = analogRead(potR);
g = analogRead(potG);
b = analogRead(potB);

r = map(r, 0, 1023, 0, 255);
g = map(g, 0, 1023, 0, 255);
b = map(b, 0, 1023, 0, 255);

rgb(r, g, b);
Serial.print(r);
Serial.print(", ");
Serial.print(g);
Serial.print(", ");
Serial.println(b);


}




Saturday, March 06, 2010

March Madness Challenge - Day 6

Loss of brain power leads to coding RGB LED enumeration for Arduino. Tired going to bed soon.


int redPin = 9; // LED connected to digital pin 9
int greenPin = 10;
int bluePin = 11;

void fadeIn(int pin, int fadeInc, int delayValue)
{
for (int fadeValue = 0; fadeValue<= 255; fadeValue += fadeInc)
{
analogWrite(pin, fadeValue);
delay(delayValue);
}
}

// fade out from max to min in increments
void fadeOut(int pin, int fadeInc, int delayValue)
{
for (int fadeValue = 255; fadeValue >= 0; fadeValue -= fadeInc)
{
analogWrite(pin, fadeValue);
delay(delayValue);
}
}

void rgb (int r, int g, int b)
{
analogWrite(redPin, r);
analogWrite(greenPin, g);
analogWrite(bluePin, b);
delay(30);
}

void setup() {
Serial.begin(9600);

// diagnostic lights on
fadeIn(redPin, 5, 60);
fadeOut(redPin, 5, 60);
analogWrite(redPin, 0);
delay(30);
fadeIn(greenPin, 5, 60);
fadeOut(greenPin, 5, 60);
analogWrite(greenPin, 0);
delay(30);
fadeIn(bluePin, 5, 60);
fadeOut(bluePin, 5, 60);
analogWrite(bluePin, 0);
delay(30);
Serial.print(redPin);
Serial.print(", ");
Serial.print(greenPin);
Serial.print(", ");
Serial.println(bluePin);

}


void loop() {
for (int r = 0; r <= 255; r++)
{
for (int g = 0; g <= 255; g++)
{
for (int b = 0; b <= 255; b++)
{
rgb(r, g, b);
Serial.print(r);
Serial.print(", ");
Serial.print(g);
Serial.print(", ");
Serial.println(b);

}
}
}
}

Friday, March 05, 2010

March Madness Challenge - Day 5

For tonight's March madness I will be demonstrating a variation on the theme of storing your private key locally. This program will up the ante and store your username and password as a QRCode. This way only a few machines can compromise your accounts when you take a picture of your username/password for decryption. Inspired by the following super high security tech technology: SafeBerg Technology

A bit of preparation is required. I'm using the python library huBarcode. You will need to run some flavor of "git clone git://github.com/hudora/huBarcode.git" followed by python setup.py install. Last option: sudo easy_install huBarcode

This code would have worked brilliantly if not for this error:
IOError: [Errno 2] No such file or directory: '/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/huBarcode-0.56p5-py2.4.egg/qrcode/qrcode_data/qrv1_0.dat'

And here is the code:



#
# Turn a username/password into a QRCode
#
#
import getopt
import sys
import getpass
import qrcode

#Describe usage
def usage():
print "-h, --help\n -v, --verbose\n -u, --username\n -p, --password\n -f, --filename\n"

def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "h:u:pvf:", ["help", "username=", "password", "filename"])
except getopt.GetoptError, err:
#print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
username = None
password = None
verbose = False
filename = "default.png"

for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-u", "--username"):
username = a
if verbose:
print "username: " + username
elif o in ("-p", "--password"):
password = getpass.getpass("Enter password: ")
if verbose:
print "password: " + password
elif o in ("-f", "--filename"):
filename = a;
if verbose:
print "filename: " + filename
else:
assert False, "unhandled option"
if username is None:
print "-u, --username was not given"
usage()
sys.exit(2)
if password is None:
print "-p, --password was not given"
usage()
sys.exit(2)


encoder = qrcode.QRCodeEncoder( username + "\n" + password)
print encoder.get_ascii()
encoder.save(filename, 3)

if __name__ == "__main__":
main()