KNOCKOUTJS CODE EXAMPLE: Knockout.js Button Click and Counter
added 5 days ago
Knockout.js Button Click and Counter
This is an example of showing hints by clicking a button, and when user has seen enough, button is disabled and can be reset.

index.htm
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div>You've seen <span data-bind="text: numberOfHints"></span> hints.</div>
<button data-bind="click: processHint, disable: hasShownAllHints">Show Hint</button>
<div id="hintArea"></div>
<div data-bind="visible: hasShownAllHints">
You have shown all hints. <span class="pseudoLink" data-bind="click:resetHints">reset</a>
</div>
</body>
</html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<div>You've seen <span data-bind="text: numberOfHints"></span> hints.</div>
<button data-bind="click: processHint, disable: hasShownAllHints">Show Hint</button>
<div id="hintArea"></div>
<div data-bind="visible: hasShownAllHints">
You have shown all hints. <span class="pseudoLink" data-bind="click:resetHints">reset</a>
</div>
</body>
</html>
main.js
var hintViewModel = function() {
this.numberOfHints = ko.observable(0);
this.hints = ['first hint', 'second hint', 'third hint'];
this.processHint = function() {
this.numberOfHints(this.numberOfHints() + 1);
$('#hintArea').html(this.hints[this.numberOfHints()-1]);
};
this.resetHints = function() {
this.numberOfHints(0);
$('#hintArea').html('');
};
this.hasShownAllHints = ko.computed(function() {
return this.numberOfHints() >= 3;
}, this);
};
$(document).ready(init);
function init() {
ko.applyBindings(new hintViewModel());
}
this.numberOfHints = ko.observable(0);
this.hints = ['first hint', 'second hint', 'third hint'];
this.processHint = function() {
this.numberOfHints(this.numberOfHints() + 1);
$('#hintArea').html(this.hints[this.numberOfHints()-1]);
};
this.resetHints = function() {
this.numberOfHints(0);
$('#hintArea').html('');
};
this.hasShownAllHints = ko.computed(function() {
return this.numberOfHints() >= 3;
}, this);
};
$(document).ready(init);
function init() {
ko.applyBindings(new hintViewModel());
}
KNOCKOUTJS CODE EXAMPLE: Hello World knockout.js
added 5 days ago
Hello World knockout.js
index.htm
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<p>First Name: <input data-bind="value:firstName"/></p>
<p>Last Name: <input data-bind="value:lastName"/></p>
<p>Hello, <span data-bind="text:fullName"></span></p>
</body>
</html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/main.css"/>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js/knockout-2.2.1.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<p>First Name: <input data-bind="value:firstName"/></p>
<p>Last Name: <input data-bind="value:lastName"/></p>
<p>Hello, <span data-bind="text:fullName"></span></p>
</body>
</html>

main.js
var ViewModel = function(p_firstName, p_lastName) {
this.firstName = ko.observable(p_firstName);
this.lastName = ko.observable(p_lastName);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
$(document).ready(function() {
ko.applyBindings(new ViewModel('Jim', 'Smith'));
});
this.firstName = ko.observable(p_firstName);
this.lastName = ko.observable(p_lastName);
this.fullName = ko.computed(function() {
return this.firstName() + " " + this.lastName();
}, this);
};
$(document).ready(function() {
ko.applyBindings(new ViewModel('Jim', 'Smith'));
});
PHP CODE EXAMPLE: A PHP script that observes another and kills is process if it hangs
added on Feb 5, 2013
A PHP script that observes another and kills is process if it hangs
If you have a PHP script running on a linux server which hangs now and then, this is an example of a script that can observe that script and when it hangs, kills it, so the cronjob can restart it.

test.ThatHangs.php
class TestThatHangs {
protected $keepalive_file_name = 'test_keepalive_info.txt';
protected $test_phase = self:nnn:TESTPHASE_HANG;
protected $number_of_seconds_to_run_before_hang = 10;
const TESTPHASE_HANG = 1;
const TESTPHASE_EXITCORRECTLY = 2;
public function process() {
$this->_createKeepAliveFile();
$this->_display('started script');
for ($index = 0; $index < $this->number_of_seconds_to_run_before_hang; $index++) {
$this->_display('test output');
sleep(1);
$this->_touchKeepAliveFile();
}
if ($this->test_phase == self:nnn:TESTPHASE_HANG) {
$this->_emulateHang();
} else {
$this->_exitCorrectly();
}
}
protected function _exitCorrectly() {
$this->_cleanUpKeepAliveFile();
$this->_display('exited correctly');
exit;
}
protected function _emulateHang() {
$this->_display('emulating hang...');
sleep(10000);
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _touchKeepAliveFile() {
touch($this->keepalive_file_name);
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
protected function _createKeepAliveFile() {
file_put_contents($this->keepalive_file_name, getmypid());
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
}
$testThatHangs = new TestThatHangs();
$testThatHangs->process();
protected $keepalive_file_name = 'test_keepalive_info.txt';
protected $test_phase = self:nnn:TESTPHASE_HANG;
protected $number_of_seconds_to_run_before_hang = 10;
const TESTPHASE_HANG = 1;
const TESTPHASE_EXITCORRECTLY = 2;
public function process() {
$this->_createKeepAliveFile();
$this->_display('started script');
for ($index = 0; $index < $this->number_of_seconds_to_run_before_hang; $index++) {
$this->_display('test output');
sleep(1);
$this->_touchKeepAliveFile();
}
if ($this->test_phase == self:nnn:TESTPHASE_HANG) {
$this->_emulateHang();
} else {
$this->_exitCorrectly();
}
}
protected function _exitCorrectly() {
$this->_cleanUpKeepAliveFile();
$this->_display('exited correctly');
exit;
}
protected function _emulateHang() {
$this->_display('emulating hang...');
sleep(10000);
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _touchKeepAliveFile() {
touch($this->keepalive_file_name);
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
protected function _createKeepAliveFile() {
file_put_contents($this->keepalive_file_name, getmypid());
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
}
$testThatHangs = new TestThatHangs();
$testThatHangs->process();
testKeepAlive.php
class TestKeepAlive {
protected $seconds_of_nonactivity_to_kill_script = 10;
protected $keepalive_file_name = 'test_keepalive_info.txt';
public function process() {
$this->_display('keep alive script is observing keepalive file...');
while (true) {
sleep(1);
$keepAliveFileLastTouchedAbsoluteSeconds = $this->_getKeepAliveFileLastTouchedAbsoluteSeconds();
if ($keepAliveFileLastTouchedAbsoluteSeconds == 0) {
$this->_display('the script is not running');
} else {
$currentAbsoluteSeconds = $this->_getCurrentAbsoluteSeconds();
$touchedAgoSeconds = $currentAbsoluteSeconds - $keepAliveFileLastTouchedAbsoluteSeconds;
$this->_display('script is running and keep alive file was touched ' . $touchedAgoSeconds . ' seconds ago');
if($touchedAgoSeconds >= $this->seconds_of_nonactivity_to_kill_script) {
$this->_killProcess();
}
}
}
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
if (!file_exists($this->keepalive_file_name)) {
return 0;
} else {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getProcessId() {
$lines = file($this->keepalive_file_name);
if(count($lines) > 0) {
return intval($lines[0]);
} else {
return 0;
}
}
protected function _killProcess() {
$processId = $this->_getProcessId();
$this->_display('killing process ' . $processId);
exec("kill $processId");
$this->_cleanUpKeepAliveFile();
}
}
$testKeepAlive = new TestKeepAlive();
$testKeepAlive->process();
protected $seconds_of_nonactivity_to_kill_script = 10;
protected $keepalive_file_name = 'test_keepalive_info.txt';
public function process() {
$this->_display('keep alive script is observing keepalive file...');
while (true) {
sleep(1);
$keepAliveFileLastTouchedAbsoluteSeconds = $this->_getKeepAliveFileLastTouchedAbsoluteSeconds();
if ($keepAliveFileLastTouchedAbsoluteSeconds == 0) {
$this->_display('the script is not running');
} else {
$currentAbsoluteSeconds = $this->_getCurrentAbsoluteSeconds();
$touchedAgoSeconds = $currentAbsoluteSeconds - $keepAliveFileLastTouchedAbsoluteSeconds;
$this->_display('script is running and keep alive file was touched ' . $touchedAgoSeconds . ' seconds ago');
if($touchedAgoSeconds >= $this->seconds_of_nonactivity_to_kill_script) {
$this->_killProcess();
}
}
}
}
protected function _display($text) {
echo $text . PHP_EOL;
}
protected function _getKeepAliveFileLastTouchedAbsoluteSeconds() {
if (!file_exists($this->keepalive_file_name)) {
return 0;
} else {
clearstatcache();
return filemtime($this->keepalive_file_name);
}
}
protected function _getCurrentAbsoluteSeconds() {
return strtotime(date("Y-m-d H:i:s"));
}
protected function _cleanUpKeepAliveFile() {
unlink($this->keepalive_file_name);
}
protected function _getProcessId() {
$lines = file($this->keepalive_file_name);
if(count($lines) > 0) {
return intval($lines[0]);
} else {
return 0;
}
}
protected function _killProcess() {
$processId = $this->_getProcessId();
$this->_display('killing process ' . $processId);
exec("kill $processId");
$this->_cleanUpKeepAliveFile();
}
}
$testKeepAlive = new TestKeepAlive();
$testKeepAlive->process();
run.sh
DIR=$( cd "$( dirname "$0" )" && pwd )
cd $DIR
if ps ax | grep "$1" | grep -v grep | grep -v "/bin/sh" > /dev/null
then
echo ""
else
php $1 $2 $3 $4 $5 $6
fi
cd $DIR
if ps ax | grep "$1" | grep -v grep | grep -v "/bin/sh" > /dev/null
then
echo ""
else
php $1 $2 $3 $4 $5 $6
fi
cronjobs (crontab -e)
MAILTO="test@company.com"
#* * * * * ~/work/testing/run.sh testThatHangs.php >> /var/log/cronjobs/log_testThatHangs
#* * * * * ~/work/testing/run.sh testKeepAlive.php >> /var/log/cronjobs/log_testKeepAlive
#* * * * * ~/work/testing/run.sh testThatHangs.php >> /var/log/cronjobs/log_testThatHangs
#* * * * * ~/work/testing/run.sh testKeepAlive.php >> /var/log/cronjobs/log_testKeepAlive
(replace :nnn: with two colons)
JQUERY CODE EXAMPLE: List of elements with similar functionality
added on Jan 30, 2013
List of elements with similar functionality
Shows how to create a list of elements, each with a unique id, each element with similar funtionality.

<html>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="infoItem_123" class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
<div class="contentOne">you clicked one</div>
<div class="contentTwo">you clicked two</div>
</div>
<div id="infoItem_456" class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
<div class="contentOne">du hast auf eins geklickt</div>
<div class="contentTwo">du hast auf zwei geklickt</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
var elemContentOne;
var elemContentTwo;
var itemId;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
elemContentOne = infoItem.find('.contentOne');
elemContentTwo = infoItem.find('.contentTwo');
itemId = infoItem.attr('id');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
elemContentOne.hide();
elemContentTwo.hide();
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText($('#'+itemId), elemContentOne.html());
});
elemMenuTwo.click(function(e) {
that.displayText($('#'+itemId), elemContentTwo.html());
});
}
this.displayText = function(clickedInfoItem, text) {
clickedInfoItem.find('.content').html(text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>
<head>
<script type="text/javascript" src="systemJavascript/jquery-1.8.3.min.js"></script>
</head>
<body>
<div id="infoItem_123" class="infoItem">
<div class="menu">
<span class="menuOne">one</span>
<span class="menuTwo">two</span>
</div>
<div class="content">intro message</div>
<div class="contentOne">you clicked one</div>
<div class="contentTwo">you clicked two</div>
</div>
<div id="infoItem_456" class="infoItem">
<div class="menu">
<span class="menuOne">eins</span>
<span class="menuTwo">zwei</span>
</div>
<div class="content">Introtext</div>
<div class="contentOne">du hast auf eins geklickt</div>
<div class="contentTwo">du hast auf zwei geklickt</div>
</div>
</body>
</html>
<script type="text/javascript">
var INFOITEM = INFOITEM || {};
INFOITEM.initialize = function(infoItem) {
var elemMenuOne;
var elemMenuTwo;
var elemContent;
var elemContentOne;
var elemContentTwo;
var itemId;
this.defineVariables = function() {
elemMenuOne = infoItem.find('.menuOne');
elemMenuTwo = infoItem.find('.menuTwo');
elemContent = infoItem.find('.content');
elemContentOne = infoItem.find('.contentOne');
elemContentTwo = infoItem.find('.contentTwo');
itemId = infoItem.attr('id');
}
this.decorateElements = function() {
elemMenuOne.css('background-color', 'beige');
this.decorateAsLink(elemMenuOne);
elemMenuTwo.css('background-color', 'beige');
this.decorateAsLink(elemMenuTwo);
elemContentOne.hide();
elemContentTwo.hide();
}
this.functionalizeElements = function() {
that = this;
elemMenuOne.click(function(e) {
that.displayText($('#'+itemId), elemContentOne.html());
});
elemMenuTwo.click(function(e) {
that.displayText($('#'+itemId), elemContentTwo.html());
});
}
this.displayText = function(clickedInfoItem, text) {
clickedInfoItem.find('.content').html(text);
}
this.decorateAsLink = function(elem) {
elem.css({
'cursor' :'pointer',
'text-decoration' : 'underline',
'font-weight' : 'normal'
});
}
this.defineVariables();
this.decorateElements();
this.functionalizeElements();
}
$('.infoItem').each(function(){
INFOITEM.initialize($(this));
});
</script>
UBUNTU BOOK NOTES: Ubuntu Unleased 2012 | 4.2
added on Jan 8, 2013
Ubuntu Unleased 2012
- chap1,has 12 variants, cloud, etc., warns against dual boot, you can try, wubi (ubuntu within windows);finished
- chap2,dmesg, sudo, apt-get update, installing drivers, hwclock, wireless;finished
- chap3,gnome and x, xorg.conf in /usr/share/X11, Unity (a fresh take on the GUI), workspaces nice and ctrl-alt-arrow;finished
- chap4,browsers and email clients, etc, then ubuntu one cloud storage;finished
- chap5,libreoffice etc;finished
- chap6,dvds, video, audio, etc;finished
- chap7,ldxe, lunbuntu, as of 4.10 gnome;finished
- chap8,games;finished
- chap9,apt-get to install and remove, very apt-get instructions, shows how to compile from source with apt-get;4.8
- chap10,command-line quickstart, ssh, ubuntu doesn't have a root account, would be a good read for directories in linux, how to add user but not groups, shutdown;finished
- chap11, more command-line, basics, fu, cp, find, grep, ln, whereis, tail, top, ps, using < for input, pipe for combining commands, xargs, tar;4.2
- chap12,managing users, learned: use the gui to create users, otherwise cannot login;3.2;be able to create users wihtout gui
- chap13,automating, at, cron, semicolon, regex in names, piping, writing shell script;4.8
- todo: write shell script, how to make scripts executable but didn't work (alias), basics of scripting, for, if, etc;4.3;learn basic scripting
- chap14, boot process, various infos on booting;finished
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
- chap34,
- chap35,
- chap36,
- chap37,
- chap38,
- chap39,
- chap40,
- chap41,
- chap42,
JQUERY CODE EXAMPLE: Base code to simply attach jQuery code to numberous like elements on page
added on Jan 8, 2013
Base code to simply attach jQuery code to numberous like elements on page
Use this code as a basis if you want to have numerous elements on a page which each act individually. The trick is to separate out the trigger elements from the relative elements.

PHP:
echo display();
function display() {
$r = '';
for ($x = 0; $x < 10; $x++) {
$r .= '<div class="quickReviewItem" data-item-id="' . $x . '"><span class="title">title</span><span class="message">nnn</span></div>';
}
return $r;
}
function display() {
$r = '';
for ($x = 0; $x < 10; $x++) {
$r .= '<div class="quickReviewItem" data-item-id="' . $x . '"><span class="title">title</span><span class="message">nnn</span></div>';
}
return $r;
}
calling jQuery from HTML:
$('.quickReviewItem').each(function(){
QUICKREVIEWITEM.initialize($(this));
});
QUICKREVIEWITEM.initialize($(this));
});
jQuery code:
var QUICKREVIEWITEM = QUICKREVIEWITEM || {};
QUICKREVIEWITEM.initialize = function(elemQuickReview) {
var elemTitle;
this.defineTriggerVariables = function() {
elemTitle = elemQuickReview.find('.title');
}
this.defineRelativeVariables = function(elem) {
elemMessage = elem.find('.message');
itemId = $.trim(elem.data('itemId')); //note: trim necessary to be able to compare string values
}
this.functionalizeElements = function() {
that = this;
elemTitle.click(function(e) {
that.defineRelativeVariables(elemTitle.parent());
e.preventDefault();
elemMessage.html(elemMessage.html() + 'new' + itemId);
});
}
this.decorateElements = function() {
elemTitle.css('color','brown');
elemTitle.css('cursor','pointer');
elemMessage.css('color','green');
elemMessage.html(elemMessage.html()+itemId);
}
this.defineTriggerVariables();
this.defineRelativeVariables(elemQuickReview);
this.decorateElements();
this.functionalizeElements();
}
QUICKREVIEWITEM.initialize = function(elemQuickReview) {
var elemTitle;
this.defineTriggerVariables = function() {
elemTitle = elemQuickReview.find('.title');
}
this.defineRelativeVariables = function(elem) {
elemMessage = elem.find('.message');
itemId = $.trim(elem.data('itemId')); //note: trim necessary to be able to compare string values
}
this.functionalizeElements = function() {
that = this;
elemTitle.click(function(e) {
that.defineRelativeVariables(elemTitle.parent());
e.preventDefault();
elemMessage.html(elemMessage.html() + 'new' + itemId);
});
}
this.decorateElements = function() {
elemTitle.css('color','brown');
elemTitle.css('cursor','pointer');
elemMessage.css('color','green');
elemMessage.html(elemMessage.html()+itemId);
}
this.defineTriggerVariables();
this.defineRelativeVariables(elemQuickReview);
this.decorateElements();
this.functionalizeElements();
}
JQUERY CODE EXAMPLE: A simple JQuery/AJAX form with PHP processing page
added on Nov 16, 2012
A simple JQuery/AJAX form with PHP processing page
This is a simple HTML/JQuery/AJAX form that sends data via AJAX to a PHP page and displays the results.

HTML Page:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing - Test</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<script type="text/javascript" src="systemJavascript/jquery-1.8.2.min.js"></script>
<style type="text/css">
#result {
margin: 10px;
background: #eee;
padding: 10px;
height: 40px;
overflow: auto;
}
</style>
<script type="text/javascript">
$(function() {
SMARTFORM.initialize($('form#form1'));
SMARTFORM.initialize($('form#form2'));
});
var SMARTFORM = SMARTFORM || {};
SMARTFORM.initialize = function(form) {
var id = form.attr('id');
var elemsTextBoxes = form.find('input[type=text]');
var elemFirstField = form.find('input[type=text]').filter(':first');
var elemButton = form.find('#formButton');
var elemFieldFirstName = form.find('#firstName');
var elemFieldLastName = form.find('#lastName');
var elemResultArea = form.find('#resultArea');
elemsTextBoxes.on('focus', function() {
$(this).css('background-color', '#eee');
});
elemsTextBoxes.on('blur', function() {
$(this).css('background-color', '#fff');
});
elemFirstField.focus();
elemButton.click(function(e) {
e.preventDefault();
elemButton.blur();
elemFirstField.focus();
if(elemFieldFirstName.val() != '') {
$.post(
'testAjaxProcess2.php',
{
firstName: elemFieldFirstName.val(),
lastName: elemFieldLastName.val()
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
elemResultArea.html(data['message']).hide().fadeIn('slow');
elemFieldFirstName.val('');
elemFieldLastName.val('');
elemButton.hide();
elemFieldFirstName.css('background-color', 'white');
});
} else {
elemFieldFirstName.css('background-color', 'red');
}
});
}
</script>
</head>
<body>
<form id="form1">
<h2>Form1</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
<form id="form2">
<h2>Form2</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
</body>
</html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Testing - Test</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<script type="text/javascript" src="systemJavascript/jquery-1.8.2.min.js"></script>
<style type="text/css">
#result {
margin: 10px;
background: #eee;
padding: 10px;
height: 40px;
overflow: auto;
}
</style>
<script type="text/javascript">
$(function() {
SMARTFORM.initialize($('form#form1'));
SMARTFORM.initialize($('form#form2'));
});
var SMARTFORM = SMARTFORM || {};
SMARTFORM.initialize = function(form) {
var id = form.attr('id');
var elemsTextBoxes = form.find('input[type=text]');
var elemFirstField = form.find('input[type=text]').filter(':first');
var elemButton = form.find('#formButton');
var elemFieldFirstName = form.find('#firstName');
var elemFieldLastName = form.find('#lastName');
var elemResultArea = form.find('#resultArea');
elemsTextBoxes.on('focus', function() {
$(this).css('background-color', '#eee');
});
elemsTextBoxes.on('blur', function() {
$(this).css('background-color', '#fff');
});
elemFirstField.focus();
elemButton.click(function(e) {
e.preventDefault();
elemButton.blur();
elemFirstField.focus();
if(elemFieldFirstName.val() != '') {
$.post(
'testAjaxProcess2.php',
{
firstName: elemFieldFirstName.val(),
lastName: elemFieldLastName.val()
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
elemResultArea.html(data['message']).hide().fadeIn('slow');
elemFieldFirstName.val('');
elemFieldLastName.val('');
elemButton.hide();
elemFieldFirstName.css('background-color', 'white');
});
} else {
elemFieldFirstName.css('background-color', 'red');
}
});
}
</script>
</head>
<body>
<form id="form1">
<h2>Form1</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
<form id="form2">
<h2>Form2</h2>
<div>First Name:<input type="text" id="firstName"/></div>
<div>Last Name:<input type="text" id="lastName"/></div>
<div><button id="formButton">Send</button></div>
<div id="resultArea">
</div>
</form>
</body>
</html>
Processing Page:
<?php
$data = array();
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$data['message'] = 'Thank you, '. strtoupper($firstName) . ' ' . strtoupper($lastName) . ' was processed.';
echo json_encode($data);
$data = array();
$firstName = filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRING);
$lastName = filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRING);
$data['message'] = 'Thank you, '. strtoupper($firstName) . ' ' . strtoupper($lastName) . ' was processed.';
echo json_encode($data);
PHP CODE EXAMPLE: How to send multiple MySQL commands in one line from PHP
added on Jul 18, 2012
How to send multiple MySQL commands in one line from PHP
Although a semicolon-separated statement will work in e.g. phpmyadmin, you cannot just copy it to a string in PHP and execute it without splitting it and executing each command. This code shows you how.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
$sql = "SELECT @i:=0;
SELECT @i:=@i+1 AS `No.`,
CONCAT(c.FirstName, ' ', c.LastName) AS `Customer Name`,
CONCAT(e.FirstName, ' ', e.LastName) AS `Support Rep`
FROM customer AS c
JOIN employee AS e ON e.EmployeeId = c.SupportRepId";
$db = new mysqli('localhost', 'root', 'password', 'chinook');
$queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
foreach ($queries as $query) {
if (strlen(trim($query)) > 0) {
$result = $db->query($query);
$numberOfColumns = $db->field_count;
if ($numberOfColumns > 1) {
echo '<table border="1">';
while ($row = $result->fetch_array()) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
}
?>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php
$sql = "SELECT @i:=0;
SELECT @i:=@i+1 AS `No.`,
CONCAT(c.FirstName, ' ', c.LastName) AS `Customer Name`,
CONCAT(e.FirstName, ' ', e.LastName) AS `Support Rep`
FROM customer AS c
JOIN employee AS e ON e.EmployeeId = c.SupportRepId";
$db = new mysqli('localhost', 'root', 'password', 'chinook');
$queries = preg_split("/;+(?=([^'|^\\\']*['|\\\'][^'|^\\\']*['|\\\'])*[^'|^\\\']*[^'|^\\\']$)/", $sql);
foreach ($queries as $query) {
if (strlen(trim($query)) > 0) {
$result = $db->query($query);
$numberOfColumns = $db->field_count;
if ($numberOfColumns > 1) {
echo '<table border="1">';
while ($row = $result->fetch_array()) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
}
?>
</body>
</html>
SQL CODE EXAMPLE: How to find doubles in SQL
added on Jul 7, 2012
How to find doubles in SQL
This query finds all tracks ordered for two customers:
SELECT inv.BillingCity,cus.LastName,tra.Name
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
WHERE cus.LastName IN ('Schneider','Schröder')
ORDER BY inv.BillingCity,cus.LastName,tra.Name
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
WHERE cus.LastName IN ('Schneider','Schröder')
ORDER BY inv.BillingCity,cus.LastName,tra.Name

and this finds all tracks that a customer ordered multiple times:
SELECT cus.CustomerId,tra.Name,COUNT(cus.CustomerId) AS TheTotal
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
GROUP BY cus.CustomerId,tra.Name
HAVING TheTotal > 1
FROM invoice AS inv
JOIN customer AS cus ON inv.CustomerId=cus.CustomerId
JOIN invoiceline inl ON inv.InvoiceId=inl.InvoiceId
JOIN track tra ON tra.TrackId=inl.TrackId
GROUP BY cus.CustomerId,tra.Name
HAVING TheTotal > 1
LINUX BOOK NOTES: Macintosh Terminal Pocket Guide | 4.8
added on Jul 7, 2012
Macintosh Terminal Pocket Guide
skimming: try all examples in ubuntu, should be about the same, would be useful to see where ubuntu differes as well, piping, lost of useful commands, background processes, etc, %%page64
- chap1,
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
CLOJURE FORAY: setup and use clojure in ubuntu






added on Jul 4, 2012
Setup and use clojure in ubuntu
- install
- get ubuntu running in virtualbox
- reading this guide
- sudo apt-get install clojure
- quote: Debian is the rock upon which Ubuntu is built.
- last thing it said was "ldconfig deferred processing now taking place", seems to have installed
- yes I get user=>
- did: (defn hello [name] (str "Hello, " name)), ok

- clojure basics
- define variable x to true

- another way to define z as true (constantly)

- define and execute a function:

- how to do a loop:

- how to call java from clojure:

- leiningen
- how to download and install Leiningen:
- download lein script
- create a new project:

- add a new dependency:

JAVASCRIPT BOOK NOTES: The Linux Command Line | 5.0
added on Jul 4, 2012
The Linux Command Line
- chap1,launch the terminal, starts with "command not found", date, cal, df, free, exit;2.8;super basic;finished
- chap2,pwd, cd, ls, limit names to period, hyphen, underscore
- fc: goto home directory;cd
- fc: goto previous working directory;cd -
- fc: goto home directory of user;cd ~username
- chap3,file, etc. %%page50
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
- chap34,
WEB BOOK NOTES: Web Performance Daybook | 5.0
added on Jul 4, 2012
Web Performance Daybook
- chap1, talks about how webpagetest.org works, very technical;3.1;finished
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
- chap17,
- chap18,
- chap19,
- chap20,
- chap21,
- chap22,
- chap23,
- chap24,
- chap25,
- chap26,
- chap27,
- chap28,
- chap29,
- chap30,
- chap31,
- chap32,
- chap33,
JAVASCRIPT BOOK NOTES: Learning Node | 5.0
added on Jul 4, 2012
Learning Node
- preface, introductions and quotes;finished;3.1
- quote: True, you can use CoffeeScript with node.js, but JavaScript is the lingua franca of the technology.
- quote: If you explore the source code for Node, you'll find the source code for Google's V8.
- quote: One advantage to Node.js, then, is that you can develop Node applications for just one implementation of JavaScript.
- quote: Node is designed to be used for applications that are heavy on input/output, but light on computation.
- chap1, shows how to set up a development environment for Node in Windows 7 and Linux (Ubuntu).
- page6
- chap2,
- chap3,
- chap4,
- chap5,
- chap6,
- chap7,l
- chap8,
- chap9,
- chap10,
- chap11,
- chap12,
- chap13,
- chap14,
- chap15,
- chap16,
CLOJURE BOOK NOTES: Programming Clojure | 4.5
added on Jul 4, 2012
Programming Clojure
If you are not familiar with functional programming, Java, then is a very abtract book.
- chap1,why, functional programming is simple, best of java, lisp for the jvm, short programs, simpler, defrecord Person[first-name last-name], lisp reloaded, improves on lisp syntax, commas are whitespace, not a pure functional language like haskell, threadsafe, contrast with imperitive languages, where explicit statements alter program state, functional programming is more urgent, uses software transcational memory, clojure dynamic typing (many functional language statically typed), simplifies concurrent programming (thread-safe), embraces JVM, via git, REPL, *1 and *2, libraries, (doc str) for documentation, conventions;skimmed;4.6
- chap2, exploring clojure, nice abbreviations, macros, callings java, no for loop, cons for construct, functions return lists;skimmed;4.1
- chap3,sequences, maps, lazy and infinite sequences, regex use java.util.regex, peek/pop, somewhat like javascript object literals;skimmed;4.0
- chap4, functional programming, "how to be lazy", self-recursion, currying () and partial application, Trampolining Mutual Recursion, expose sequences instead of functions;skimmed;4.0
- chap5, state, software transactional memory, atoms and refs, unified update model, java callback apis, snake game; skimmed;2.3-state issues abstract
- chap6,protocols and databases, "spit and slurp i/o functions", gulp and expectorate, ok now they have files such as "src/examples/protocols.clj", interfaces, can create java interfaces in clojure, macros;skimmed;4.1-some code for reading databases
- question: where are the touch points between clojure and java?
- chap7, macros, if you can write it as a function, don't write a macro, defmacro, java interop;skimmed;3.7-said not to write macros
- chap8, multimethods, associate function with set of inputs (like polymorphism), defmulti, clojure's inspector library uses swing; skimmed;3.9-the polymorphism reference made sense
- chap9, java down and dirty, clojure compiles to bytecode, exception handling easy, creating java classes in clojure, logging;skimmed;3.5-didn't really show how it calls java
- chap10,building application, running tests, the REPL, has example with html output, deploying: lien run, example of deploying at heroku;skimmed;2.4-not really sure what the application was
- question: not really sure how clojure is used in relation to java, is it used in conjunction with java, instead of java, or does it use java?
GIT BOOK NOTES: Getting Good with Git (2010) | 5.0
added on Jun 25, 2012
Getting Good with Git (2010)
This is a very basic book which treats the user as if he hasn't used the command line before, i.e. first teaches "ls" for linux and "dir" for windows command line.
- chap1, introduction, it's a program, allows you to put marks in project;done;3.0
- quote: if you're grokking the concept of timeline markers for your code, you're understanding where Git fits in
- quote: with Git, your code repositories don't need to have a single home
- quote: almost everything you do with Git is done on your own machine
- checkout: whygitisbetterthanx.com (500 error)
- chap2, commands;done;done;1.0;very simplistic background to commandlines (ls and dir)
- quote: in GIT, 99% of everything you do on the command line is irreversible
- foray: get textmate working on ubuntu (mate)
- chap3, configuration, uses msysgit on windows, %%here:pg32
- recon: homebrew and macports for mac
- chap4, beyond the basics
- chap5, github
PHP CODE EXAMPLE: Base code to retrieve data from MySQL and display with PHP/mysql_connect
added on Jun 13, 2012
Base code to retrieve data from MySQL and display with PHP/mysql_connect
This is the simplest code that uses the mysql_connect commands to retreive data from a MySQL database and displays it in a nice table. (Get the Chinook database here.)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table thead tr td {
background-color: #ddd;
padding: 5px;
font-weight: bold;
}
table tbody tr td {
background-color: #eee;
padding: 5px;
color: navy;
}
div.sqlCommand {
font-family: courier;
}
</style>
</head>
<body>
<?php
$sql = 'SELECT LastName,FirstName FROM employee ORDER BY LastName';
$con = mysql_connect('localhost', 'root', 'thepass');
if (!$con) {
die('database error');
} else {
mysql_select_db('chinook', $con);
$result = mysql_query($sql);
$numberOfColumns = mysql_num_fields($result);
echo '<div class="sqlCommand">' . $sql . '</div>';
echo '<table>';
echo '<thead>';
echo '<tr>';
while ($property = mysql_fetch_field($result)) {
echo '<td>' . $property -> name . '</td>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '<table>';
}
?>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
table thead tr td {
background-color: #ddd;
padding: 5px;
font-weight: bold;
}
table tbody tr td {
background-color: #eee;
padding: 5px;
color: navy;
}
div.sqlCommand {
font-family: courier;
}
</style>
</head>
<body>
<?php
$sql = 'SELECT LastName,FirstName FROM employee ORDER BY LastName';
$con = mysql_connect('localhost', 'root', 'thepass');
if (!$con) {
die('database error');
} else {
mysql_select_db('chinook', $con);
$result = mysql_query($sql);
$numberOfColumns = mysql_num_fields($result);
echo '<div class="sqlCommand">' . $sql . '</div>';
echo '<table>';
echo '<thead>';
echo '<tr>';
while ($property = mysql_fetch_field($result)) {
echo '<td>' . $property -> name . '</td>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
for ($x = 0; $x < $numberOfColumns; $x++) {
echo '<td>' . $row[$x] . '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '<table>';
}
?>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: JavaScript Singleton Refactored
added on Jun 11, 2012
JavaScript Singleton Refactored
This is a refactored version of my other JavaScript singleton. Basically the getInstance function was removed which also allowed me to remove the that = this, more succinct now:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var DatapodManager = (function() {
return {
message: 'singleton defined at ' + getMilliseconds(),
getMessage: function() {
return this.message;
},
id: '1234'
}
}());
function dowait() {
for(x=1; x<=10000000; x++) {
var y = 1000;
var z = 1000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
dowait();
console.log('getting second singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
console.log('the static id is ' + DatapodManager.id);
};
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var DatapodManager = (function() {
return {
message: 'singleton defined at ' + getMilliseconds(),
getMessage: function() {
return this.message;
},
id: '1234'
}
}());
function dowait() {
for(x=1; x<=10000000; x++) {
var y = 1000;
var z = 1000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
dowait();
console.log('getting second singleton message at: ' + getMilliseconds());
console.log(DatapodManager.getMessage());
console.log('the static id is ' + DatapodManager.id);
};
</script>
</head>
<body>
</body>
</html>
JAVASCRIPT CODE EXAMPLE: Basic JavaScript Singleton
added on Jun 8, 2012
Basic JavaScript Singleton
I needed a singleton in JavaScript in order to make a DataManager which is called multiple times, but I just want it to load its data only the first time it is called, then give pieces of the data out view public methods, never loading the initial data again.

<!DOCTYPE html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>
</html>
<html>
<head>
<title>test singleton</title>
<script type="text/javascript">
var DatapodManager = (function() {
var instantiated;
that = this;
//DEFINE INTERNAL VARIABLES HERE:
var message = '';
function init() {
//LOAD DATA ONCE HERE:
that.message = 'singleton message defined at: ' + getMilliseconds();
//ALLOW PUBLIC ACCESS TO SINGLETON DATA HERE:
return {
getMessage : function() {
return that.message;
},
id : '1234'
}
}
return {
getInstance : function() {
if(!instantiated) {
instantiated = init();
}
return instantiated;
}
}
})()
function dowait() {
for( x = 1; x <= 10000000; x++) {
var y = 1000;
var z = 2000;
var b = y * z;
}
}
function getMilliseconds() {
var d = new Date();
return d.getMilliseconds();
}
window.onload = function() {
console.log('getting first singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
dowait();
console.log('getting second singleton message at: '+getMilliseconds());
console.log(DatapodManager.getInstance().getMessage());
console.log('the static id is '+DatapodManager.getInstance().id);
};
</script>
</head>
<body></body>
</html>
JAVASCRIPT CODE EXAMPLE: Example of using prototype property to add functionality to a class
added on Jun 7, 2012
Example of using prototype property to add functionality to a class
The following example shows how you can create an object (c1) from a class (Circle), then add a function to that class, which automatically is accessible by the object that was already created by the class.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var Circle = function(radius) {
this.radius = radius;
this.doubleRadius = function() {
return this.radius * 2;
}
}
var c1 = new Circle(4);
Circle.prototype.area = function() {
return Math.PI*this.radius*this.radius;
}
var c2 = new Circle(5);
console.log('--- first circle object, created before adding "area" method');
console.log(c1.radius);
console.log(c1.doubleRadius());
console.log(c1.area());
console.log('--- second circle object, created after adding "area" method');
console.log(c2.radius);
console.log(c2.doubleRadius());
console.log(c2.area());
console.log(c2.constructor.prototype); // Object { area=function() }
console.log(c2.__proto__); // Object { area=function() }
}
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var Circle = function(radius) {
this.radius = radius;
this.doubleRadius = function() {
return this.radius * 2;
}
}
var c1 = new Circle(4);
Circle.prototype.area = function() {
return Math.PI*this.radius*this.radius;
}
var c2 = new Circle(5);
console.log('--- first circle object, created before adding "area" method');
console.log(c1.radius);
console.log(c1.doubleRadius());
console.log(c1.area());
console.log('--- second circle object, created after adding "area" method');
console.log(c2.radius);
console.log(c2.doubleRadius());
console.log(c2.area());
console.log(c2.constructor.prototype); // Object { area=function() }
console.log(c2.__proto__); // Object { area=function() }
}
</script>
</head>
<body>
</body>
</html>