What does __name__=='__main__' in Python mean ??

All python beginners, once in a while must have stumbled upon the below piece of code.


 __name__=='__main__' 

What does it actually mean and what is the use of the above piece of code. We'll see what the above code does and its relevance with the help of an example.

 Lets create a simple python program hello.py with a function called foo

#!/usr/bin/python
# hello.py

def foo():
    print 'foo is called'

foo()
If you try running the above program, you should have the following output on the console.

foo is called
Now, suppose we need to import this hello.py file into another python program in order to access the foo function.
Let's create another python program called world.py. In world.py we'll import our hello.py and try to call foo. Here is how world.py would look like:

#!/usr/bin/python
# world.py

import hello

def bar():
    hello.foo()

bar()

Now, if you execute world.py, you should have the following output on the terminal console;

foo is called
foo is called

We'll as you saw the message gets printed twice. The simple solution would be to remove the foo function call from hello.py. But in that case it won't print the message when we execute hello.py. Well, this is where

__name__=='__main__'

comes into the picture. When a python program starts to execute, it sets a few special variable, __name__ is one of them. It contains the value __main__ if it's the main program being executed. But it won't have the value as __main__ being set, if it's being imported and executed, since it's not the main program when imported.
Let's modify hello.py to include the checking for __name__

#!/usr/bin/python
# hello.py

def foo():
    print 'foo is called'

if __name__ == '__main__':
    foo()
Now, if you try running the world.py program it won't print the message twice. The only message that is printed is of the hello.foo function call.

File Upload in Asp.Net C#

In this tutorial, we'll see how to implement file upload in asp.net C#. We'll be using a beautiful jQuery file upload plugin called blueimp.

Implementing file upload can be quite a task, if we try to implement it from scratch. But using a plugin like blueimp we really don't need to worry about anything. It's quite simple and can be used with any serve side platforms like PHP, Python, Ruby on Rails, Java, Go etc to name a few.

We'll be implementing the basic type of file upload. To get started, create a web application and add a new page called index.aspx. Here is how it looks like:
<table align="center" style="padding-top:200px;">
    <tr>
        <td>
            <input type="file" name="file" id="btnFileUpload" />
        </td>
    </tr>
    <tr>
        <td>
            <div id="progressbar" style="width:100px;display:none;">
                <div>
                    saadsd
                </div>
            </div>
        </td>
    </tr>
</table>
Download blueimp and include the required libraries as shown below in index.aspx :
<script src="Scripts/jquery-1.11.1.js" type="text/javascript"></script>
<script src="Scripts/jquery.ui.widget.js" type="text/javascript"></script>
<script src="Scripts/jquery.iframe-transport.js" type="text/javascript"></script>
<script src="Scripts/jquery.fileupload.js" type="text/javascript"></script>

Next we'll create a generic handler called FileUploadHandler.ashx which will handle the server side of file upload process. Here is how it looks like:
try {
    if (context.Request.QueryString["upload"] != null) {
        string pathrefer = context.Request.UrlReferrer.ToString();
        string Serverpath = HttpContext.Current.Server.MapPath("Upload");

        var postedFile = context.Request.Files[0];

        string file;

        //In case of IE
        if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE") {
            string[] files = postedFile.FileName.Split(new char[] {
                '\\'
            });
            file = files[files.Length - 1];
        } else // In case of other browsers
        {
            file = postedFile.FileName;
        }


        if (!Directory.Exists(Serverpath))
            Directory.CreateDirectory(Serverpath);

        string fileDirectory = Serverpath;
        if (context.Request.QueryString["fileName"] != null) {
            file = context.Request.QueryString["fileName"];
            if (File.Exists(fileDirectory + "\\" + file)) {
                File.Delete(fileDirectory + "\\" + file);
            }
        }

        string ext = Path.GetExtension(fileDirectory + "\\" + file);
        file = Guid.NewGuid() + ext; // Creating a unique name for the file 

        fileDirectory = Serverpath + "\\" + file;

        postedFile.SaveAs(fileDirectory);

        context.Response.AddHeader("Vary", "Accept");
        try {
            if (context.Request["HTTP_ACCEPT"].Contains("application/json"))
                context.Response.ContentType = "application/json";
            else
                context.Response.ContentType = "text/plain";
        } catch {
            context.Response.ContentType = "text/plain";
        }

        context.Response.Write("Success");
    }
} catch (Exception exp) {
    context.Response.Write(exp.Message);
}
I won't be going into the details of the generic handler code. It's quite self explanatory but still in case you don't understand anything please do let me know in the comments.

Initializing the file upload control plugin is quite simple. After you have included the required libraries, simply call the file upload plugin as shown below:
$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        data.submit();
    },
    success: function(response, status) {
        // Success callback
    },
    error: function(error) {
        // Error callback
    }
});
Blueimp plugin also makes it possible to show the upload progress which is a must in case files are of large size. Tracking file upload progress is quite simple. You simply need to add another setting called progress as shown below:
$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        data.submit();
    },
    progress: function(e, data) {
        // Track Progress
    },
    success: function(response, status) {
        // Success callback
    },
    error: function(error) {
        // Error callback
    }
});
From the Blueimp plugin we get the total data which is to be uploaded and the data which is uploaded. So it's easy to calculate the percentage of data uploaded. Now in order to show data upload progress graphically or as a progress bar we make use of css. As you can see we have already added a div called progressBar in our page. Next add the following css to the div :
#progressbar {
    background - color: black;
    background - repeat: repeat - x;
    border - radius: 13px;
    padding: 3px;
}

#progressbar > div {
    background - color: orange;
    width: 0 % ;
    height: 20px;
    border - radius: 10px;
}
Now modify the fileupload jQuery code as shown below to make the file upload and progress bar work:
$('#btnFileUpload').fileupload({
    url: 'FileUploadHandler.ashx?upload=start',
    add: function(e, data) {
        console.log('add', data);
        $('#progressbar').show();
        data.submit();
    },
    progress: function(e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progressbar div').css('width', progress + '%');
    },
    success: function(response, status) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('success', response);
    },
    error: function(error) {
        $('#progressbar').hide();
        $('#progressbar div').css('width', '0%');
        console.log('error', error);
    }
});
One more important thing. In order to support upload of large files you need to set the MaxRequestLength in the web.config
<httpRuntime  executionTimeout="6000000" maxRequestLength="2147483647" />
Now try to run the app and upload some files. Uploaded files can be found in the Upload folder inside the web application.

Code from the above tutorial is available on GitHub.

Call asmx web service from jQuery Ajax

I had earlier posted a tutorial on how to call c# server side methods using JavaScript. It made use of Page Method provided by .NET framework.
In this tutorial, we'll see how to call an asmx service web method using jQuery Ajax. So lets start by creating a web application in Visual Studio. Download and include the latest jQuery in your html or aspx page.
<script src=" jquery-2.1.1.js="" scripts="" type="text/javascript"></script>

Python Flask and jQuery Ajax POST

I have already covered an introductory article on getting started with python web application development using Python Flask and MySQL. In this tutorial, we'll focus on the client side of the web application. We'll see how to use jQuery AJAX along with Python Flask.

Prior to getting started with this tutorial, make sure you have Python installed. You can check if it's installed from the command prompt:

python --version

How to Check 3G/ Wifi Dongle/ Data Card Usage in Ubuntu Linux

3G WiFi dongle or data card come in handy, when it comes to using internet on the go. Simply plug in the dongle and you are ready to go online. 3G dongle has completely revolutionized the way we use internet today.

I have been using 3G Airtel dongle for quite a while now. The 3G dongle was quite easy to install and use. In windows 7 on plugging in, it automatically installed the required software and within minutes it was ready to be connected. The interface was quite user friendly with options to check the usage balance too.

JavaScript JSON Encode/Decode with Asp.Net Sample Code

JavaScript JSON Encode/Decode with Asp.Net Sample Code


In this article, we'll discuss how to Encode and Decode JavaScript JSON arrays when passing it from client to server side and vice versa using Asp.Net WebMethods.
We encode JavaScript object into JSON when we need to pass it from client side to server side. Decoding is done on the server side, so that the JavaScript object can be converted  into a C# class object. Consider for instance that we need to collect a few details about an employee and pass it to the server side to a web method.


Installing Python Matplotlib in Ubuntu 12.04

Installing Python Matplotlib in Ubuntu 12.04 directly was quite a mess and I ended up with some weird errors.
A cleaner and smoother way to install matplotlib was using Pip. I wonder why it never crossed my mind given that fact, I had already used Pip for installation in the Python Flask MySQL tutorial.

In order to install matplotlib in Ubuntu 12.04, run the following code :

sudo apt-get install python-pip
easy_install -U distribute
sudo apt-get install libfreetype6-dev libpng-dev
sudo pip install matplotlib
Keep watching this space for a tutorial on getting started with creating graphs using Python and Matplotlib.

JavaScript JSON Array Revisited

JavaScript JSON Array Revisited

In this article, we'll discuss all about JavaScript JSON Array. We'll see how to create a JSON object in JavaScript and also how to convert a JSON string to JavaScript object.

JSON stands for JavaScript Object Notation. It is a text format which we normally use to exchange information between a client and server. It's independent of the language you use and almost all languages support JSON. In this article, we'll see how to convert JavaScript to JSON.

Building a Simple App Using AngularJS and Firebase

Building a Simple App Using AngularJS and Firebase

In the following series of tutorials, we'll create a web blog using AngularJS and Firebase.
AngularJS is the super awesome framework for developing web applications using JavaScript and Firebase provides the capability to store and sync data in real time for web app and mobile apps.

This tutorial requires basic knowledge of AngularJS. Any one looking for any refreshers can find some tutorials in AngularJS docs.
As far as Firebase is concerned, you'll need to create a free account on Firebase.

JavaScript Splice and other Array manipulation methods

Recently, during one of the local JavaScript weekend workshops, one of the guys raised a question about JavaScript Array.prototype.splice(). He showed the below sample code:



The question was quite simple, he asked "Why is JavaScript Splice() method called so, even though it splits the array into two." From the point of view of someone who has used splice to only split arrays, the question is quite a legit one. But one thing that he didn't knew or forgot was that splice can remove as well as add elements from an array and that too at the same time. JavaScript splice if used to add and remove elements at the same time, takes in 3 arguments and this process of removing and adding elements is called splicing.