<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">

    <title type="text">Gaurav &#45; Web Development blog</title>
    <subtitle type="text">Gaurav &#45; Web Development blog:</subtitle>
    <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/index/" />
    <link rel="self" type="application/atom+xml" href="http://www.gauravjassal.com/index.php/site/atom/" />
    <updated>2008-11-20T15:17:42Z</updated>
    <rights>Copyright (c) 2008, Gaurav Jassal</rights>
    <generator uri="http://expressionengine.com/" version="1.6.4">ExpressionEngine</generator>
    <id>tag:gauravjassal.com,2008:11:15</id>


    <entry>
      <title>Filter Array into Categorized format</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/filter_array_into_categorized_format/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.19</id>
      <published>2008-11-15T17:59:12Z</published>
      <updated>2008-11-17T09:12:13Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="PHP"
        scheme="http://www.gauravjassal.com/index.php/site/C1/"
        label="PHP" />
      <content type="html"><![CDATA[
       <p>This simple yet powerful class to filters an array and breaks in to a categorized array format.You can use this class if you are dealing with large and complex array and want to convert it into and simple array that is easy to understand and use. Recently i required a function that can categorize an array and break it into categorize format.I couldn't find any core function to do that so i decided to create my own class that can do this job for me. I have also added an example to demonstrate the usage to its benefit. Make sure you comment it if you find it useful.  </p>

<h3> Original Array </h3>

<pre name="code"class="php">
$arrProducts=array(
        array(
        "product_id" 			=> "007",
        "product_name"      	=> "Blackberry R-900 Mobile",
        "product_price" 		=> "£450",
        "product_status"		=>"1",
        "product_category"		=>"Mobile"
        ),
		array(
        "product_id" 			=> "033",
        "product_name"      	=> "8 GB Pendrive",
        "product_price" 		=> "£14.99",
        "product_status"		=> "0",
        "product_category"		=> "Computers"
        )
);
</pre>  <h3> Array2ArrayTree Class </h3>

<p> Here is the class that converts the array to and organize format. The constructor take two arguments first the Array you want to format and the second category key you want to filter by.Then you have to call makeTree() function to format the array. The makeTree() function will return you the organized array.</p>

<pre name="code"class="php">
&lt;?php
/**
 * Array2ArrayTree
 * @package   
 * @author Gaurav Jassal
 * @copyright <a href="http://www.gauravjassal.com">http://www.gauravjassal.com</a>
 * @version 1.0
 * @access public
 */
class Array2ArrayTree
{
    public $arrOriginal = array();
    public $arrDummy = array();
    public $strKey = "";
    /**
     * Array2ArrayTree::__construct()
     * 
     * @param $arrData Array
     * @param $arrKey String 
     * @return
     */
    public function __construct($arrData, $arrKey)
    {
        $this->arrOriginal = $arrData;
        $this->strKey = $arrKey;
        $this->arrDummy = array();
    }

    /**
     * Array2ArrayTree::makeTree()
     * 
     * @return Array
     */
    public function makeTree()
    {
        for ($i = 0; $i <= sizeof($this->arrOriginal) - 1; $i++) {
            $keyPosition = $this->searchKey($this->arrOriginal[$i][$this->strKey]);
            if ($keyPosition == -1) {
                $this->addNode($this->arrOriginal[$i]);
            } else {
                $this->appendNode($this->arrOriginal[$i], $keyPosition);
            }
        }
        return $this->arrDummy;
    }
    /**
     * Array2ArrayTree::searchKey()
     * 
     * @param $strCurrentValue String
     * @return
     */
    function searchKey($strCurrentValue)
    {
        for ($i = 0; $i <= sizeof($this->arrDummy) - 1; $i++) {
            if ($this->arrDummy[$i][0][$this->strKey] == $strCurrentValue) {
                return $i;
            }
        }
        return - 1;
    }
    /**
     * Array2ArrayTree::addNode()
     * 
     * @param $arrNode Array
     * @return
     */
    function addNode($arrNode)
    {
        $this->arrDummy[sizeof($this->arrDummy)][0] = $arrNode;
    }
    /**
     * Array2ArrayTree::appendNode()
     * 
     * @param $arrNode Array
     * @param $keyPosition Integer
     * @return
     */
    function appendNode($arrNode, $keyPosition)
    {
        array_push($this->arrDummy[$keyPosition], $arrNode);
    }
}
?&gt;
</pre>

</h3>Usage </h3>
<pre name="code" class="php">
&lt;?php
require_once("array2arraytree.php");
$arrProducts=array(
                array(
                "product_id" 			=> "007",
                "product_name"      	=> "Blackberry R-900 Mobile",
                "product_price" 		=> "£450",
                "product_status"		=>"1",
                "product_category"		=>"Mobile"
                ),
				array(
                "product_id" 			=> "033",
                "product_name"      	=> "8 GB Pendrive",
                "product_price" 		=> "£14.99",
                "product_status"		=> "0",
                "product_category"		=> "Computers"
                ),
				array(
                "product_id" 			=> "033",
                "product_name"      	=> "The White Tiger – Aravind Adiga",
                "product_price" 		=> "£29.99",
                "product_status"		=> "1",
                "product_category"		=> "Books"
                ),
				array(
                "product_id" 			=> "4501",
                "product_name"      	=> "The Final Reckoning - Sam Bourne",
                "product_price" 		=> "£19.99",
                "product_status"		=> "0",
                "product_category"		=> "Books"
                ),
				array(
                "product_id" 			=> "001",
                "product_name"      	=> "Wespro Multi-SIM & Touch-screen Mobile",
                "product_price" 		=> "£150",
                "product_status"		=> "1",
                "product_category"		=> "Mobile"
                ),
				array(
                "product_id" 			=> "004",
                "product_name"      	=> "Sigmatel MP4/MP3 + Camera Mobile",
                "product_price" 		=> "£150",
                "product_status"		=> "1",
                "product_category"		=> "Mobile"
                ),
				array(
                "product_id" 			=> "034",
                "product_name"      	=> "The Final Reckoning - Sam Bourne",
                "product_price" 		=> "£15.79",
                "product_status"		=> "0",
                "product_category"		=> "Books"
                ),
				array(
                "product_id" 			=> "334",
                "product_name"      	=> "250 GB Portable Hard Drive",
                "product_price" 		=> "£79.99",
                "product_status"		=> "1",
                "product_category"		=> "Computers"
                )
			);

$objTree=new Array2ArrayTree($arrProducts,"product_category");
$arrTree=$objTree->makeTree();
print("<pre>");
print_r($arrTree);
print("</pre>");
?&gt;
</pre>


<h3> Result Array </h3>

<pre name="code" class="php">Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [product_id] => 007
                    [product_name] => Blackberry R-900 Mobile
                    [product_price] => £450
                    [product_status] => 1
                    [product_category] => Mobile
                )

            [1] => Array
                (
                    [product_id] => 001
                    [product_name] => Wespro Multi-SIM & Touch-screen Mobile
                    [product_price] => £150
                    [product_status] => 1
                    [product_category] => Mobile
                )

            [2] => Array
                (
                    [product_id] => 004
                    [product_name] => Sigmatel MP4/MP3 + Camera Mobile
                    [product_price] => £150
                    [product_status] => 1
                    [product_category] => Mobile
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [product_id] => 033
                    [product_name] => 8 GB Pendrive
                    [product_price] => £14.99
                    [product_status] => 0
                    [product_category] => Computers
                )

            [1] => Array
                (
                    [product_id] => 334
                    [product_name] => 250 GB Portable Hard Drive
                    [product_price] => £79.99
                    [product_status] => 1
                    [product_category] => Computers
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [product_id] => 033
                    [product_name] => The White Tiger – Aravind Adiga
                    [product_price] => £29.99
                    [product_status] => 1
                    [product_category] => Books
                )

            [1] => Array
                (
                    [product_id] => 4501
                    [product_name] => The Final Reckoning - Sam Bourne
                    [product_price] => £19.99
                    [product_status] => 0
                    [product_category] => Books
                )

            [2] => Array
                (
                    [product_id] => 034
                    [product_name] => The Final Reckoning - Sam Bourne
                    [product_price] => £15.79
                    [product_status] => 0
                    [product_category] => Books
                )

        )

)
</pre>

<p>You can download the files <a href="http://www.gauravjassal.com/downloads/array2arraytree.zip">here</a> </p> 
      ]]></content>
    </entry>

    <entry>
      <title>Why use Constraints in SQL ?</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/why_use_constraints_in_sql/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.15</id>
      <published>2008-10-01T14:19:57Z</published>
      <updated>2008-11-01T12:04:58Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="MySQL"
        scheme="http://www.gauravjassal.com/index.php/site/C10/"
        label="MySQL" />
      <category term="PostgresSQL"
        scheme="http://www.gauravjassal.com/index.php/site/C9/"
        label="PostgresSQL" />
      <content type="html"><![CDATA[
       <p>Constraints enables business rules to be enforced by the database instead of via
application code. Through the judicious use of constraints, application and SQL coding
can be minimized and data integrity can be maximized. Constraints may be applied to
columns in the form of uniqueness requirements, relational integrity constraints to other
tables/rows, allowable values and data types.For example, a column containing a product
price should probably only accept positive values. But there is no standard data type
that accepts only positive numbers. Another issue is that you might want to constrain
column data with respect to other columns or rows. For example, in a table containing
product information, there should be only one row for each product number.</p>

<p>With constraints you can have much control over the data and you can have it the way
you want to be. You can have same rules in your web applications that you are writing in
whatever language like PHP, ASP.NET, Perl, Python but constraints can save your alot of
valuable time.</p>

<p><strong>Constraints, in SQL Server, can be used to:</strong></p>

<ul>
<li># Enforce the range of data values that can be stored in a column (check
constraints)&nbsp;</li>

<li># Enforce the uniqueness of a column or group of columns within a table (unique /
primary key constraints)&nbsp;</li>

<li># Eenforce referential integrity (primary key and foreign key constraints)</li>
</ul>

<p>A <strong>PRIMARY KEY</strong> constraint is a unique identifier for a row within a
database table. Every table should have a primary key constraint to uniquely identify
each row and only one primary key constraint can be created for each table. The primary
key constraints are used to enforce entity integrity.</p>
<pre name="code" class="sql">
CREATE TABLE products ( 
        product_no integer PRIMARY KEY, 
        name text, 
        price numeric
); 
</pre>  <p>A <strong>UNIQUE</strong> constraint enforces the uniqueness of the values in a set of
columns, so no duplicate values are entered. The unique key constraints are used to
enforce entity integrity as the primary key constraints.</p>

<pre name="code" class="sql">
CREATE TABLE products (
product_no integer UNIQUE NOT NULL,
name text,
price numeric
);
</pre>

<p>A <strong>FOREIGN KEY</strong> constraint prevents any actions that would destroy link
between tables with the corresponding data values. A foreign key in one table points to a
primary key in another table. Foreign keys prevent actions that would leave rows with
foreign key values when there are no primary keys with that value. The foreign key
constraints are used to enforce referential integrity.&nbsp;</p>
<pre name="code" class="sql">
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
shipping_address text,
...
);

CREATE TABLE order_items (
product_no integer REFERENCES products,
order_id integer REFERENCES orders,
quantity integer,
PRIMARY KEY (product_no, order_id)
);
</pre>

<p>In the above example the foreign keys disallow creation of orders that do not relate
to any products. But what if a product is removed after an order is created that
references it? SQL allows you to handle that as well. Intuitively, we have a few
options:</p>

<p># Disallow deleting a referenced product</p>

<p># Delete the orders as well</p>

<p># Something else?</p>

<p>To illustrate this, In the second example implemented the following policy on the
many-to-many relationship example above: when someone wants to remove a product that is
still referenced by an order (via order_items), we disallow it. If someone removes an
order, the order items are removed as well. This is a very important feature of
contraints. Without this implementation you wil be writing additional SQL statements and
conditional statement in your server side code.</p>

<pre name="code" class="sql">
CREATE TABLE products (
product_no integer PRIMARY KEY,
name text,
price numeric
);

CREATE TABLE orders (
order_id integer PRIMARY KEY,
shipping_address text,
...
);

CREATE TABLE order_items (
product_no integer REFERENCES products ON DELETE RESTRICT,
order_id integer REFERENCES orders ON DELETE CASCADE,
quantity integer,
PRIMARY KEY (product_no, order_id)
);
</pre>

<p>A <strong>Check</strong> constraint is a mechanism for allowing predicates to be
defined on a column. The predicate is attached to the column as DDL and performs
automatic edit checking of values as they are presented for insert or update to the
table.</p>
<pre name="code" class="sql">

CREATE TABLE tblproducts (
product_id   integer,
product_name text,
price numeric CHECK (price > 0) 
);
</pre>

<p><strong>Another Example</strong></p>

<pre name="code" class="sql">
CREATE TABLE tblproducts (
product_id integer,
name text,
price numeric CHECK (price > 0),
discounted_price numeric CHECK (discounted_price > 0),
CHECK (price > discounted_price)
);
</pre>

<p>A <strong>NOT NULL</strong> constraint enforces that the column will not accept null
values. The not null constraints are used to enforce domain integrity, as the check
constraints.</p>
<pre name="code" class="sql">
CREATE TABLE products (
product_no integer NOT NULL,
name text NOT NULL,
price numeric
);
</pre>

 
      ]]></content>
    </entry>

    <entry>
      <title>Google&#8217;s Project10tothe100</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/googles_project10tothe100/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.13</id>
      <published>2008-09-29T10:09:41Z</published>
      <updated>2008-11-20T15:17:42Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="Daily Digest"
        scheme="http://www.gauravjassal.com/index.php/site/C8/"
        label="Daily Digest" />
      <category term="News"
        scheme="http://www.gauravjassal.com/index.php/site/C2/"
        label="News" />
      <content type="html"><![CDATA[
       <p><a href="http://www.google.com">Google</a> &nbsp;came up with a new project called&nbsp;<a href="http://www.project10tothe100.com/" title="project10tothe100">Project10tothe100</a> &nbsp;Google has sent an invitation to all the people who has an idea or ideas to change the world, just share the same with Google and help the people in all.</p>

<p>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" height="361" width="448">
<param name="src" value="http://www.youtube.com/v/NgSRwOZtDQ8&amp;hl=en&amp;fs=1%26rel=0" />
<param name="wmode" value="transparent" />
</object>
</p>  <p><strong>Why this project?</strong></p>
<p>Never in history have so many people had so much information, so many tools at their disposal, so many ways of making good ideas come to life. Yet at the same time, so many people, of all walks of life, could use so much help, in both little ways and big.</p>
<p>In the midst of this, new studies are reinforcing the simple wisdom that beyond a certain very basic level of material wealth, the only thing that increases individual happiness over time is helping other people.</p>
<p><a href="http://www.project10tothe100.com/why.html">http://www.project10tothe100.com/why.html</a></p>
<p>&nbsp;</p>
<h2>How it works</h2>
<p>Project 10<sup>100</sup> &nbsp;(pronounced &quot;Project 10 to the 100th&quot;) is a call for ideas to change the world by helping as many people as possible. Here's how to join in.</p>
<p><span class="blacktitle">1. Send us your idea by October 20th.</span> <br /> Simply fill out&nbsp;<a href="http://www.project10tothe100.com/submit_your_idea.html">the submission form</a> &nbsp;giving us the gist of your idea. You can supplement your proposal with a 30-second video.</p>
<p><span class="blacktitle">2. Voting on ideas begins on January 27th.</span> <br /> We'll post a selection of one hundred ideas and ask you, the public, to choose twenty semi-finalists. Then an advisory board will select up to five final ideas.&nbsp;<a href="http://www.project10tothe100.com/reminder.html">Send me a reminder to vote.</a></p>
<p><span class="blacktitle">3. We'll help bring these ideas to life.</span> <br /> We're committing $10 million to implement these projects, and our goal is to help as many people as possible. So remember, money may provide a jumpstart, but the idea is the thing.</p>
<p>Good luck, and may those who help the most win.</p>
<p><a href="http://www.project10tothe100.com/how_it_works.html">http://www.project10tothe100.com/how_it_works.html</a></p>
<p>&nbsp;</p>
<h2>Category Descriptions</h2>
<p>Here are the categories in which we'll be considering ideas.</p>
<ul class="categories">
<li class="community"><strong>Community:</strong> &nbsp;How can we help connect people, build communities and protect unique cultures?</li>
<li class="opportunity"><strong>Opportunity:</strong> &nbsp;How can we help people better provide for themselves and their families?</li>
<li class="energy"><strong>Energy:</strong> &nbsp;How can we help move the world toward safe, clean, inexpensive energy?</li>
<li class="environment"><strong>Environment:</strong> &nbsp;How can we help promote a cleaner and more sustainable global ecosystem?</li>
<li class="health"><strong>Health:</strong> &nbsp;How can we help individuals lead longer, healthier lives?</li>
<li class="education"><strong>Education:</strong> &nbsp;How can we help more people get more access to better education?</li>
<li class="shelter"><strong>Shelter:</strong> &nbsp;How can we help ensure that everyone has a safe place to live?</li>
<li class="else"><strong>Everything else:</strong> &nbsp;Sometimes the best ideas don't fit into any category at all.</li>
</ul>
<p>&nbsp;</p>
<p><a href="http://www.project10tothe100.com/categories.html">http://www.project10tothe100.com/categories.html</a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p> 
      ]]></content>
    </entry>

    <entry>
      <title>Catch Errors in ActionScript 3.0</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/catch_errors_in_actionscript_30/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.12</id>
      <published>2008-09-26T09:53:41Z</published>
      <updated>2008-11-01T12:28:43Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="Actionscript 3.0"
        scheme="http://www.gauravjassal.com/index.php/site/C4/"
        label="Actionscript 3.0" />
      <category term="Daily Digest"
        scheme="http://www.gauravjassal.com/index.php/site/C8/"
        label="Daily Digest" />
      <category term="Flash 8"
        scheme="http://www.gauravjassal.com/index.php/site/C11/"
        label="Flash 8" />
      <category term="Flex 3"
        scheme="http://www.gauravjassal.com/index.php/site/C6/"
        label="Flex 3" />
      <content type="html"><![CDATA[
       <p><strong>Errors</strong></p>

<p>One thing you may notice about ActionScript 3 how error prone it is or, rather, how
error prone it perceives you to be. You&rsquo;ll see a lot more errors, not only during
compile, but also runtime. ActionScript 3 is much less lenient in letting you get away
with mistakes or code conflicts. Whereas ActionScript 1 and 2 may silently fail or ignore
many errors, ActionScript 3 will be sure to let you know something went wrong.</p>

<p><strong>Synchronous Errors</strong></p>

<p>Normal errors in code which occur as a code block is being executed are synchronous
errors. When the Flash player encounters one of these errors in code, an error, or
exception, is thrown. At that point the Flash player will suspend all code in the current
block and prevent it from continuing unless the exception is taken care of or caught. To
catch exceptions in ActionScript, you use a try..catch..finally statement.</p>

<p>The try..catch..finally statement lets you try a block of code possible of throwing an
error and react accordingly if an error occurs. It consists of 2 or more blocks of code:
an initial try block, consisting of the code that could throw an error, 1 or more catch
blocks that catch errors of different types and run if that type of error is thrown, and
an optional finally block which is run after the try and any catches whether or not an
error occurs. Its format is as follows:</p>
  <pre name="code" class="js">
try {
    // potential error causing code
}
catch (error : Error) {
    // error of type Error occurred
    // additional catch blocks may follow
}
finally {
    // optional to follow try and catch blocks
}
</pre>
<p>If an exception is thrown within a try block, Flash will look through each catch block until a matching error type is found. When a match is found, that code is run followed by the finally block if it exists. Any additional code following a try..catch..finally statement will be executed as normal even if an error occurs because it was caught by the try..catch..finally statement.</p>
<p>Throw custom errors</p>
<p>Errors are not thrown exclusively by Flash. You also have the ability to throw errors in your own code if you so desire. To throw errors you would use the throw statement. The throw statement throws any value that precedes it (namely an Error object). When thrown, the error will act just like any error and would require a try..catch..finally block to be correctly caught.</p>
<p>// Throwing your own errors in ActionScript<br />throw new Error(&rdquo;Error message&rdquo;);</p>
<p>Throwing your own errors can be a helpful debugging tool, especially as you work with more complicated applications.</p>
<p><strong>Asynchronous Errors</strong></p>
<p>Errors can also occur during asynchronous actions, such as loading external content, and take the form of events. These errors cannot be caught with try..catch..finally statements. Instead you have to create event handlers to handle and &ldquo;catch&rdquo; the error events. If you do not have an event listener assigned to an error event and that error occurs, the Flash player will inform you of the unhandled error event.</p>
<pre name="code" class="js">
// creating listeners for error events handles
// asynchronous errors
target.addEventListener(ErrorEvent.TYPE, handler);
function handler(event:ErrorEvent):void {
// handle error
}
</pre>
<p><strong>Creating Asynchronous Errors</strong></p>
<p>If you want to invoke your own asynchronous errors, all you need to do is dispatch an event using dispatchEvent that is of the type ErrorEvent. When an unhandled ErrorEvent reaches the Flash player when authoring in Flash, the output window will display the error.</p>

<pre name="code" class="js">
// target object is an event dispatcher
// that needs to dispatch an error event
target.dispatchEvent(new ErrorEvent(&rdquo;type&rdquo;));
</pre>
<p><strong>Release and Debug Players</strong></p>
<p>The release of the Flash player is available in two versions, the release and debug. The release player is the standard, public player. This player is what you will have installed for your browser(s) when you download and install Flash player from adobe.com.</p>
<p>The debug player is an alternate player with additional debug information and capabilities embedded within it. This makes the player a little heftier in file size (which is why its not preferred for distribution) but also provides popup dialogs for uncaught exceptions and unhandled asynchronous errors &ndash; something the public would rather not see when your Flash movie or application runs into a snag. For developers, however, this player provides useful information when testing your movies.</p>
<p>You can find installers for both the release and debug players in the Players folder within your Flash CS3 (or older) install directory.</p>
<p>One thing to keep in mind is that just because the release player doesn&rsquo;t visually show an error when an exception is thrown, it doesn&rsquo;t mean that error line is simply ignored like with previous versions of ActionScript. The code block where that error occurred will be exited and the remaining script ignored.<br />Example: Loading external text with error handling</p>
<p>To load text content from an external source into the Flash player, you would use the URLLoader class. An instance of URLLoader will load a text file into its data property to be read as a string. Because the process of locating, downloading, and reading an external file into the Flash player takes time, events are used to indicate when the content has been loaded and is available. Not only that, events are used to indicate loading progress and also any errors that occur.</p>
<p>The URLLoader class uses the load method to start the loading process which is also capable of throwing exceptions of many different error types. When using the URLLoader class to load external content, its always best to listen for all asynchronous errors as well as call the load method within a try..catch..finally statement.</p>

<pre name="code" class="js">
// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(&rdquo;textfile.txt&rdquo;);
var loader:URLLoader = new URLLoader();
// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events
loader.addEventListener(IOErrorEvent.IO_ERROR, loadIOError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadSecurityError);
// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for IO error
function loadIOError(event:IOErrorEvent):void {
trace(&rdquo;IOError: &ldquo;+event);
}
// handler for security error
function loadSecurityError(event:SecurityErrorEvent):void {
trace(&rdquo;SecurityError: &ldquo;+event);
}
// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:ArgumentError){
trace(&rdquo;ArgumentError: &ldquo;+error);
}catch (error:MemoryError){
trace(&rdquo;MemoryError: &ldquo;+error);
}catch (error:SecurityError){
trace(&rdquo;SecurityError: &ldquo;+error);
}catch (error:TypeError){
trace(&rdquo;TypeError: &ldquo;+error);
}catch (error:Error){
trace(&rdquo;Unknown Error: &ldquo;+error);
}
</pre>
<p>In the above example, each error event has its own listener tracing the error if an error occurs during loading. Additionally, each type of error thrown by the load operation is being checked within respective catch blocks. An ending catch with the type Error is used in case there was an error thrown not within the other catches. Then that final block would catch the error no matter what it was. And really, you could just have one catch of the type Error to handle all error events. Similarly one event handler could be used for all error events. In doing this you can still catch and handle all errors but it would involve less code.</p>
<pre name="code" class="js">
// load textfile.txt text into loader instance
var request:URLRequest = new URLRequest(&rdquo;textfile.txt&rdquo;);
var loader:URLLoader = new URLLoader();
// listen for complete event (and others if desired)
loader.addEventListener(Event.COMPLETE, loadComplete);
// listen for error events using one handler
loader.addEventListener(IOErrorEvent.IO_ERROR, loadError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, loadError);
// complete event handler
function loadComplete(event:Event):void {
trace(loader.data); // textfile.txt contents
}
// handler for errors
function loadError(event:ErrorEvent):void {
trace(&rdquo;Error: &ldquo;+event);
}
// try the load operation and
// catch any thrown exceptions
try {
loader.load(request);
}catch (error:Error){
trace(&rdquo;Error: &ldquo;+error);
}
</pre>
<p>Here, all errors are still accounted for but less code is involved.</p>
<p>Note that the event parameter of the loadError method is typed as ErrorEvent. Just like all errors thrown by Flash are also of the type Error as well as their own type (their classes extend the Error class), the event errors are also of the type ErrorEvent. By typing the event parameter as ErrorEvent, you can be sure that whatever type of error occurs, it will correctly match with the type of event used in the event handler.</p>
<p>&nbsp;</p> 
      ]]></content>
    </entry>

    <entry>
      <title>What Makes a Great Developer?</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/what_makes_a_great_developer/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.11</id>
      <published>2008-09-26T09:18:58Z</published>
      <updated>2008-09-29T16:01:58Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="Daily Digest"
        scheme="http://www.gauravjassal.com/index.php/site/C8/"
        label="Daily Digest" />
      <category term="PHP"
        scheme="http://www.gauravjassal.com/index.php/site/C1/"
        label="PHP" />
      <category term="Personal"
        scheme="http://www.gauravjassal.com/index.php/site/C3/"
        label="Personal" />
      <category term="PostgresSQL"
        scheme="http://www.gauravjassal.com/index.php/site/C9/"
        label="PostgresSQL" />
      <category term="Regular Expression"
        scheme="http://www.gauravjassal.com/index.php/site/C12/"
        label="Regular Expression" />
      <content type="html"><![CDATA[
       <p>What makes a truly great developer? Some might say a positive attitude. Some might say a high-sugar, high-caffeine, high-bacon diet. Some might say an absence of sunlight and as many monitors as a desk can support.</p>
<p>Certainly, everyone has anecdotes about developers they&rsquo;ve worked with who they thought were brilliant. Unfortunately, most of the time that judgement is made not based on code quality, or hitting of deadlines, but on less relevant criteria, like whether or not the developer knew the names of their colleagues, how many lines of code they output or how confident they sounded when talking about their work.</p>
<p>Unfortunately, the best developers don&rsquo;t always come across positively. While this list may not be applicable to every development environment, here are a few of the traits to look out for to spot a great developer.</p>  <p><strong>Pessimistic</strong></p>
<p>Great developers are almost always pessimistic with regard to their work. That doesn&rsquo;t mean they&rsquo;re not upbeat, lively or even cheerful - just that they will always be thinking about what can go wrong and how it can be dealt with.</p>
<p>They&rsquo;ll assume that at some point they&rsquo;ll need to undo work already completed, that hardware will fail, that all security will be compromised, and that your office will burn to the ground. The really brilliant ones will assume that will all happen on the same day. And they won&rsquo;t be happy until there is a specific, actionable, testable - and fully tested - plan for dealing with these sorts of issues. Even then they won&rsquo;t be completely happy.</p>
<p>Pessimistic developers will be the ones that find constant flaws in ideas, and the important thing to remember when working with them is that they&rsquo;re not doing that to tear down other people&rsquo;s ideas - they&rsquo;re doing it to ensure that the ideas that turn into projects are properly thought through and that as many problems as possible have been anticipated in advance. That neurotic, paranoid, pessimistic attitude is exactly what you should be looking for if what you want from your developers is robust, secure, reliable code.</p>
<p>By contrast, an optimistic developer will be more likely to simply assume code will work, or that it is secure, or give a deadline for a project without considering all the potential pitfalls.</p>
<p>Likely to be heard saying:&nbsp;&ldquo;And what happens when that goes wrong?&rdquo;</p>
<p>&nbsp;</p>
<p><strong>Lazy</strong></p>
<p>Laziness is not usually viewed as a desirable trait, and in this case I don&rsquo;t mean turns-up-late-and-pretends-to-work laziness or just-move-that-logic-to-the-view laziness - both entirely unwanted. I mean a desire to not do tasks that are repetitive, or to waste time doing things a machine can do for you, or even to avoid future work by writing better code now. A lazy developer is one that builds a reusable code library, or wants a fully automated build process rather than a manual copy-and-paste one, or wants comprehensive automated unit testing, or writes code to be scalable even though that wasn&rsquo;t a requirement (rather than revisit it later).</p>
<p>As a bonus, a lazy developer is also usually one who will try and keep a project focussed on its core goals, rather than try and cram more work into the same time, providing a buffer against feature creep.</p>
<p>For example, when writing a category structure, a lazy developer might be likely to assume a many-to-many relationship between parent and child categories, even though the project specification says it will be a one-to-many relationship. Why? Because it might be needed one day and it would be better to write it that way from the start than to revisit it later.</p>
<p>Likely to be heard saying:&nbsp;<strong>&ldquo;We could automate that.&rdquo;</strong></p>
<h3>Curious</h3>
<p>Good developers are often rather like&nbsp;<a href="http://en.wikipedia.org/wiki/House_md" target="_blank">Gregory House</a>. They&rsquo;re very easily bored by repetitive work (see laziness) and spend most of their time ploughing through it looking for an interesting and challenging (and hopefully new) problem to solve. The less time they can spend on the repetitive, the higher the frequency of the challenges.</p>
<p>Curious developers will be constantly looking for new problems to solve, and better ways to solve previous problems. They&rsquo;ll be the ones encouraging new ways to work and constantly tweaking and trying to improve existing systems. They&rsquo;ll also be the ones most conscious of existing problems in the current working environment, and trying to correct those problems. Curious developers will usually have a wide breadth of knowledge, not just of their primary language(s), but of supportive, associated and alternative technologies.</p>
<p>Curious (or easily-bored) developers are often the least stuck in their ways - the most open to change. They may well need convincing of why a new way of working is better (and that&rsquo;s no bad thing) but as long as it&rsquo;s an improvement, and likely to release more time to spend on the interesting problems, they&rsquo;ll embrace it with a minimum of resistance.</p>
<p>Curiosity also breeds creativity, another highly desirable trait in any developer. A strong desire to work out what has caused a problem and how to solve it is highly likely to motivate someone to continue once obvious avenues are exhausted. It is that sort of mentality that fosters &ldquo;outside the box&rdquo; thinking and creative coding.</p>
<p>Possibly the most useful attribute of a curious developer is that desire to find and cure a problem rather than just paper over the crack.</p>
<p>Likely to be heard saying:&nbsp;<strong>&ldquo;Maybe there&rsquo;s another way to do this.&rdquo;</strong></p>
<h3>Meticulous</h3>
<p>Many great developers are sticklers for detail. They will demand consistency in their work and the work of their team (they&rsquo;re likely to care about common code standards and naming conventions, for example). They&rsquo;ll want unit testing and peer review of code. They&rsquo;ll want everyone in their team to comment on and document code. They are likely to be fussy about version control log messages.</p>
<p>They&rsquo;ll also be fussy about details in communication, and happy to ask what might seem like obvious questions, simply to be sure they have properly understood. This is especially true of things like bug reports. While they may not be terribly motivational communicators, they will usually be able to explain concepts clearly and effectively. That clarity is a tremendous advantage in any development environment, especially if teaching and learning are encouraged.</p>
<p>Likely to be heard saying:&nbsp;<strong>&ldquo;I just have a couple of questions &hellip;&rdquo;</strong>&nbsp;<strong>I&rsquo;m lazy, a little bit pessimistic, too much curious and meticulous: i&rsquo;ll be a GREAT developer! soonn&hellip;&hellip;&hellip;..</strong></p>
<p>I think this is the best article to judge how great developer you are.This article is from ILoveJackDaniels.com.</p>
<p><a href="http://www.ilovejackdaniels.com/blog/what-makes-a-great-developer" title="What Makes a Great Developer?" target="_blank">http://www.ilovejackdaniels.com/blog/what-makes-a-great-developer</a></p>
<p>&nbsp;</p> 
      ]]></content>
    </entry>

    <entry>
      <title>Who invented “CTRL + ALT + DEL”?</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/who_invented_ctrl_alt_del/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.10</id>
      <published>2008-09-23T09:58:35Z</published>
      <updated>2008-09-24T08:31:35Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="Daily Digest"
        scheme="http://www.gauravjassal.com/index.php/site/C8/"
        label="Daily Digest" />
      <content type="html"><![CDATA[
       <p><span>Have you ever thought of the person who invented &ldquo;<strong>CTRL + ALT + DEL</strong> &rdquo; key combination? &ldquo;David Bradley&rdquo; &mdash; He is the One who spent 1 minute and 23 seconds in writing the source code that rescues the world&rsquo;s PC users for decades.<br /> <br /> </span></p>
<p><span id="test1"><a href="http://farm1.static.flickr.com/64/201215800_3b65d808c4_b.jpg"><img alt="CTRL + ALT + DEL" height="230" src="http://farm1.static.flickr.com/64/201215800_3b65d808c4.jpg" width="400" /></a></span></p>
<p><span>This extraordinary IBM employee is retiring on Friday after a prolong service of 29 years. His formula forces obstinate computers to restart when they no longer follow other commands. By 1980, Bradley was one of 12 people working to create the debut. The engineers knew they had to design a simple way to restart the computer when it fails to respond the user &mdash; Bradley wrote the code to make it work.&nbsp;</span></p>  <p>Bradley says. &ldquo;I did a lot of other things than Ctrl-Alt-Delete, but I&rsquo;m famous for that one.&rdquo; His fame and success is achieved each time a PC user fails. He commented his relationship with Bill gates by saying &rdquo; I may have invented it, but Bill gates made it famous by applying my formul&nbsp;Bradley says. &ldquo;I did a lot of other things than Ctrl-Alt-Delete, but I&rsquo;m famous for that one.&rdquo; His fame and success is achieved each time a PC user fails. He commented his relationship with Bill gates by saying &rdquo; I may have invented it, but Bill gates made it famous by applying my formula when ever any Microsoft&rsquo;s Windows operating system made by him CRASHES, thus I win when ever he looses&rdquo;&nbsp;a when ever any Microsoft&rsquo;s Windows operating system made by him CRASHES, thus I win when ever he looses&rdquo;</p> 
      ]]></content>
    </entry>

    <entry>
      <title>Understanding _root &amp;amp; Scope</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/understanding_root_scope/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.9</id>
      <published>2008-09-23T08:48:43Z</published>
      <updated>2008-09-23T12:25:43Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="Actionscript 2.0"
        scheme="http://www.gauravjassal.com/index.php/site/C5/"
        label="Actionscript 2.0" />
      <category term="Actionscript 3.0"
        scheme="http://www.gauravjassal.com/index.php/site/C4/"
        label="Actionscript 3.0" />
      <category term="Flash 8"
        scheme="http://www.gauravjassal.com/index.php/site/C11/"
        label="Flash 8" />
      <category term="Flex 3"
        scheme="http://www.gauravjassal.com/index.php/site/C6/"
        label="Flex 3" />
      <content type="html"><![CDATA[
       <p>Recently was called up to fix an issue with a client&rsquo;s SWF file that we were trying to use on one of our channels. The file worked on its own, but not in the container <a href="http://en.wikipedia.org/wiki/SWF" target="_blank">SWF</a> on our site. Jumping into the client&rsquo;s code, I immediately spotted the problem where their developer declared a class instance used in their movie on the &ldquo;<a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary633.html" title="_root" target="_blank">_root</a> &rdquo; timeline. Since we loaded their SWF into a movieclip within our&nbsp;<a href="http://en.wikipedia.org/wiki/SWF" target="_blank">SWF</a> , the scope had changed, breaking the entire file.</p>  <p>Scope is one of the first things I usually check for when debugging ActionScript. It&rsquo;s easy to make errors related to scope and it seems that many Flash designers and developers don&rsquo;t have a 100% grasp on the idea of what it is. That&rsquo;s sometimes due to the Normal Mode in our editor, through free Flash tutorials or through the copy and paste learning pattern of the self taught (guilt am I of this at first.) So why is using &ldquo;_root&rdquo; such a headache when it&rsquo;s provided for us to use? In reference to &ldquo;_root&rdquo;, I think it&rsquo;s the fact that we learn it as an absolute path which doesn&rsquo;t always hold true. In addition it&rsquo;s knowing how to code with good practice and trying not to cut corners. Let&rsquo;s take a look at some types of scope and use of them within Flash.</p>
<p><span align="left"><span><br /> <strong>Understanding _level</strong> </span> </span></p>
<p>The keyword &ldquo;_level&rdquo; refers to the absolute main timeline of a specified level (ie: _level4). When you start with a&nbsp;<a href="http://en.wikipedia.org/wiki/SWF" target="_blank">SWF</a> &nbsp;file, that movie is always referred to as &ldquo;_level0&Prime;, the first in any possible stack of movies. By using &ldquo;_level&rdquo;, your code will only work in the intended &ldquo;_level&rdquo; order. If code tries to reach data on &ldquo;_level4&Prime; and we rearrange our stack in another project, the data won&rsquo;t be there, breaking our code. Levels can be thought of like floors on a building, when loading new SWF files into additional levels, they reside on top of one another. It&rsquo;s not necessarily bad practice to use &ldquo;<a href="http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary422.html" target="_blank">_level</a> &rdquo;, you just need to understand the consequences of being tied to a rigid structure.</p>
<p><strong>Understanding _root</strong></p>
<p>The keyword &ldquo;_root&rdquo; is used to refer to the absolute main timeline of a given &ldquo;_level&rdquo;. Depending on where a SWF resides, the reference to &ldquo;_root&rdquo; can be different. When using a SWF file all on its own, that file is &ldquo;_level0&Prime;. In this case, referencing the file&rsquo;s main timeline with &ldquo;_root&rdquo; is the same as saying &ldquo;_level0&Prime;. If the same file were loaded into &ldquo;_level5&Prime; we would be referencing the main timeline of &ldquo;_level5&Prime; with &ldquo;_root&rdquo;. However, if we load that same SWF file into a target movieclip vs. a &ldquo;_level&rdquo; our scope changes because the SWF isn&rsquo;t used being used in the context of a &ldquo;_level&rdquo; anymore. What was referenced as &ldquo;_root&rdquo; in the SWF&rsquo;s main timeline while used on its own now points to the main timeline of the SWF loading it. It&rsquo;s important to know that using &ldquo;_root&rdquo; as an absolute can be misleading and for all intents and purposes it should be avoided.</p>
<p><strong>Contrasting _level &amp; _root</strong></p>
<p>The above explanations are similar when described but they are very different when used. Code using &ldquo;_level3&Prime; for example, written on a given timeline in a given movie will ALWAYS refer to the main timeline in &ldquo;_level3&Prime; regardless of its position. In contrast, if you&rsquo;re working in a SWF and using &ldquo;_root&rdquo;, your code will refer to the main timeline of the current &ldquo;_level&rdquo;. Where the use of &ldquo;_level&rdquo; will always be the same, &ldquo;_root&rdquo; changes based on where your SWF file is used. Even though both are considered &ldquo;absolute&rdquo; paths in Flash&rsquo;s ActionScript dictionary, &ldquo;_root&rdquo; in my opinion is actually a &ldquo;relative&rdquo; path based on where your clip is used. While it does always point to &ldquo;_root&rdquo; as an ideal, &ldquo;_root&rdquo; can vary based on load position.</p>
<p><strong>Understanding _global</strong></p>
<p>In contrast to &ldquo;_root&rdquo;, the &ldquo;_global&rdquo; scope never changes and, unlike the other two fore mentioned spaces, &ldquo;_global&rdquo; isn&rsquo;t a physical location. If you think of a timeline as a physical location (ie: places you can attach objects to like graphics and movieclips), &ldquo;_global&rdquo; acts differently. It&rsquo;s a name space within Flash where only code can reside. You can find a lot of articles with pros and cons to using &ldquo;_global&rdquo; but all I&rsquo;ll say here is that you can always set data within the &ldquo;_global&rdquo; space and your path will never change. Once set, anything can access that data from anywhere inside your movie. Data written to &ldquo;_global&rdquo; should be limited due to the chance of overwriting other references in that scope.</p>
<p><strong>Wrapping Up</strong></p>
<p>Portability is king. As a developer or designer, you should write code that is portable and can be reused. You don&rsquo;t need to reinvent the wheel every time you start a new project. Using relative paths and reference variables within classes and even simple pieces of Flash work enables you to reuse code that you have already written.</p>
<p>This will allow you to reuse script within different locations of different movies, as well as load those movies into others without losing functionality due to broken paths. There are many articles on what is referred to as the Singleton Pattern on the web, which some consider an alternative to &ldquo;_global&rdquo; as a reference point within class structure</p>
<p>So the next time you decide to just drop in a quick reference to &ldquo;_root&rdquo; or &ldquo;_level&rdquo; consider the file&rsquo;s future use. That quick and dirty solution can be done in a better manner and save you (or someone like me) even more time down the road. There is always a better solution to a given problem, you just need to take a moment to find it.</p>
<p>&nbsp;</p> 
      ]]></content>
    </entry>

    <entry>
      <title>PHP Regular Expression to parse image path on flickr page</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/php_regular_expression_to_parse_image_path_on_flickr_page/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.8</id>
      <published>2008-09-22T09:58:47Z</published>
      <updated>2008-11-01T12:21:48Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="PHP"
        scheme="http://www.gauravjassal.com/index.php/site/C1/"
        label="PHP" />
      <category term="Regular Expression"
        scheme="http://www.gauravjassal.com/index.php/site/C12/"
        label="Regular Expression" />
      <content type="html"><![CDATA[
       <p>Recently i wrote a function to parse image path from a flickr page without using any API. I use magical <a href="http://www.php.net/preg_match_all" target="_blank">preg_match_all</a> function in php to look for a particular tag. This <a href="http://www.php.net/preg_match_all" target="_blank">preg_match_all</a> function is so usefull you can try it for <a href="http://www.youtube.com" target="_blank">YouTube</a> too. I will post a similar function for youtube very soon. 
</p><pre name="code" class="sql">
&nbsp;   public static function getImageURL()
&nbsp;   {
&nbsp;  &nbsp;  &nbsp; $url = 'http://www.flickr.com/photos/22401332@N05/2861372233';
&nbsp;  &nbsp;  &nbsp; $pagina = @file_get_contents($url);
&nbsp;  &nbsp;  &nbsp; if (preg_match_all('!<img src="([^"]*)"\s+alt="([^"]*)"\s+title="([^"]*)"\s+width="([^"]*)"\s+height="([^"]*)"\s+onload="([^"]*)"\s+class="reflect">!Usi&#8217;,
&nbsp;  &nbsp;  &nbsp;  &nbsp;  $pagina, $info, PREG_SET_ORDER)) {
&nbsp;  &nbsp;  &nbsp;  &nbsp;  print ($info[0][0]);
&nbsp;  &nbsp;  &nbsp; }
&nbsp;   }
</pre>   
      ]]></content>
    </entry>

    <entry>
      <title>2008 Email Design Guidelines</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/2008_email_design_guidelines/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.7</id>
      <published>2008-09-19T21:02:59Z</published>
      <updated>2008-09-21T19:06:59Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="CSS"
        scheme="http://www.gauravjassal.com/index.php/site/C7/"
        label="CSS" />
      <category term="Daily Digest"
        scheme="http://www.gauravjassal.com/index.php/site/C8/"
        label="Daily Digest" />
      <content type="html"><![CDATA[
       <p>As web designers, we’ve grown pretty good at understanding how to create a modern, semantic, accessible website using XHTML and CSS. We understand what makes a good website, and how to make it happen.When it comes time to design emails though, do all the same rules apply? Are there things we should be doing specifically for email that don’t make sense on a website? In this article we’ll discuss the technical, design and information elements that make up a successful HTML email.
</p>  <p>The quick and dirty guidelines</p>

<p>If you want to dive right in and just need some direction, here’s the outline:</p>

<p>&nbsp;   * Don’t waste your readers’ time — An email inbox is a busy place, you won’t get much attention.<br />
&nbsp;   * Permission matters — Not only do you need to have permission to email people, but it helps to remind them of how they gave you permission, as specifically as you can.<br />
&nbsp;   * Relevance trumps permission — Just having permission is not enough, the content you are sending must also be relevant.<br />
&nbsp;   * Make unsubscribing easy — There’s no point emailing people who are not interested.<br />
&nbsp;   * Image blocking is common — You can’t rely on people actually seeing your images.<br />
&nbsp;   * Bring back tables — Structural tables are still often necessary for creating columns.<br />
&nbsp;   * Add inline styles — Gmail removes anything else.<br />
&nbsp;   * Don’t forget your plain text version — You can make blocks of text more readable.<br />
&nbsp;   * Meet your legal obligations — For example, CAN-SPAM for US senders.<br />
&nbsp;   * Test, test, test — It’s the only way to be confident about your design working.</p> 
      ]]></content>
    </entry>

    <entry>
      <title>Install PostgreSQL on Ubuntu</title>
      <link rel="alternate" type="text/html" href="http://www.gauravjassal.com/index.php/site/install_postgresql_on_ubuntu/" />
      <id>tag:gauravjassal.com,2008:index.php/site/index/1.5</id>
      <published>2008-08-03T18:54:35Z</published>
      <updated>2008-09-20T15:31:35Z</updated>
      <author>
            <name>Gaurav Jassal</name>
            <email>hello@gauravjassal.com</email>
                  </author>

      <category term="PostgresSQL"
        scheme="http://www.gauravjassal.com/index.php/site/C9/"
        label="PostgresSQL" />
      <content type="html"><![CDATA[
       <p>Installing Mysql is very easy just one step but postgres can mess you around,so here is the quick walk-through for installing the PostgreSQL database server and the PgAdmin administration application on Ubuntu Linux, and also set up the server so it allows access to other PC’s on your network.</p>

<p>Before we move on, this guide was tested on the current release of Ubuntu Linux, (7.10 - Gutsy Gibbon) and PostgreSQL 8.2, but it should also be applicable to older versions (of Ubuntu and PostgreSQL) and other Debian based distros.</p>  <p>Right for the basic installation, at the command-line, enter the following commands (or search for the listed packages in synaptic if you prefer that way of working):</p>

<pre name="code" class="css">
$ sudo apt-get install postgresql postgresql-client postgresql-contrib
$ sudo apt-get install pgadmin3
</pre>

<p>This installs the database server/client, some extra utility scripts and the pgAdmin GUI application for working with the database.</p>

<p>Now we need to reset the password for the ‘postgres’ admin account for the server, so we can use this for all of the system administration tasks. Type the following at the command-line (substitute in the password you want to use for your administrator account):</p>

<p>$ sudo su postgres -c psql template1<br />
template1=# ALTER USER postgres WITH PASSWORD &#8216;password&#8217;;<br />
template1=# q</p>

<p>That alters the password for within the database, now we need to do the same for the unix user ‘postgres’:</p>

<p>$ sudo passwd -d postgres<br />
$ sudo su postgres -c passwd</p>

<p>Now enter the same password that you used previously.</p>

<p>Then, from here on in we can use both pgAdmin and command-line access (as the postgres user) to run the database server. But before you jump into pgAdmin we should set-up the PostgreSQL admin pack that enables better logging and monitoring within pgAdmin. Run the following at the command-line:</p>

<p>$ sudo su postgres -c psql < /usr/share/postgresql/8.2/contrib/adminpack.sql</p>

<p>Finally, we need to open up the server so that we can access and use it remotely - unless you only want to access the database on the local machine. To do this, first, we need to edit the postgresql.conf file:</p>

<p>$ sudo gedit /etc/postgresql/8.2/main/postgresql.conf</p>

<p>Now, to edit a couple of lines in the ‘Connections and Authentication’ section…</p>

<p>Change the line:</p>

<p>#listen_addresses = &#8216;localhost&#8217;</p>

<p>to</p>

<p>listen_addresses = &#8217;*&#8217;</p>

<p>and also change the line:</p>

<p>#password_encryption = on</p>

<p>to</p>

<p>password_encryption = on</p>

<p>Then save the file and close gedit.</p>

<p>Now for the final step, we must define who can access the server. This is all done using the pg_hba.conf file.1</p>

<p>$ sudo gedit /etc/postgresql/8.2/main/pg_hba.conf</p>

<p>Comment out, or delete the current contents of the file, then add this text to the bottom of the file:</p>

<p># DO NOT DISABLE!<br />
# If you change this first entry you will need to make sure that the<br />
# database<br />
# super user can access the database using some other method.<br />
# Noninteractive<br />
# access to all databases is required during automatic maintenance<br />
# (autovacuum, daily cronjob, replication, and similar tasks).<br />
#
# Database administrative login by UNIX sockets<br />
local &nbsp; all &nbsp;  &nbsp;  &nbsp; postgres &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;   ident sameuser<br />
# TYPE  DATABASE &nbsp;  USER &nbsp;  &nbsp;   CIDR-ADDRESS &nbsp;  &nbsp;  &nbsp;  METHOD</p>

<p># &#8220;local&#8221; is for Unix domain socket connections only<br />
local &nbsp; all &nbsp;  &nbsp;  &nbsp; all &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp;  md5<br />
# IPv4 local connections:<br />
host &nbsp;  all &nbsp;  &nbsp;  &nbsp; all &nbsp;  &nbsp;  &nbsp; 127.0.0.1/32 &nbsp;  &nbsp;  &nbsp;  md5<br />
# IPv6 local connections:<br />
host &nbsp;  all &nbsp;  &nbsp;  &nbsp; all &nbsp;  &nbsp;  &nbsp; ::1/128 &nbsp;  &nbsp;  &nbsp;  &nbsp;  &nbsp; md5</p>

<p># Connections for all PCs on the subnet<br />
#
# TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD<br />
host &nbsp;  all &nbsp;  &nbsp;  &nbsp; all &nbsp;  &nbsp;  &nbsp; [ip address]&nbsp;  &nbsp;  &nbsp;   [subnet mask]&nbsp; md5</p>

<p>and in the last line, add in your subnet mask (i.e. 255.255.255.0) and the IP address of the machine that you would like to access your server (i.e. 138.250.192.115). However, if you would like to enable access to a range of IP addresses, just substitute the last number for a zero and all machines within that range will be allowed access (i.e. 138.250.192.0 would allow all machines with an IP address 138.250.192.x to use the database server).</p>

<p>That’s it, now all you have to do is restart the server:</p>

<p>$ sudo /etc/init.d/postgresql-8.2 restart</p>

<p>And all should be working. </p> <p>Right for the basic installation, at the command-line, enter the following commands (or search for the listed packages in synaptic if you prefer that way of working):</p>
      ]]></content>
    </entry>


</feed>