Primer for Python Decorators

In this introductory tutorial, we’ll look at what decorators are and how to create and use them. Decorators provide a simple syntax for calling higher-order functions. By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it. Sounds confusing – but it’s really not, especially after we go over a number of examples.

python decorators


Before you can understand decorators, you must first understand how functions work. Essentially, functions return a value based on the given arguments.

def foo(bar):
    return bar + 1

print(foo(2) == 3)

First Class Objects

In Python, functions are first-class objects. This means that functions can be passed around, and used as arguments, just like any other value (e.g, string, int, float).

def foo(bar):
    return bar + 1


def call_foo_with_arg(foo, arg):
    return foo(arg)

print(call_foo_with_arg(foo, 3))

Nested Functions

Because of the first-class nature of functions in Python, you can define functions inside other functions. Such functions are called nested functions.

def parent():
    print("Printing from the parent() function.")

    def first_child():
        return "Printing from the first_child() function."

    def second_child():
        return "Printing from the second_child() function."


What happens when you call the parent() function? Think about this for a minute. You should get…

Printing from the parent() function.
Printing from the first_child() function.
Printing from the second_child() function

Try calling the first_child(). You should get an error:

Traceback (most recent call last):
File "", line 15, in <module>
NameError: name 'first_child' is not defined

What have we learned?

Whenever you call parent(), the sibling functions, first_child() and second_child() are also called AND because of scope, both of the sibling functions are not available (e.g., cannot be called) outside of the parent function.

Returning Functions

Python also allows you to return functions from other functions. Let’s alter the previous function for this example.

def parent(num):

    def first_child():
        return "Printing from the first_child() function."

    def second_child():
        return "Printing from the second_child() function."

        assert num == 10
        return first_child
    except AssertionError:
        return second_child

foo = parent(10)
bar = parent(11)



The output of the first two print statements is:

<function first_child at 0x1004a8c08>
<function second_child at 0x1004a8cf8>

This simply means that foo points to the first_child() function, while bar points to the second_child() function.

The output of the second two functions confirms this:

Printing from the first_child() function.
Printing from the second_child() function.

Finally, did you notice that in example three, we executed the sibling functions within the parent functions – e.g, second_child(). Meanwhile in this last example, we did not add parenthesis to the sibling functions – first_child – when called so that way we can use them in the future. Make sense?

Now, my friend, you are ready to take on decorators!


Let’s look at two examples …

Example 1:

def my_decorator(some_function):

    def wrapper():

        print("Something is happening before some_function() is called.")


        print("Something is happening after some_function() is called.")

    return wrapper

def just_some_function():

just_some_function = my_decorator(just_some_function)


Can you guess what the output will be? Try.

Something is happening before some_function() is called.
Something is happening after some_function() is called.

To understand what’s going on here, just look back at the four previous examples. We are literally just applying everything learned. Put simply, decorators wrap a function, modifying its behavior.

Let’s take it one step further and add an if statement.

Example 2:

def my_decorator(some_function):

    def wrapper():

        num = 10

        if num == 10:


        print("Something is happening after some_function() is called.")

    return wrapper

def just_some_function():

just_some_function = my_decorator(just_some_function)


This will output in:

Something is happening after some_function() is called.

Syntactic sugar!

Python allows you to simplify the calling of decorators using the @ symbol (this is called “pie” syntax).

Let’s create a module for our decorator:

def my_decorator(some_function):

    def wrapper():

        num = 10

        if num == 10:


        print("Something is happening after some_function() is called.")

    return wrapper

if __name__ == "__main__":

Okay. Stay with me. Let’s look at how to call the function with the decorator:

from decorator07 import my_decorator

def just_some_function():


When you run this example, you should get the same output as in the previous one:

Something is happening after some_function() is called.

So, @my_decorator is just an easier way of saying just_some_function = my_decorator(just_some_function). It’s how you apply a decorator to a function.

Real World Examples

How about a few real world examples …

import time

def timing_function(some_function):

    Outputs the time a function takes
    to execute.

    def wrapper():
        t1 = time.time()
        t2 = time.time()
        return "Time it took to run the function: " + str((t2 - t1)) + "\n"
    return wrapper

def my_function():
    num_list = []
    for num in (range(0, 10000)):
    print("\nSum of all the numbers: " + str((sum(num_list))))


This returns the time before you run my_function() as well as the time after. Then we simply subtract the two to see how long it took to run the function.

Run it. Work through the code, line by line. Make sure you understand how it works.

from time import sleep

def sleep_decorator(function):

    Limits how fast the function is

    def wrapper(*args, **kwargs):
        return function(*args, **kwargs)
    return wrapper

def print_number(num):
    return num


for num in range(1, 6):

This decorator is used for rate limiting. Test it out.

One of the most used decorators in Python is the login_required() decorator, which ensures that a user is logged in/properly authenticated before s/he can access a specific route (/secret, in this case):

from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

def secret():

Did you notice that the function gets passed to the functools.wraps() decorator? This simply preserves the metadata of the wrapped function.

Let’s look at one last use case. Take a quick look at the following Flask route handler:

@app.route('/grade', methods=['POST'])
def update_grade():
    json_data = request.get_json()
    if 'student_id' not in json_data:
    # update database
    return "success!"

Here we ensure that the key student_id is part of the request. Although this validation works it really does not belong in the function itself. Plus, perhaps there are other routes that use the exact same validation. So, let’s keep it DRY and abstract out any unnecessary logic with a decorator.

from flask import Flask, request, abort
from functools import wraps

app = Flask(__name__)

def validate_json(*expected_args):
    def decorator(func):
        def wrapper(*args, **kwargs):
            json_object = request.get_json()
            for expected_arg in expected_args:
                if expected_arg not in json_object:
            return func(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/grade', methods=['POST'])
def update_grade():
    json_data = request.get_json()
    # update database
    return "success!"

In the above code, the decorator takes a variable length list as an argument so that we can pass in as many string arguments as necessary, each representing a key used to validate the JSON data. Did you notice that this dynamically creates new decorators based on those strings? Test this out.



Apple TV 2 XBMC Install / Kodi Downgrade

So you have a Jailbroken Apple TV 2 and want install a specific version of XBMC or Kodi, this mini tutorial will show you how to do so.

You might be wondering why would you not simply do:

  • apt-get update
  • apt-get remove org.xbmc.kodi-atv2

That would install the latest version of Kodi, which normally wouldn’t be a problem. However development of Kodi for the Apple TV 2 platform has come to an end, so eventually you might no longer be able to do this. Another reason might be you want to boot in to boot Kodi / XBMC directly when the Apple TV is powered on for ease of use by family members, this is not possible with the latest version of Kodi.

First ssh in to your Jailbroken Apple TV, the default username is root and the default password is alpine.

Now do: apt-get update – This updates the packages available from the repositories, it wont hurt to do this.

Remove Previous versions of XBMC / Kodi:

Work you way down the list below and copy / paste the commands which are highlighted in bold to remove and clean-up from any previous Xbmc / Kodi installs.

rm -f *kodi*.deb – Deletes any previous Kodi .deb files you might have downloaded

rm -f *xbmc*.deb – Deletes any previous XBMC .deb files you might have downloaded

apt-get remove org.xbmc.xbmc-atv2 – removes XBMC if you have installed it from the repository

apt-get remove org.xbmc.kodi-atv2 – removes Kodi if you have installed it from the repository

rm -Rf /private/var/mobile/Library/Preferences/XBMC – Removes any previous user settings for XBMC

rm -Rf /private/var/mobile/Library/Preferences/Kodi – Removes any previous user settings for Kodi

Installing a specific version of XBMC or Kodi:

You can download any past version of XBMC / Kodi you desire here, the repository has all of the past XBMC / Kodi versions at the moment.

So if for example if you wanted to install the final version of XBMC which is 13.2 Gotham I would do the following:

wget – this would download the XBMC 13.2 Gotham version to my Apple TV. If i wanted to download a different version i would simply type wget then the address of the deb I wished to download.

dpkg -i *xbmc*.deb – This will install the XBMC 13.2 Gotham version i just downloaded.

If you get error about the dependency then do:  apt-get -f install

apt-get install org.tomcool.xbmc-booter – This installs the XBMC booter which automatically boots in to XBMC instead of the default Apple TV 2 user interface. Note: Do not install this if you wish to use Kodi, your Apple TV will siply boot to a black screen. However you can simply ssh in to the Apple TV again and type apt-get remove org.tomcool.xbmc-booter to remove the XBMC booter

reboot – Reboots the Apple TV

Once rebooted you should be presented with a clean install of your chosen version of XBMC / Kodi.

Here is a simple list of commands for your copy + pasting pleasure:

apt-get update
rm -f *kodi*.deb
rm -f *xbmc*.deb
apt-get remove org.xbmc.xbmc-atv2
apt-get remove org.xbmc.kodi-atv2
rm -Rf /private/var/mobile/Library/Preferences/XBMC
rm -Rf /private/var/mobile/Library/Preferences/Kodi
dpkg -i *xbmc*.deb
apt-get install org.tomcool.xbmc-booter

Hopefully someone will find this useful sometime in the future to downgrade or simply install XBMC on their Apple TV 2. I personally wanted to downgrade to XBMC 13.2 Gotham because I wanted the Apple TV to automatically boot in to XBMC for ease of use by family members.

SSH Tunneling with Putty

Let say if you have the remote machine that running the web server on the certain port but that port is blocked from outside. You can set up the ssh tunnel to access to that web server from desktop using the steps below:

– You must have access to remote machine with ssh ( i.e. you can login to ssh with your credential)
– Install Putty on your desktop


1/ Set up the putty session for your remote machine ( ip address, port , etc.)
2/ Go to SSH – Tunnels then enter your choice for the Source port ( it can be any random port)
3/ Enter in the Destination where is the port which is blocked on the remote machine

Capture23/ Save the configuration and run the ssh session from your desktop.

4/ Go to the browser and access the remote site with the url : http://localhost:8111  ( In this case 8111 is my random port)

Woala !!!

ECEF (Earth Centered Earth Fixed) Coords with WGS-4 Ellipsoid to Latitude Longitude Altitude

* ECEF - Earth Centered Earth Fixed
* LLA - Lat Lon Alt
* ported from matlab code at

// WGS84 ellipsoid constants
private final double a = 6378137; // radius
private final double e = 8.1819190842622e-2; // eccentricity

private final double asq = Math.pow(a,2);
private final double esq = Math.pow(e,2);

private double[] ecef2lla(double[] ecef){
double x = ecef[0];
double y = ecef[1];
double z = ecef[2];

double b = Math.sqrt( asq * (1-esq) );
double bsq = Math.pow(b,2);
double ep = Math.sqrt( (asq – bsq)/bsq);
double p = Math.sqrt( Math.pow(x,2) + Math.pow(y,2) );
double th = Math.atan2(a*z, b*p);

double lon = Math.atan2(y,x);
double lat = Math.atan2( (z + Math.pow(ep,2)*b*Math.pow(Math.sin(th),3) ), (p – esq*a*Math.pow(Math.cos(th),3)) );
double N = a/( Math.sqrt(1-esq*Math.pow(Math.sin(lat),2)) );
double alt = p / Math.cos(lat) – N;

// mod lat to 0-2pi
lon = lon % (2*Math.PI);

// correction for altitude near poles left out.

double[] ret = {lat, lon, alt};

return ret;

private double[] lla2ecef(double[] lla){
double lat = lla[0];
double lon = lla[1];
double alt = lla[2];

double N = a / Math.sqrt(1 – esq * Math.pow(Math.sin(lat),2) );

double x = (N+alt) * Math.cos(lat) * Math.cos(lon);
double y = (N+alt) * Math.cos(lat) * Math.sin(lon);
double z = ((1-esq) * N + alt) * Math.sin(lat);

double[] ret = {x, y, z};
return ret;

Python How To Check the Point is inside the Polygon

# determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs

def point_inside_polygon(x, y, poly):
n = len(poly)
inside = False

p1x, p1y = poly[0]
for i in range(n + 1):
p2x, p2y = poly[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y – p1y) * (p2x – p1x) / (p2y – p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y

return inside

SSH Keying through PuTTY on Windows or Linux

Here we will go over how to setup SSH keys using PuTTY, a popular SSH client for Windows. There is also a Linux version as well.

1. Download PuTTY and PuTTYgen

First you will need to download PuTTY and PuTTYgen. You can get the latest version for both at the following links:

  • PuTTY: the Telnet and SSH client itself (Windows x86)
  • PuTTYgen: an RSA and DSA key generation utility (Windows x86)

The Unix/Linux version is available on the PuTTY download page.

2. Configure PuTTY

First things first, we need to create a profile in PuTTY to access our server. Run PuTTY and you’ll be shown the basic PuTTY options. In the Host Name field, enter your domain, or the IP address of your server. The port should already be default (22). However, if you’re connecting to your shared/reseller account, we use a non-standard port. In that event, change 22 to 2222.

Under Connection > Data, specify the username you wish to connect with under Auto-login username. If this is not root, it will most likely be your cPanel username.

Click back over to Session (top of the left menu), type a name to identify your settings, i usually use my domain name, then click save. This will save the current configuration profile into PuTTY for later use.

3. Connect to the Server

Now that PuTTY is configured, we should connect to the server at this time. To do so, click Open. This will open the PuTTY session. You will prompted about a potential security breach. This is normal, click Yes. This should bring you to the bash prompt of your server. If you see something like the below, then everything worked.

gator100 ~ $

4. Generate the SSH Key

Now we need to generate the SSH key itself. To do this, fire up PuTTYgen. Make sure to select SSH-2 RSA under type of key to generate, and specify the bits to 1024 (this is default).

Go ahead and click on generate, then move the cursor around the blank area. PuTTYgen uses this movement to generate the key’s randomness.

Once this is generated, you can set a key comment, or a passphrase. The comment isn’t important, as it’s just a label, but the passphrase will require that you enter this passphrase when using the key. If you’re trying to have a ‘passwordless login’ then this should be left blank.

Now click Save Public Key, and save this file to a name of your choosing somewhere safe on your harddrive. Please remember the location of this file, as it is needed later. Then do the same for Save Private Key.

5. Get the Keys on the Server

Now that we have the keys generated and saved, we need to get the keys on the server. Copy the data inside the putty window under Public Key for pasting into SSH authorized keys file. It should look something like this. (Note that the below example is all on one line. Do not use 3 lines, as displayed in the example.)

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAi5zTs+THmSa5rxfc3rYzVORk9neoefVZg1PZwSI

Please Note:When you paste the key, it needs to be all on one line, with no extra spaces or line returns.

Go back to the PuTTY session and run the following commands in order.

mkdir ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys2

This will bring up a text editor, simply right click in the putty window to paste the key you copied earlier. Now generally this will paste into three lines, you want it to be on one line. so go to the beginning of the second and third lines, and hit backspace once. This should move the entire string all into one line.

Once it’s all in one line, and looks good, hit CTRL+X, then Y, then Enter. This will save the file and return you back to the bash prompt. There, run the following command.

chmod 600 ~/.ssh/authorized_keys2

6. Configure SSH Keys to Work

Now we’re almost done. Close PuTTY, and re-open it, so we get back to the configuration menu. Click on the profile you saved earlier, and click load. This will load the profiles configuration into the current PuTTY window.

On the left hand side, click SSH > Auth. Here is the configuration for the key. Click on browse, and browse your harddrive for the private key. we saved earlier. Now go back to sessions (again, top left) and click save once more.

7. Confirm Setup is Successful

And you’re all set. To confirm that all this worked, simply click open again. PuTTY will attempt a connection with your server, send the key, and your server should accept it without error. You should be returned instantly to the bash prompt.

Disable Notification Center on Mountain Lion

This is the preferred method:

  1. Open Terminal and enter the following command:
    launchctl unload -w /System/Library/LaunchAgents/
  2. Next type the following command to kill NotificationCenter:
    killall NotificationCenter
  3. Finally, quit out of Terminal and return to Finder

This unloads Notification Center for the current user only and does not require admin access. To re-enable Notifications with this approach:

  1. Launch Terminal and enter a similar command – notice load instead of unload:
    launchctl load -w /System/Library/LaunchAgents/
  2. Hit Command+Shift+G and go to /System/Library/CoreServices/ then find “Notification Center” and double-click it to launch it again

This is the older approach that is less preferred, but it does work in OS X Mountain Lion:

  1. From the OS X Finder, hit Command+Shift+G and enter the path to /System/Library/CoreServices/
  2. Locate “Notification” and click on the name to rename it to “Notification”, authenticate the change when prompted
  3. Now launch Terminal, found in /Applications/Utilities/ and type the following command:
        killall NotificationCenter
  4. Quit out of Terminal