Showing all articles tagged with Programming
31 October 2007
Programming, PHP

I had 2 hours to kill so I thought I'd write a LOLCode interpreter.
I know there's already a few LOLCode interpreters around, but I couldn't help myself. Plus I've always been interested in interpreter design.
It's still a work in progress at this stage, so a lot of the language hasn't been fully implemented.
Here are two working programs...
Hello World
BTW the classic hello world program
HAI
VISIBLE "Hello world!"
KTHXBAI
Output:

Accepting User Input
HAI
VISIBLE "Hello there, what is your name?!"
I HAS A NAME ""
BTW ask for the users name
GIMMEH NAME
BTW welcome the user
VISIBLE "Welcome to LOLCode " N NAME N "!"
KTHXBAIOutput:
11 September 2007
PHP, Programming
Here's a quick tip for working with the command line in PHP.
If you've ever run a PHP script via the command line, you would have noticed that output from the script is not printed until the script has finished.
If you need your output displayed in real time, you can open a stream to the command line...
$stdout = fopen('php://stdout', 'w');Simply write any output to the stream and it will be printed on the command line in real time...
fwrite($stdout, "Hello CLI\n");
28 August 2007
PHP, Programming, Security, Web Design
One thing I keep noticing is the use of background noise or clutter in CAPTCHAS. It's now well known in the OCR (Optical Character recognition) field that background noise can be easily removed by computers. It's basically useless at hindering spam bots.
It's so easy that I was able to clean the following CAPTCHA up in only 20 lines of PHP code.
Here's how...
At a glance, you can see the CAPTCHA's background noise has a blue tint.
Looking at the RGB value of the image in Photoshop, I can see that all parts of the background have a blue value higher than 180.
That's the only piece of information needed to remove the background.
The code simply loops through every pixel of the image and checks the RGB value of it. If the blue (B) value is higher than 180, color it white.
Here's the final image. The characters can now be easily separated and identified using OCR software.
So you can see why most background noise is basically useless in CAPTCHAS.
23 August 2007
Programming, PHP
Ray Casting is a extremely fast method of generating 3D images using high-school level mathematics.
Remember playing Wolfenstein 3-D? This was one of the first games made using the ray casting technique.

The graphics in Wolfenstein don't even come close to today's gaming standards; but it was still impressive for it's time. It was also fast, considering the speed of the hardware it ran on.
Although ray casting is an outdated method, it's a good introduction to 3D imagery and game design. It's also quite easy to recreate yourself (if you can remember pythagoras theorem).
The basic idea of ray casting is very simple. To transform a 2d image map into a 3d representation, "rays" are projected from the viewer towards the light source. If a ray hits an object on the 2d map, a vertical line is drawn on our "3d" image to represent this section of the wall or object. Think of the image as vertical slices.
This diagram might do a better job of explaining.

Textures can be applied using texture maps but unfortunately other effects like reflections aren't so easy to create. They can be faked though.
If you've got nothing to do for a few hours, consider creating a simple ray cay caster in your favourite language.
Here's a few resources to get you started.
16 August 2007
PHP, Programming, Security

Most developers have now heard about Facebook's leaked index.php source code, which was anonymously posted here. If you haven't seen it already, there are a number of links listed on Techcrunch.
I've seen a few bloggers criticize Facebook developers for using procedural programming rather than classes and object oriented techniques. I'm not exactly sure why they've chosen to develop the site like this; but I am going to take a guess and say it was to improve speed and efficiency.
Object oriented programming was first introduced to PHP in version 4. However, the language wasn't originally designed around objects and classes, so the implementation was clunky and awkward. This meant that procedural code was often much faster than object oriented code.
Considering the size and popularity of social networks, I'm not surprised they chose procedural code over objects. That tiny boost in performance would easily outweigh the advantages of using classes.
Fortunately, most (if not all) issues with objects have been solved in PHP 5, which is now closer to a truly object oriented language.
08 August 2007
Programming
The goal of a signup form is to quickly convert visitors into registered users. The easiest way to increase your sign up form's conversion rate is to lower the amount of time it takes to complete.
One way to do that, is to add a "check username availability" feature. Users will often choose conflicting usernames, especially on large community websites.
Rather than reporting the error on the next page, give the user a quick and easy way to check their username availability. This will speed up the sign up process.
As always, start with your interface. A simple form with a text box, a div, and a "Check Availability" button is all that's needed. You can copy the HTML from the demo.

Using the prototype javascript library, we will send an AJAX request to a seperate checkuser.php page, which will print either 1 for "available", or 0 for "not available". Our javascript function will print the appropriate message in our div, then highlight the textbox with green (available), or red (not available).
Here is the checkUser() javascript function. Don't forget to include the Prototype Javascript file.
function checkUser(user)
{
var url = encodeURIComponent('checkuser.php');
var params = 'user=' + escape(user);
new Ajax.Request(url, {
method: 'get', parameters: params,
onSuccess: function(transport) {
if(transport.responseText == 1){
$('userstatus').innerHTML = 'Your username is available.',
$('user').style.backgroundColor = '#caffd5'
}else{
$('userstatus').innerHTML = 'Sorry, that username is already taken.',
$('user').style.backgroundColor = '#ffd4ca';
}}});
}
View the Demo.
This is only a small way you can increase the effectiveness of your sign up form. I will be writing about other methods in the near future.
17 July 2007
Programming
I won't list reasons why every programmer should know C because there have already been numerous discussions on the subject.
As a programmer, you can decide for yourself whether learning C will benefit your career.
I've chosen to start writing a small project in C so I can get a better knowledge of pointers, structs and memory allocation.
I'm going to share a small snippet of code which creates a process in Unix. You might find this interesting if you've never seen C code before.
Processes are created using the fork() function, which basically makes a copy of the existing process running and assigns a new process id (PID) to the child process. The rest of the code is fairly self explanatory.
#include <stdio.h>
/* the main() function is automatically executed... */
int main()
{
/* fork the process */
int p_id = fork();
/* this is the code the child process will execute */
if(p_id == 0)
{
/* endless loop */
for(;;)
{
printf("Im a child processn");
sleep(10);
}
}
/* close the parent process */
exit(0);
}
Save and compile the code using gcc (gcc process.c -o process). The process should now be listed in the process list (type ps -aux in unix).
11 July 2007
Programming
I've been experimenting with 2D game development in the last few weeks. It's fun because it let's me combine my love for code and art into one project.
When I first became interested, it took some time gathering information about best practices and methods for creating games. So I'm writing this article for people who are interested but aren't sure where to start.
The Tools You Need
I recommend C++ for game development. It is widely used and there are thousands of tutorials/recources available on the net. It's object-oriented, so it's perfect for modeling real world objects you might see in a game, e.g. paddle.moveUp().
For C++ development on Windows, I recommend Bloodshed Dev-C++, which is bundled with the Mingw compiler.

You can of course develop your game in almost any language, it really depends on how complex your game needs to be.
If you're after extreme speed and efficiency, you might chose to develop your game in assembly language (not for the faint hearted). If you just want to make a simple hang man game, you could use visual basic.
Python is also a good language for game development.
Learning C/C++ is quite easy if you're proficient in PHP, Ruby, Python or any other OO language. Cplusplus.com has a great introductory tutorial for beginners.
If you're coming from PHP and you're not used to event driven programming, you might find game development a bit unnatural at first. Stick with it, you'll get used to it within a few hours.

Getting started
SDL (Simple DirectMedia Layer) is a development library which makes using animation and audio very easy. Handling user input with SDL is also a walk in the park. My first "hello world" application was compiled and running within 2 minutes.
For a quick guide on getting started, have a look at "Setting up SDL in Dev C++". Once everything is set up, start working your way through these great tutorials.
Inspiration
If you want to make a game but don't have any concept ideas, check out the following sites for some inspiration.
If you're looking for a fun way to learn C/C++, developing a small 2D game is perfect. My first game was Pong, which only took a few hours to complete...
05 July 2007
PHP, Programming
Here's an easy way of filtering empty variables from an array, without using a loop or multiple if statements.
<?php
$var1 = '';
$var2 = 'dog';
$var3 = '';
$var4 = 'fish';
$my_array = array($var1, $var2, $var3, $var4);
print_r(array_filter($my_array));
?>
Output:
Array ( [1] => dog [3] => fish )
27 June 2007
PHP, Programming
PHP errors are ugly and should never be shown to your users. Luckily with PHP we can handle errors our own way using the set_error_handler function.
I'll start by defining the error handling function which will write the error to a log file and stop execution.
function handleError($level, $error, $file, $line)
{
if ($logfile = fopen('log.txt', 'a'))
{
fwrite($logfile, date("F j, Y, g:i a") ." $error on line $line in $file\n");
fclose($logfile);
}
die('An error has occured.');
}
Then set it as the error handling function.
set_error_handler('handleError');Trigger an error to see if it works.
echo 100 / 0;You could also get your function to notify you via email. Or you could forget about logging, and just display better looking errors...
function handleError($level, $error, $file, $line)
{
$errorhtml = '<div style="border: 4px solid #bfbfbf; font-size: 12px; font-family: arial, sans-serif; padding: 1px">';
$errorhtml .= '<div style="background-color: #a3503f; color: #ffffff; padding: 3px;">ERROR</strong></div>';
$errorhtml .= $error.'<br />';
$errorhtml .= 'Line: '.$line.'<br />';
$errorhtml .= 'File: '.$file;
$errorhtml .= '</div>';
echo $errorhtml;
}
14 June 2007
PHP, Ruby, Programming

Here is a short comparison between Ruby and PHP. The task was to print the location of all HTML links in a webpage using regular expressions.
If anyone knows of a cleaner or more efficient way to do this in Ruby or PHP, please post it in the comments!
Ruby
require 'net/http'
#connect and get the webpage
host = Net::HTTP.new('www.site.com.au', 80)
body = host.get('/index.php', nil ).body
puts "Links found..."
#find link URIs
links = body.scan(/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/)
#print all link URIs
links.each {|id,uri| puts uri}PHP
<?php
$page = file_get_contents('http://www.site.com.au/index.php');
// find links
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/', $page, $links);
// links found
foreach($links[2] as $link)
{
print "$link\n";
}
?>
30 May 2007
Ruby, Programming

Since I'm fairly new to Ruby, I thought it would be a good idea to give myself a trivial programming task.
I decided to create a simple script to generate a star field typical of the DOS gaming era.
To make things a little more challenging, I used a grid to make sure stars were evenly spaced and covered the whole image.
Here's the code:
require 'rubygems'
require 'RMagick'
include Magick
#create the sky
$sky = Image.new(200,200){ self.background_color = "black" }
#define possible star colours
$colours = [white, grey, blue, pink, yellow]
#define the create star function
def draw_star(x, y)
$sky.pixel_color(x, y, $colours[rand($colours.length)])
end
#define starting coordinates
x = 0
y = 0
#define starting block
block = 0
while block < 100
#define random coordinates for the star in the block
rand_x = x + rand(20)
rand_y = y + rand(20)
#draw the star
draw_star(rand_x, rand_y)
#move the x coodinate position to the next block
x += 20
#check if its the last block on the row
if block % 10 == 0
y += 20
x = 0
end
#next block
block += 1
end
#create the image
$sky.write("sky.jpg")And here is the output:
29 May 2007
Security, Programming

MD5 is a popular hash function which is often used to encrypt passwords in web applications. In most applications, when a user enters their password, it is encrypted and compared to the one stored in the database. If both md5 hashes match, the user is granted access.
This approach is generally considered to be quite secure for authenticating users. However, it still has it's weaknesses.
MD5 hashes are vulnerable to dictionary and brute force attacks using rainbow tables; which store millions of passwords and their hashed values.
Which means if your database is compromised there's a good chance that your passwords can be recovered by an experienced cracker.
Here are a few tips for protecting your passwords...
Also make sure you're using SSL if your web application has any importance. It's extremely easy to intercept passwords using packet sniffers.
24 May 2007
Programming
Data visualisation isn't a new concept. For decades, scientists and geographers have been been relying on data visualisations to present their huge amounts of data.
Only recently has it started gaining interest on the web, and I believe we have Digg Labs to thank for that.
Since releasing their API, a number of great visualisations have surfaced. Two of my favourites are Digg RADAR and Digg Swarm.

There are also some great visualizations in the networking industry. You can even monitor your network traffic in video game style with Netcosm.
Visit Visual Complexity for hundreds more examples.
I thought it would be fun to make a visualization of my own, and here's what I came up with.

Each "star" represents a product, and is grouped in a cluster which represents the user it belongs to. The end result is an interesting star field.
Obviously it's not as impressive as the Wikipedia activity image mosaic, but I had fun making it.
11 April 2007
Ruby, Programming

While working with mod_ruby over the past week, I put together a small list of tips which might help other beginners like me...
403 Forbidden Error
After successfully installing mod_ruby, I would get a "403 Forbidden" error when attempting to run a ruby script. My apache log file showed..
[Wed Apr 11 10:32:13 2007] [error] access to /var/www/ruby/ruby.rb failed for (null), reason: Options ExecCGI is off in this directoryI simply added "Options +ExecCGI" to my httpd.conf file like so...
<Files *.rb>
Options +ExecCGI
SetHandler ruby-object
RubyHandler Apache::RubyRun.instance
</Files>I was still getting a 403 error when running the script, but my apache logs were now reporting that the file permissions were incorrect. Easy fix, I chmod'd the file to 777, and the test script worked perfectly.
Incorrect HTTP Headers
I found that I could change the content type from text/plain to text/html by using this code...
r = Apache.request
r.content_type = 'text/html'
r.send_http_header
exit(Apache::OK) if r.header_only?There are other solutions to this problem.Changes in included files not taking effect
mod_ruby caches scripts included using 'require'. Using 'load' instead will force mod_ruby to reload the included script.
Fetching GET variables
variable = Apache.request.paramtable['variable']
04 April 2007
Ruby, Programming

I've been trying to make an effort to learn Ruby for a few months now. Finally, the other night I decided I would start writing a small project in Ruby to see what everyone is talking about.
Fortunately Ruby comes prepackaged with CentOS, but the ruby-mysql module was not installed. This was my first minor problem. Attempting to install the mysql module, resulted in Make errors. I finally located the mysql-ruby RPM in the CentOS testing repo. Problem solved.
I admit, I underestimated Ruby. It's more challenging than I expected, but it definitely brought the "fun" back into programming.
I'm still not sure about the best way to structure a Ruby application. I've had a look around some other open source apps though, and it's slowly starting to make more sense to me. If anyone could point me in the direction of a good tutorial that would be much appreciated.
I'm having fun learning though, and I'm sure all my questions will be answered soon.
28 March 2007
Programming
Plan for the future
I know it can be hard, but try and look one year down the track, when your ecommerce project needs to support more than one payment gateway, or your boss decides to switch from MySQL to Oracle database. This point is especially important for database design.
Document
Document everything you can. It's a lot harder trying to document an already built project. Believe me, I'm paying for that mistake now.
Don't do unimportant jobs first
Sometimes it can be hard to focus on the big picture when there are lots of little "fun" things to do. Get stuck into creating the codebase, rather than spending an hour on that "RSS" button.
Design your interfaces
The interface is what your end users will see. If you have a poorly designed interface, your project is doomed to fail, no matter how great your codebase is.
Avoid writing your own library/framework if possible
It's hard fighting urges to create a new framework for every project. The thought of using someone else's framework makes some developers feel dirty, but it's worth it. Finding a suitable library/framework and learning to use it will always be faster than spending weeks building your own.
Create a project plan
I know this one seems obvious, but you would be surprised at how often a project plan isn't written. Make sure everyone working on the project knows what they're supposed to be doing, and when to have it done by. Writing a project plan will also help you identify problems you might encounter in the future.
Pick an appropriate language
Don't get caught up in the hype of new languages. Pick one that everyone on the team is proficient in.
Remove yourself from distractions
It's hard to get into "The Zone" with phone calls interrupting your work flow constantly. Try and set aside a few uninterrupted hours a day to devote to your project. I know this won't always be possible.
Enforce quality control from day one
When first starting a project, a lot of developers tend to slap code together to get a working demo. This is fine if you go back and rewrite the bad code, but every now and then some of it makes it into production. Take some extra time, and do things right.
Identify problems that may occur later on in the development process
Communicate with fellow team members, and talk about your application's design and structure. Some members will have different views on areas of the project. Sitting down and discussing these can avoid conflict 2-3 months down the track.
22 March 2007
PHP, Programming
I've been an advocate of seperating logic from presentation for a long time now. But after working on a few large PHP projects lately, I've decided that I need to have loops in my template class, it's too time conusming creating seperate templates to be placed inside loops.
I started off by defining a readable syntax for the loops inside my templates.
<@loop(contacts)
{
<p>Name: {name}<br />
Sex: {sex}</p>
}
@>
'contacts' would be the name of the array I'm going to loop through.
Here is the function that will process the loop. Simply pass a string containing the loop, and it will return the output.
<?php
function parseLoop($loop)
{
$loop_result = '';
// get the name of the loop
preg_match('/loop\((.*)\)/', $loop, $loop_name);
// get the loop contents
preg_match('/\{(.*)\}/s', $loop, $loop_contents);
// get all the vars from loop_contents
preg_match_all('/\{(.*)\}/', $loop_contents[1], $vars);
// loop through the global array
foreach($arrays[$loop_name[1]] as $item)
{
$loop_item = $loop_contents[1];
// loop through every variable found, and replace it with its value in the global array
foreach($vars[1] as $var)
{
$loop_item = @str_replace('{'.$var.'}', $item[$var], $loop_item);
}
$loop_result .= $loop_item;
}
return $loop_result;
}
?>
And here is the array containing the contacts.
<?php
$arrays = array('contacts' = array(
array('name' => 'jane', 'sex' => 'f'),
array('name' => 'bob', 'sex' => 'm')
);
?>
To use the function you need to find the loops in the templates using regular expressions, pass it through parseLoop(), then replace the loop block with the output.
09 March 2007
PHP, Programming
I needed to make a script in PHP to scan a page of text and return the top 10 keywords.
I decided to give more importance to words starting with uppercase characters. I couldn't find any PHP functions available, so I thought I would write my own. Hopefully someone finds this useful.
<?php
$string = 'Titanic';
function isFirstUC($string)
{
if(strstr($string[0], ucfirst($string[0])))
return True;
else
return False;
}
echo isFirstUC($string);
?>
21 February 2007
Programming

Building a Ray-Tracing 3D Renderer from Scratch Over a Weekend
"I've always liked the idea of ray-tracing to render 3D images with crazy accuracy. On Saturday night (being a huge nerd) I decided I'd try to write one from scratch for the hell of it. By from scratch I mean I started with this C++ code in a text file."
29 January 2007
Programming

Creating a GUI using Python, WxWidgets, and wxPython
I've never used python for anything more than 10 line scripts, so I'm looking forward to giving this tutorial a go. ;)