Friday, September 12, 2008

HTML Canvas Element - Part 3

This is Part 3 of the HTML Canvas Tutorial. If you haven't already you should read Part 1 and Part 2.

In this section we will create a key press listener and zoom our triangle in when we press 'z' and out when we press 'x'.

To do this we add a onKeyUp event to the body tag, and a corresponding handleKeyUp javascript function:

function handleKeyUp(evt) {
var e = evt ? evt : event;
if (e.keyCode == 90) {
scale+=.1;
} else if(e.keyCode == 88) {
scale-=.1;
}
draw();
}


<body onload="draw();" onkeyup="handleKeyUp(event);">
<canvas id="canvas" width="150" height="150"></canvas>
</body>


The variable scale is defined as a global javascript variable and we'll use it to call 'ctx.scale(x,y)'

Before we do that though we'll have to call clearRect(x,y,width,height) to clear the image and redraw. The entire script is displayed below:

<html>
<head>
<script type="application/x-javascript">

var scale=1;
function draw() {
// Get Reference to the 'canvas' tag
var canvas = document.getElementById("canvas");
if (canvas.getContext){
// Get a context that allows us to draw on.
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.scale(scale,scale);

// Move cursor and draw the outline of the Triangle
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(50,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);

// Actually Draw, you could call stroke instead which will draw the outline
ctx.fill();
ctx.restore();

}

}
function handleKeyUp(evt) {
var e = evt ? evt : event;
if (e.keyCode == 90) {
scale+=.1;
} else if(e.keyCode == 88) {
scale-=.1;
}
draw();
}


</script>
</head>
<body onload="draw();" onkeyup="handleKeyUp(event);">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>


That's it! I hope that got you interested in the Canvas element. If you have any questions leave a comment and I would be glad to answer them.

For more information I recommend the following sites:
http://developer.mozilla.org/en/Canvas_tutorial
http://en.wikipedia.org/wiki/Canvas_(HTML_element)
http://blog.vlad1.com/2008/06/04/html-canvas-in-firefox-3/

HTML Canvas Element - Part 2

In Part 1 of the series we set up a simple template to build the rest of the example on.

Our goal is to display a triangle and allow the user to zoom in and zoom out.

In this part we will display a black triangle on a white background. Replace your draw function with this one and then refresh your browser.

function draw() {
// Get Reference to the 'canvas' tag
var canvas = document.getElementById("canvas");
if (canvas.getContext){
// Get a context that allows us to draw on.
var ctx = canvas.getContext('2d');

// Move cursor and draw the outline of the Triangle
ctx.beginPath();
ctx.moveTo(0,100);
ctx.lineTo(50,0);
ctx.lineTo(100,100);
ctx.lineTo(0,100);

// Actually Draw, you could call stroke instead which will draw the outline
ctx.fill();
}

}


You should now see a black triangle on a white background. The code got a drawing context by calling canvas.getContext("2d").

We then use the moveTo command which picks up the cursor and moves to the location without drawing. Notice the coordinate system starts in the upper left with x extending to the right and y extending down.

We start our path with beginPath(). This will clear out any other draw commands and now your ready to trace your path with lineTo. One we have traced our triangle with the lineTo commands we call 'ctx.fill()' Which draws the shape and fills it with a solid color. Alternatively we could of called 'ctx.stroke()' which will draw the outline.

Continue to Part 3 to learn how to Zoom in/out the triangle.

HTML Canvas Element

The canvas html tag element allows web developers to draw graphics in the browser through a scripting language, typically JavaScript.

In this tutorial, we will create a triangle and allow the user to zoom in or zoom out the picture. Before we get started lets set up our environment. All you'll need is your web browser and a text editor.

Open your text editor (notepad will work just fine) and enter the following:
<html>
<head>
<script type="application/x-javascript">

function draw() {
alert("hi");
}


</script>
</head>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>
</body>
</html>


This is our template that we will use for the rest of the tutorial. We've added a canvas element and when the HTML body is loaded our draw() function will be called.

If you save the text file and load it in your browser it should print a message box saying 'hi'. If not please re-read the above until you have this working.

Continue to Part 2

Google Web Toolkit - Monthly Payment Calculator

This example displays a simple Loan Calculator. When the user clicks calculate a ClickListener is fired which calculates the monthly payment and dispays it.

This example illustrates GWT Labels, TextBox, and Button controls.


/*
* mcintoshEntryPoint.java
*
* Created on June 29, 2008, 1:46 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.client;

import com.google.gwt.core.client.EntryPoint;
import com.client.time.*;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
*
* @author avalanche
*/
public class mcintoshEntryPoint implements EntryPoint {

final Label lblLoanAmount = new Label("Loan Amount:");
final TextBox txtLoanAmount = new TextBox();
final Label lblLoanLength = new Label("Loan Length (Month):");
final TextBox txtLoanLength = new TextBox();
final Label lblInterestRate = new Label("Interest Rate (Yearly):");
final TextBox txtInterestRate = new TextBox();
final Button calculate = new Button("Calculate");
final Label lblResult = new Label("Payment per month:");

public mcintoshEntryPoint() {
calculate.addClickListener(new ClickListener() {

public void onClick(Widget arg0) {

//P = A (1 + r ) ^ N /( 1 + r ) ^ N -1
int loanAmount = Integer.parseInt(txtLoanAmount.getText());
int loanLength = Integer.parseInt(txtLoanLength.getText());
double interestRate = Double.parseDouble(txtInterestRate.getText())/1200;
double temp = Math.pow(( 1 + interestRate ) , loanLength);
Double result = new Double((loanAmount * interestRate * temp) / (temp -1));
lblResult.setText(result.toString());
}
});


}

/**
* The entry point method, called automatically by loading a module
* that declares an implementing class as an entry-point
*/
public void onModuleLoad() {
RootPanel.get().add(lblLoanAmount);
RootPanel.get().add(txtLoanAmount);
RootPanel.get().add(lblLoanLength);
RootPanel.get().add(txtLoanLength);
RootPanel.get().add(lblInterestRate);
RootPanel.get().add(txtInterestRate);
RootPanel.get().add(calculate);
RootPanel.get().add(lblResult);

}
}

Thursday, September 11, 2008

Google Web Toolkit Data Grid Example

At work I have a java J2EE application that displays a large table. The report is about 15 MB when rendered. I've been experimenting with GWT and I think it would be a good tool to rewrite this report with.

The main problem with the page is when someone updates a value it has to post back to the server then re-render everything. Using GWT it seems like it would be trivial to reload a single row at a time. Along those lines here is a simple DataGrid example that lets me add/remove rows.

See GWT Simple Example for more information on setting up your environment.


/*
* mcintoshEntryPoint.java
*
* Created on June 29, 2008, 1:46 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package com.client;

import com.google.gwt.core.client.EntryPoint;
import com.client.time.*;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;
import com.google.gwt.user.client.ui.Widget;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
*
* @author avalanche
*/
public class mcintoshEntryPoint implements EntryPoint {

final Button addButton = new Button("Add Row");
final Button deleteButton = new Button("Delete Row");
final FlexTable table = new FlexTable();
final Set selectedTableRows = new HashSet();

public mcintoshEntryPoint() {
addButton.addClickListener(new ClickListener() {

public void onClick(Widget arg0) {
table.insertRow(table.getRowCount());
table.addCell(table.getRowCount() - 1);
table.addCell(table.getRowCount() - 1);
table.setText(table.getRowCount() - 1, 1, "foo" + table.getRowCount());
}
});
deleteButton.addClickListener(new ClickListener() {

public void onClick(Widget arg0) {
Object[] array = selectedTableRows.toArray();
Arrays.sort(array);
for(int i=array.length-1;i>-1;i-- ) {
int row = ((Integer)array[i]).intValue();
table.removeRow(row);
selectedTableRows.remove(new Integer(row));
}
}
});
table.addTableListener(new TableListener() {

public void onCellClicked(SourcesTableEvents arg0, int rrow, int col) {
Integer row = new Integer(rrow);
if (selectedTableRows.contains(row)) {
selectedTableRows.remove(row);
table.setText(rrow, 0, "x");
} else {
selectedTableRows.add(row);
table.setText(rrow, 0, "y");
}
}
});


}

/**
* The entry point method, called automatically by loading a module
* that declares an implementing class as an entry-point
*/
public void onModuleLoad() {
RootPanel.get().add(table);
RootPanel.get().add(addButton);
RootPanel.get().add(deleteButton);
}
}

Wednesday, September 10, 2008

Modified Preorder Tree Traversal

How do you represent an organizational structure in a SQL data table? When I ask this question in interviews the answer I always get is with an adjacency list (although no one refers to it as that)

An adjaceny list structure would look like this:


EmployeeId, EmployeeName,ManagerId
----------------------------------
1, Bob,
2, Frank, 1
3, Stan, 1
4, James, 3


This structure shoes that Bob is the boss with no manager. Frank and Stan report to Bob, and James reports to Stan. This structure is very common. If you want to list all of Stan's reports, its easy:

select EmployeeName from Employees where ManagerId = (select EmployeeId from Employees where EmployeeName = 'Stan')


But what if you want to list all of Bob's reports? I have yet had anyone answer this question completely to my satisfaction. The typical response is to use a recursive look up. That is all well and good if your tree isn't very deep, but can we do better? Yes!

We can instead structure our table as follows:


EmployeeName,LeftId, RightId
----------------------------------
Bob, 1, 8
Frank, 2, 3
Stan, 4, 7
James, 5, 6


Huh you ask what did we just do? Let visualize it like this:


1-bob-8
/ \
2-Frank-3 4-Stan-7
/
5 James 6



We start at the left of Bob and assign the first id 1. We move down his org chart and hit Frank and assign him next id of 2. Frank has no children so we go to his right node and assign next id of 3. The next sibling is Stan with id 4. Stan has a child so we go to James with id 5, then work our way back up the tree assigning James Right 6, Stan 7 and Bob 8.

So our algorithm is:

AssignId(Node n)
n.leftid = nextId()
foreach(Node child : n.children)
AssignId(child)
// No more children assign my right
n.rightid = nextId()


So what does this accomplish? Lets answer my orignal question. Display all reports of Bob:

(leftid,rightid) =select LeftId,RightId from Employee where EmployeeName = 'Bob'
select * from Employee where lft between $leftid, $rightid;


That's it. With this tree structure you can easily find all the children of a given node. Of course this method has drawbacks. Inserts are more difficult. But if you have a database that is mostly read only you may consider giving this a try.

Enjoy...

Cuda Hello World: Entire Code Listing


/********************************************************************
* CUDAWin32App10.cu
* This is a example of the CUDA program.
*********************************************************************/

#include
#include
#include

/************************************************************************/
/* Init CUDA */
/************************************************************************/
bool InitCUDA(void)
{
int count = 0;
int i = 0;

cudaGetDeviceCount(&count);
if(count == 0) {
fprintf(stderr, "There is no device.\n");
return false;
}

for(i = 0; i <>= 1) {
break;
}
}
}
if(i == count) {
fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
return false;
}
cudaSetDevice(i);
return true;
}

/************************************************************************/
/* Example */
/************************************************************************/
__global__ static void HelloCUDA(char* result, int num, clock_t* time,int foo)
{
int i = 0;
char p_HelloCUDA[] = "Hello CUDA!";
clock_t start = clock();
for(i = 0; i < time =" clock()" device_result =" 0;" time =" 0;" time_used =" 0;">>>(device_result, 11 , time,1);


cudaMemcpy(&host_result, device_result, sizeof(char) * 11, cudaMemcpyDeviceToHost);
cudaMemcpy(&time_used, time, sizeof(clock_t), cudaMemcpyDeviceToHost);
cudaFree(device_result);
cudaFree(time);

printf("%s,%d\n", host_result, time_used);

return 0;
}