Bubble Sort PHP Example

Written by Tully on July 1, 2010 Categories: PHP Tags: , , ,

Yesterday I posted an example of the Bubble Sort algorithm in C++. Today I wrote the sorting algorithm in PHP. I have provided an example of the Bubble Sort Algorithm in PHP.

// Bubble Sort Algorithm
// www.TullyRankin.com/bubble-sort-php

$numbers = array(1,3,2,5,2);
$array_size = count($numbers);

echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
   echo $numbers[$i];
echo "\n";

for ( $i = 0; $i < $array_size; $i++ )
{
   for ($j = 0; $j < $array_size; $j++ )
   {
      if ($numbers[$i] < $numbers[$j])
      {
         $temp = $numbers[$i];
         $numbers[$i] = $numbers[$j];
         $numbers[$j] = $temp;
      }
   }
}

echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
   echo $numbers[$i];
echo "\n";
1 Comment

Bubble Sort Algorithm

Written by Tully on June 30, 2010 Categories: C++ Tags: , , ,

Was reading about sorting arrays in C++ and came across the bubble sort. Wikipedias definition says the bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements “bubble” to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort.

Example Bubble Sort Algorithm in C++

// Bubble Sort in C++
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

int num[ 10 ] = { 0, 2 ,1 ,55 ,22, 77, 32, 22, 77, 99 };
int numSize = 10;
int temp;

// Before sorting
cout << "Before the sort! " << endl;
for ( int i = 0; i < numSize; i++ )
cout << setw(5) << num[i];
cout << "\n\n";

for( int i = 0; i < numSize; i++ )
{
for (int j = 0; j < numSize; j++)
{
if ( num[i] < num[j] )
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}

cout << "After the sort!" << endl;
for ( int i = 0; i < numSize; i++ )
cout << setw(5) << num[i];
return 0;
}
No Comments

Ubuntu 64 10.04 LTS Flash

Written by Tully on June 24, 2010 Categories: Linux

Today I upgraded to Ubuntu 10.04 LTS. After upgrading I was unable to get flash working. I had successfully installed  the 32bit version working with flash at work. After doing some searches on Google for my problem, I found the cause. The problem is that the version in the repository is for the 32 bit version. This was not going to work. After doing some more research, I found a shell script that could get flash working

Steps to get flash working under Ubuntu 10.04 LTS.

  1. Open up a terminal Applications->Accessories->Terminal
  2. wget http://www.tullyrankin.com/code/ubuntu-64-10-04-flash.sh
  3. chmod +x ubuntu-64-10-04-flash.sh
  4. ./ubuntu-64-10-04-flash.sh

Ubuntu 64 10.04 LTS Flash Player Fix

No Comments

JAVA Letter Frequency

Written by Tully on June 21, 2010 Categories: JAVA Tags: , ,

I picked up a book on JAVA this last weekend at the local borders. The book I bought was JAVA in 24 hours. So far I’m on page 116 in 2 days and the read is very easy. I’m currently on chapter 9 “Storing Information with Arrays” and found JAVA a very easy language to pick up. In this chapter they have an example program that counts the letter frequency in an array of phrases. I thought this was a pretty cool and have provided the JAVA class below.

I plan on developing Android applications within the next couple months. I set-up the Android SDK and emulator with Net Beans IDE. So far I have only created the basic “Hello World!” application which I got running successfully. I will provide my Android application code on this site as soon as I have some source code to reveal.

// Word Frequency Class

class Wheel {
public static void main(String[] args) {
String phrase[] = {
"A STITCH IN TIME SAVES NINE",
"DON'T EAT YELLOW SNOW",
"JUST DO IT",
"EVERY GOOD BOY DOES FINE",
"I WANT MY MTV",
"I LIKE IKE",
"PLAY IT AGAIN, SAME",
"FROSTY THE SNOWMAN",
"ONE MORE FOR THE ROAD",
"HOME FIELD ADVANTAGE",
"VALENTINE'S DAY MASSACRE",
"GROVER CLEVELAN OHIO",
"SPAGHETTI WESTERN",
"AQUA TEEN HUNGER FORCE",
"IT'S A WONDERFUL LIFE"
};
int[] letterCount = new int[26];
for (int count = 0; count < phrase.length; count++) {
String current = phrase[count];
char[] letters = current.toCharArray();
for (int count2 = 0; count2 < letters.length; count2++) { char lett = letters[count2]; if ( (lett >= 'A') & (lett <= 'Z') ) {
letterCount[lett - 'A']++;
}
}
}
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount[count - 'A'] +
" ");
}
System.out.println();
}
}

Output:
A: 22 B: 1 C: 4 D: 9 E: 34 F: 7 G: 6 H: 7 I: 18 J: 1 K: 2 L: 10 M: 8 N: 19 O: 20 P: 2 Q: 1 R: 12 S: 15 T: 20 U: 4 V: 7 W: 6 X: 0 Y: 7 Z: 0

1 Comment

C++ Development Phases

Written by admin on June 7, 2010 Categories: C++

Phase 1: Creating a Program
Phase 1 consists of editing a file with an editor program (normally known simply as an editor). You type a C++ program (typically referred to as source code) using the editor, make any necessary corrections and save the program on a secondary storage device, such as your hard drive. C++ source code filenames often end with the .cpp, .cxx, .cc or .C extensions (note that C is in uppercase) which indicate that a file contains C++ source code. See the documentation for your C++ compiler for more information on file-name extensions.
Two editors widely used on UNIX systems are vi and emacs. C++ software packages for Microsoft Windows such as Microsoft Visual C++ (msdn.microsoft.com/vstudio/express/visualc/default.aspx) and Code Gear C++ Builder (www.codegear.com) ahve editors integrated ito the programming environment. You can also use a simple text editor, such as Notepad in Windows, to write your C++ code. We assume you know how to edit a file.

Phase 2 and 3: Preprocessing and Compiling a C++ Program
In phase 2, you give the command to compile the program. In a C++ system, a preprocessor program executes automatically before the compiler’s translation phase begins (so we call preprocessing phase 2 and compiling phase 3). The C++ preprocessor obeys commands called preprocessor directives, which indicate that certain manipulations are to be performed on the program before compilation. These manipulations usually include other text files to be compiled, and perform various text replacements. In phase 3, the compiler translates the C++ program into machine-language code (also referred to as object code).

Phase 4: Linking
Phase 4 is called linking. C++ programs typically contain references to functions and data defined elsewhere, such as in the standard libraries or in the private libraries of groups of programmers working on a particular project. The objectcode produced by the C++ compiler typically contains “holes” due to these missing parts. A linker links the object code with the code forthe missing functions to produce an executable image (with no missing pieces). If the program compiles and links correctly, an executable image is produced.

Phase 5: Loading
Phase 5 is called loading. Before a program can be executed, it must first be placed in memory. This is done by the loader, which takes the executable iamge from disk and transfers it to memory. Additional components from shared libraries that support the program are also loaded.

Phase 6: Execution
Finally, the computer, under the control of its CPU, executesthe program one instruction at a time.

No Comments

Six logical units of a computer

Written by admin on  Categories: General Tags: , , , , , ,

Input unit – This is the “receiving” section of the computer. It obtains information (data and computer programs) from input devices and places this information at the disposal of the other units for processing. Most information is entered into computers through keyboards and mouse devices. Information also can be entered in many other ways, including by speaking to your computer, scanning images, uplaoding digital photos and videos, and receiving information from a network, such as the Internet.

Output unit - This is the “shipping” section of the computer. It takes information that the computer has processed and places it on various output devices to make the information available for use outside the computer. Most information output from computers today is displayed on screens, printed on paper or used to control other devices. Computers also can output their information to networks, such as the Internet.

Memory unit - This is the rapid-access, relatively low-capacity “warehouse” section of the computer. It stores computer programs while they are being executed. It retains information that has been entered through the input unit, so that it will be immediately available for processing when needed. The memory unit also retains processed information until it can be placed on output devices by the output unit. Information in the memory unit is typically lost when the computer’s power is turned off. The memory unit is often called with memory or primary memory. [Historically, this unit has been called "core memory," but that term is fading from use today.]

Arithmetic and logic unit (ALU) – This is the “manufacturing” section of the computer. It is responsible for performing calculations, such as addition, subtraction, multiplication and division. It contains the decision mechanisms that allow the computer, for example, to compare two items from the memory unit to determine whether they are equal.

Central processing unit (CPU) - This is the computer’s “administrative” section. It coordinates and supervises the other sections’ operations. The CPU tells the input unit when information should be read into the memory unit, tell the ALU when information from the memory unit should be used in calculations and tells the output unit when to send information form the memory unit to certain output devices. Many of today’s computers have multiple CPUs and, hence, can perform many operations simultaneously—such computers are called multiprocessors.

Secondary storage unit - This is the computer’s long-term, high-capacity “warehousing” section. Programs or data not actively being used by the other units normally are placed on secondary storage devices, such as your hard drive, until they are needed, possibly hours, days, months or even years later. Information in secondary storage takes much longer to access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary memory. Other secondary storage devices include CDs and DVDs, which can hold hundreds of millions and billions of characters, respectively.

No Comments

Apache Includes Parser

Written by Tully on April 2, 2010 Categories: Apache, PHP Tags: , , ,

Wrote this script to read and parse all included files in httpd.conf or any file specified when calling the PHP script. Will output content from httpd.conf(or any file specified) and all included files found and output to stdout. I used this to pipe the output to grep when searching for various Apache directives. Useful to find directives that are in a included file that are overwriting your directives set in httpd.conf.


<?php
error_reporting
(0);
if (
$argc != 2) {
echo <<<FILE
#################################################

Reads all ”Included files” in specified file and outputs to stdout.

Usage: php $argv[0] file
Example: php $argv
[0] httpd.conf
#####################################

FILE;
}
else
{
$file = file($argv[1]);
$content = “”;
try {
foreach (
$file as $line) {
$line = str_replace(“\n”,“”,$line);
if (
stristr($line,‘Include’) && !stristr($line,‘#’)) {
if (
preg_match(‘/^.*\*\.conf$/’,$line)) {
$str = str_replace(“Include ”,“”,$line);
$str = str_replace(“*.conf”,“”,$str);
$dirFiles = @scandir($str);
foreach (
$dirFiles as $dirFile) {
if (
stristr($dirFile,“.conf”)) {
$content .= file_get_contents($str.$dirFile);
}
}
}
elseif (
preg_match(‘/^.*[a-zA-z0-9]\.conf$/’,$line)) {
$content .= file_get_contents(substr($line, 8));
}
else
{
$str = str_replace(“Include ”,“”,$line);
$dirFiles = @scandir($str);
foreach (
$dirFiles as $dirFile) {
if (
stristr($dirFile,“.conf”)) {
$content .= file_get_contents($str.$dirFile);
}
}
}
}
print_r($content);
}
} catch (
Exception $e) {
echo
$e->getMessage();
}
}

No Comments

Packet Storm ATOM Feed

Written by Tully on March 4, 2010 Categories: PHP Tags: , , , ,

I was searching around Packet Storm today and wanted to add there new files as a RSS/ATOM feed on my browser. I didn’t find a link for this, so I created one in PHP. Below is the code that creates the atom.xml file.

Click Here To View


<?php
/*
* Connects to packstormsecurity.org and created a
* atom feed of the last 20 uploaded files.
*
* @requires php-curl php-tidy
* @author Tully Rankin
* @url    http://www.TullyRankin.com
*/
$ch = curl_init();
$url = 'http://www.packetstormsecurity.org/last20.html';
$site = 'http://www.packetstormsecurity.org';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

$tidy_config = array(
‘clean’ => true,
‘output-xhtml’ => true,
‘show-body-only’ => false,
‘wrap’ => 0
);
$tidy = tidy_parse_string($data, $tidy_config, ‘UTF8′);
$tidy->cleanRepair();
$xhtml = preg_replace(‘/\<spacer.*\>/’,,$tidy);

$xml = new DOMDocument();
$xml->loadHTML($xhtml);

$body = $xml->getElementsByTagName(“body”)->item(0);
$links = $body->getElementsByTagName(“a”);
$x = 0;
foreach(
$links as $link)
{
if (
$link->getAttribute(“class”) == “fname”)
{
$files[$x]['name'] = $link->nodeValue;
$files[$x]['link'] = $link->getAttribute(“href”);
$x++;
}
}

$tables = $body->getElementsByTagName
style=”color: #007700″>(
“table”);
foreach (
$tables as $table)
{
if (
$table->getAttribute(“class”) != “fbox2″) continue;
$tRows = $table->getElementsByTagName(“tr”);
foreach(
$tRows as $row)
{
if (
$row->getAttribute(“class”) == “finfo”)
{
if (
$row->getElementsByTagName(“td”)->item(1) != null &&
$row->getElementsByTagName(“td”)->item(1)->getAttribute(“valign”) == “top”)
{
$td = $row->getElementsByTagName(“td”)->item(1);
$text[] = $td->nodeValue;
}
}
}
}

$x = 0;
$fileNames = array();
foreach (
$files as $file)
{
if (
substr($file['link'],0,1) == “/”)
{
$content[$x]['name'] = $file['name'];
$content[$x]['link'] = $site.$file['link'];
$content[$x]['text'] = $text[$x];
$x++;
}
}

$result = ‘<?xml version=”1.0″ encoding=”utf-8″?>
<feed xmlns=”http://www.w3.org/2005/Atom”>
<title>PacketStorm Security</title>
<link rel=”alternate” type=”text/html” href=”http://www.tullyrankin.com/” />
<link rel=”self” type=”application/atom+xml” href=”http://www.tullyrankin.com/atom.xml” />
<id></id>
<updated>2010-03-03</updated>
<subtitle>Security Feed</subtitle>
;
foreach (
$content as $node)
{
$result .= “<entry>”;

$result .= “<title>{$node['name']}</title>”;
$result .= “<link href=\”{$node['link']}\” />”;
$result .= “<summary>{$node['text']}</summary>”;
$result .= “</entry>”;
}
$result .= “</feed>”;

$conn = @fopen(‘packetstorm.xml’,‘w+’);

if (@fwrite($conn, $result) === false)
{
die(
‘<h1>Could Not create feed</h1>’);

}
else
{
echo ‘<h1>Created new packetstorm.xml file!</h1>’;
}
fclose($conn);

No Comments

PHP Class Passwd

Written by Tully on February 5, 2010 Categories: PHP Tags: , , ,

Just for fun, I wrote a short simple class to parse the Linux “passwd” file. The class has functions to return the content in either html or text for the command line. The difference being one has “<br />” statements and the other has “\n” for new lines. The class also contains a function to search for a user, and a function to delete a user.

/**
 * Class is used to read, search, and manipulate linux passwd file.
 *
 * @author  Tully Rankin
 * @website www.tullyrankin.com
 */
class ReadPasswd {
    private $file;
    private $fileData;
    private $error;

    /*
     * Initialize the class and add contents of
     * the password file into the variable file.
     */
    function __construct($file) {
        try{
            if (is_file($file))
            {
                $this->fileData = file($file);
                $this->file = $file;
            }
            else
            {
                throw new Exception(“Couldn’t open file.”);
            }
        } catch (Exception $e) {
            $this->error[] = $e->getMessage();
        }
    }
   
    /*
     * Returns string of all rows of data from the passwd file.
     * Use this file if your trying to display in the browser.
     *
     * @type Public
     * @return String
     */
    public function getAllHTML() {
        foreach ($this->fileData as $content)
        {
            $temp = explode(‘:’, $content);
            $output .= “<b>Username:  {$temp[0]} </b><br />”;
            $output .= “Validation: {$temp[1]} <br />”;
            $output .= “User Identifier: {$temp[2]} <br />”;
            $output .= “Group Identifier: {$temp[3]} <br />”;
            $output .= “Gecos Field: {$temp[4]} <br />”;
            $output .= “Home Directory: {$temp[5]} <br />”;
            $output .= “Shell: {$temp[6]} <br />”;
            $output .= “<br />”;
        }
        return $output;
    }
   
    /*
     * Returns string of all rows of data from the passwd file. This is
     * used if running the command from the command line.
     *
     * @type Public
     * @return String
     */
    public function getAllCLI() {
        foreach ($this->fileData as $content)
        {
            $temp = explode(‘:’, $content);
            $output .= “Username: {$temp[0]} \n”;
            $output .= “Validation: {$temp[1]} \n”;
            $output .= “User Identifier: {$temp[2]} \n”;
            $output .= “Group Identifier: {$temp[3]} \n”;
            $output .= “Gecos Field: {$temp[4]} \n”;
            $output .= “Home Directory: {$temp[5]} \n”;
            $output .= “Shell: {$temp[6]} \n”;
            $output .= “\n”;
        }
        return $output;
    }
   
    /*
     * Searches for a user. Will return an array with
     * the users credentials unless the second param is set.
     * If true is set on the second parameter then the function
     * will withold add the the user information to the returned array.
     *
     * @type Public
     * @params String, Boolean
     * @return Array
     */
    public function searchUser($user,$data=0) {
        try{
            $data = array();
            if (is_string($user))
            {
                foreach($this->fileData as $line)
                {
                    $temp = explode(‘:’, $line);
                    if (in_array($user,$temp))
                    {
                        if ($data) return 1;
                        $data['username'] = $temp[0];
                        $data['validation'] = $temp[1];
                        $data['user_identifier'] = $temp[2];
                        $data['group_identifier'] = $temp[3];
                        $data['gecos'] = $temp[4];
                        $data['home_directory'] = $temp[5];
                        $data['shell'] = $temp[6];
                    }
         &
nbsp;      }
            }
            else
            {
                throw new Exception(‘A search error has occured.’);
            }
        } catch (Exception $e) {
            $this->error[] = $e->getMessage();
        }
    return $data;
    }
   
    /*
     * Getter for Error Exception Array
     * @type Public
     * @return Array
     */
    public function getError() {
        return $this->error;
    }
   
    /*
     * Removes user from passwd file
     * @type public
     * @return Boolean
     */
    public function deleteUser($user) {
        try{
            if ($this->searchUser($user,1))
            {
                foreach ($this->fileData as $line)
                {
                    $lines = explode(“:”,$line);
                    if (!in_array($user,$lines))
                    {
                        $final .= $line;
                    }
                }
                if(!file_put_contents($this->file,$final))
                {
                    throw new Exception(“Could not delete user.”);
                }
            }
            else
            {
                throw new Exception(“User doesn’t exist.”);
            }
        } catch (Exception $e) {
            echo $this->error[] = $e->getMessage();
        }
    }   
}

No Comments

Simple AJAX Example

Written by Tully on January 31, 2010 Categories: PHP Tags: , , ,

I started re-writing a lot of my old code today to use AJAX. AJAX
stands for (Asynchronous Javascript and XML) and is a way of making
your web applications more interactive. So for example, you can refresh
results on the page from a form without having to reload the page. The
example that I’m going to show you is a name suggestion form. It will
display a html form input and will return results from a mysql database
that start with whatever char/chars you type in real time.

The form page looks like the following…


<html>
<head>
<title>Simple Ajax Example</title>
<script type="text/javascript">
var xmlhttp;

function showUser(str) {
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null)
    {
      alert ("Browser does not support HTTP Request");
      return;
    }
    var url="getNames.php";
    url=url+"?name="+str.value;
    url=url+"&nocache="+Math.random();
    xmlhttp.onreadystatechange=stateChanged;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}

function stateChanged() {
    if (xmlhttp.readyState==4)
    {
        document.getElementById("nameHint").innerHTML=xmlhttp.responseText;
    }
}

function GetXmlHttpObject() {
    if (window.XMLHttpRequest)
    {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
      // code for IE6, IE5
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
return null;
}
</script>
</head>
<body>

<form name="formName" id="formName">
<input type="text" name="name" id="name" onKeyUp="showUser(this)">
</form>

<span id="nameHint" name="nameHint"></span>

</body>
</html>

The form calls getNames.php with the params name=[Input Field Value].
The Input field value is the value of whatever you type into the form
text input. The code that processes this request is below:


<?php

$name strip_tags($_GET['name']);

if (!empty($name)) 
{
    if (
$con mysql_connect('127.0.0.1''root''1234'))
    {
        if (!
mysql_select_db('test'))
        {
            echo 
'Could not connect to database';
            exit;
        }
        
$sql sprintf("SELECT name FROM names WHERE name like '%s'"
                        
mysql_real_escape_string($name.'%'));
        
$result mysql_query($sql,$con);
        if (!
$result
        {
            echo 
'Bad Query';
        }
        
$rowCount mysql_num_rows($result);
        while (
$row mysql_fetch_assoc($result)) 
        {
            
$names[] = $row['name'];
        }
    }
}

if (count($names) > 0
{
    echo 
'<ul>';
    foreach (
$names as $name)
    {
        echo 
"<li>$name</li>";
    }
    echo 
'</ul>';
}


As you can see, the getNames.php file first looks at the GET value for the name Parameter. I also have it wrapped in the strip_tags function
which will eliminate the chance of a user entering any kind of tags
that may end up breaking or altering the script. Next, I check to see
if the $name value is empty. The script will not display anything if the $name value is empty or there is no results. Now the script can connect to a mysql server and select the correct DB. Now I write
the query using the sprintf function. This allows me to alter multiple
variables in the string. I use the %s for string and have
mysql_real_escape_string function return the $name variable. The
mysql_real_escape_string prepends backslashes to the following
characters “\x00, \n, \r, \, ‘, ” and \x1a”.

I now query the database with the $sql string that I just created. I
create the variable rowCount which will return the # of rows returned
from the query. Next we loop through the results and add each name to
the $names variable.

We now have all the results in an array and need to display the result. I first check to see if the array is not empty. I do this by using the count() function on the $names array. If the count is greater then 0 we will display each of the rows returned in a unordered list <ul> tag.

This is by far the simplest AJAX example. We could have returned the results as JSON and looped through them better in the index.php page. I will write a more technical and more advanced example in the near future.

No Comments