Archive for the ‘programming’ Category

TSP Problem

editprogrammingcommentsNo Comments »
July 22nd 2010

I have just run into what appears to be a very classic problem that has been studied a lot:

The Problem:

A list of addresses in a neighborhood that someone must visit and complete in a timely manner.

This is very much related to a problem called The traveling salesman problem (TSP) where an optimal walking order needs to be computed which result in the shortest distance traveled and/or shortest time taken.

After taking a look at different approach to this problem and taking look at a current javascript implementation at
http://www.gebweb.net/optimap/

It gave me hope that this problem can be solved with web implementations, however there were two problems with the above solution.

1. It restricted to 24 addresses (Which is fine because TSP originally is for larger area route planning, even between cities)
2. Only given 15 or less address did it return the optimal route

The solution:

Due to computational resources and restrictions in scripting languages, I have decided that the best and easiest way to solve this problem would be using the “Nearest Neighbor” approach.

This approach takes the closest location as the next location and repeat this process for route planning. Although this is not the most optimal way of solving the problem but it provides a couple of advantages:

1. Can always calculate straight line distance to the next address and then use google map API to calculate the direction
2. The step can be repeated and increment the current location to the next address which is just calculated.

The biggest problem with the approach so far is that in order to calculate the route (On the server side), we must specify a starting point. Some ideas include use one of the boundary corners as a starting point, or use the middle most point and walk in a circular fashion.

Will keep updated with some implementation soon.

Useful PHP class: ezSQL

editphp / programmingcommentsNo Comments »
November 23rd 2009

I first used this class 3 years ago, I found it still to be one of the best php class you can find on the web.

the ezSQL class enables you to use php to connect to many different databases including

  • MySQL
  • MSSQL
  • PostgreSQL

It provides many methods to retrieve single data value, data sets and rows of data.

I especially find the following method useful

// get n number of rows of result set based on your query
// can return a standard object, associate array or numeric (index) array
$db->get_results(string "query string", [OBJECT | ARRAY_N | ARRAY_A]);

// returns a single variable from database
// very useful for select count or other aggregate value SQL statements
$db->get_var(string "query string");

// execute a query without return, gives true/false if the query succeed or fails
// useful for create table, insert, update queries
$db->query(string "query string");

You can download it here

php func_get_args

editphp / programmingcommentsNo Comments »
September 22nd 2009

Recently looking in Drupal’s source code I found the func_get_args function. It is quite a powerful function for newer version of php

It basically takes in a random number of arguments and parses them in an argument array.

Basically, here’s what how it works

function foo_bar() {

$args = func_get_args;

for($i = 0; $i< count($args; $i++)
{
       echo $args[$i] . '< br/ > ';
}

foo_bar('monday', 'tuesday', 'wednesday');

The above function call will return

monday
tuesday
wednesday

It works very much like passing in an array as a parameter except it's less clunky.

function foo_bar($args = array())
{
     for($i = 0; $i < count($args); $i++)
     {
          echo $args[$i] . '< br/ > ';
     }

}

foo_bar(array('Monday', 'Tuesday', 'Wednesday'));

Adding javascript to specific node/url in drupal

editDrupal / Open source development / phpcommentsNo Comments »
July 28th 2009

This was in one of the module I’ve written in Drupal and I thought it would be useful to share.

The Problem: I wanted to dynamically add javascript file to a specific url under Drupal. The benefit would been that I did not have to include the .js file for the whole site therefore optimize the performance of site. Not to mention that it by including the javascript file in a specific url, it will not interfere with other scripts, etc.

To review, the function to add javascript in drupal is

drupal_add_js() (http://api.drupal.org/api/function/drupal_add_js/)

However, this function will add a javascript file or script to the head section on all of the drupal path/urls, making it clunky.

The Solution:


// The function passes in a parameter which is the url you want to check
// It will return true if the url the user is browsing matches the url you are trying to
// act on
function module_name_helper_is_page($check_url)
{
	global $base_url;

	$page_url = module_name_helper_get_curl_url();

	if(!stristr($page_url, $check_url))
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

/*
 * This function simply returns the current url of the web page
*/
function module_name_helper_get_curl_url()
{
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
	$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
	$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}

	return $pageURL;
}

To put it into action, say we wanted to only add a javascript file to the user registration page, here would be what it looks like. (By the way, module_name stands for the module you are writing)

if(module_name_helper_is_page($base_url . 'user/register'))
{
     drupal_add_js(drupal_get_path('module', 'module_name') .'/yourjavascript.js', 'module', 'header');
}

Cheers!

Custom 403 module on Drupal.org

editDrupal / Open source development / php / programmingcommentsNo Comments »
June 22nd 2009

custom_403_screen_shotThis is a module I have worked on a while back. I have recently had the time to finish it and it is now released and hosted on drupal.org, which is very exciting.

You can view the module project page here, to see a demo page, please visit here

The module was made with one thing specifically in mind, giving the users more information when they encounter a 403 on a website. Since drupal uses various role based node access privileges, I thought a module that provides custom information based on the roles allowed or disallowed on any specific node will be more helpful.

The module works with the content access module to give the visitors information on what roles are allowed to access the nodes and maybe the admins can also give more information on how to obtain these roles. Anyways, please enjoy the module, if you have questions and comments, please let me know

Cheers!

Add a Database

editVisual Basic / programmingcommentsNo Comments »
June 30th 2008

Chapter3_Prog1_001
The first step in adding a database to visual basic project is going to Project -> Add New Item…

Select SQL Database

Right Click Tables -> Add New Table
Chapter3_Prog1_002
Add the colums and their data types

Primary key – foreign key relationship can be found under the menu-relationship
Chapter3_Prog1_003

After adding the database connection to the data source, you can now drag tables or do other manipulation with the data

Chapter3_Prog1_004
To download the source code for this program, click here

Lessons learned: code optmization

editphp / programmingcommentsNo Comments »
June 25th 2008

Have you ever written a piece of code that works, but the amount of redundancy and inefficiency drove you nuts? Always had the itch to go back and pretty it up? Well, that’s exactly what I did. I recently wrote a script for a people directory, it contained 3 parts

  1. An database storing the information of the people (i.e. name, states, country, etc etc.)
  2. the html input file (see example below)
  3. The data processor using PHP

input file (input.html)

The idea is that you will be able to select a last name or a state and find the corresponding results. For example, finding someone in the state of Virginia, finding someone with last name start with W, or a combination of both.

This was the first attempt for selecting the matching last name:

HERE

HERE

By using arrays, here are the code for selecting the matching last name and state and generate the SQL query

HERE

HERE

Joomla content backup using php

editphp / programmingcommentsNo Comments »
May 3rd 2008

A while back one of my project was to create a joomla based content management website. Afterwards I was asked to make a backup mechanism that would back up all of the content on the website. There were plenty of third party plugins available on joomla’s extension directory but I found them either too complicated for normal users to operate or costed money. Another option was to use PhpMyAdmin to backup the entire joomla database, however that was too
complicated for the user in this situation as well. Therefore I decided to write a custom php script made just to handle the content backup.

Some file you need download: (PHP ZIP library: PHP zip library, contains: Zip.php and PEAR.php)

1st: I had to find where the content was stored, luckily for joomla based CMS all contents are stored in the database under the table “jos_content” or whatever the pre-fix: “xx_content” in the joomla database you created.

2nd: I had to create the basic MySQL connection script: here are the following:

openning the database:

//********************************************************************************
//opendb
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');

mysql_select_db($dbname);
//********************************************************************************

configure the database information: Simple enter the MySQL database information

//*******************************************************************************
//configuration file
$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = 'password';
$dbname = 'db_name';
//end of configuration file
//*******************************************************************************

Close connection:

//*******************************************************************************
//close connection
mysql_close($conn);
//*******************************************************************************

Here are the basic scripts for openning and closing a mySQL database connection in php, for more information on them, visit w3schools to learn more

Now comes the meat of the script:

//************************************************
//include the php library for zip file compression
//************************************************
include ('Zip.php');

//*************************************************************************************
//Querying the database table containing the contents of the website, notice we used a
//concat function to combine the introtext and fulltext together
//*************************************************************************************
$query  = "SELECT id, title, concat(introtext, concat('\n', `fulltext`)) content FROM jos_content";
$result = mysql_query($query);

//*****************************************************************
//Displaying the SQL querying result in html using a form text area
//*****************************************************************
echo "";
echo " 

$number files created under /help/backup

"; //providing download link echo "Click here to download the backup package";

As some of you can tell, this script is still in very immature stage, future updates could include SQL injection prevention measures, validation of the backup directory and also deletion of the html files once they have been packaged. Anyways I hope this have been useful.

A simple internet Browser

editVisual Basic / programmingcomments1 Comment »
March 19th 2008

It’s very exciting isn’t it, in the second program, We are attempting to create a customized simple internet browser. My program consist of the following controls:

1 WebBrowser (the web content area)
Name: BrowseWindow

3 buttons (HomeButton, BackButton, Button_1)

Some thoughts: The browser is very simple, address does not address content of the web. Maximize, content area does not, future considerations.

Code

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

BrowseWindow.Navigate(TextBox1.Text)

End Sub

Private Sub BackButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BackButton.Click

BrowseWindow.GoBack()

End Sub

Private Sub HomeButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HomeButton.Click

BrowseWindow.GoHome()

End Sub
End Class

Screen shot (click to enlarge)

Chapter 1 Program 2 Screen shot

download Chapter 1 Program 2 Code download