Chomper Stomping jQuery/JavaScript/CSS 3/HTML 5, Java/PHP/Python/ActionScript, Git, Chrome/Firefox Extensions, Wordpress/Game/iPhone App Development and other random techie tidbits I've collected

21Dec/090

TOTW: Firebug HTML > Layout

This week's tool of the week is another component of Firebug, the "Layout" tool.

What it does:

Allows you to edit html element box dimensions directly in the browser to get that perfect witdh/height/padding/margin/border combo you're looking for.

When you need it:

  • Resolving float issues
  • Adjusting Padding/Margin
  • Prototyping Layouts

How to use it:

Screencast on screencast.com

The example:

14Dec/090

JavaScript Console v0.0.1

jsConsoleSS

So I just made this little extension for Chrome.

There were some pretty convoluted to gymnastics I had to go through to get the console on the page and get it to execute the JS I wanted it to execute. Pretty much the only hook you have it an onClick (from what I can tell). They've got it locked down TIGHT.

This needs a LOT of experimentation done, but it looks like you can use it to define functions on the page through the console and call those functions. However, the functions do NOT persist. So, you can do:

function test(){
alert('test');
}
test();

and "execute js" and an alert will come up and say "test".

But you can't do:

function test(){
alert('test');
}

and "execute js" and then:

test();

and "execute js" and expect an alert to pop up.

I'm sure there are many sound reasons for this from a security standpoint, but it's annoying as hell to try and program for. It would be great if I could fix this and I have a few ideas as to how I can do that...

The main reason I'm making this is basically as a prototype/POC for the Status-bar Calculator port from FF since I'm going to have to do some very similar things to get the Calculator to show up in the bottom right hand corner (like this does).

EDIT: After publishing the extension, it was pointed out to me that Chrome already *has* a JavaScript console if you hit Ctrl + Shift + J. However, that console only allows single line input, whereas this allows for as many lines as you want, making this just a *little* more functional. It would be awesome if I could find a way to hook this console into that console.

Checkout the project page.

14Dec/092

TOTW: Spoon.net/browsers

This weeks Tool of the Week is spoon.net's browser sandbox tool.

What it does:

Allows you to run sand-boxed versions of each of the major (and minor) browsers from within Firefox.

When you need it:

  • Cross browser testing
  • Running multiple versions of the same browser at once

How to use it:

Screencast hosted on screencast.com

9Dec/090

Chrome Extension – Status-bar Calculator v0.1.9

So I ported the Status-bar Calculator over to Chrome. It took me a little under 2 hours.

Chrome extensions are shaping up to be a gagillion times easier to create than FF extensions were back when I started doing them four years ago. I actually re-wrote the entire thing from scratch. It functions completely differently, relying entirely on the eval() function to do all of the math (where the FF version jumps through some crazy hoops).

The Chrome version has something I've wanted for a long time: history.

It's not persistent yet, but while you are in a "session" the equation history keeps building below the box so you can see where you've been if you are plugging away at a list and lose your place.

As with the FF version, it's MIT license. Steal it, or hack on it and contribute back to me (I'll definitely credit you and much appreciate it).

You can check out the source code here or on Etherpad here.

I'm looking forward to really fleshing this thing out and making it rock for whenever extensions make their public debut in Chrome. Oh, yeah, btw, you have to install the developer beta of Chrome to get extensions...

7Dec/090

TOTW: Firebug Console

This is a special Tool of the Week, because it focuses on a sub-set of a larger tool. This week's Tool of the Week is the console feature of the Firefox extension Firebug by Joe Hewitt, Rob Campbell, FirebugWorkingGroup.

What it does:

Allows you to run commands and play with the JavaScript on a web page, as well as output information from a webpage through a dos/shell style console; all from within the browser window. It's as if you "opened the hood" of the browser and started running diagnostics/talking to the robot that controls the page display.

When you need it:

  • prototyping JavaScript
  • debugging JavaScript
  • writing JavaScript

How to use it:

Please note that this doesn't even BEGIN to scratch the surface of the power of this little tool. Check out the documentation, here and here.

The Example:

30Nov/090

TOTW: Pastebin.me

This week's Tool of the Week is Pastebin by Dale Harvey.

What it does:

Allows for quick, IN BROWSER PROTOTYPING.

When you need it:

  • Quick testing of a bit of HTML/JS code
  • Demonstrating/Teaching HTML/JS in front of a group
  • IMing/Linking/Emailing editable code

How to use it:

Full Screencast here

The Example:

http://pastebin.me/198414be57085581cd82c85877387fc1

28Aug/092

Finding the number of hex tiles inside of a hex shaped grid…

EDIT: There is a mathematical formula that is much better than the method I illustrate below. It is: 3n^2 - 3n + 1

A huge thanks to Sam Hughes for very patiently helping me out with this formula. He's the best mathematician I know...

Here's the JavaScript code to execute this formula (just change maxTiles to be however wide your hex grid is):

	var maxTiles = 7;	
	var n = Math.ceil((maxTiles - 2) / 2);
	var numberTiles = 3 * Math.pow(n, 2) - 3 * n + 1;

Below is the original post:


This is kind of like finding the area of a hex grid, except that for some reason none of the formulas I found for doing that would work. Also, finding the area of a triangle made of hex grids won't work with the normal triangle area formula either.

What I am illustrating here is how to find out how many hex tiles are inside of a hex shaped grid of hex tiles.

Here is a picture of the grid:

What you have to do is:

1. Take the half the width of the hex grid rounded down. So, if the hex grid is 7 wide, you take half of seven, 3.5, and round it down to 3. This can also be called "flooring" the number.
2. Take that number and use it to seed a floor loop, which counts down from that number, adding the new number to a grand total each time.
3. Multiply that grand total by 7 and add one for the middle tile (which never got counted).

Here is the code:

	var triangleTotal = 0;
	for(var spaces = Math.ceil((maxTiles-1)/2); spaces > 0; spaces--){
		triangleTotal += spaces;
	}
	var triangles = triangleTotal * 6;
	var numberTiles = triangles + 1;
	return numberTiles;

You'll notice that I took the total minus 1 divided by 2 and "ceil"ed it, instead of taking the total divided by two and "floor"ing it. It doesn't matter which you do...

Here's a visualization proving this out:

I only took one math class in college, otherwise this would have probably been very obvious to me as it may seem to you. There is probably even a really fancy easy little formula for this, but I don't know it and couldn't find it...

Here's a page where you can test this formula out in action. Note that a hex is always going to be an odd number of hexes wide, so if you enter an even number and get a funny shaped hex, this formula isn't going to work...

27Aug/092

JavaScript Haxagon Game Board with Hexagon tiles

I'm working on a JavaScript version of The Settlers of Catan. The first problem I decided to tackle was constructing (visually and array-structure wise) the game board using nothing but loops (didn't want to hard code it).

This ended up being much more difficult than I thought it would be.

I am going to split this up into two parts:

1. Setting up the game board visually
2. Setting up the array structure

Creating a Hexagonal game board with hexagonal spaces in JavaScript with for loops:

For this to work properly, you must have an even number of columns and rows. I chose seven since that is what makes up the Settlers of Catan game-board.

You have to split the building of the board into three stages:

1. The expanding stage
2. The apex or middle of the board
3. The contracting stage

I placed everything in one large for loop that counted off the "rows".

I figured out that while the rows are less than half the max rows divided by two (and rounded down) the board would be contracting. The number of tiles you would start with would be equal to the maximum number of tiles divided by two, rounded up, plus the current row number.

Once the number of rows equals exactly half the number of maximum tiles (rounded down) you are on the middle row. In this case the number of tiles is the max number of tiles, no math required.

Otherwise, you are in the contracting stage and the number of tiles you need is equal to the maximum number of tiles, minus the current row, minus half of the maximum rounded down.

Sound complicated? That's because it is. This took me about 30 minutes to get straight in my head after studying the game-board shape, tiles, and making several diagrams and sudo-coding and then writing the actual code and fixing bugs (and deciding if I had to round up or down at certain places).

Here is the actual code:

<html>
<head>
<style>
img{
	margin-top: -18px;
}
#board{
	padding: 50px 25px;
	background-color: #000;
}
</style>
</head>
<body>
<div id="board">error loading</div>
</body>
<script>
function boardSetup(){
	var max = 7;
	var html = "";

	for(var row = 0; row < max; row++){
		if(row < Math.floor(max/2)){
			//place spacer tiles
			for(var space = 0; space < (Math.floor(max/2) - row); space++){
				html += '<img src="spacerTile.png" />';
			}

			//place game tiles
			for(var cols = 0; cols < (Math.ceil(max/2) + row); cols++){
				html += '<img src="tile.png" />';
			}
			html += "<br />";
		}else if(row == Math.floor(max/2)){
			for(var cols = 0; cols < max; cols++){
				html += '<img src="tile.png" />';
			}
			html += "<br />";
		}else{
			for(var space = 0; space < (row - Math.floor(max/2)); space++){
				html += '<img src="spacerTile.png" />';
			}
			for(var cols = 0; cols < (max - (row - Math.floor(max/2))); cols++){
				html += '<img src="tile.png" />';
			}
			html += "<br />";
		}
	}

	document.getElementById("board").innerHTML = html;
}

boardSetup();
</script>
</html>

Here are the images that go with it:

Here is the tile:tile
Here is the spacer. This one is completely invisible: start->spacerTile<-end

Here is the code running on my site.

18Jul/089

Creating A PHP Spider/Bot/Crawler

Today begins the first in a series of posts about creating a PHP Spider/Crawler/Bot. I'm actually not sure what to call it.

At my work, we deal with hundreds of shipments to and from hundreds of vendors. We have thousands (possibly more) "tracking codes" for Fedex, UPS, DHL, Conway, etc. All of these places have websites where you can go to look up a specific tracking code and see the status of your delivery. Fedex has an API, as does USPS, as does UPS, as does DHL, but Conway does not. The question I'm facing is, do I integrate four different APIs plus a bot to get the info I need, or do I just brute force it all with a bot?

First things first though, can I even make a bot in PHP? Yes! As a test case I have created a simple page scraping bot. It will open up the OCA website and scrape today's scripture off and print it out:

//get a connection to the desired page (remove the space between fopen and the "(")

$handle = fopen ("http://www.oca.org/Reading.asp?SID=25" , "r");
//pull down the contents of that page
$contents = stream_get_contents($handle);
//close the connection
fclose($handle);

/*convert everything to lower case so it's easier to do my string matching (not necessarily a must)*/
$contents = strtolower($contents);

/*I looked at the HTML coming down, and found that this was the best consistent place to look at to determine the beginning of the "scripture" content.*/
$start = 'class="scriptureheader">';
//find the position of the start text in the page content
$start_pos = strpos($contents, $start);

//drop the text before the start position
$first_trim = substr($contents, $start_pos);

/*this looked to be the best consistent ending of the scripture in the HTML*/
$stop = '</table>';
//find the position of the stop string in the content
$stop_pos = strpos($first_trim, $stop);

//drop everything after the stop position
$second_trim = substr($first_trim, 0, $stop_pos);

//print out the results
print "<div>$second_trim</div>";

It's important to note that the start and end positions can not have any spaces in them. This could (and would need to be) greatly improved to really be useful. I'd probably recommend incorporating regular expressions instead of using the "strpos" command. Next I'm going to look at the cURL library for PHP. I'll re-use the same website again to navigate forms to get the scriptures readings for Sundays instead of the current day.

20May/0812

How to ORDER BY before GROUP BY with MySQL

I've got a table that tracks inventory at multiple vendors for multiple products by timestamp. I want to only select the most recent inventory count per vendor by product.

One way to do this is with a bunch of while loops and hitting the DB over and over, or selecting a crap load of data and just dropping out everything but the most recent inventory count manually. Both of these are viable solutions with a lot of overhead, but what I really want is just a silver bullet SQL statement that does this for me. I think I have it.

What I initially envisioned was:

SELECT *
FROM INVENTORY
ORDER BY vendors_no,
timestamp DESC
GROUP BY vendors_no,
product_no

However, if you are familiar with MySQL, you will know that you cannot put ORDER BY before GROUP BY. You have to GROUP BY and then ORDER BY.

It appears that the way that GROUP BY works is that it takes the first row of each "group" and just drops the rest. So whichever row happens to be first in the DB when the SQL is executing will get grabbed and the rest will get dropped. If I had wanted to get the first inventory count for each vendor/product, this would have been ok, since those would have been the first row, but it's going to be the last row each time. So what to do? If only I could flip the whole table on it's head or something...

Actually, I kind of can! This is what I came up with:

SELECT *
FROM(
SELECT *
FROM INVENTORY
ORDER BY vendors_no,
timestamp DESC
) as inv
GROUP BY vendors_no,
product_no

If I understand GROUP BY correctly and ORDER BY correctly (which I very well may not) the sub-query will first basically create a temporary table with the results in reverse timestamp order. Then when GROUP BY is going through and finding the first vendor_no and dropping the rest it will be keeping the most recent one.

If anyone knows any reason why this is stupid or wrong, please let me know. It's the best solution I've been able to find so far.

***UPDATED: In response to Brian's suggestion***

Dang. I really wanted that to work, but it didn't.

Here is the original SQL:

Here is the SQL you suggested:

Did I do something wrong?

Here is the total data being queried:

Thanks for the suggestion!