<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://rss.anjanesh.net/~d/styles/itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-7869472979536208643</atom:id><lastBuildDate>Thu, 25 Feb 2010 04:30:34 +0000</lastBuildDate><title>Code</title><description>Coding, Programming &amp; Algorithms, Tips, Tweaks &amp; Hacks</description><link>http://code.anjanesh.net/</link><managingEditor>anjanesh@anjanesh.com (Anjanesh)</managingEditor><generator>Blogger</generator><openSearch:totalResults>15</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://rss.anjanesh.net/anjanesh/code" /><feedburner:info uri="anjanesh/code" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-8461333669567523678</guid><pubDate>Sun, 24 Jan 2010 19:14:00 +0000</pubDate><atom:updated>2010-01-25T00:47:37.965+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>One-liner check for the existence of all required fields from a POSTed form</title><description>&lt;p&gt;If you have a simple contact / registration form for a non-CMS / non-framework website with many input fields, it becomes cumbersome to do a server check if all fields passed through doing isset for every field. Many people just check for the existance of a single POST field, but for security reasons, it is better to check for the existence of all required fields.&lt;/p&gt;
&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;if (isset($_POST['name']) &amp;&amp; isset($_POST['email']) &amp;&amp; isset($_POST['phone']) &amp;&amp; isset($_POST['message']))
{
    # POSTed
    # Process form
}&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP&lt;/dfn&gt;&lt;/fieldset&gt;
&lt;p&gt;What if there were 20 fields ? That'll be one long line of &lt;i&gt;isset&lt;/i&gt;s.&lt;br/&gt;
&lt;a href="http://php.net/array_diff"&gt;array_diff&lt;/a&gt; is a built-in array function in PHP that computes the difference between arrays - it returns an array containing all the entries from the first array  that are not present in any of the other arrays.&lt;br/&gt;
All we need to check is if the list of required fields are all present as &lt;i&gt;keys&lt;/i&gt; in &lt;b&gt;$_POST&lt;/b&gt; - this is easily achievable by checking against &lt;a href="http://php.net/array_keys"&gt;array_keys&lt;/a&gt; of &lt;b&gt;$_POST&lt;/b&gt;.&lt;br/&gt;
And finally for the count - if all required fields are present in the &lt;b&gt;$_POST&lt;/b&gt;'s &lt;i&gt;keys&lt;/i&gt;, it'll return 0 which is what we want and how we can confirm that all POST field values got sent through.&lt;/p&gt;
&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;$requiredFields = array('name','email','phone','message');
if (count(array_diff($requiredFields, array_keys($_POST))) == 0)
{
    # POSTed
    # Process form
}&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-8461333669567523678?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/ftsKOX9CBAk" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/ftsKOX9CBAk/one-liner-check-for-existence-of-all.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2010/01/one-liner-check-for-existence-of-all.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-1608370116214083374</guid><pubDate>Sat, 21 Nov 2009 16:38:00 +0000</pubDate><atom:updated>2009-11-21T23:02:26.470+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python2's String = Python3's Text Vs. Data</title><description>A significant change from Python 2 to Python 3 is the way strings are dealt with.&lt;br/&gt;Python 3 doesnt always return a string when expected.&lt;br/&gt;For example, the return type of read() in version 2 has always been a string. But in version 3, its very often a "bytes" string.&lt;br/&gt;When you print a "bytes" string, you'll see every character in its byte format, special characters as escape secquences (newline as \n) and other unicode characters as escape sequences.&lt;br/&gt;This is because Python 3 differentiates between text (string) and data ("bytes" string) as oppossed to Unicode vs 8-bit string. (&lt;a href="http://docs.python.org/3.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit" target="_blank"&gt;Text Vs. Data Instead Of Unicode Vs. 8-bit&lt;/a&gt;)&lt;br/&gt;&lt;br/&gt;My localhost/index.html contains just this :&lt;br/&gt;&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;h1&amp;gt;It works!. st&amp;#228;rke gl&amp;#228;ser&amp;lt;/h1&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;br/&gt;&lt;br/&gt;&lt;fieldset&gt;&lt;legend&gt;Python 2.x&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;import urllib

url = "http://localhost"&lt;br/&gt;fp = urllib.urlopen(url)&lt;br/&gt;data = fp.read()&lt;br/&gt;print "%s, %s" % (type(data), type(data).__name__)&lt;br/&gt;print data&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 2.6.4&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;Python 2.x&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;~$ python&lt;br/&gt;Python 2.6.4 (r264:75706, Nov  2 2009, 14:44:17)&lt;br/&gt;[GCC 4.4.1] on linux2&lt;br/&gt;Type "help", "copyright", "credits" or "license" for more information.&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; import urllib&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; url = "http://localhost"&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; fp = urllib.urlopen(url)&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; data = fp.read()&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; print "%s, %s" % (type(data), type(data).__name__)&lt;br/&gt;&amp;lt;type 'str'&amp;gt;, str&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; print data&lt;br/&gt;&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;h1&amp;gt;It works!. st&amp;#228;rke gl&amp;#228;ser&amp;lt;/h1&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;br/&gt;&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 2.6.4&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;In Python 3, we need to need to explicitly convert it to string format via the str() function and specify the encoding-type.&lt;br/&gt;If you are getting errors using Python 3.0, you may want to update to atleast Python 3.0.1 - many have reported possible Unciode encoding/decoding bugs in 3.0.&lt;br/&gt;&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;Python 3.x&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;import urllib.request

url = "http://localhost"&lt;br/&gt;fp = urllib.request.urlopen(url)&lt;br/&gt;data = fp.read()&lt;br/&gt;print ("%s, %s" % (type(data), type(data).__name__))&lt;br/&gt;print (data)&lt;br/&gt;data = str(data,'utf-8') # convert a byte datatype to string datatype using utf-8 encoding. For ASCII, data = str(data,'ascii')&lt;br/&gt;print (data)&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 3.1.1&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;Python 3.x&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;~$ python3&lt;br/&gt;Python 3.1.1+ (r311:74480, Oct 12 2009, 02:14:03)&lt;br/&gt;[GCC 4.4.1] on linux2&lt;br/&gt;Type "help", "copyright", "credits" or "license" for more information.&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; import urllib.request&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; url = "http://localhost"&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; fp = urllib.request.urlopen(url)&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; data = fp.read()&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; print ("%s, %s" % (type(data), type(data).__name__))&lt;br/&gt;&amp;lt;class 'bytes'&amp;gt;, bytes&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; print (data)&lt;br/&gt;b'&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;h1&amp;gt;It works!. st\xc3\xa4rke gl\xc3\xa4ser&amp;lt;/h1&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;\n'&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; data = str(data,'utf-8') # convert a byte datatype to string datatype using utf-8 encoding. For ASCII, data = str(data,'ascii')&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt; print (data)&lt;br/&gt;&amp;lt;html&amp;gt;&amp;lt;body&amp;gt;&amp;lt;h1&amp;gt;It works!. st&amp;#228;rke gl&amp;#228;ser&amp;lt;/h1&amp;gt;&amp;lt;/body&amp;gt;&amp;lt;/html&amp;gt;&lt;br/&gt;&lt;br/&gt;&amp;gt;&amp;gt;&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 3.1.1&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-1608370116214083374?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/Ix2iFKAkvSg" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/Ix2iFKAkvSg/python2s-string-python3s-text-vs-data.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2009/11/python2s-string-python3s-text-vs-data.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-3109435950736710244</guid><pubDate>Wed, 15 Jul 2009 09:19:00 +0000</pubDate><atom:updated>2009-07-15T14:51:58.792+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">MySQL</category><title>Sorting a String in SQL</title><description>Even though stored procedures are really slow, sometimes they come in handy.
&lt;fieldset&gt;&lt;legend&gt;SQL&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;DROP FUNCTION IF EXISTS `SORTEDSTRING`;
DELIMITER ///
CREATE FUNCTION SORTEDSTRING(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
BEGIN
    DECLARE i INT DEFAULT 1;
    DECLARE j INT;
    DECLARE si CHAR(1);
    DECLARE sj CHAR(1);
    DECLARE ss VARCHAR(1000); -- Sorted String

    SET ss = s;
    SET @length = LENGTH(s);

    WHILE i &lt; @length DO
        SET j = i + 1;
        WHILE j &lt;= @length DO
            SET si = SUBSTRING(ss, i, 1);
            SET sj = SUBSTRING(ss, j, 1);
            IF si &gt; sj THEN
                SET ss = INSERT(ss, i, 1, sj);
                SET ss = INSERT(ss, j, 1, si);
            END IF;
            SET j = j + 1;
        END WHILE;
        SET i = i + 1;
    END WHILE;

    RETURN ss;
END
///
DELIMITER ;

mysql&gt; SELECT SORTEDSTRING("elephant");
+--------------------------+
| SORTEDSTRING("elephant") |
+--------------------------+
| aeehlnpt                 |
+--------------------------+
1 row in set (0.00 sec)

mysql&gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;MySQL 5.0&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-3109435950736710244?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/5gz_xEvVGwE" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/5gz_xEvVGwE/sorting-string-in-sql.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2009/07/sorting-string-in-sql.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-6289871592571597742</guid><pubDate>Mon, 13 Jul 2009 16:56:00 +0000</pubDate><atom:updated>2009-07-13T22:41:06.102+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><title>Loading AJAX locally, without a webserver</title><description>So far, while developing web applications I have always taken one point into assumption - that it has to run on a web-server.
But when dealing with pure client-side web apps, we often overlook the fact that it should be able to be run by simply double-clicking on the homepage file (index.html).
When &lt;a href="http://en.wikipedia.org/wiki/XMLHttpRequest" target="_blank"&gt;XMLHttpRequest's&lt;/a&gt; &lt;span style="font-family:Monospace"&gt;readyState&lt;/span&gt; reaches a value of 4, we further check for a response code 200 from the web-server before doing anything with the &lt;span style="font-family:Monospace"&gt;responseText&lt;/span&gt; / &lt;span style="font-family:Monospace"&gt;responseXML&lt;/span&gt;. But when running it locally - not on a webserver, the &lt;span style="font-family:Monospace"&gt;status&lt;/span&gt; code value will alway be 0.
&lt;fieldset&gt;&lt;legend&gt;JavaScript&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;window.onload = function()
{
    var xhr = NewXMLHttpRequest();
    if (xhr != false)
    {
        try
        {
            xhr.open("GET", "local-ajax.txt", true);
            xhr.onreadystatechange = xhr_load;
            xhr.setRequestHeader("Connection", "close");
            xhr.send(null);
        }
        catch(e)
        {
            alert("Error Loading File\n" + e.code + "\n" + e.message);
        }
    }
    else
    {
        alert("AJAX not supported");
    }
}

function xhr_load()
{
    switch (this.readyState)
    {
        case 1: // Open
        case 2: // Send
        case 3: // Receiving
        break;

        case 4: // Loaded
        if (this.status == 200 || (this.status == 0 &amp;&amp; document.location.protocol == "file:")) // OK
        {
            var text = this.responseText;
            alert(text);
        }
        break;
    }
}

function NewXMLHttpRequest()
{
    var xhr = false;

    if (window.XMLHttpRequest) // native XMLHttpRequest object
    {
        try { xhr = new XMLHttpRequest(); }
        catch(e) { xhr = false; }
    }
    else if (window.ActiveXObject) // IE/Windows ActiveX version
    {
        try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e)
        {
            try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch(e) { xhr = false; }
        }
    }

    return xhr;
}&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JavaScript 1.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-6289871592571597742?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/6ic1o4srE4c" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/6ic1o4srE4c/loading-ajax-locally-without-webserver.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2009/07/loading-ajax-locally-without-webserver.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-8737681185097054139</guid><pubDate>Sat, 23 May 2009 13:26:00 +0000</pubDate><atom:updated>2009-05-25T18:45:30.939+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">Canvas</category><category domain="http://www.blogger.com/atom/ns#">HTML</category><title>1 pixel wide line parallel to the axis in HTML's Canvas element</title><description>I was playing around with HTML's Canvas element and I spent a whole day trying to figure out why I can't draw a 1-pixel wide straight line (parallel to the axes).
If you try dawing a black (#000000) straight line parallel to the axes, then for all odd numbered widths :
&lt;ul&gt;&lt;li&gt;the first line is of colour #9d9d9d and the last one is of #8d8d8d&lt;/li&gt;&lt;li&gt;The width of the line is one pixel more&lt;/li&gt;&lt;/ul&gt;&lt;fieldset&gt;&lt;legend&gt;Canvas Lines&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
        &amp;lt;meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/&amp;gt;
        &amp;lt;title&amp;gt;HTML5 - Canvas&amp;lt;/title&amp;gt;
        &amp;lt;meta http-equiv="Content-Language" content="en-us"/&amp;gt;
        &amp;lt;script type="text/javascript"&amp;gt;
        function foo()
        {
            var canvas = document.getElementById("canvas-line");
            var ctx = canvas.getContext('2d');
            
            for (i = 1, j = 0; i &amp;lt; 15; i++, j+=i+7)
            {
                ctx.beginPath();
                ctx.lineWidth = i;
                ctx.strokeStyle = "black";
                ctx.moveTo(50,25 + j);
                ctx.lineTo(300,25 + j);
                ctx.stroke();
            }
        }

        &amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body onload="foo()"&amp;gt;
&amp;lt;canvas id="canvas-line" width="350" height="250" style="border:1px solid #cf1313; margin-left:100px;"&amp;gt;&amp;lt;/canvas&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;HTML 5 + JavaScript&lt;/dfn&gt;&lt;/fieldset&gt;The above should give an output like this :

&lt;img src="http://i81.photobucket.com/albums/j212/anjanesh/code/canvas-lines.gif" alt="" /&gt;

If you zooom in, you should be able to see the top and bottom border colours.

&lt;img src="http://i81.photobucket.com/albums/j212/anjanesh/code/canvas-line.gif" alt="" /&gt;

This happens in all canvas-supported browsers (FF 3, FF 3.5 beta 4, Opera 10 beta, Chrome 2 beta, Safari 4 beta).
Reason : &lt;a href="https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors#section_8"&gt;https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors#section_8&lt;/a&gt;
Mozilla's canvas tutorial on &lt;a href="https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes#section_4" target="_blank"&gt;drawing shapes&lt;/a&gt; shows a screenshot which has the inner most rectangle of exactly 1 pixel wide and colour black. But viewing the &lt;a href="https://developer.mozilla.org/samples/canvas-tutorial/2_1_canvas_rect.html" target="_blank"&gt;example&lt;/a&gt; itself in the browser, shows otherwise - 2 pixel wide with faded colours.

I've written a small function that draws exactly 1 pixel wide straight line parallel to the axis.

&lt;fieldset&gt;&lt;legend&gt;1 pixel wide Canvas line&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
        &amp;lt;meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"/&amp;gt;
        &amp;lt;title&amp;gt;HTML5 - Canvas&amp;lt;/title&amp;gt;
        &amp;lt;meta http-equiv="Content-Language" content="en-us"/&amp;gt;
        &amp;lt;script type="text/javascript"&amp;gt;
        /*
        draw1pxLinePA
            Draw a 1 pixel width line parallel to the axis
        Parameters
            x : x coordinate
            y : y coordinate
            l : length
            o : orientation
                0 = horizontal (default)
                1 = vertical
            bg : erase-with colour - for background
        */
        CanvasRenderingContext2D.prototype.draw1pxLinePA = function(x, y, l, o, bg)
        {
            o = o || 0;
            bg = bg || "white";

            this.beginPath();
            this.lineWidth = 2; // 1 creates a 2 pixel wide line with fading
            this.moveTo(x, y);
            this.lineTo(x + (l * !o), y + (l * o));
            this.stroke();

            var strokeStyle = this.strokeStyle; // Save current strokeStyle

            // Erase the extra line
            this.beginPath();
            this.lineWidth = 2;
            this.strokeStyle = bg;
            this.moveTo(x + (1 * o), y + (1 * !o));
            this.lineTo(x + (l * !o) + (1 * o), y + (l * o) + (1 * !o));
            this.stroke();

            this.strokeStyle = strokeStyle; // Restore strokeStyle
        }

        function foo()
        {
            var canvas = document.getElementById("canvas-line");
            var ctx = canvas.getContext('2d');

            ctx.strokeStyle = "black";
            ctx.draw1pxLinePA(20, 20, 260, 1);
            ctx.draw1pxLinePA(30, 150, 400);
        }

        &amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body onload="foo()"&amp;gt;

&amp;lt;canvas id="canvas-line" width="450" height="300" style="border:1px solid #cf1313; margin-left:100px;"&amp;gt;&amp;lt;/canvas&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;HTML 5 + JavaScript&lt;/dfn&gt;&lt;/fieldset&gt;
&lt;img src="http://i81.photobucket.com/albums/j212/anjanesh/code/canvas-1px-line.gif" alt="" /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-8737681185097054139?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/whiIFoKSR34" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/whiIFoKSR34/1-pixel-wide-line-parallel-to-axis-in.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://code.anjanesh.net/2009/05/1-pixel-wide-line-parallel-to-axis-in.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-2835223677868688370</guid><pubDate>Mon, 25 Feb 2008 09:27:00 +0000</pubDate><atom:updated>2009-06-06T00:24:26.204+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">php</category><title>Property getters &amp; setters</title><description>&lt;p&gt;In traditional OOP, if we wanted to get or set an object's private member, we would need to write a public method to do the job.&lt;br/&gt;The reason behind making a member data private and then accessing it through a public method is to avoid the implementing-user to access it directly.&lt;br/&gt;There can be many reasons for prohibiting direct access to member data to the implementing-code.&lt;br/&gt;For example, you may want a radius of a Circle to be within the range of 10 - 500.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;C++: Traditional OOP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;class Circle
 {
        private:
          int radius;

        public:
          Circle(int radius = 15)
           {
                  setRadius(radius);
           }

          void setRadius(int radius)
           {
                  if (radius &lt; 10 || radius &gt; 500)
                   {
                          this-&gt;radius = -1;
                          cout &lt;&lt; "Radius must be within the range of 10 - 500" &lt;&lt; endl;
                   }
                  else
                   this-&gt;radius = radius;
           }

          int getRadius()
           {
                  return this-&gt;radius;
           }
 }

void main()
 {
        Circle c = Circle();
        c.setRadius(25);
        cout &lt;&lt; c.getRadius();
 }
&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;C++&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;In languages like PHP &lt;span style="text-decoration:line-through"&gt;&amp;amp; Python&lt;/span&gt; &amp;amp; PERL which have a weak type system, a further check of the data type may be necessary.&lt;br/&gt;But for Python unfortunately even traditional getter &amp;amp; setter methods cannot be implemted because Python doesn't have a public or private. Everything is public by default - though a member can be made private by prefixing two underscores to it. But this is only for convention, it doesn't really serve its true purpose.&lt;br/&gt;&lt;br/&gt;PHP 5 and C# .NET have a getter and setter method feature, making it look like we're accessing the data member directly.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
class Circle
 {
        private $radius; # integer

        # Constructor
        public function __construct($radius = 15)
         {
                self::__set('radius', $radius);
         }

        # Setter
        public function __set($name, $value)
         {
                switch ($name)
                 {
                        case 'radius':

                          if (!is_numeric($value)) # is_int() for strong type checking
                           throw new Exception('Radius must be of a numeric type');

                          if ($value &lt; 10 || $value &gt; 500)
                           throw new Exception('Radius must be within the range of 10 - 500');

                          $this-&gt;radius = $value;

                        break;

                        default:
                          throw new Exception("Attempt to set a non-existing property: $name");
                        break;
                 }
         }

        # Getter
        public function __get($name)
         {
                if (in_array($name, array('radius')))
                 return $this-&gt;$name;

                switch ($name)
                 {
                        default:
                          throw new Exception("Attempt to get a non-existing property: $name");
                        break;
                 }
         }

 }

$c = new Circle();
$c-&gt;radius = 25;
echo $c-&gt;radius;
&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.x&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;C#&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;using System;

public class Circle
 {
        private int __radius = 5;

        public Circle()
         {
         }

        public Circle(int radius)
         {
                this.radius = radius; // This will call the property defined below
         }

        public int radius // Property getter/setter name cannot be the same as the member variable name
         {
                get
                 {
                        return __radius;
                 }

                set
                 {
                        if (value &lt; 10 || value &gt; 500)
                         throw new Exception("Radius must be within the range of 10 - 500");

                        __radius = value;
                 }
         }
 }

public class main
 {
        public static void Main(string[] args)
         {
                Circle c = new Circle(); // Circle c = new Circle(5); will throw an Exception
                c.radius = 25;
                Console.WriteLine(c.radius);
         }
 }&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;.NET 2.0&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;C# .NET 3.0 has introduced &lt;a href="http://msdn2.microsoft.com/en-us/library/bb384054.aspx"&gt;Automatic Properties&lt;/a&gt; where you don't need to specify code for the getter &amp;amp; setter - the compiler takes generates the method body.&lt;br/&gt;&lt;br/&gt;JavaScript does seem to have a &lt;a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters"&gt;getter and setter method&lt;/a&gt; which I came across just now when searching for the official source to Java 7's new features' documentation, but : &lt;ul&gt;&lt;li&gt;only within an object initializer - not inside a function so it doesn't seem to be of much use as we can't create instances&lt;/li&gt;&lt;li&gt;doesn't hide the member from being accessed directly&lt;/li&gt;&lt;li&gt;doesn't work in IE.&lt;/li&gt;&lt;/ul&gt;&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;JavaScript&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;var someObj =
 {
        a : 7,
        get b()
         {
                return this.a * 3;
         },
        set c(x)
         {
                this.a = x / 2;
         }
 }

someObj.foo1 = function()
 {
        //
 }

alert(someObj.a); // 7
alert(someObj.b); // 21
someObj.c = 5; alert(someObj.a); // 2.5
someObj.foo1();&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JavaScript 1.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;The Getter &amp;amp; Setter feature does not seem to be a much "wanted" feature in the Java community.&lt;br/&gt;Still, this has been proposed by &lt;a href="http://weblogs.java.net/blog/forax/archive/2007/01/property_reload.html"&gt;Rémi Forax&lt;/a&gt; for JDK 7.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;Java: Proposal&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;public class Circle
 {
        private int __radius = 5;

        public Circle()
         {
         }

        public Circle(int radius)
         {
                this.radius = radius; // This will call the property defined below
         }

        public property int radius // Property getter/setter name cannot be the same as the member variable name
         {
                get
                 {
                        return __radius;
                 }

                set (int radius)
                 {
                        if (radius &lt; 10 || radius &gt; 500)
                         throw new Exception("Radius must be within the range of 10 - 500");

                        __radius = radius;
                        // firePropertyChange(radius);
                 }
         }

        public static void main(String[] args)
         {
                Circle c = new Circle(2); // Circle c = new Circle(5); will throw an Exception
                c.radius = 25;
                System.out.println(c.radius);
         }
 }&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JDK 7&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-2835223677868688370?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/rXVSq5szd_4" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/rXVSq5szd_4/property-getters-setters.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2008/02/property-getters-setters.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-622895424704792600</guid><pubDate>Wed, 26 Dec 2007 16:23:00 +0000</pubDate><atom:updated>2007-12-26T22:03:58.430+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Python's Classmethods</title><description>&lt;p&gt;Lets say I have an abstract class called &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; and 3 classes that descend from it are &lt;span class="code-class"&gt;Bike&lt;/span&gt;, &lt;span class="code-class"&gt;Car&lt;/span&gt; &amp; &lt;span class="code-class"&gt;Truck&lt;/span&gt;.&lt;br/&gt;I use a static variable in &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; called &lt;span class="code-static-var"&gt;total&lt;/span&gt; to keep track of the total number of &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;s. But I really don't want to keep track of the total number general &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;s. What I really want is to keep track of the total number of  &lt;span class="code-class"&gt;Bike&lt;/span&gt;s, &lt;span class="code-class"&gt;Car&lt;/span&gt;s &amp;amp; &lt;span class="code-class"&gt;Truck&lt;/span&gt;s individually. This is easy - just declare &lt;span class="code-static-var"&gt;total&lt;/span&gt; in &lt;span class="code-class"&gt;Bike&lt;/span&gt;, &lt;span class="code-class"&gt;Car&lt;/span&gt; &amp;amp; &lt;span class="code-class"&gt;Truck&lt;/span&gt; classes.&lt;/p&gt;&lt;p&gt;Now arises a situation where we need a function &lt;span class="code-function"&gt;println&lt;/span&gt; in &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; that accesses &lt;span class="code-static-var"&gt;total&lt;/span&gt;. We'll also include a function called &lt;span class="code-function"&gt;set&lt;/span&gt; in &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; to explicitly set the value of &lt;span class="code-static-var"&gt;total&lt;/span&gt; (instead of creating 10 instances to prove a point).&lt;/p&gt;&lt;p&gt;There are two scenarios to this, both of which are not possible :&lt;/p&gt;&lt;ol&gt;&lt;li&gt;Declare a static variable &lt;span class="code-static-var"&gt;total&lt;/span&gt; in &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; but different values persist in &lt;span class="code-class"&gt;Bike&lt;/span&gt;::&lt;span class="code-static-var"&gt;total&lt;/span&gt;, &lt;span class="code-class"&gt;Car&lt;/span&gt;::&lt;span class="code-static-var"&gt;total&lt;/span&gt; &amp;amp; &lt;span class="code-class"&gt;Truck&lt;/span&gt;::&lt;span class="code-static-var"&gt;total&lt;/span&gt;. This is impossible because &lt;span class="code-static-var"&gt;total&lt;/span&gt; is &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;'s static variable which is common to all. The following will output 2 2 2.&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
abstract class Vehicle
 {
        protected static $total;

        public static function println()
         {
                echo self::$total."\n";
         }

        public static function set($value)
         {
                self::$total = $value;
         }
 }

class Bike extends Vehicle
 {
 }

class Car extends Vehicle
 {
 }

class Truck extends Vehicle
 {
 }

Bike::set(3);
Car::set(5);
Truck::set(2);

$b = new Bike();
$c = new Car();
$t = new Truck();

Bike::println()
Car::println()
Truck::println()

// Is there any way for Bike's static variable to hold 3 and Car's static to hold 5 &amp; Truck's static to hold 2 ?
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.2.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;/li&gt;&lt;li&gt;Declare the static variable &lt;span class="code-static-var"&gt;total&lt;/span&gt; in each of &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;'s subclasses, &lt;span class="code-class"&gt;Bike&lt;/span&gt;, &lt;span class="code-class"&gt;Car&lt;/span&gt; &amp; &lt;span class="code-class"&gt;Truck&lt;/span&gt;. But in this case, &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;'s &lt;span class="code-function"&gt;println&lt;/span&gt; needs to access the descendant class static variable like child::&lt;span class="code-static-var"&gt;total&lt;/span&gt; which is not possible in most(all) languages.&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
abstract class Vehicle
 {
        public static function println()
         {
                echo child::$total."\n";
         }

        public static function set($value)
         {
                child::$total = $value;
         }
 }

class Bike extends Vehicle
 {
        public static $total; # Should've been protected, but then parent wouldn't able to access
 }

class Car extends Vehicle
 {
        public static $total;
 }

class Truck extends Vehicle
 {
        public static $total;
 }

Bike::set(3);
Car::set(5);
Truck::set(2);

$b = new Bike();
$c = new Car();
$t = new Truck();

Bike::println();
Car::println();
Truck::println();
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.2.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;br/&gt;It is possible to overcome this problem by setting and getting the value in the subclasses and use $this-&amp;gt;&lt;span class="code-function"&gt;childMethod()&lt;/span&gt; in the parent class, &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;.&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
abstract class Vehicle
 {
        public function set($value)
         {
                $this-&amp;gt;setChildValue($value);
         }

        public function println()
         {
                echo $this-&amp;gt;getChildValue()."\n";
         }
 }

class Bike extends Vehicle
 {
        protected static $total;

        public function getChildValue()
         {
                return self::$total;
         }

        public function setChildValue($value)
         {
                self::$total = $value;
         }
 }

class Car extends Vehicle
 {
        protected static $total;

        public function getChildValue()
         {
                return self::$total;
         }

        public function setChildValue($value)
         {
                self::$total = $value;
         }
 }

class Truck extends Vehicle
 {
        protected static $total;

        public function getChildValue()
         {
                return self::$total;
         }

        public function setChildValue($value)
         {
                self::$total = $value;
         }
 }

$b = new Bike();  $b-&amp;gt;set(3);
$c = new Car();   $c-&amp;gt;set(5);
$t = new Truck(); $t-&amp;gt;set(2);

$b-&amp;gt;println();
$c-&amp;gt;println();
$t-&amp;gt;println();
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.2.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;But the two methods, &lt;span class="code-function"&gt;getChildValue&lt;/span&gt; and &lt;span class="code-function"&gt;setChildValue&lt;/span&gt; must be defined properly in all subclasses.&lt;br/&gt;__CLASS__ returns the class in which its called from and &lt;span class="code-function"&gt;get_class($this)&lt;/span&gt; returns the class of the current instance.&lt;br/&gt;Example : &lt;span class="code-line"&gt;echo __CLASS__;&lt;/span&gt; in a method in &lt;span class="code-class"&gt;Vehicle&lt;/span&gt; will always output Vehicle, but &lt;span class="code-function"&gt;get_class($this)&lt;/span&gt; will output the classname of the object (In this case, &lt;span class="code-class"&gt;Bike&lt;/span&gt;, &lt;span class="code-class"&gt;Car&lt;/span&gt; or &lt;span class="code-class"&gt;Truck&lt;/span&gt;).&lt;br/&gt;If we could do &lt;span class="code-line"&gt;get_class($this)::$total&lt;/span&gt; (Bike::$total), then it could've been easily solved.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
abstract class Vehicle
 {
        public function set($value)
         {
                get_class($this)::$total = $value;
         }

        public function println()
         {
                echo get_class($this)::$total."\n";
         }
 }

class Bike extends Vehicle
 {
        public static $total;
 }

class Car extends Vehicle
 {
        public static $total;
 }

class Truck extends Vehicle
 {
        public static $total;
 }

$b = new Bike();  $b-&amp;gt;set(3);
$c = new Car();   $c-&amp;gt;set(5);
$t = new Truck(); $t-&amp;gt;set(2);

$b-&amp;gt;println();
$c-&amp;gt;println();
$t-&amp;gt;println();
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.2.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;The last method is possible in Python in two ways - self.__class__.total &amp;amp; classmethod. Python has a way to access class member of the caller's class, not just the class members in which its being accessed. Here each of the subclasses have a static member called &lt;span class="code-static-var"&gt;total&lt;/span&gt; which gets created and assigned in its parent, &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;Python : Using __class__&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;class Vehicle:

      def println(self):
          print self.__class__.total

      def set(self, value):
          self.__class__.total = value

class Bike(Vehicle):
          pass

class Car(Vehicle):
          pass

class Truck(Vehicle):
          pass

Bike().set(3)   # Bike.total = 3
Car().set(5)    # Car.total = 5
Truck().set(2)  # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 2.5.1&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;Python : Using classmethod&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;class Vehicle:

      @classmethod
      def println(cls):
          print cls.total

      @classmethod
      def set(cls, value):
          cls.total = value

class Bike(Vehicle):
          pass

class Car(Vehicle):
          pass

class Truck(Vehicle):
          pass

Bike.set(3)   # Bike.total = 3
Car.set(5)    # Car.total = 5
Truck.set(2)  # Truck.total = 2

b = Bike()
c = Car()
t = Truck()

b.println()
c.println()
t.println()

Bike.println()
Car.println()
Truck.println()&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 2.5.1&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;self.__class__.total points to the static member &lt;span class="code-static-var"&gt;total&lt;/span&gt; of the object's (this) class and not of the class &lt;span class="code-class"&gt;Vehicle&lt;/span&gt;.&lt;br/&gt;cls.total references the same thing as the first argument is actually the classname which is not passed in the parentheses, but by using the classname preceding the dot.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-622895424704792600?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/Rq_oiCnvpxs" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/Rq_oiCnvpxs/python-classmethods.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/12/python-classmethods.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-870464040635025101</guid><pubDate>Fri, 21 Dec 2007 08:21:00 +0000</pubDate><atom:updated>2007-12-22T23:14:27.203+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">MySQL</category><title>Export MySQL data to Excel compatible CSV format</title><description>&lt;p&gt;One of the most often used feature in front-end GUI tools like phpMyAdmin is to export your data to an Microsoft Excel compatible CSV format. Excel compatible because, CSV functions in Python, PHP, Java or C# can read CSV files created using Excel. Because there is no CSV standard, we'll use Microsoft Excel's CSV format. Microsoft Excel uses 2 double-quotes to indicate a double-quote within a column-value enclosed by double-quotes.&lt;br/&gt;For example, a &lt;b&gt;Hello"World&lt;/b&gt; in Excel is internally &lt;b&gt;"Hello""World"&lt;/b&gt; if you open the file in Notepad.&lt;/p&gt;&lt;p&gt;When you're dealing with large sets of data, its better to use MySQL in command-line mode for export. A stand-alone Py/PHP/Java script may do the job but it would still be faster in MySQL command-line mode.&lt;/p&gt;&lt;p&gt;Lets take a simple person-info table type as an example. `persons` is a table in database `community`.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;MySQL&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;CREATE TABLE IF NOT EXISTS `persons` (
  `ID` bigint(20) NOT NULL auto_increment,
  `Name` varchar(255) NOT NULL,
  `Address` varchar(255) NOT NULL,
  `City` varchar(255) NOT NULL,
  `State` varchar(255) NOT NULL,
  `Zip` varchar(255) NOT NULL,
  `Phone` varchar(255) NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;MySQL 5.0.45&lt;/dfn&gt;&lt;/fieldset&gt;&lt;ol&gt;&lt;li&gt;&lt;h3 style="font-size:16px; text-decoration:underline;"&gt;mysqldump&lt;/h3&gt;&lt;p&gt;Dumping SQL via the mysqldump command-line tool is the most common use for database backup. Using mysqldump, it &lt;i&gt;is&lt;/i&gt; possible to export to CSV but there are some limitations :&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Its not possible to select columns, so you end up exporting all columns. And I can't see options for columns in the newer versions, &lt;a href="http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html" target="_blank"&gt;5.1&lt;/a&gt; or &lt;a href="http://dev.mysql.com/doc/refman/6.0/en/mysqldump.html" target="_blank"&gt;6.0&lt;/a&gt;, so I guess theres no way out here.&lt;/li&gt;&lt;li&gt;When exporting to CSV format, we indicate the column data is to be seperated by a comma by specifying options such as &lt;span class="cmd-line-option"&gt;--fields-terminated-by=","&lt;/span&gt;. When using &lt;span class="cmd-line-option"&gt;--fields-xx&lt;/span&gt; options, its mandatory to use the &lt;span class="cmd-line-option"&gt;--tab=&amp;lt;dir name&amp;gt;&lt;/span&gt; option which specifies the folder to dump to. &lt;span class="cmd-line-option"&gt;--tab&lt;/span&gt; accepts a foldername because it'll export the tables in a separate file text format to that folder. Even if we select only one table to dump, it'll still have to dump to the specified folder. So we can't output to a file by using pipe (&lt;span class="cmd-line-option"&gt;mysqldump ... &amp;gt; los-angeles-persons.csv&lt;/span&gt;).&lt;br/&gt;&lt;u&gt;Note:&lt;/u&gt; &lt;span class="cmd-line-option"&gt;--result-file=&amp;lt;filename&amp;gt;&lt;/span&gt; option is used to output to a specified file but not in conjunction with the &lt;span class="cmd-line-option"&gt;--tab&lt;/span&gt; option.&lt;/li&gt;&lt;li&gt;Its not possible to sort the result, expect by the PK (Primary Key) column by specifying the &lt;span class="cmd-line-option"&gt;--order-by-primary&lt;/span&gt; option.&lt;/li&gt;&lt;/ul&gt;&lt;pre class="cmd-line"&gt;&lt;code&gt;mysqldump community persons --user=root --where="`City` LIKE '%Los Angeles%'" --tab="csv data" --fields-terminated-by="," --fields-enclosed-by="\"" --fields-escaped-by="\"\"" --lines-terminated-by="\r\n" --no-create-db --no-create-info -p&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This will export (dump) all persons located in &lt;b&gt;Los Angeles&lt;/b&gt; into a folder named &lt;i&gt;csv data&lt;/i&gt; (an &lt;u&gt;existing folder&lt;/u&gt; relative to your current path).&lt;br/&gt;&lt;span class="cmd-line-option"&gt;--fields-escaped-by="\"\""&lt;/span&gt; : specify 2 double-quotes("") to indicate a double-quote(") - since the column values are enclosed by double-quotes(").&lt;br/&gt;Internally, this executes a SELECT INTO OUTFILE query.&lt;/p&gt;&lt;/li&gt;&lt;li&gt;&lt;h3 style="font-size:16px;; text-decoration:underline"&gt;SELECT ... INTO OUTFILE&lt;/h3&gt;&lt;p&gt;Enter mysql in command-line mode.&lt;/p&gt;&lt;pre class="cmd-line"&gt;&lt;code&gt;C:\MySQL\bin&amp;gt;mysql --user=root -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 81
Server version: 5.0.45-community-nt-log MySQL Community Edition (GPL)

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql&amp;gt; USE community;
Database changed
mysql&amp;gt; SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone`
    -&amp;gt; FROM `persons`
    -&amp;gt; WHERE `City` LIKE '%Los Angeles%'
    -&amp;gt; ORDER BY `Name` ASC, `Zip` ASC
    -&amp;gt; INTO OUTFILE 'los-angeles-persons.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';
Query OK, 299 rows affected (0.05 sec)

mysql&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is probably the best option because you're inside the MySQL console.&lt;br/&gt;This selects only `Name`, `Address`, `City`, `State`, `Zip`, `Phone` columns and again filtered by Los Angeles city.&lt;br/&gt;The &lt;filename&gt; in INTO OUTFILE &lt;filename&gt; is relative to the database directory in the MySQL data directory. MySQL data directory is the one assigned to &lt;b&gt;datadir=&lt;/b&gt; in the configuration file (my.ini or my.cnf).&lt;br/&gt;My path is D:\Data\MySQL\community\los-angeles-persons.csv (for default setup : C:\MySQL\data\community\los-angeles-persons.csv)&lt;br/&gt;&lt;br/&gt;Unfortunately, export options (FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n') can only be used with INTO OUTFILE option, so something like this in command-prompt is not possible:&lt;/p&gt;&lt;pre class="cmd-line"&gt;&lt;code&gt;C:\MySQL\bin&amp;gt;mysql --user=root --database=community --execute="SELECT `Name`, `Address`, `City`, `State`, `Zip`, `Phone` FROM `persons` WHERE `City` LIKE '%Los Angeles%' ORDER BY `Name` ASC, `Zip` ASC FIELDS ESCAPED BY '\"\"' TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n';" -p &gt; los-angeles-persons.csv&lt;/code&gt;&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;&lt;h3 style="font-size:16px;; text-decoration:underline"&gt;CONCAT()&lt;/h3&gt;&lt;p&gt;Because of limitations of the first two methods, piping output to a file using &lt;b&gt;&amp;gt;&lt;/b&gt; is not possible.&lt;br/&gt;The only other way is to join all the column-values using the CONCAT() function.&lt;br/&gt;In script.sql enter&lt;/p&gt;&lt;pre class="cmd-line"&gt;&lt;code&gt;USE `community`;

DROP FUNCTION IF EXISTS toXLCell;
delimiter ///
CREATE FUNCTION toXLCell(s VARCHAR(1000)) RETURNS VARCHAR(1000) DETERMINISTIC
BEGIN
    SET @XLs = CONCAT('"', REPLACE(s,'"','""'), '",');
    RETURN @XLs;
END;
///
delimiter ;

SELECT
CONCAT(toXLCell(`Name`), toXLCell(`Address`), toXLCell(`City`), toXLCell(`State`), toXLCell(`Zip`), toXLCell(`Phone`)) AS `Row`
FROM `persons`
WHERE `City` LIKE '%Los Angeles%'
ORDER BY `Name` ASC, `Zip` ASC;&lt;/code&gt;&lt;/pre&gt;&lt;pre class="cmd-line"&gt;&lt;code&gt;C:\MySQL\bin&amp;gt;mysql --user=root -p &amp;lt; script.sql &amp;gt; los-angeles-persons.csv&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Using CONCAT &amp;amp; REPLACE may be tedious, but helps in batch scripts.&lt;br/&gt;&lt;br/&gt;This will create an extra empty column at the end because of the trailing comma. If default parameter value was supported , the function could've been defined as &lt;code class="code-line"&gt;toXLCell(s VARCHAR(1000), bLast BIT(1) = FALSE)&lt;/code&gt; and &lt;code class="code-line"&gt;toXLCell(`Phone`)&lt;/code&gt; would be changed to &lt;code class="code-line"&gt;toXLCell(`Phone`, TRUE)&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;MySQL doesn't support variable number of parameters, otherwise we could've had a function&lt;br/&gt;&lt;code class="code-line"&gt;toXLLine(`Name`, `Address`, `City`, `State`, `Zip`, `Phone`)&lt;/code&gt;&lt;br/&gt;accepting variable number of column names.&lt;br/&gt;&lt;/p&gt;&lt;/li&gt;&lt;/ol&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-870464040635025101?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/rdxq_yW2iLc" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/rdxq_yW2iLc/export-mysql-data-to-excel-compatible.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/12/export-mysql-data-to-excel-compatible.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-8113518494764803863</guid><pubDate>Tue, 18 Sep 2007 07:18:00 +0000</pubDate><atom:updated>2007-09-18T13:14:25.444+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">AJAX</category><category domain="http://www.blogger.com/atom/ns#">HTML</category><title>Form submission using AJAX &amp; HTML</title><description>One of the biggest concerns using AJAX based form submissions are JavaScript related issues : &lt;ul&gt; &lt;li&gt;What if JavaScript is disabled or not available on the client's browser ?&lt;/li&gt; &lt;li&gt;What if XMLHttpRequest / Msxml2.XMLHTTP / Microsoft.XMLHTTP aren't available ?&lt;/li&gt; &lt;li&gt;What if the creation of XMLHttpRequest object failed for some reason ?&lt;/li&gt; &lt;li&gt;What if all the JavaScript scripts didn't load properly and screwed up the damn thing ?&lt;/li&gt; &lt;li&gt;What if the user clicked the button much faster than the scripts to completely load ? You must be on a real slow connection for this to happen.&lt;/li&gt; &lt;/ul&gt; The only solution is to give your users the option to automatically fall back to the normal form submission if AJAX doesn't work. Relying solely on client side scripting should only be done only if the application demands it. &lt;fieldset&gt;&lt;legend&gt;HTML&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;form id="Comment-Form" action="http://mydomain.com/PostComment" method="post"&amp;gt;
&amp;lt;div id="Comment-Box"&amp;gt;
&amp;lt;table&amp;gt;
&amp;lt;tr&amp;gt;&amp;lt;th&amp;gt;Leave a Comment&amp;lt;/th&amp;gt;&amp;lt;/tr&amp;gt;
&amp;lt;tr&amp;gt;&amp;lt;td id="Comment-Box-Msg" style="display:none"&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;
&amp;lt;tr&amp;gt;&amp;lt;td&amp;gt;&amp;lt;textarea name="Comment" id="Comment-Reply" rows="10" cols="50"&amp;gt;&amp;lt;/textarea&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;
&amp;lt;tr&amp;gt;&amp;lt;td style="text-align:center"&amp;gt;
&amp;lt;input type="submit" value="Post Comment" name="Submit" id="Comment-Button"/&amp;gt;
&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;
&amp;lt;/table&amp;gt;
&amp;lt;/div&amp;gt;
&amp;lt;/form&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;HTML 4.01&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;JavaScript&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;window.onload = function() { init(); }
function init()
 {
        /* 
        This is set only after the entire page is loaded,
        so if the button is clicked way before its loaded,
        it'll 'normal' submit to the form's action value
        */
        document.getElementById("Comment-Button").onclick = PostCommment;
 }
function PostCommment()
 {
        // AJAX error : switch to &amp;lt;form&amp;gt; submit
        if (ajax_error) document.getElementById("Comment-Form").submit();

        // Do the form submission via AJAX

        // To stop the &amp;lt;form&amp;gt; being submitted, since its done via AJAX
        return false;
 }
&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Javascript 1.5&lt;/dfn&gt;&lt;/fieldset&gt;
This way, it ensures that if there is a problem with JavaScript or AJAX in particular, you can always fall back to the normal form submission. &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-8113518494764803863?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/l_yIRKHEQoM" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/l_yIRKHEQoM/form-submission-using-ajax-html.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/09/form-submission-using-ajax-html.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-78061508367061634</guid><pubDate>Wed, 22 Aug 2007 12:46:00 +0000</pubDate><atom:updated>2007-08-27T11:50:53.746+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">JavaScript</category><category domain="http://www.blogger.com/atom/ns#">Java</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">php</category><category domain="http://www.blogger.com/atom/ns#">Python</category><title>Generating a Random String</title><description>&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
class RandomText
 {
        const RAND_NUMBERS       = 1;
        const RAND_SMALL_LETTERS = 2;
        const RAND_CAP_LETTERS   = 4;
        const RAND_ALL           = 7;

        /**
         * @access public
         * @param Type (INT) One of the random constants RAND_*
         * @NoOfChars [INT] Optional - No of characters to generate
         * @return (string) random string
         * @example echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
         */
 	public static function Random_String($Type = self::RAND_NUMBERS, $NoOfChars = 6)
 	 {
 	 	$strList = array();

 	 	// Convert to binary format and find out what combination of random characters are required
 	 	$binType = base_convert($Type, 10, 2);

 	 	// Loop through the bits from Right To Left
 	 	for ($i = strlen($binType) - 1; $i &amp;gt;= 0; $i--)
 	 	 {
 	 	 	if ($binType[$i])
 	 	 	 {
 	 	 	 	switch (pow(2, strlen($binType) - $i - 1))
 	 	 	 	 {
 	 	 	 	 	default:

 	 	 	 	 	case self::RAND_NUMBERS:
 	 	 	 	 	 $Ascii_Range = array(48, 57);  // Numbers - Characters 0 to 9
 	 	 	 	 	break;

 	 	 	 	 	case self::RAND_SMALL_LETTERS:
   	 	 	 	 	 $Ascii_Range = array(97, 122); // Small Letters - Characters a to z
 	 	 	 	 	break;

 	 	 	 	 	case self::RAND_CAP_LETTERS:
 	 	 	 	 	 $Ascii_Range = array(65, 90);  // Capital Letters - Characters A to Z
 	 	 	 	 	break;
 	 	 	 	 }

 	 	 	 	for ($j = $Ascii_Range[0]; $j &amp;lt;= $Ascii_Range[1]; $j++)
 	 	 	 	 $strList[] = chr($j);
 	 	 	 }
 	 	 }

 	 	$RndString = "";
 	 	for ($i = 0; $i &amp;lt; $NoOfChars; $i++)
 	 	 $RndString .= $strList[rand(0, count($strList) - 1)];

 	 	return $RndString;
 	 }
 }

echo RandomText::Random_String(RandomText::RAND_NUMBERS + RandomText::RAND_CAP_LETTERS, 25);
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;PHP 5.2.3&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;C#&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;using System;
using System.Text;

public class RandomText
 {
        public const int RAND_NUMBERS       = 1;
        public const int RAND_SMALL_LETTERS = 2;
        public const int RAND_CAP_LETTERS   = 4;
        public const int RAND_ALL           = 7;

        public static string Random_String()
         {
                return Random_String(RAND_NUMBERS, 6);
         }

        public static string Random_String(int Type)
         {
                return Random_String(Type, 6);
         }

        public static string Random_String(int Type, int NoOfChars)
         {
                StringBuilder strList = new StringBuilder();
                int[] Ascii_Range;
                int i;

                // Convert to binary format and find out what combination of random characters are required
                string binType = Convert.ToString(Type, 2);

                // Loop through the bits from Right To Left
                for (i = binType.Length - 1; i &amp;gt;= 0; i--)
                 {
                        if (binType[i] == '1')
                         {
                                switch ((int)Math.Pow(2, binType.Length - i - 1))
                                 {
                                        default:

                                        case RAND_NUMBERS:
                                         Ascii_Range = new int[] {48, 57};  // Numbers - Characters 0 to 9
                                        break;

                                        case RAND_SMALL_LETTERS:
                                         Ascii_Range = new int[] {97, 122};  // Small Letters - Characters a to z
                                        break;

                                        case RAND_CAP_LETTERS:
                                         Ascii_Range = new int[] {65, 90};  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (int j = Ascii_Range[0]; j &amp;lt;= Ascii_Range[1]; j++)
                                 strList.Append((char)j);
                         }
                 }

 	 	StringBuilder RndString = new StringBuilder();
 	 	Random rnd = new Random();
 	 	
 	 	for (i = 0; i &amp;lt; NoOfChars; i++)
 	 	 RndString.Append(strList[rnd.Next(strList.Length - 1)]);

 	 	return RndString;
         }

        public static void Main(string[] args)
         {
                Console.WriteLine(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
         }
 }&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;.NET 2.0&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;Java&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;import java.io.*;
import java.util.Random;

public class RandomText
 {
        public static final int RAND_NUMBERS       = 1;
        public static final int RAND_SMALL_LETTERS = 2;
        public static final int RAND_CAP_LETTERS   = 4;
        public static final int RAND_ALL           = 7;

        public static String Random_String()
         {
                return Random_String(RAND_NUMBERS, 6);
         }

        public static String Random_String(int Type)
         {
                return Random_String(Type, 6);
         }

        public static String Random_String(int Type, int NoOfChars)
         {
                StringBuilder strList = new StringBuilder();
                int[] Ascii_Range;
                int i;

                // Convert to binary format and find out what combination of random characters are required
                String binType = Integer.toString(Type, 2); // Type.toString(2);

                // Loop through the bits from Right To Left
                for (i = binType.length() - 1; i &amp;gt;= 0; i--)
                 {
                        if (binType.charAt(i) == '1')
                         {
                                switch ((int)Math.pow(2, binType.length() - i - 1))
                                 {
                                        default:

                                        case RAND_NUMBERS:
                                         Ascii_Range = new int[] {48, 57};  // Numbers - Characters 0 to 9
                                        break;

                                        case RAND_SMALL_LETTERS:
                                         Ascii_Range = new int[] {97, 122};  // Small Letters - Characters a to z
                                        break;

                                        case RAND_CAP_LETTERS:
                                         Ascii_Range = new int[] {65, 90};  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (int j = Ascii_Range[0]; j &amp;lt;= Ascii_Range[1]; j++)
                                 strList.append((char)j);
                         }
                 }

                StringBuilder RndString = new StringBuilder();
                Random rnd = new Random();

                for (i = 0; i &amp;lt; NoOfChars; i++)
                 RndString.append(strList.charAt(rnd.nextInt(strList.length() - 1)));

                return RndString.toString();
         }

        public static void main(String[] args) throws Exception
         {
                System.out.println(RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25));
         }
 }&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JDK 6.0&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;JavaScript&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;function RandomText()
 {
        this.RAND_NUMBERS       = 1;
        this.RAND_SMALL_LETTERS = 2;
        this.RAND_CAP_LETTERS   = 4;
        this.RAND_ALL           = 7;

        this.Random_String = function(Type, NoOfChars)
         {
                var strList = "";
                var Ascii_Range;
                var i;

                // Convert to binary format and find out what combination of random characters are required
                binType = Type.toString(2);

                // Loop through the bits from Right To Left
                for (i = binType.length - 1; i &amp;gt;= 0; i--)
                 {
                        if (binType[i] == '1')
                         {
                                switch (Math.pow(2, binType.length - i - 1))
                                 {
                                        default:

                                        case this.RAND_NUMBERS:
                                         Ascii_Range = new Array(48, 57);  // Numbers - Characters 0 to 9
                                        break;

                                        case this.RAND_SMALL_LETTERS:
                                         Ascii_Range = new Array(97, 122); // Small Letters - Characters a to z
                                        break;

                                        case this.RAND_CAP_LETTERS:
                                         Ascii_Range = new Array(65, 90);  // Capital Letters - Characters A to Z
                                        break;
                                 }

                                for (var j = Ascii_Range[0]; j &amp;lt;= Ascii_Range[1]; j++)
                                 strList += String.fromCharCode(j);
                         }
                 }

                var RndString = "";
                for (i = 0; i &amp;lt; NoOfChars; i++)
                 RndString += strList[Math.floor(Math.random() * strList.length)];

                return RndString;
         }
 }

var oRandomText = new RandomText();
alert(oRandomText.Random_String(oRandomText.RAND_NUMBERS + oRandomText.RAND_CAP_LETTERS, 25));
&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JavaScript 1.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;fieldset&gt;&lt;legend&gt;Python&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;import array
import random

def int2bin(n):
    "Convert an integer to binary - no built-in function"
    bStr = ''
    while n &gt; 0:
          bStr = str(n % 2) + bStr
          n = n &gt;&gt; 1
    return bStr

class RandomText:

      RAND_NUMBERS       = 1;
      RAND_SMALL_LETTERS = 2;
      RAND_CAP_LETTERS   = 4;
      RAND_ALL           = 7;

      def Random_String(Type = RAND_NUMBERS, NoOfChars = 6):
          strList = array.array('c', '')

          # Convert to binary format and find out what combination of random characters are required
          binType = int2bin(Type)

          # Loop through the bits from Right To Left
          for i in range(len(binType) - 1, -1, -1):

              if binType[i] == '1':

                 x = 2 ** (len(binType) - i - 1)

                 if x == RandomText.RAND_NUMBERS:
                    Ascii_Range = [48, 57]   # Numbers - Characters 0 to 9
                 elif x == RandomText.RAND_SMALL_LETTERS:
                    Ascii_Range = [97, 122]  # Small Letters - Characters a to z
                 elif x == RandomText.RAND_CAP_LETTERS:
                    Ascii_Range = [65, 90]   # Capital Letters - Characters A to Z
                 else:
                    Ascii_Range = [48, 57]   # Numbers - Characters 0 to 9

                 for j in range(Ascii_Range[0], Ascii_Range[1] + 1):
                    strList.append(chr(j))

              RndString = array.array('c', '')

              for i in range(0, NoOfChars):
                  RndString.append(strList[random.randint(0, len(strList) - 1)])

          return RndString.tostring()

      Random_String = staticmethod(Random_String)


print RandomText.Random_String(RandomText.RAND_NUMBERS + RandomText.RAND_CAP_LETTERS, 25)
&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;Python 2.5&lt;/dfn&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-78061508367061634?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/12EXL6aHYlU" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/12EXL6aHYlU/generating-random-string.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/08/generating-random-string.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-5097242308687710053</guid><pubDate>Mon, 13 Aug 2007 11:08:00 +0000</pubDate><atom:updated>2008-03-01T13:10:20.802+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>Detecting the Absolute URI</title><description>&lt;p&gt;In PHP there's a function called &lt;a href="http://php.net/parse_url" target="_blank"&gt;parse_url&lt;/a&gt; which splits a given absolute url into various parts as an array.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
function AbsURI()
 {
        $ThisLink = 'http'.(isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
                    '://'.
                    $_SERVER['HTTP_HOST'].
                    $_SERVER['REQUEST_URI'];

        $UrlParts = parse_url($ThisLink);

        $Path = $UrlParts['path'];

        // Get rid of filename.html in /folder1/folder2/filename.html
        $Path = preg_replace('#(/)([^/]*?\..*?$)#i', '$1', $Path);

        // Make it standard to have trailing / at the end of a foldername
        if (substr($Path, -1) != '/')
         $Path .= '/';
        
        $absURI = $UrlParts['scheme'].'://'.$UrlParts['host'].$Path;

        return $absURI;
 }
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;You can probably get the absolute URI with something as simple as : 
&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
$s = substr($_SERVER["SCRIPT_FILENAME"], strlen($_SERVER["DOCUMENT_ROOT"]));
// Not very sure if the above always evaluates to $_SERVER["SCRIPT_NAME"]

$ThisPath = 'http'.
            (isset($_SERVER["HTTPS"]) ? $_SERVER["HTTPS"] == 'off' ? '' : 's' : '').
            '://'.$_SERVER['HTTP_HOST'].
            substr($s, 0, strrpos($s, '/') + 1);
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;but unfortunately, how filename &amp;amp; directory name values are stored in $_SERVER varies in server setup and relying on it may not be 100% accurate, though in 99% of the cases, it should do just fine.&lt;br&gt;&lt;br&gt;There's another reason to use the 2nd snippet instead of the 1st - that's if a &lt;a href="http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewriterule" target="_blank"&gt;RewriteRule&lt;/a&gt; is used for the given current url ($ThisLink).&lt;br&gt;Lets say I had the 1st code snippet in absURI.php in &lt;b&gt;test&lt;/b&gt; folder in my document root. So http://localhost/test/absURI.php would be the link. And something like this in my .htaccess file : 
&lt;fieldset&gt;&lt;legend&gt;Apache&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;RewriteEngine On
RewriteRule ^fakefolder/test\.html$ absURI.php&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;and I access the url using http://localhost/test/fakefolder/test.html?a=2&amp;amp;b=c&lt;br&gt;AbsURI() will end up returning http://localhost/test/fakefolder/ which would be incorrect. &lt;br&gt;&lt;br&gt;Tested on different hosts having Apache 2.0.x.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-5097242308687710053?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/7ITBIK4dj8E" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/7ITBIK4dj8E/detecting-absolute-uri.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/08/detecting-absolute-uri.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-6609665929133265513</guid><pubDate>Fri, 06 Jul 2007 09:05:00 +0000</pubDate><atom:updated>2008-07-03T15:39:05.832+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">c++</category><category domain="http://www.blogger.com/atom/ns#">algorithms</category><category domain="http://www.blogger.com/atom/ns#">Java</category><title>All Possible Permutations</title><description>&lt;p&gt;All possible permutations of a string - Total number of permutations of a given word taking all &lt;i&gt;n&lt;/i&gt; letters is n!.&lt;br&gt;For example, the word &lt;b&gt;post&lt;/b&gt; will give 24 possible permutations inclusive of the original word (post).&lt;/p&gt; &lt;p&gt; &lt;ol&gt; &lt;li&gt;post  &lt;li&gt;pots  &lt;li&gt;psot  &lt;li&gt;psto  &lt;li&gt;ptos  &lt;li&gt;ptso  &lt;li&gt;opts  &lt;li&gt;opst  &lt;li&gt;ostp  &lt;li&gt;ospt  &lt;li&gt;otsp  &lt;li&gt;otps  &lt;li&gt;spot  &lt;li&gt;spto  &lt;li&gt;sopt  &lt;li&gt;sotp  &lt;li&gt;stpo  &lt;li&gt;stop  &lt;li&gt;tpso  &lt;li&gt;tpos  &lt;li&gt;tosp  &lt;li&gt;tops  &lt;li&gt;tsop  &lt;li&gt;tspo&lt;/li&gt;&lt;/ol&gt; &lt;p&gt;This snippet here doesn't exactly output permutations of a string, but its indexes - which should correspond to the array indexes.&lt;/p&gt; &lt;fieldset&gt;&lt;legend&gt;C++&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;// All possible permutations upto n digits

#include&amp;lt;fstream.h&amp;gt;
#include&amp;lt;conio.h&amp;gt;

unsigned long fact(unsigned long);
void swap(int[], int, int);
void display(int[]);
void Add(int[], int);

ofstream fout("out.txt");

void main()
 {
        int j, k, n;
        unsigned long i;

        cout &amp;lt;&amp;lt; "How many digits ? "; cin &amp;gt;&amp;gt; n;

        int *key = new int[n + 1];
        key[0] = n; // n contains the total no: of digits

        for (i = 1; i &amp;lt;=key[0]; i++)
         key[i] = i;

        display(key);
        swap(key, key[0], key[0] - 1);
        display(key);

        for (i = 3; i &amp;lt;= fact(key[0]); i+=2)
         {
                for (j = key[0] - 1; j &amp;gt;= 0; j--)
                 {
                        if ((i-1) % fact(j) == 0)
                         {
                                Add(key, key[0] - j);
                                for (k = 1; k &amp;lt;= key[0] - j - 1; k++)
                                 {
                                        if (key[k] == key[key[0] - j])
                                         {
                                                Add(key, key[0] - j);
                                                k = 0;
                                         }
                                 }
                         }
                 }

                display(key);
                swap(key, key[0], key[0] - 1);
                display(key);
         }

        cout &amp;lt;&amp;lt; "Total no: of permutations = " &amp;lt;&amp;lt; key[0] &amp;lt;&amp;lt; "! = " &amp;lt;&amp;lt; i - 1;
        fout.close();
 }

unsigned long fact(unsigned long f) { return f == 0 ? 1: f * fact(f - 1); }

void swap(int k[], int a, int b)
 {
        int t = k[a]; 
        k[a] = k[b];
        k[b] = t; 
 }

void display(int k[])
 {
        for(int i = 1; i &amp;lt;= k[0]; i++)
         fout &amp;lt;&amp;lt; k[i];

        fout &amp;lt;&amp;lt; '\n';
 }

void Add(int k[], int i)
 {
        k[i]++;
        if (k[i] == k[0] + 1)
         k[i] = 1;
 }&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;&lt;p&gt;Now, its pretty obvious why I had the permutations written to a file instead of console output. 9! is 362,880 but 10! is 10 times 9! which is more than 3.5 million lines of text.&lt;br/&gt;&lt;br/&gt;&lt;b&gt;Update&lt;/b&gt; : I have ported the C code in Java with some modifications in the way output is handled. This is much safer than that big for loop.&lt;/p&gt;&lt;fieldset&gt;&lt;legend&gt;Java&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;/*
javac Permutations.java
java Permutations post
*/
public class Permutations
{
        private int[] key;
        private String word, pWord;
        private int n, i = 1;

        public Permutations(String word)
        {
                this.word = word;

                n = word.length();
                key = new int[n + 1];

                for (int i = 1; i &lt;= n; i++)
                 key[i] = i;
        }

        public boolean next()
        {
                if (i == 1)
                {
                        build();
                }
                else if (i == fact(n) + 1)
                {
                        return false;
                }
                else if (i % 2 == 0)
                {
                        swap(n, n - 1);
                        build();
                }
                else if (i % 2 == 1)
                {
                        int j, k;

                        for (j = n - 1; j &gt;= 0; j--)
                        {
                                if ((i - 1) % fact(j) == 0)
                                {
                                        add(n - j);
                                        for (k = 1; k &lt;= n - j - 1; k++)
                                        {
                                                if (key[k] == key[n - j])
                                                {
                                                        add(n - j);
                                                        k = 0;
                                                }
                                        }
                                }
                        }

                        build();
                }

                i++;
                return true;
        }

        private long fact(long f) { return f == 0 ? 1: f * fact(f - 1); }

        private void swap(int a, int b)
        {
                int t = key[a];
                key[a] = key[b];
                key[b] = t;
        }

        private void build()
        {
                StringBuilder s = new StringBuilder();

                for(int i = 1; i &lt;= n; i++)
                 s.append(word.charAt(key[i] - 1));

                pWord = s.toString();
        }

        private void add(int i)
        {
                key[i]++;
                if (key[i] == n + 1)
                 key[i] = 1;
        }

        public String nextWord()
        {
                return pWord;
        }

        public static void main(String[] args)
        {
                if (args.length == 0)
                {
                        System.out.println("Got to give an argument");
                        System.exit(0);
                }

                Permutations p = new Permutations(args[0]);
                while (p.next())
                {
                        System.out.println(p.nextWord());
                }
        }
}&lt;/code&gt;&lt;/pre&gt;&lt;dfn&gt;JDK 1.6&lt;/dfn&gt;&lt;/fieldset&gt;&lt;p&gt;PS: I wrote this half a decade ago but never documented it. I'll try to update it with an explanation soon.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-6609665929133265513?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/F-Y445bvrgg" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/F-Y445bvrgg/all-possible-permutations.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/07/all-possible-permutations.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-2181531853327945750</guid><pubDate>Mon, 07 May 2007 08:45:00 +0000</pubDate><atom:updated>2007-08-22T22:39:09.462+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>fputcsv for PHP4</title><description>I found it strange why fgetcsv() was included since version 3.0.8 and fputcsv() only since 5.1.0RC1 when both are so closely interrelated. Heres fputcsv for ones not running on a minimum of PHP 5.1.0RC1.  &lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;if (!function_exists('fputcsv'))
 include_once("php4.inc.php");&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;Assuming php4.inc.php includes functions that natively exist in PHP 5 and not in version 4. 
&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;function fputcsv($fh, $arr)
 {
        $csv = "";
        while (list($key, $val) = each($arr))
         {
                $val = str_replace('"', '""', $val);
                $csv .= '"'.$val.'",';
         }
        $csv = substr($csv, 0, -1);
        $csv .= "\n";
        if (!@fwrite($fh, $csv))
         return FALSE;
 }&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;The &lt;span style="font-size: 12px; font-family: verdana"&gt;str_replace('"', '""', $val);&lt;/span&gt; is because Excel doesn't seem to understand &lt;b&gt;\"&lt;/b&gt;. &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-2181531853327945750?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/f6PV-7bxHWg" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/f6PV-7bxHWg/fputcsv-for-php4.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/05/fputcsv-for-php4.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-2172098654627453973</guid><pubDate>Sun, 06 May 2007 12:30:00 +0000</pubDate><atom:updated>2007-08-22T22:38:16.155+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>Absolute path of current php file in execution</title><description>Sometimes it is necessary to know the absolute path of the current php-file in execution. A common example is when you have loaded a 3rd-party module and all its related files (like php, css, js, images etc) are in a folder of its own and moving these related files to your own specific-folders for the sake of organization can be disadvantageous instead of structuring them to match your own. If moving the files to different locations, editing the module code could end up being cumbersome. Hence, modules are like Java packages where all the files are kept in a separate folder and better left untouched. In php, if we can extract a lot of file and folder information from these global variables $_SERVER['DOCUMENT_ROOT'], $_SERVER['SCRIPT_FILENAME'], $_SERVER['SCRIPT_NAME'], $_SERVER['PHP_SELF'] But none of these would give the current php-file name in consideration if mod_rewrite, include() etc were used to retrieve a php file. PHP's __FILE__ magic constant is the only way to retrieve the absolute path. Given this path you can create a OO module within which you can access the related-files within the folder and thus be independent of any CMS. This is one very simple function you'll come across but I still felt the need to emphasize on this function.  &lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
echo __FILE__AbsolutePath(__FILE__)."\n";

function __FILE__AbsolutePath($Filename)
 {
        switch (PHP_OS)
         {
                case "WINNT": $needle = "\\"; break;
                case "Linux": $needle = "/";  break;
                default:      $needle = "/";  break; // TODO : Mac check
         }
        $AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
        return $AbsPath;
 }
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;I haven't done a MAC and other OS checks. If you have tried this on an OS that shows a different value for PHP_OS, please do share it with others.&lt;br&gt;&lt;br&gt;&lt;strong&gt;Update&lt;/strong&gt;: Getting the current file equivalent to __FILE__ can be retrieved using the &lt;a href="http://www.php.net/debug_backtrace"&gt;debug_backtrace()&lt;/a&gt; function. 
&lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;&amp;lt;?php
function __FILE__AbsolutePath()
 {
        $d = debug_backtrace();
        $Filename = $d[0]['file'];

        switch (PHP_OS)
         {
                case "WINNT": $needle = "\\"; break;
                case "Linux": $needle = "/";  break;
                default:      $needle = "/";  break; // TODO : Mac check
         }
        $AbsPath = substr($Filename, 0, strrpos($Filename, $needle));
        return $AbsPath;
 }
?&amp;gt;&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-2172098654627453973?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/ixz0Ien7QHo" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/ixz0Ien7QHo/absolute-path-of-current-php-file-in.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/05/absolute-path-of-current-php-file-in.html</feedburner:origLink></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-7869472979536208643.post-3884929829584267144</guid><pubDate>Sun, 18 Feb 2007 03:10:00 +0000</pubDate><atom:updated>2007-08-22T22:35:17.748+05:30</atom:updated><category domain="http://www.blogger.com/atom/ns#">php</category><title>get_file_contents</title><description>Sometimes we need to retrieve a remote file/url's content which is easily done using PHP's &lt;a href="http://php.net/file_get_contents"&gt;file_get_contents()&lt;/a&gt;. This returns FALSE on failure but on many occasions file_get_contents() returns FALSE due to a network error or server overload and could've worked the next second. Here is a function get_file_contents(), that tries to retrieve the url's contents over and over again until its TRUE (it has successfully fetched the contents) or until it has exhausted the number of tries. Because threading is not yet available in PHP, it is not recommended to set the $totalTries to a higher value.  &lt;fieldset&gt;&lt;legend&gt;PHP&lt;/legend&gt;&lt;pre&gt;&lt;code&gt;function get_file_contents($url, $totalTries = 5)
 {
        $Tries = 0;
        do
         {
                if ($Tries &amp;gt; 0) sleep(1); # Wait for a sec before retrieving again
                $contents = @file_get_contents($url);
                $Tries++;
         } while ($Tries &amp;lt;= $totalTries &amp;amp;&amp;amp; $contents === FALSE);
         if ($contents == "") $contents = FALSE;
         return $contents;
 }&lt;/code&gt;&lt;/pre&gt;&lt;/fieldset&gt;This ends the beginning of my first post here !&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7869472979536208643-3884929829584267144?l=code.anjanesh.net' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/anjanesh/code/~4/eIAj_xClg7E" height="1" width="1"/&gt;</description><link>http://rss.anjanesh.net/~r/anjanesh/code/~3/eIAj_xClg7E/getfilecontents.html</link><author>anjanesh@anjanesh.com (Anjanesh)</author><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://code.anjanesh.net/2007/02/getfilecontents.html</feedburner:origLink></item></channel></rss>
