JQUERY CODE EXAMPLE: Site with Non-Scrollable Scoreboard as Header
added on Oct 29, 2013
Site with Non-Scrollable Scoreboard as Header
This site shows a name and score in the header, body scrolls, when links are clicked anywhere, user sees his score change.

jQuery:
$(function() {
$('.hotlink').click(function() {
var elemScore = $('.thescore');
var score = parseInt(elemScore.html());
var newScore = score +1;
var strNewStore = padDigits(newScore, 5);
elemScore.html(strNewStore).css('color','navy').hide().fadeIn();
});
});
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
$('.hotlink').click(function() {
var elemScore = $('.thescore');
var score = parseInt(elemScore.html());
var newScore = score +1;
var strNewStore = padDigits(newScore, 5);
elemScore.html(strNewStore).css('color','navy').hide().fadeIn();
});
});
function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
HTML/CSS:
<style type="text/css">
#site_topbanner {
position: fixed;
top: 0px;
width:100%;
height: 40px;
background-color:#eee;
margin:0;
padding:0;
border-bottom: 1px solid #ddd;
}
#site_topbanner .thename {
font-size: 29px;
float: left;
}
#site_topbanner .thescore {
font-size: 29px;
color: navy;
float: right;
}
#site_topbanner .site_topbanner_wrapper {
width: 600px;
margin-left: auto;
margin-right: auto;
}
#site_content {
width: 600px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
padding-top: 1px;
}
div.clear {
clear: both;
}
span.hotlink {
color:navy;
font-weight: bold;
cursor: pointer;
}
body {
margin:0;
padding:0;
}
</style>
<body>
<div id="site_topbanner">
<div class="site_topbanner_wrapper">
<div class="thename">The Name</div>
<div class="thescore">00345</div>
<div class="clear"></div>
</div>
</div>
<div id="site_content">...
#site_topbanner {
position: fixed;
top: 0px;
width:100%;
height: 40px;
background-color:#eee;
margin:0;
padding:0;
border-bottom: 1px solid #ddd;
}
#site_topbanner .thename {
font-size: 29px;
float: left;
}
#site_topbanner .thescore {
font-size: 29px;
color: navy;
float: right;
}
#site_topbanner .site_topbanner_wrapper {
width: 600px;
margin-left: auto;
margin-right: auto;
}
#site_content {
width: 600px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
padding-top: 1px;
}
div.clear {
clear: both;
}
span.hotlink {
color:navy;
font-weight: bold;
cursor: pointer;
}
body {
margin:0;
padding:0;
}
</style>
<body>
<div id="site_topbanner">
<div class="site_topbanner_wrapper">
<div class="thename">The Name</div>
<div class="thescore">00345</div>
<div class="clear"></div>
</div>
</div>
<div id="site_content">...
JQUERY CODE EXAMPLE: Basic code for flashcards using jquery widgets
added on Sep 8, 2013
Basic code for flashcards using jquery widgets
This code reads a list of flashcards from a text file and displays them as interactive flashcards which keep a score.

(function($){
$.widget("ui.itemFlashcard", {
options: {
elementId: null,
id: null,
front: null,
back: null
},
_create: function(){
//define
var that = this;
this.status = 'hiding';
this.backContentElem = $(this.element).find('.backContent');
this.backBlankElem = $(this.element).find('.backBlank');
//display
this.element.fadeIn();
//functionalize
this.element
.click(function(e) {
e.preventDefault();
if(that.status == 'showing') {
that.status = 'hiding';
that.backContentElem.hide();
that.backBlankElem.show();
} else {
that.status = 'showing';
that.backContentElem.show();
that.backBlankElem.hide();
$.post('process.php',
{
itemTypeIdCode: 'flashcards',
id: that.options.id,
action: 'viewed'
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
});
$.event.trigger({
type: "scoreChange",
changeBy: 5
});
}
});
}
});
})(jQuery);
$.widget("ui.itemFlashcard", {
options: {
elementId: null,
id: null,
front: null,
back: null
},
_create: function(){
//define
var that = this;
this.status = 'hiding';
this.backContentElem = $(this.element).find('.backContent');
this.backBlankElem = $(this.element).find('.backBlank');
//display
this.element.fadeIn();
//functionalize
this.element
.click(function(e) {
e.preventDefault();
if(that.status == 'showing') {
that.status = 'hiding';
that.backContentElem.hide();
that.backBlankElem.show();
} else {
that.status = 'showing';
that.backContentElem.show();
that.backBlankElem.hide();
$.post('process.php',
{
itemTypeIdCode: 'flashcards',
id: that.options.id,
action: 'viewed'
},
function( jsonString )
{
var data = $.parseJSON(jsonString);
});
$.event.trigger({
type: "scoreChange",
changeBy: 5
});
}
});
}
});
})(jQuery);
REDBEAN CODE EXAMPLE: Basic code for SQLite access with Redbean
added on Sep 5, 2013
Basic code for SQLite access with Redbean
Uncomment out the following lines to see how you can read and write to an SQLite database.

//test_createBean();
//echo test_getSingleBean();
//echo test_getCountRecords();
//echo test_getMultipleBeansByIdList();
//test_executeQuery();
//echo test_getMultipleRecords();
//echo test_getMultipleRecordsWithParameterBindings();
//echo test_getSingleRecord();
//echo test_getSingleColumn();
//test_setColumnWithVariables();
test_createMultipleBeans();
R..close();
function test_createBean() {
$comparisonBean = R.dispense('comparisons');
$comparisonBean->categories = 'member,backbone';
$comparisonBean->whenCreated = '2013-05-31 04:30:06';
$comparisonBean->score = 23;
$comparisonBean->body = "Ember's sweet spot is applications where the user will keep the application open for long periods of time, perhaps all day, and interactions with the application's views or underlying data trigger deep changes in the view hierarchy. Ember is larger than Backbone, but thanks to Expires, Cache-Control this only matters on the the first load. After two days of daily use that extra 30k will be overshadowed by data transfers, sooner if your content involves images. Backbone apps focus more on brief or casual interactions, that are often just small sections of a larger static page: airbnb, Khan Academy, Foursquare's map and lists.";
R@@DOUBLE_SEMICOLONstore($comparisonBean);
}
function test_getSingleBean() {
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', 1);
echo $comparisonBean->body;
}
function test_getCountRecords() {
$r = '';
$r .= R@@DOUBLE_SEMICOLONcount('comparisons');
return $r;
}
function test_getMultipleBeansByIdList() {
$r = '';
$comparisons = R@@DOUBLE_SEMICOLONbatch('comparisons', [1, 2]);
if (count($comparisons) > 0) {
$r .= '<ul>';
foreach ($comparisons as $comparison) {
$r .= '<li>' . $comparison->body . '</li>';
}
$r .= '</ul>';
}
return $r;
}
function test_executeQuery() {
R@@DOUBLE_SEMICOLONexec('UPDATE comparisons SET categories="changed" WHERE id=2');
}
function test_getMultipleRecords() {
$r = '';
//$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE id>2');
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE "%javascript%"');
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getMultipleRecordsWithParameterBindings() {
$r = '';
$searchText = 'also';
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE :body', [':body'=>'%'.$searchText.'%']);
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getSingleRecord() {
$r = '';
$comparisonRecord = R@@DOUBLE_SEMICOLONgetRow('SELECT * FROM comparisons WHERE id=6');
$r .= '<b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'];
return $r;
}
function test_getSingleColumn() {
$r = '';
$ids = R@@DOUBLE_SEMICOLONgetCol('SELECT id FROM comparisons WHERE id > 3');
$r .= join($ids,',');
return $r;
}
function test_setColumnWithVariables() {
$id = 2;
$fieldName = 'body';
$fieldValue = 'the body was changed for record with id='.$id;
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', $id);
$comparisonBean->setAttr($fieldName, $fieldValue);
$idAffected = R@@DOUBLE_SEMICOLONstore($comparisonBean);
echo 'record with id '.$idAffected. ' changed';
}
function test_createMultipleBeans() {
$comparisonBeans = R@@DOUBLE_SEMICOLONdispense('comparisons',2);
if (count($comparisonBeans) > 0) {
foreach ($comparisonBeans as $comparisonBean) {
$comparisonBean->setAttr('categories', 'newone');
}
}
R@@DOUBLE_SEMICOLONstoreAll($comparisonBeans);
echo 'created';
}
//echo test_getSingleBean();
//echo test_getCountRecords();
//echo test_getMultipleBeansByIdList();
//test_executeQuery();
//echo test_getMultipleRecords();
//echo test_getMultipleRecordsWithParameterBindings();
//echo test_getSingleRecord();
//echo test_getSingleColumn();
//test_setColumnWithVariables();
test_createMultipleBeans();
R..close();
function test_createBean() {
$comparisonBean = R.dispense('comparisons');
$comparisonBean->categories = 'member,backbone';
$comparisonBean->whenCreated = '2013-05-31 04:30:06';
$comparisonBean->score = 23;
$comparisonBean->body = "Ember's sweet spot is applications where the user will keep the application open for long periods of time, perhaps all day, and interactions with the application's views or underlying data trigger deep changes in the view hierarchy. Ember is larger than Backbone, but thanks to Expires, Cache-Control this only matters on the the first load. After two days of daily use that extra 30k will be overshadowed by data transfers, sooner if your content involves images. Backbone apps focus more on brief or casual interactions, that are often just small sections of a larger static page: airbnb, Khan Academy, Foursquare's map and lists.";
R@@DOUBLE_SEMICOLONstore($comparisonBean);
}
function test_getSingleBean() {
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', 1);
echo $comparisonBean->body;
}
function test_getCountRecords() {
$r = '';
$r .= R@@DOUBLE_SEMICOLONcount('comparisons');
return $r;
}
function test_getMultipleBeansByIdList() {
$r = '';
$comparisons = R@@DOUBLE_SEMICOLONbatch('comparisons', [1, 2]);
if (count($comparisons) > 0) {
$r .= '<ul>';
foreach ($comparisons as $comparison) {
$r .= '<li>' . $comparison->body . '</li>';
}
$r .= '</ul>';
}
return $r;
}
function test_executeQuery() {
R@@DOUBLE_SEMICOLONexec('UPDATE comparisons SET categories="changed" WHERE id=2');
}
function test_getMultipleRecords() {
$r = '';
//$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE id>2');
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE "%javascript%"');
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getMultipleRecordsWithParameterBindings() {
$r = '';
$searchText = 'also';
$comparisonRecords = R@@DOUBLE_SEMICOLONgetAll('SELECT * FROM comparisons WHERE body LIKE :body', [':body'=>'%'.$searchText.'%']);
if (count($comparisonRecords) > 0) {
foreach ($comparisonRecords as $comparisonRecord) {
$r .= '<li><b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'] . '</li>';
}
}
return $r;
}
function test_getSingleRecord() {
$r = '';
$comparisonRecord = R@@DOUBLE_SEMICOLONgetRow('SELECT * FROM comparisons WHERE id=6');
$r .= '<b>'. $comparisonRecord['id'] . '</b>: '. $comparisonRecord['body'];
return $r;
}
function test_getSingleColumn() {
$r = '';
$ids = R@@DOUBLE_SEMICOLONgetCol('SELECT id FROM comparisons WHERE id > 3');
$r .= join($ids,',');
return $r;
}
function test_setColumnWithVariables() {
$id = 2;
$fieldName = 'body';
$fieldValue = 'the body was changed for record with id='.$id;
$comparisonBean = R@@DOUBLE_SEMICOLONload('comparisons', $id);
$comparisonBean->setAttr($fieldName, $fieldValue);
$idAffected = R@@DOUBLE_SEMICOLONstore($comparisonBean);
echo 'record with id '.$idAffected. ' changed';
}
function test_createMultipleBeans() {
$comparisonBeans = R@@DOUBLE_SEMICOLONdispense('comparisons',2);
if (count($comparisonBeans) > 0) {
foreach ($comparisonBeans as $comparisonBean) {
$comparisonBean->setAttr('categories', 'newone');
}
}
R@@DOUBLE_SEMICOLONstoreAll($comparisonBeans);
echo 'created';
}
JQUERY CODE EXAMPLE: Site with JQuery Page Switching and URL Rewriting
added on Jun 14, 2013
Site with JQuery Page Switching and URL Rewriting
This site contains everything you need to create a menu and "page area" with links which switch the page and also update the URL and page title.

index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery.history.js"></script>
<script src="js/jquery.getUrlParam.js"></script>
<script src="js/site.js"></script>
<link href="css/main.css" rel="stylesheet"/>
<script>
var CONFIG = {
pageIdCodes: [
'pageNews',
'pageEvents',
'pageInfo',
'pageCourses',
'pageHelp'],
pageTitles: [
'News',
'Events',
'Info',
'Courses',
'Help'
],
defaultPageIdCode: 'pageEvents'
};
$(document).ready(function() {
SITE.initialize();
});
function displayText(text) {
text = text === undefined ? 'defaultValue' : text;
console.log(text);
}
</script>
</head>
<body>
<ul id="nav">
</ul>
<div id="pageNews" class="pageArea">
<p>This is the news page which will have lots of news. This is the news page which will have lots of news. This is the news page which will have lots of news.</p>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<p>And more text.</p>
</div>
<div id="pageEvents" class="pageArea">
<p>This is the news page about all the events.</p>
<ul>
<li>Event #1</li>
<li>Event #2</li>
<li>Event #3</li>
</ul>
And here is a <a href="?page=pageNews">link to the news page</a>, which shows you that you can have both kinds of links: javascript and browser reload.
</div>
<div id="pageInfo" class="pageArea">This is the info page.</div>
<div id="pageCourses" class="pageArea">
<p>This is a page with all the list of courses on it.</p>
</div>
<div id="pageHelp" class="pageArea">This is the help page with lots of help.</div>
</body>
</html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/jquery.history.js"></script>
<script src="js/jquery.getUrlParam.js"></script>
<script src="js/site.js"></script>
<link href="css/main.css" rel="stylesheet"/>
<script>
var CONFIG = {
pageIdCodes: [
'pageNews',
'pageEvents',
'pageInfo',
'pageCourses',
'pageHelp'],
pageTitles: [
'News',
'Events',
'Info',
'Courses',
'Help'
],
defaultPageIdCode: 'pageEvents'
};
$(document).ready(function() {
SITE.initialize();
});
function displayText(text) {
text = text === undefined ? 'defaultValue' : text;
console.log(text);
}
</script>
</head>
<body>
<ul id="nav">
</ul>
<div id="pageNews" class="pageArea">
<p>This is the news page which will have lots of news. This is the news page which will have lots of news. This is the news page which will have lots of news.</p>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
<p>And more text.</p>
</div>
<div id="pageEvents" class="pageArea">
<p>This is the news page about all the events.</p>
<ul>
<li>Event #1</li>
<li>Event #2</li>
<li>Event #3</li>
</ul>
And here is a <a href="?page=pageNews">link to the news page</a>, which shows you that you can have both kinds of links: javascript and browser reload.
</div>
<div id="pageInfo" class="pageArea">This is the info page.</div>
<div id="pageCourses" class="pageArea">
<p>This is a page with all the list of courses on it.</p>
</div>
<div id="pageHelp" class="pageArea">This is the help page with lots of help.</div>
</body>
</html>
site.js
var SITE = SITE || {};
SITE.initialize = function() {
var defaultPageIdCode;
var explicitPageIdCode;
var currentPageIdCode;
this.defineVariables = function() {
explicitPageIdCode = $(document).getUrlParam('page');
currentPageIdCode = this.isEmpty(explicitPageIdCode) ? CONFIG.defaultPageIdCode : explicitPageIdCode;
}
this.buildElements = function() {
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var pageTitle = CONFIG.pageTitles[i];
$('ul#nav').append('<li class="navLink" data-id-code="'+pageIdCode+'">'+pageTitle+'</li>');
}
}
this.decorateElements = function() {
this.showCurrentPage(currentPageIdCode);
}
this.functionalizeElements = function() {
that = this;
$('li.navLink').click(function() {
var idCode = $(this).data('idCode');
that.showCurrentPage(idCode);
});
}
this.showCurrentPage = function(desiredPageIdCode) {
var r = '';
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var elemPage = $('#'+pageIdCode);
var elemMenuLink = $('li.navLink[data-id-code="'+pageIdCode+'"]');
if(pageIdCode == desiredPageIdCode) {
elemPage.show();
elemMenuLink.addClass('selected');
} else {
elemPage.hide();
elemMenuLink.removeClass('selected');
}
}
this.updateUrl(desiredPageIdCode);
return r;
}
this.updateUrl = function(desiredPageIdCode) {
var urlPageIdCode = $(document).getUrlParam('page');
var currentPageIdCode = urlPageIdCode === null ? CONFIG.defaultPageIdCode : urlPageIdCode;
var finalPageIdCode = desiredPageIdCode === undefined ? currentPageIdCode : desiredPageIdCode;
History.replaceState({}, this.getTitleWithIdCode(finalPageIdCode), '?page='+finalPageIdCode);
}
this.getTitleWithIdCode = function(idCode) {
var index = CONFIG.pageIdCodes.indexOf(idCode);
return CONFIG.pageTitles[index];
}
this.isEmpty = function(value) {
if(value == '' || value == null) {
return true;
} else {
return false;
}
}
this.defineVariables();
this.buildElements();
this.decorateElements();
this.functionalizeElements();
}
SITE.initialize = function() {
var defaultPageIdCode;
var explicitPageIdCode;
var currentPageIdCode;
this.defineVariables = function() {
explicitPageIdCode = $(document).getUrlParam('page');
currentPageIdCode = this.isEmpty(explicitPageIdCode) ? CONFIG.defaultPageIdCode : explicitPageIdCode;
}
this.buildElements = function() {
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var pageTitle = CONFIG.pageTitles[i];
$('ul#nav').append('<li class="navLink" data-id-code="'+pageIdCode+'">'+pageTitle+'</li>');
}
}
this.decorateElements = function() {
this.showCurrentPage(currentPageIdCode);
}
this.functionalizeElements = function() {
that = this;
$('li.navLink').click(function() {
var idCode = $(this).data('idCode');
that.showCurrentPage(idCode);
});
}
this.showCurrentPage = function(desiredPageIdCode) {
var r = '';
for(var i = 0; i < CONFIG.pageIdCodes.length; i++) {
var pageIdCode = CONFIG.pageIdCodes[i];
var elemPage = $('#'+pageIdCode);
var elemMenuLink = $('li.navLink[data-id-code="'+pageIdCode+'"]');
if(pageIdCode == desiredPageIdCode) {
elemPage.show();
elemMenuLink.addClass('selected');
} else {
elemPage.hide();
elemMenuLink.removeClass('selected');
}
}
this.updateUrl(desiredPageIdCode);
return r;
}
this.updateUrl = function(desiredPageIdCode) {
var urlPageIdCode = $(document).getUrlParam('page');
var currentPageIdCode = urlPageIdCode === null ? CONFIG.defaultPageIdCode : urlPageIdCode;
var finalPageIdCode = desiredPageIdCode === undefined ? currentPageIdCode : desiredPageIdCode;
History.replaceState({}, this.getTitleWithIdCode(finalPageIdCode), '?page='+finalPageIdCode);
}
this.getTitleWithIdCode = function(idCode) {
var index = CONFIG.pageIdCodes.indexOf(idCode);
return CONFIG.pageTitles[index];
}
this.isEmpty = function(value) {
if(value == '' || value == null) {
return true;
} else {
return false;
}
}
this.defineVariables();
this.buildElements();
this.decorateElements();
this.functionalizeElements();
}
PHP CODE EXAMPLE: How to roll your own PHP routing
added on Jun 12, 2013
How to roll your own PHP routing
This is an example of a PHP page using an .htaccess file to redirect all calls to the index.php file so that you can parse the URL the way you want. Not that all calls to css, js, and images have to be absolute.

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]
RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?params=$1 [L,QSA]
JQUERY CODE EXAMPLE: Simple and Smart Popups with PowerTip
added on Jun 7, 2013
Simple and Smart Popups with PowerTip
This powertip tool is lightweight and allows you to very easily make popup tips for e.g. titles where you don't have to specify a height. Notice the "smartPlacement: true" and that you have to have it in generally the right direction for this to work.

index.htm
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.powertip.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript" src="js/jquery.powertip.js"></script>
<script type="text/javascript">
$(function() {
// placement examples
$('#helpButton1').powerTip({placement: 's', smartPlacement: true});
$('#helpButton2').powerTip({placement: 'e', smartPlacement: true});
});
</script>
</head>
<body>
<input type="button" id="helpButton1" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
<input type="button" id="helpButton2" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
</body>
</html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.powertip.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript" src="js/jquery.powertip.js"></script>
<script type="text/javascript">
$(function() {
// placement examples
$('#helpButton1').powerTip({placement: 's', smartPlacement: true});
$('#helpButton2').powerTip({placement: 'e', smartPlacement: true});
});
</script>
</head>
<body>
<input type="button" id="helpButton1" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
<input type="button" id="helpButton2" value="Help" title="Click this if you need technical help, otherwise ask your manager." />
</body>
</html>
JQUERY CODE EXAMPLE: JQueryUI Radio Buttons
added on Jun 4, 2013
JQueryUI Radio Buttons
This shows how to use the JQueryUI radio buttons.

index.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Button - Radios</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$("#displayKind" ).buttonset();
$("input#displayKindFullText").click(function() {
$('div#message').html('this is the full text');
});
$("input#displayKindGuessBlanks").click(function() {
$('div#message').html('this is the text as with blanks to guess the words')
});
$("input#displayKindFullText").click();
});
</script>
</head>
<body>
<form>
<div id="displayKind" style="font-size: 8pt">
<input type="radio" id="displayKindFullText" name="radio" checked="checked" /><label for="displayKindFullText">Full Text</label>
<input type="radio" id="displayKindGuessBlanks" name="radio" /><label for="displayKindGuessBlanks">Guess Blanks</label>
</div>
<div id="message" style="margin:10px"></div>
</form>
</body>
</html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Button - Radios</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function() {
$("#displayKind" ).buttonset();
$("input#displayKindFullText").click(function() {
$('div#message').html('this is the full text');
});
$("input#displayKindGuessBlanks").click(function() {
$('div#message').html('this is the text as with blanks to guess the words')
});
$("input#displayKindFullText").click();
});
</script>
</head>
<body>
<form>
<div id="displayKind" style="font-size: 8pt">
<input type="radio" id="displayKindFullText" name="radio" checked="checked" /><label for="displayKindFullText">Full Text</label>
<input type="radio" id="displayKindGuessBlanks" name="radio" /><label for="displayKindGuessBlanks">Guess Blanks</label>
</div>
<div id="message" style="margin:10px"></div>
</form>
</body>
</html>
BOOSTRAP CODE EXAMPLE: Basic, Interactive Bootstrap Site
added on May 30, 2013
Basic, Interactive Bootstrap Site
This is a site that is based on bootstrap (CSS file) and had jQuery added to it so that the menus are interactive.

html
<!DOCTYPE html>
<head>
<title>btest</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/site.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="container">
<h1>The Title</h1>
<div class='navbar navbar-inverse'>
<div class='navbar-inner nav-collapse' style="height: auto;">
<ul class="nav">
<li id="linkHome" class="active"><a href="#">Home</a></li>
<li id="linkInfo"><a href="#">Info</a></li>
<li id="linkAbout"><a href="#">About</a></li>
</ul>
</div>
</div>
<div id='content' class='row-fluid'>
<div class='span9 main'>
<div class="sitePage" id="pageHome">
<h2>Home</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageInfo">
<h2>Info</h2>
<p>N...</p>
</div>
<div class="sitePage" id="pageAbout">
<h2>About</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection1">
<h2>Nation States at the End of the 19th Century</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection2">
<h2>1880-1910: Technological Inventions</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection3">
<h2>Late 19th Century Japan</h2>
<p>...</p>
</div>
</div>
<div class='span3 sidebar'>
<ul class="nav nav-tabs nav-stacked">
<li><a id="linkSection1" class="sideLink" href='#'>Nation States at the End of the 19th Century</a></li>
<li><a id="linkSection2" class="sideLink" href='#'>1880-1910: Technological Inventions</a></li>
<li><a id="linkSection3" class="sideLink" href='#'>Late 19th Century Japan</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
<head>
<title>btest</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/site.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="container">
<h1>The Title</h1>
<div class='navbar navbar-inverse'>
<div class='navbar-inner nav-collapse' style="height: auto;">
<ul class="nav">
<li id="linkHome" class="active"><a href="#">Home</a></li>
<li id="linkInfo"><a href="#">Info</a></li>
<li id="linkAbout"><a href="#">About</a></li>
</ul>
</div>
</div>
<div id='content' class='row-fluid'>
<div class='span9 main'>
<div class="sitePage" id="pageHome">
<h2>Home</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageInfo">
<h2>Info</h2>
<p>N...</p>
</div>
<div class="sitePage" id="pageAbout">
<h2>About</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection1">
<h2>Nation States at the End of the 19th Century</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection2">
<h2>1880-1910: Technological Inventions</h2>
<p>...</p>
</div>
<div class="sitePage" id="pageSection3">
<h2>Late 19th Century Japan</h2>
<p>...</p>
</div>
</div>
<div class='span3 sidebar'>
<ul class="nav nav-tabs nav-stacked">
<li><a id="linkSection1" class="sideLink" href='#'>Nation States at the End of the 19th Century</a></li>
<li><a id="linkSection2" class="sideLink" href='#'>1880-1910: Technological Inventions</a></li>
<li><a id="linkSection3" class="sideLink" href='#'>Late 19th Century Japan</a></li>
</ul>
</div>
</div>
</div>
</body>
</html>
site.js
var SITE = SITE || {};
SITE.initialize = function() {
var fadeTime = 100;
that = this;
$('li#linkHome').click(function() {
resetPageLinks();
$('li#linkHome').addClass('active');
resetPages();
$('div#pageHome').fadeIn(fadeTime);
});
$('li#linkInfo').click(function() {
resetPageLinks();
$('li#linkInfo').addClass('active');
resetPages();
$('div#pageInfo').fadeIn(fadeTime);
});
$('li#linkAbout').click(function() {
resetPageLinks();
$('li#linkAbout').addClass('active');
resetPages();
$('div#pageAbout').fadeIn(fadeTime);
});
$('a#linkSection1').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection1').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection2').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection2').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection3').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection3').fadeIn(fadeTime);
markSideLink(this);
});
function resetPageLinks() {
$('ul.nav li').removeClass('active');
$('a.sideLink').css('font-weight','normal');
}
function resetPages() {
$('div.sitePage').hide();
}
function markSideLink(elem) {
$(elem).css('font-weight', 'bold');
}
}
SITE.initialize = function() {
var fadeTime = 100;
that = this;
$('li#linkHome').click(function() {
resetPageLinks();
$('li#linkHome').addClass('active');
resetPages();
$('div#pageHome').fadeIn(fadeTime);
});
$('li#linkInfo').click(function() {
resetPageLinks();
$('li#linkInfo').addClass('active');
resetPages();
$('div#pageInfo').fadeIn(fadeTime);
});
$('li#linkAbout').click(function() {
resetPageLinks();
$('li#linkAbout').addClass('active');
resetPages();
$('div#pageAbout').fadeIn(fadeTime);
});
$('a#linkSection1').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection1').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection2').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection2').fadeIn(fadeTime);
markSideLink(this);
});
$('a#linkSection3').click(function() {
resetPageLinks();
resetPages();
$('div#pageSection3').fadeIn(fadeTime);
markSideLink(this);
});
function resetPageLinks() {
$('ul.nav li').removeClass('active');
$('a.sideLink').css('font-weight','normal');
}
function resetPages() {
$('div.sitePage').hide();
}
function markSideLink(elem) {
$(elem).css('font-weight', 'bold');
}
}
KNOCKOUT CODE EXAMPLE: Knockout list adding
added on May 27, 2013
Knockout list adding
index.htm
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/main.css"/>
<script src="js/jquery-1.10.0.js"></script>
<script src="js/knockout-2.2.1.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="formWrapper">
<form data-bind="submit: addItem">
New Item:
<input id="itemToAdd" data-bind="value:itemToAdd, valueUpdate: 'afterkeydown'">
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p style="margin: 10px 0 10px 0">Your items:</p>
<select multiple="multiple" style="width:200px;height:300px" data-bind="options: items"></select>
</form>
</div>
</body>
</html>
<html>
<head>
<link rel="stylesheet" href="css/main.css"/>
<script src="js/jquery-1.10.0.js"></script>
<script src="js/knockout-2.2.1.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="formWrapper">
<form data-bind="submit: addItem">
New Item:
<input id="itemToAdd" data-bind="value:itemToAdd, valueUpdate: 'afterkeydown'">
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p style="margin: 10px 0 10px 0">Your items:</p>
<select multiple="multiple" style="width:200px;height:300px" data-bind="options: items"></select>
</form>
</div>
</body>
</html>

main.js
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
initForm();
}
}.bind(this);
};
function initForm() {
$('#itemToAdd').focus();
}
$(document).ready(function() {
initForm();
ko.applyBindings(new SimpleListModel(["German", "French", "English"]));
});
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd());
this.itemToAdd("");
initForm();
}
}.bind(this);
};
function initForm() {
$('#itemToAdd').focus();
}
$(document).ready(function() {
initForm();
ko.applyBindings(new SimpleListModel(["German", "French", "English"]));
});
JQUERY CODE EXAMPLE: Nice, cascading fade-in of multiple items
added on May 23, 2013
Nice, cascading fade-in of multiple items
This simple effect is produce with various length fades and different shades of a color.

index.html
<!DOCTYPE>
<html>
<link rel="stylesheet" href="css/main.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(init);
function init() {
$('.showArea .course1').fadeIn(500);
$('.showArea .course2').fadeIn(1000);
$('.showArea .course3').fadeIn(1500);
$('.showArea .course4').fadeIn(2000);
};
</script>
<body>
<div class="showArea">
<div class="course1">Course #1</div>
<div class="course2">Course #2</div>
<div class="course3">Course #3</div>
<div class="course4">Course #4</div>
</div>
</body>
</html>
<html>
<link rel="stylesheet" href="css/main.css"/>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(init);
function init() {
$('.showArea .course1').fadeIn(500);
$('.showArea .course2').fadeIn(1000);
$('.showArea .course3').fadeIn(1500);
$('.showArea .course4').fadeIn(2000);
};
</script>
<body>
<div class="showArea">
<div class="course1">Course #1</div>
<div class="course2">Course #2</div>
<div class="course3">Course #3</div>
<div class="course4">Course #4</div>
</div>
</body>
</html>
main.css
.showArea div {
width: 300px;
height: 50px;
margin: 0 0 5px 5px;
padding: 10px;
display: none;
}
.showArea .course1 {
background-color: #eee;
}
.showArea .course2 {
background-color: #ddd;
}
.showArea .course3 {
background-color: #ccc;
}
.showArea .course4 {
background-color: #bbb;
}
width: 300px;
height: 50px;
margin: 0 0 5px 5px;
padding: 10px;
display: none;
}
.showArea .course1 {
background-color: #eee;
}
.showArea .course2 {
background-color: #ddd;
}
.showArea .course3 {
background-color: #ccc;
}
.showArea .course4 {
background-color: #bbb;
}
JQUERY CODE EXAMPLE: Flashcard example with clicks
added on May 23, 2013
Flashcard example with clicks
This shows how to use mouseenter, mousedown and a right click to affect a flashcard-like interaction.
(no image found with Id-Code = "jqueryClicks")
index.html
<!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/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body oncontextmenu="return false;">
<div class="learnItem">
<div class="areaShow"></div>
<div class="areaHelp"></div>
<div class="clear"></div>
</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/jquery-ui-1.10.3.custom.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body oncontextmenu="return false;">
<div class="learnItem">
<div class="areaShow"></div>
<div class="areaHelp"></div>
<div class="clear"></div>
</div>
</body>
</html>
main.js
$(document).ready(function() {
$('div.areaShow').html('asdkfsdfj').fadeIn(3000);
$('div.areaShow').css({
'cursor':'pointer'
}).mousedown(function(e) {
if(e.which === 3) {
e.preventDefault();
$('div.areaHelp').html('Answer.');
$('div.areaHelp').data('status','answer');
$(this).hide(1000);
}
});
$('div.areaShow').mouseenter(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
$('div.areaShow').mouseleave(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('');
}
});
$('div.areaShow').mousedown(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #2');
}
});
$('div.areaShow').mouseup(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
});
$('div.areaShow').html('asdkfsdfj').fadeIn(3000);
$('div.areaShow').css({
'cursor':'pointer'
}).mousedown(function(e) {
if(e.which === 3) {
e.preventDefault();
$('div.areaHelp').html('Answer.');
$('div.areaHelp').data('status','answer');
$(this).hide(1000);
}
});
$('div.areaShow').mouseenter(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
$('div.areaShow').mouseleave(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('');
}
});
$('div.areaShow').mousedown(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #2');
}
});
$('div.areaShow').mouseup(function() {
if($('div.areaHelp').data('status') != 'answer') {
$('div.areaHelp').html('hint #1');
}
});
});
KNOCKOUTJS CODE EXAMPLE: Knockout.js Button Click and Counter
added on May 21, 2013
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 on May 21, 2013
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