Input:
How do I get user IP address in django? How do I get user's IP in django?
I have a view like this:
# Create your views
from django.contrib.gis.utils import GeoIP
from django.template import  RequestContext
from django.shortcuts import render_to_response

def home(request):
  g = GeoIP()
  client_ip = request.META['REMOTE_ADDR']
  lat,long = g.lat_lon(client_ip)
  return render_to_response('home_page_tmp.html',locals())

But I get this error:
KeyError at /mypage/
    'REMOTE_ADDR'
    Request Method: GET
    Request URL:    http://mywebsite.com/mypage/
    Django Version: 1.2.4
    Exception Type: KeyError
    Exception Value:
    'REMOTE_ADDR'
    Exception Location: /mysite/homepage/views.py in home, line 9
    Python Executable:  /usr/bin/python
    Python Version: 2.6.6
    Python Path:    ['/mysite', '/usr/local/lib/python2.6/dist-packages/flup-1.0.2-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/local/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages', '/usr/lib/pymodules/python2.6']
    Server time:    Sun, 2 Jan 2011 20:42:50 -0600

Output:
def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

Make sure you have reverse proxy (if any) configured correctly (e.g. mod_rpaf installed for Apache).
Note: the above uses the first item in X-Forwarded-For, but you might want to use the last item (e.g., in the case of Heroku: Get client's real IP address on Heroku)
get_client_ip = lambda req: req.META.get('HTTP_X_FORWARDED_FOR') if req.META.get('HTTP_X_FORWARDED_FOR') else ip = request.META.get('REMOTE_ADDR')

And then just pass the request as argument to it;
get_client_ip(request)


Input:
Python, Matplotlib, subplot: How to set the axis range? How can I set the y axis range of the second subplot to e.g. [0,1000] ?
The FFT plot of my data (a column in a text file) results in a (inf.?) spike so that the actual data is not visible.
pylab.ylim([0,1000])

has no effect, unfortunately. This is the whole script:
# based on http://www.swharden.com/blog/2009-01-21-signal-filtering-with-python/
import numpy, scipy, pylab, random

xs = []
rawsignal = []
with open("test.dat", 'r') as f:
      for line in f:
            if line[0] != '#' and len(line) > 0:
                xs.append( int( line.split()[0] ) )
                rawsignal.append( int( line.split()[1] ) )

h, w = 3, 1
pylab.figure(figsize=(12,9))
pylab.subplots_adjust(hspace=.7)

pylab.subplot(h,w,1)
pylab.title("Signal")
pylab.plot(xs,rawsignal)

pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
#~ pylab.axis([None,None,0,1000])
pylab.ylim([0,1000])
pylab.plot(abs(fft))

pylab.savefig("SIG.png",dpi=200)
pylab.show()

Other improvements are also appreciated!

Output:
As found in http://www.mofeel.net/582-comp-soft-sys-matlab/54166.aspx
 pylab.ylim([0,1000])

Note: The command has to be executed after the plot!


Input: What can you use Python generator functions for? I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them.  I want to know what types of problems that these functions are really good at solving.

Output:
Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.
Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses another generator, or consumes some other resource, and it's more convenient if that happened as late as possible.
Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.
For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.
If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:
big_list = list(the_generator)


Input:
ImportError: Cannot import name X I have four different files named: main, vector, entity, and physics. I will not post all the code, mostly just the imports, because I think that's where the error is. But if you want, I can post more.
Main:
import time
from entity import Ent
from vector import Vect
#the rest just creates an entity and prints the result of movement

Entity:
from vector import Vect
from physics import Physics
class Ent:
    #holds vector information and id
def tick(self, dt):
    #this is where physics changes the velocity and position vectors

Vector:
from math import *
class Vect:
    #holds i, j, k, and does vector math

Physics:
from entity import Ent
class Physics:
    #physics class gets an entity and does physics calculations on it.

I then run from main.py and I get the following error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
    from entity import Ent
File ".../entity.py", line 5, in <module>
    from physics import Physics
File ".../physics.py", line 2, in <module>
    from entity import Ent
ImportError: cannot import name Ent

I am very new to python, but have worked with C++ for a long time. I am guessing that the cause is from importing entity twice, once in main, and later in physics, but I don't know a workaround. Anyone help?

Output: You have circular dependent imports. physics.py is imported from entity before class Ent is defined and physics tries to import entity that is already initializing. Remove the depency to physics from entity module.


Input: Python read a single character from the user Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()). I know there's a function in Windows for it, but I'd like something that is cross-platform.

Output:
Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: http://code.activestate.com/recipes/134892/
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()


Input:
How do I create a slug in Django? I am trying to create a SlugField in Django.
I created this simple model:
from django.db import models

class Test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

I then do this:
>>> from mysite.books.models import Test
>>> t=Test(q="aa a a a", s="b b b b")
>>> t.s
'b b b b'
>>> t.save()
>>> t.s
'b b b b'
>>>

I was expecting b-b-b-b

Output:
You will need to use the slugify function.
>>> from django.template.defaultfilters import slugify
>>> slugify("b b b b")
u'b-b-b-b'
>>>

You can call slugify automatically by overriding the save method:
class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        self.s = slugify(self.q)
        super(test, self).save(*args, **kwargs)

Be aware that the above will cause your URL to change when the q field is edited, which can cause broken links. It may be preferable to generate the slug only once when you create a new object:
class test(models.Model):
    q = models.CharField(max_length=30)
    s = models.SlugField()

    def save(self, *args, **kwargs):
        if not self.id:
            # Newly created object, so set slug
            self.s = slugify(self.q)

        super(test, self).save(*args, **kwargs)


Input:
Why aren't python nested functions called closures? I have seen and used nested functions in Python, and they match the definition of a closure.  So why are they called nested functions instead of closures?
Are nested functions not closures because they are not used by the external world?
UPDATE: I was reading about closures and it got me thinking about this concept with respect to Python. I searched and found the article mentioned by someone in a comment below, but I couldn't completely understand the explanation in that article, so that is why I am asking this question.

Output:
A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution.
def make_printer(msg):
    def printer():
        print msg
    return printer

printer = make_printer('Foo!')
printer()

When make_printer is called, a new frame is put on the stack with the compiled code for the printer function as a constant and the value of msg as a local. It then creates and returns the function. Because the function printer references the msg variable, it is kept alive after the make_printer function has returned.
So, if your nested functions don't

access variables that are local to enclosing scopes,
do so when they are executed outside of that scope,

then they are not closures.
Here's an example of a nested function which is not a closure.
def make_printer(msg):
    def printer(msg=msg):
        print msg
    return printer

printer = make_printer("Foo!")
printer()  #Output: Foo!

Here, we are binding the value to the default value of a parameter. This occurs when the function printer is created and so no reference to the value of msg external to printer  needs to be maintained after make_printer returns. msg is just a normal local variable of the function printer in this context.


Input:
Lazy Method for Reading Big File in Python? I have a very big file 4GB and when I try to read it my computer hangs.
So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.
Is there any method to yield these pieces ?
I would love to have a lazy method.

Output:
To write a lazy function, just use yield:
def read_in_chunks(file_object, chunk_size=1024):
    """Lazy function (generator) to read a file piece by piece.
    Default chunk size: 1k."""
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

f = open('really_big_file.dat')
for piece in read_in_chunks(f):
    process_data(piece)

Another option would be to use iter and a helper function:
f = open('really_big_file.dat')
def read1k():
    return f.read(1024)

for piece in iter(read1k, ''):
    process_data(piece)

If the file is line-based, the file object is already a lazy generator of lines:
for line in open('really_big_file.dat'):
    process_data(line)


Input:
check if all elements in a list are identical I need the following function:
Input: a list
Output:

True if all elements in the input list evaluate as equal to each other using the standard equality operator;
False otherwise.

Performance: of course, I prefer not to incur any unnecessary overhead.
I feel it would be best to:

iterate through the list
compare adjacent elements
and AND all the resulting Boolean values

But I'm not sure what's the most Pythonic way to do that.

EDIT:
Thank you for all the great answers. I rated up several, and it was really hard to choose between @KennyTM and @Ivo van der Wijk solutions.
The lack of short-circuit feature only hurts on a long input (over ~50 elements) that have unequal elements early on. If this occurs often enough (how often depends on how long the lists might be), the short-circuit is required. The best short-circuit algorithm seems to be @KennyTM checkEqual1. It pays, however, a significant cost for this:

up to 20x in performance nearly-identical lists
up to 2.5x in performance on short lists

If the long inputs with early unequal elements don't happen (or happen sufficiently rarely), short-circuit isn't required. Then, by far the fastest is @Ivo van der Wijk solution.

Output:
General method:
def checkEqual1(iterator):
    iterator = iter(iterator)
    try:
        first = next(iterator)
    except StopIteration:
        return True
    return all(first == rest for rest in iterator)

One-liner:
def checkEqual2(iterator):
   return len(set(iterator)) <= 1

Also one-liner:
def checkEqual3(lst):
   return lst[1:] == lst[:-1]

The difference between the 3 versions are that:

In checkEqual2 the content must be hashable.
checkEqual1 and checkEqual2 can use any iterators, but checkEqual3 must take a sequence input, typically concrete containers like a list or tuple.
checkEqual1 stops as soon as a difference is found.
Since checkEqual1 contains more Python code, it is less efficient when many of the items are equal in the beginning.
Since checkEqual2 and checkEqual3 always perform O(N) copying operations, they will take longer if most of your input will return False.
checkEqual2 and checkEqual3 can't be easily changed to adopt to compare a is b instead of a == b.

timeit result, for Python 2.7 and (only s1, s4, s7, s9 should return True)
s1 = [1] * 5000
s2 = [1] * 4999 + [2]
s3 = [2] + [1]*4999
s4 = [set([9])] * 5000
s5 = [set([9])] * 4999 + [set([10])]
s6 = [set([10])] + [set([9])] * 4999
s7 = [1,1]
s8 = [1,2]
s9 = []

we get
      | checkEqual1 | checkEqual2 | checkEqual3  | checkEqualIvo | checkEqual6502 |
|-----|-------------|-------------|--------------|---------------|----------------|
| s1  | 1.19   msec | 348    usec | 183     usec | 51.6    usec  | 121     usec   |
| s2  | 1.17   msec | 376    usec | 185     usec | 50.9    usec  | 118     usec   |
| s3  | 4.17   usec | 348    usec | 120     usec | 264     usec  | 61.3    usec   |
|     |             |             |              |               |                |
| s4  | 1.73   msec |             | 182     usec | 50.5    usec  | 121     usec   |
| s5  | 1.71   msec |             | 181     usec | 50.6    usec  | 125     usec   |
| s6  | 4.29   usec |             | 122     usec | 423     usec  | 61.1    usec   |
|     |             |             |              |               |                |
| s7  | 3.1    usec | 1.4    usec | 1.24    usec | 0.932   usec  | 1.92    usec   |
| s8  | 4.07   usec | 1.54   usec | 1.28    usec | 0.997   usec  | 1.79    usec   |
| s9  | 5.91   usec | 1.25   usec | 0.749   usec | 0.407   usec  | 0.386   usec   |

Note:
# http://stackoverflow.com/q/3844948/
def checkEqualIvo(lst):
    return not lst or lst.count(lst[0]) == len(lst)

# http://stackoverflow.com/q/3844931/
def checkEqual6502(lst):
    return not lst or [lst[0]]*len(lst) == lst


Input:
Get MD5 hash of big files in Python I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in hashlib.md5() function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loading the whole file to memory?

Output:
You need to read the file in chunks of suitable size:
def md5_for_file(f, block_size=2**20):
    md5 = hashlib.md5()
    while True:
        data = f.read(block_size)
        if not data:
            break
        md5.update(data)
    return md5.digest()

NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
def generate_file_md5(rootdir, filename, blocksize=2**20):
    m = hashlib.md5()
    with open( os.path.join(rootdir, filename) , "rb" ) as f:
        while True:
            buf = f.read(blocksize)
            if not buf:
                break
            m.update( buf )
    return m.hexdigest()

The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation
I cross-checked the results using the 'jacksum' tool.
jacksum -a md5 <filename>

http://www.jonelo.de/java/jacksum/


Input:
How to exit from Python without traceback? I would like to know how to I exit from Python without having an traceback dump on the output.
I still want want to be able to return an error code but I do not want to display the traceback log.
I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.

Output:
You are presumably encountering an exception and the program is exiting because of this (with a traceback).  The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main routine:
import sys, traceback

def main():
    try:
        do main program stuff here
        ....
    except KeyboardInterrupt:
        print "Shutdown requested...exiting"
    except Exception:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)

if __name__ == "__main__":
    main()


Input: How do I execute a string containing Python code in Python? How do I execute a string containing Python code in Python?

Output:
For statements, use exec(string) (Python 2/3) or exec string (Python 2):
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world

When you need the value of an expression, use eval(string):
>>> x = eval("2+2")
>>> x
4

However, the first step should be to ask yourself if you really need to.  Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code.  You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.


Input:
How to comment out a block of Python code in Vim I was wondering if there was any key mapping in Vim to allow me to indent certain lines of code (whether those lines have been selected in visual mode, or n lines above/below current cursor position).
So basically something that converts the following
def my_fun(x, y):
    return x + y

to
#def my_fun(x, y):
#    return x + y

I am okay with using either # or """ for commenting out the relevant lines. Ideally, I would also like the same keymapping to uncomment the lines if the given lines have been commented out.

Output:
Step 1: Go to the the first column of the first line you want to comment.

Step 2: Press: Ctrl+v and select the lines you want to comment:

Step 3: Shift-I#space (Enter Insert-at-left mode, type chars to insert.  The selection will disappear, but all lines within it will be modified after Step 4.)

Step 4: Esc


Input:
Store output of subprocess.Popen call in a string I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.
#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")

I've tried a few things including some of the suggestions here:
Retrieving the output of subprocess.call()
but without any luck.

Output:
In Python 2.7 or Python 3
Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:
from subprocess import check_output

out = check_output(["ntpq", "-p"])

In Python 2.4-2.6
Use the communicate method.
import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

out is what you want.
Important note about the other answers
Note how I passed in the command. The "ntpq -p" example brings up another matter. Since Popen does not involke the shell, you would use a list of the command and optionsâ["ntpq", "-p"].


Input:
Getting a map() to return a list in Python 3.x I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
A: Python 2.6:
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']

However, on Python 3.1, the above returns a map object.
B: Python 3.1:
>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>

How do I retrieve the mapped list (as in A above) on Python 3.x?
Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.

Output:
Do this:
list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves.  In most cases, this ends up saving memory, and should make things go faster.
If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:
# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)


Input:
Pretty-printing of numpy.array I'm curious, whether there is any way to print formatted numpy.arrays, e.g., in the way similar to this:
x = 1.23456
print '%.3f' % x

If I want to print the numpy.array of floats, it prints several decimals, often in 'scientific' format, which is rather hard to read even for low-dimensional arrays. However, numpy.array apparently has to be printed as a string, i.e., with %s. Is there any solution for this purpose?

Output:
You can use set_printoptions to set the precision of the output:
import numpy as np
x=np.random.random(10)
print(x)
# [ 0.07837821  0.48002108  0.41274116  0.82993414  0.77610352  0.1023732
#   0.51303098  0.4617183   0.33487207  0.71162095]

np.set_printoptions(precision=3)
print(x)
# [ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]

And suppress suppresses the use of scientific notation for small numbers:
y=np.array([1.5e-10,1.5,1500])
print(y)
# [  1.500e-10   1.500e+00   1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [    0.      1.5  1500. ]

See the docs for set_printoptions for other options.

To apply print options locally, you could use a contextmanager:
import numpy as np
import contextlib

@contextlib.contextmanager
def printoptions(*args, **kwargs):
    original = np.get_printoptions()
    np.set_printoptions(*args, **kwargs)
    yield
    np.set_printoptions(**original)

For example, inside the with-suite precision=3 and suppress=True are set:
x = np.random.random(10)
with printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

But outside the with-suite the print options are back to default settings:
print(x)
# [ 0.07334334  0.46132615  0.68935231  0.75379645  0.62424021  0.90115836
#   0.04879837  0.58207504  0.55694118  0.34768638]

To prevent zeros from being stripped from the end of floats:
np.set_printoptions now has a formatter parameter which allows you to specify a format function for each type.
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)

which prints
[ 0.078  0.480  0.413  0.830  0.776  0.102  0.513  0.462  0.335  0.712]

instead of
[ 0.078  0.48   0.413  0.83   0.776  0.102  0.513  0.462  0.335  0.712]


Input:
Convert list of dictionaries to Dataframe I have a list of dictionaries like this:
[{'points': 50, 'time': '5:00', 'year': 2010},
{'points': 25, 'time': '6:00', 'month': "february"},
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]

and I want to turn this into a pandas DataFrame like this:
      month  points  points_h1  time  year
0       NaN      50        NaN  5:00  2010
1  february      25        NaN  6:00   NaN
2   january      90        NaN  9:00   NaN
3      june     NaN         20   NaN   NaN

Note: Order of the columns does not matter.
Ultimately, the goal is to write this to a text file and this seems like the best solution I could find.  How can I turn the list of dictionaries into a panda DataFrame as shown above?

Output:
Supposing d is your list of dicts, simply:
pd.DataFrame(d)


Input:
Having Django serve downloadable files I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.
For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt
And on the server, I know that all downloadable files reside in a folder "/home/user/files/".
Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?

Output:
For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:
from django.utils.encoding import smart_str

response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response

Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.


Input:
Compiled vs. Interpreted Languages I'm trying to get a better understanding of the difference. I've found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.
Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand that there are other kinds of interpreted and compiled languages. Aside from the fact that executable files can be distributed from programs written in compiled languages, are there any advantages/disadvantages to each type? Oftentimes, I hear people arguing that interpreted languages can be used interactively, but I believe that compiled languages can have interactive implementations as well, correct?

Output:
A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code.
An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same "+" operation would be recognised by the interpreter at run time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then execute the machine code "ADD" instruction.
You can do anything that you can do in an interpreted language in a compiled language and vice-versa - they are both Turing complete. Both however have advantages and disadvantages for implementation and use.
I'm going to completely generalise (purists forgive me!) but, roughly, here are the advantages of compiled languages:

Faster performance by directly using the native code of the target machine
Opportunity to apply quite powerful optimisations during the compile stage

And here are the advantages of interpreted languages:

Easier to implement (writing good compilers is very hard!!)
No need to run a compilation stage: can execute code directly "on the fly"
Can be more convenient for dynamic languages

Note that modern techniques such as bytecode compilation add some extra complexity - what happens here is that the compiler targets a "virtual machine" which is not the same as the underlying hardware. These virtual machine instructions can then be compiled again at a later stage to get native code (e.g. as done by the Java JVM JIT compiler).


Input:
Print a list in reverse order with range()? How can you produce the following list with range() in Python?
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Output:
Use the 'range' built-in function. The signature is range(start, stop, step).  This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding stop.
>>> range(9,-1,-1)
    [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> range(-2, 6, 2)
    [-2, 0, 2, 4]

In Python 3, this produces a non-list range object, which functions effectively like a read-only list (but uses way less memory, particularly for large ranges).


Input:
Numpy array dimensions I'm currently trying to learn Numpy and Python. Given the following array:
import numpy as N
a = N.array([[1,2],[1,2]])

Is there a function that returns the dimensions of a (e.g.a is a 2 by 2 array)?
size() returns 4 and that doesn't help very much.

Output:
It is .shape:

ndarray.shape
  Tuple of array dimensions.

Thus:
>>> a.shape
(2, 2)


Input:
How to retrieve an element from a set without removing it? Suppose the following:
>>>s = set([1, 2, 3])

How do I get a value (any value) out of s without doing s.pop()? I want to leave the item in the set until I am sure I can remove it - something I can only be sure of after an asynchronous call to another host.
Quick and dirty:
>>>elem = s.pop()
>>>s.add(elem)

But do you know of a better way? Ideally in constant time.

Output:
Two options that don't require copying the whole set:
for e in s:
    break
# e is now an element from s

Or...
e = next(iter(s))

But in general, sets don't support indexing or slicing.


Input:
What is an alternative to execfile in Python 3.0? It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload().
Is there an obvious alternative I'm missing?

Output:
You are just supposed to read the file and exec the code yourself. 2to3 current replaces
execfile("somefile.py", global_vars, local_vars)

as
with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)
See:

http://docs.python.org/release/2.7.3/library/functions.html#execfile
http://docs.python.org/release/3.2.3/library/functions.html#compile
http://docs.python.org/release/3.2.3/library/functions.html#exec


Input:
How do I integrate Ajax with Django applications? I am new to Django and pretty new to Ajax. I am working on a project where I need to integrate the two. I believe that I understand the principles behind them both, but have not found a good explanation of the two together.
Could someone give me a quick explanation of how the codebase must change with the two of them integrating together?
For example, can I still use the HttpResponse with Ajax, or do my responses have to change with the use of Ajax? If so, could you please provide an example of how the responses to the requests must change? If it makes any difference, the data I am returning is JSON.

Output:
Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).
Django is server-side. It means, say a client goes to url you have a function inside views that renders what he sees and returns a response in html. let's break it up into examples:
views.py
def hello(request):
    return HttpResponse('Hello World!')

def home(request):
    return render_to_response('index.html', {'variable': 'world'})

index.html:

Hello {{ variable }}, welcome to my awesome site

urls.py
url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),

That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello means a request to the hello function, going to 127.0.0.1:8000/home will return the index.html and replace all the variables as asked (you probably know all this by now).
Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some url, you get the same data you would get as a user going to that place.
For example, an ajax call to 127.0.0.1:8000/hello will return the same thing it would as if you visited it. Only this time, you have it inside a js function and you can deal with it however you'd like. Let's look at a simple use case:
$.ajax({
    url: '127.0.0.1:8000/hello',
    type: 'get', // This is the default though, you don't actually need to always mention it
    success: function(data) {
        alert(data);
    },
    failure: function(data) {
        alert('Got an error dude');
    }
});

The general process is this:

The call goes to the url 127.0.0.1:8000/hello as if you opened a new tab and did it yourself.
If it succeeds (status code 200), do the function for success, which will alert the data recieved.
If fails, do a different function.

Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an ajax call to home? Same thing, you'll get an alert stating
Hello world, welcome to my awesome site
.
In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:

Learn jQuery. I cannot stress this enough. You're gonna have to understand it a little to know how to handle the data you receive. You'll also need to understand some basic javascript syntax (not far from python, you'll get used to it). I strongly recommend Envato's video tutorials for jQuery, they are great and will put you on the right path.
When to use JSON?. You're going to see a lot of examples where the data sent by the Django views is in JSON. I didn't go into detail on that, because it isn't important how to do it (there are plenty of explanations abound) and a lot more important when. And the answer to that is - JSON data is serialized data. That is, data you can manipulate. Like I mentioned, an AJAX call will fetch the response as if the user did it himself. Now say you don't want to mess with all the html, and instead want to send data (a list of objects perhaps). JSON is good for this, because it sends it as an object (JSON data looks like a python dictionary), and then you can iterate over it or do something else that removes the need to sift through useless html.
Add it last. When you build a web app and want to implement AJAX - do yourself a favor. First, build the entire app completely devoid of any AJAX. See that everything is working. Then, and only then, start writing the AJAX calls. That's a good process that helps you learn a lot as well.
Use chrome's developer tools. Since AJAX calls are done in the background it's sometimes very hard to debug them. You should use the chrome developer tools (or similar tools such as firebug) and console.log things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.
CSRF awareness. Finally, remember that post requests in Django require the csrf_token. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.

That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.


Input:
Generating a PNG with matplotlib when DISPLAY is undefined I am trying to use networkx with Python. When I run this program it get this error. Is there anything missing?
#!/usr/bin/env python

import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt

G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")

Traceback (most recent call last):
  File "graph.py", line 13, in <module>
    nx.draw(G)
  File "/usr/lib/pymodules/python2.5/networkx/drawing/nx_pylab.py", line 124, in draw
    cf=pylab.gcf()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

I get a different error now:
#!/usr/bin/env python

import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt

matplotlib.use('Agg')

G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")

/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning:  This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
  File "graph.py", line 15, in <module>
    nx.draw(G)
  File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
    cf=pylab.gcf()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

I get a different error now:
#!/usr/bin/env python

import networkx as nx
import matplotlib
import matplotlib.pyplot
import matplotlib.pyplot as plt

matplotlib.use('Agg')

G=nx.Graph()
G.add_node(1)
G.add_nodes_from([2,3,4,5,6,7,8,9,10])
#nx.draw_graphviz(G)
#nx_write_dot(G, 'node.png')
nx.draw(G)
plt.savefig("/var/www/node.png")

/usr/lib/pymodules/python2.5/matplotlib/__init__.py:835: UserWarning:  This call to matplotlib.use() has no effect
because the the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

  if warn: warnings.warn(_use_error_msg)
Traceback (most recent call last):
  File "graph.py", line 15, in <module>
    nx.draw(G)
  File "/usr/lib/python2.5/site-packages/networkx-1.2.dev-py2.5.egg/networkx/drawing/nx_pylab.py", line 124, in draw
    cf=pylab.gcf()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 276, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.5/matplotlib/pyplot.py", line 254, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.5/matplotlib/backends/backend_tkagg.py", line 90, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1650, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

Output:
The main problem is that (on your system) matplotlib chooses an x-using backend by default. I just had the same problem on one of my servers.  The solution for me was to add the following code in a place that gets read before any other pylab/matplotlib/pyplot import:
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')

The alternative is to set it in your .matplotlibrc


Input:
parsing boolean values with argparse I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
my_program --my_boolean_flag False

However, the following test code does not do what I would like:
import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse(cmd_line)

Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evalutates to False.
How can I get argparse to parse "False", "F", and their lower-case variants to be False?

Output:
I think a more canonical way to do this is via:
command --feature

and
command --no-feature

argparse supports this version nicely:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

Of course, if you really want the --arg <True|False> version, you could pass ast.literal_eval as the "type", or a user defined function ...
def t_or_f(arg):
    ua = str(arg).upper()
    if 'TRUE'.startswith(ua):
       return True
    elif 'FALSE'.startswith(ua):
       return False
    else:
       pass  #error condition maybe?


Input:
How to percent-encode URL parameters in Python? If I do
url = "http://example.com?p=" + urllib.quote(query)

It doesn't encode / to %2F (breaks OAuth normalization)
It doesn't handle Unicode (it throws an exception)

Is there a better library?

Output:
From the docs:
urllib.quote(string[, safe])

Replace special characters in string
  using the %xx escape. Letters, digits,
  and the characters '_.-' are never
  quoted. By default, this function is
  intended for quoting the path section
  of the URL.The optional safe parameter
  specifies additional characters that
  should not be quoted â its default
  value is '/'

That means passing '' for safe will solve your first issue:
>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:
>>> query = urllib.quote(u"MÃ¼ller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
MÃ¼ller

By the way have a look at urlencode


Input:
How to add to the pythonpath in windows 7? I have a directory which hosts all of my Django apps (C:\My_Projects). I want to add this directory to my pythonpath so I can call the apps directly.
I have tried adding C:\My_Projects\; to my Path variable from the Windows GUI (My Computer > Properties > Advanced System Settings > Environment Variables). But it still doesn't read the coltrane module and generates this error:

Error: No module named coltrane

Output:
You know what has worked for me really well on windows.
My Computer > Properties > Advanced System Settings > Environment Variables >
Then under system variables I create a new Variable called PythonPath. In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-foolder-on-the-path

This is the best way that has worked for me which I hadn't found in any of the docs offered.
EDIT: For those who are not able to get it,
Please add

C:\Python27;

along with it. Else it will never work.


Input:
Python argparse: How to insert newline in the help text? I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.
from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()

However, argparse strips all newlines and consecutive spaces. The result looks like

~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:
  -h, --help      show this help message and exit
  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e
                  = epsilon

How to insert newlines in the help text?

Output:
Try using RawTextHelpFormatter:
from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)


Input:
What is the ellipsis [...] in a Python list? I was playing around in python. I used the following code in IDLE
p  = [1, 2]
p[1:1] = [p]
print p

The output was
[1, [...], 2]

What is this [â¦]? Interestingly I could now use this as a list of list of list upto infinity i.e.
p[1][1][1]....

I could write the above as long as I wanted and it would  still work.
EDIT:

How is it represented in memory?
What's its use? Examples of some cases where it is useful would be helpful.
Any link to official documentation would be really useful.

Output:
This is what your code created

It's a list where the first and last elements are pointing to two numbers (1 and 2) and where the middle element is pointing to the list itself.
In Common Lisp when printing circular structures is enabled such an object would be printed as
#1=#(1 #1# 2)

meaning that there is an object (labelled 1 with #1=) that is a vector with three elements, the second being the object itself (back-referenced with #1#).
In Python instead you just get the information that the structure is circular with [...].
In this specific case the description is not ambiguous (it's backward pointing to a list but there is only one list so it must be that one). In other cases may be however ambiguous... for example in
[1, [2, [...], 3]]

the backward reference could either to the outer or to the inner list.
These two different structures printed in the same way can be created with
x = [1, [2, 3]]
x[1][1:1] = [x[1]]

y = [1, [2, 3]]
y[1][1:1] = [y]

print x, y

and they would be in memory as


Input:
Creating a new dict in Python I want to build a dictionary in Python. However, all the examples that I see are instantiating a dictionary from a list, etc . ..
How do I create a new empty dictionary in Python?

Output:
Call dict with no parameters
new_dict = dict()

or simply write
new_dict = {}


Input:
How do I filter ForeignKey choices in a Django ModelForm? Say I have the following in my models.py:
class Company(models.Model):
   name = ...

class Rate(models.Model):
   company = models.ForeignKey(Company)
   name = ...

class Client(models.Model):
   name = ...
   company = models.ForeignKey(Company)
   base_rate = models.ForeignKey(Rate)

I.e. there are multiple Companies, each having a range of Rates and Clients.  Each Client should have a base Rate that is chosen from it's parent Company's Rates, not another Company's Rates.
When creating a form for adding a Client, I would like to remove the Company choices (as that has already been selected via an "Add Client" button on the Company page) and limit the Rate choices to that Company as well.
How do I go about this in Django 1.0?
My current forms.py file is just boilerplate at the moment:
from models import *
from django.forms import ModelForm

class ClientForm(ModelForm):
    class Meta:
        model = Client

And the views.py is also basic:
from django.shortcuts import render_to_response, get_object_or_404
from models import *
from forms import *

def addclient(request, company_id):
    the_company = get_object_or_404(Company, id=company_id)

    if request.POST:
    	form = ClientForm(request.POST)
    	if form.is_valid():
    		form.save()
    		return HttpResponseRedirect(the_company.get_clients_url())
    else:
    	form = ClientForm()

    return render_to_response('addclient.html', {'form': form, 'the_company':the_company})

In Django 0.96 I was able to hack this in by doing something like the following before rendering the template:
manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)]

ForeignKey.limit_choices_to seems promising but I don't know how to pass in the_company.id and I'm not clear if that will work outside the Admin interface anyway.
Thanks.  (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)

Output:
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet.  See the reference for ModelChoiceField.
So, provide a QuerySet to the field's queryset attribute.  Depends on how your form is built.  If you build an explicit form, you'll have fields named directly.
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)

If you take the default ModelForm object, form.fields["rate"].queryset = ...
This is done explicitly in the view.  No hacking around.


Input:
How do I remove/delete a virtualenv? I created an environment with the following command: virtualenv venv --distribute
I cannot remove it with the following command: rmvirtualenv venv
I do an lson my current directory and I still see venv
The only way I can remove it seems to be: sudo rm -rf venv
Note that the environment is not active. I'm running Ubuntu 11.10. Any ideas? I've tried rebooting my system to no avail.

Output: That's it! There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it.


Input:
How to get a complete list of object's methods and attributes? dir(re.compile(pattern))

does not return pattern as one of the lists's elements. Namely it returns:
['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']

According to the manual, it is supposed to contain

the object's attributes' names, the
  names of its class's attributes, and
  recursively of the attributes of its
  class's base classes.

It says also that

The list is not necessarily complete.

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...
Also: is there a way to list only attributes? Or only methods?
Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)

Output:
For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The dir function returns the keys in the __dict__ attribute, i.e. all the attributes accessible if the __getattr__ method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the inspect module determine the class methods, methods or functions.


Input:
What is __future__ in Python used for and how/when to use it, and how it works People including me know there is something in Python called __future__ and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading the Python's __future__ doc.
So any explains with examples to demonstrate it?
I have got a few answers quickly, which look all correct, in terms of the basic usage.
However and also for further understanding how __future__ works:
I just realized one key thing that was confusing me when I tried to understand it, that is, how a current python release include something that will be released in future release?
and how can a program using a new feature in a future python release be compiled successfully by the current python release?
So, I guess now that, the current release has already packaged some potential features that will be included in future releases - is this right? but the features are available only by __future__, that is because it doesn't become standard yet - am I right?

Output:
With it, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do from __future__ import with_statement in 2.5, as the with keyword was new and shouldn't be used as variable names any longer. In order to be able to use a program which uses variables named with, the above import statement is needed.
Another example is
from __future__ import division
print 8/7  # prints 1.1428571428571428
print 8//7 # prints 1

Without the __future__ stuff, both print statements would print 1.
The internal difference is that without that import, / is mapped to the __div__() method, while with it, __truediv__() is used. (In any case, // calls __floordiv__().)
A propos print: print becomes a function in 3.x, losing its special property as a keyword. So it is the other way round.
>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>>


Input: Which version of Python do I have installed? I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter? I was thinking of updating to latest version of Python.

Output:
python -V

http://docs.python.org/using/cmdline.html#generic-options
--version may also work (introduced in version 2.5)


Input:
How do I remove a substring from the end of a string in Python? I have the following code:
url = 'abcdc.com'
print(url.strip('.com'))

I expected: abcdc
I got: abcd
Now I do
url.rsplit('.com', 1)

Is there a better way?

Output:
You could do this:
url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]

Or using regular expressions:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)


Input: Printing Python version in output How can I print version number for the current Python installation in the output?

Output:
Try
import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien LÃ©onard's solution is the best. You might want to examine the full string and see if you need it or portions of it.


Input:
How to get console window width in python Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.
Edit
Looking for a solution that works on Linux

Output:
import os
rows, columns = os.popen('stty size', 'r').read().split()

uses the 'stty size' command which according to a thread on the python mailing list is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.
Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).


Input:
Python: defaultdict of defaultdict? Is there a way to have a defaultdict(defaultdict(int)) in order to make the following code work?
for x in stuff:
    d[x.a][x.b] += x.c_int

d needs to be built ad-hoc, depending on x.a and x.b elements.
I could use:
for x in stuff:
    d[x.a,x.b] += x.c_int

but then I wouldn't be able to use:
d.keys()
d[x.a].keys()

Output:
Yes like this:
defaultdict(lambda : defaultdict(int))


Input:
How can the euclidean distance be calculated with numpy? I have two points in 3D:
(xa, ya, za)
(xb, yb, zb)

And I want to calculate the distance:
dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

What's the best way to do this with Numpy, or with Python in general?  I have:
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))

Output:
Use numpy.linalg.norm:
dist = numpy.linalg.norm(a-b)


Input:
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields? I have a Person model that has a foreign key relationship to Book.  Book has a number of fields, but I'm most concerned about "author" (a standard CharField).
With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display".  I've tried all of the obvious methods for doing so (see below), but nothing seems to work.  Any suggestions?
class PersonAdmin(admin.ModelAdmin):
  list_display = ['book.author',]

Output:
As another option, you can do look ups like:
class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')

    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'


Input:
How to get current CPU and RAM usage in Python? What's your preferred way of getting current system status (current CPU, RAM, free disk space, etc.) in Python? Bonus points for *nix and Windows platforms.
There seems to be a few possible ways of extracting that from my search:

Using a library such as PSI (that currently seems not actively developed and not supported on multiple platform) or something like pystatgrab (again no activity since 2007 it seems and no support for Windows).
Using platform specific code such as using a os.popen("ps") or similar for the *nix systems and MEMORYSTATUS in ctypes.windll.kernel32 (see this recipe on ActiveState) for the Windows platform. One could put a Python class together with all those code snippets.

It's not that those methods are bad but is there already a well-supported, multi-platform way of doing the same thing?

Output:
The psutil library will give you some system information (CPU / Memory usage) on a variety of platforms:

psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top  and Windows task manager.
It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).


Input:
DatabaseError: current transaction is aborted, commands ignored until end of transaction block I got a lot of errors with the message :
"DatabaseError: current transaction is aborted, commands ignored until end of transaction block"

after changed from python-psycopg to python-psycopg2 as Django project's database engine.
The code remains the same, just dont know where those errors are from.

Output:
To get rid of the error, roll back the last (erroneous) transaction after you've fixed your code:
from django.db import transaction
transaction.rollback()

You can use try-except to prevent the error from occurring:
from django.db import transaction, DatabaseError
try:
    a.save()
except DatabaseError:
    transaction.rollback()

Refer : Django documentation


Input:
Why use Python's os module methods instead of executing shell commands directly? I am trying to understand what is the motivation behind using Python's library functions for executing OS-specific tasks such as creating files/directories, changing file attributes, etc. instead of just executing those commands via os.system() or subprocess.call()?
For example, why would I want to use os.chmod instead of doing os.system("chmod...")?
I understand that it is more "pythonic" to use Python's available library methods as much as possible instead of just executing shell commands directly. But, is there any other motivation behind doing this from a functionality point of view?
I am only talking about executing simple one-line shell commands here. When we need more control over the execution of the task, I understand that using subprocess module makes more sense, for example.

Output:
It's faster, os.system and subprocess.call create new processes which is unnecessary for something this simple. In fact, os.system and subprocess.call with the shell argument usually create at least two new processes: the first one being the shell, and the second one being the command that you're running (if it's not a shell built-in like test).
Some commands are useless in a separate process. For example, if you run os.spawn("cd dir/"), it will change the current working directory of the child process, but not of the Python process. You need to use os.chdir for that.
You don't have to worry about special characters interpreted by the shell. os.chmod(path, mode) will work no matter what the filename is, whereas os.spawn("chmod 777 " + path) will fail horribly if the filename is something like ; rm -rf ~. (Note that you can work around this if you use subprocess.call without the shell argument.)
You don't have to worry about filenames that begin with a dash. os.chmod("--quiet", mode) will change the permissions of the file named --quiet, but os.spawn("chmod 777 --quiet") will fail, as --quiet is interpreted as an argument. This is true even for subprocess.call(["chmod", "777", "--quiet"]).
You have fewer cross-platform and cross-shell concerns, as Python's standard library is supposed to deal with that for you. Does your system have chmod command? Is it installed? Does it support the parameters that you expect it to support? The os module will try to be as cross-platform as possible and documents when that it's not possible.
If the command you're running has output that you care about, you need to parse it, which is trickier than it sounds, as you may forget about corner-cases (filenames with spaces, tabs and newlines in them), even when you don't care about portability.


Input:
How to write inline if statement for print? I need to print some stuff only when a boolean variable is set to True. So, after looking at this, I tried with a simple example:
>>> a = 100
>>> b = True
>>> print a if b
  File "<stdin>", line 1
    print a if b
             ^
SyntaxError: invalid syntax

Same thing if I write print a if b==True.
What am I missing here?

Output:
Python does not have a trailing if statement.
There are two kinds of if in Python:

if statement:
if condition: statement
if condition:
    block

if expression (introduced in Python 2.5)
expression_if_true if condition else expression_if_false

And note, that both print a and b = a are statements. Only the a part is an expression. So if you write
print a if b else 0

it means
print (a if b else 0)

and similarly when you write
x = a if b else 0

it means
x = (a if b else 0)

Now what would it print/assign if there was no else clause? The print/assignment is still there.
And note, that if you don't want it to be there, you can always write the regular if statement on a single line, though it's less readable and there is really no reason to avoid the two-line variant.


Input: How to uninstall Python 2.7 on a Mac OS X 10.6.4? I want to completely remove Python 2.7 from my Mac OS X 10.6.4. I managed to remove the entry from the PATH variable by reverting my .bash_profile. But I also want to remove all directories, files, symlinks, and entries that got installed by the Python 2.7 install package. I've got the install package from http://www.python.org/. What directories/files/configuration file entries do I need to remove? Is there a list somewhere?

Output:
The complete list is documented here.  Basically, all you need to do is the following:

Remove the Python 2.7 framework
sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
Remove the Python 2.7 applications directory
sudo rm -rf "/Applications/Python 2.7"
Remove the symbolic links in /usr/local/bin that point to this Python version see ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' and then run the following command to remove all the links:
cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm

If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7 to your PATH environment file.  Depending on which shell you use, any of the following files may have been modified:
~/.bash_login, ~/.bash_profile, ~/.cshrc, ~/.profile, ~/.tcshrc, and/or ~/.zprofile.


Input:
Split by comma and strip whitespace in Python I have some python code that splits on comma, but doesn't strip the whitespace:
>>> string = "blah, lots  ,  of ,  spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots  ', '  of ', '  spaces', ' here ']

I would rather end up with whitespace removed like this:
['blah', 'lots', 'of', 'spaces', 'here']

I am aware that I could loop through the list and strip() each item but, as this is Python, I'm guessing there's a quicker, easier and more elegant way of doing it.

Output:
Use list comprehension -- simpler, and just as easy to read as a for loop.
my_string = "blah, lots  ,  of ,  spaces, here "
[x.strip() for x in my_string.split(',')]

See: Python docs on List Comprehension
A good 2 second explanation of list comprehension.


Input:
What exactly are Python's iterator, iterable, and iteration protocols? What are the most basic definitions of "iterable", "iterator" and "iteration" in Python?
I've read multiple definitions but their exact meaning still won't sink in.
Can someone please help me with the basic idea?

Output:
Iteration is a general term for taking each item of something, one after another. Any time you use a loop, explicit or implicit, to go over a group of items, that is iteration.
In Python, iterable and iterator have specific meanings.
An iterable is an object that has an __iter__ method which returns an iterator, or which defines a __getitem__ method that can take sequential indexes starting from zero (and raises an IndexError when the indexes are no longer valid). So an iterable is an object that you can get an iterator from.
An iterator is an object with a next (Python 2) or __next__ (Python 3) method.
Whenever you use a for loop, or map, or a list comprehension, etc. in Python, the next method is called automatically to get each item from the iterator, thus going through the process of iteration.
A good place to start learning would be the iterators section of the tutorial and the iterator types section of the standard types page. After you understand the basics, try the iterators section of the Functional Programming HOWTO.


Input:
What is the best way to implement nested dictionaries in Python? I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:
{'new jersey': {'mercer county': {'plumbers': 3,
                                  'programmers': 81},
                'middlesex county': {'programmers': 81,
                                     'salesmen': 62}},
 'new york': {'queens county': {'plumbers': 9,
                                'salesmen': 36}}}

Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values.
I could also use tuples as keys, like such:
{('new jersey', 'mercer county', 'plumbers'): 3,
 ('new jersey', 'mercer county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'salesmen'): 62,
 ('new york', 'queens county', 'plumbers'): 9,
 ('new york', 'queens county', 'salesmen'): 36}

This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).
Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this.
How could I do this better?
Addendum: I'm aware of setdefault() but it doesn't really make for clean syntax.  Also, each sub-dictionary you create still needs to have setdefault() manually set.

Output:
class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

Testing:
a = AutoVivification()

a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6

print a

Output:
{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}


Input:
pip: dealing with multiple Python versions? Is there any way to make pip play well with multiple versions of Python? For example, I want to use pip to explicitly install things to either my site 2.5 installation or my site 2.6 installation.
For example, with easy_install, I use easy_install-2.{5,6}.
And, yes â I know about virtualenv, and no â it's not a solution to this particular problem.

Output:
Since version 0.8, Pip supports pip-{version}. You can use it the same as easy_install-{version}:
$ pip-2.5 install myfoopackage
$ pip-2.6 install otherpackage
$ pip-2.7 install mybarpackage

EDIT: pip changed its schema to use pipVERSION instead of pip-VERSION in version 1.5. You should use the following if you have pip >= 1.5:
$ pip2.6 install otherpackage
$ pip2.7 install mybarpackage

Check https://github.com/pypa/pip/pull/1053 for more details

References:

https://github.com/pypa/pip/issues/200
http://www.pip-installer.org/docs/pip/en/0.8.3/news.html#id4


Input:
How to install pip with Python 3? I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.
How can I install pip with Python 3?

Output: I was able to install pip for python 3 on Ubuntu just by running sudo apt-get install python3-pip.


Input:
Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn't? I know that most decimals don't have an exact floating point representation (Is floating point math broken?).
But I don't see why 4*0.1 is printed nicely as 0.4, but 3*0.1 isn't, when
both values actually have ugly decimal representations:
>>> 3*0.1
0.30000000000000004
>>> 4*0.1
0.4
>>> from decimal import Decimal
>>> Decimal(3*0.1)
Decimal('0.3000000000000000444089209850062616169452667236328125')
>>> Decimal(4*0.1)
Decimal('0.40000000000000002220446049250313080847263336181640625')

Output:
The simple answer is because 3*0.1 != 0.3 due to quantization (roundoff) error (whereas 4*0.1 == 0.4 because multiplying by a power of two is usually an "exact" operation).
You can use the .hex method in Python to view the internal representation of a number (basically, the exact binary floating point value, rather than the base-10 approximation). This can help to explain what's going on under the hood.
>>> (0.1).hex()
'0x1.999999999999ap-4'
>>> (0.3).hex()
'0x1.3333333333333p-2'
>>> (0.1*3).hex()
'0x1.3333333333334p-2'
>>> (0.4).hex()
'0x1.999999999999ap-2'
>>> (0.1*4).hex()
'0x1.999999999999ap-2'

0.1 is 0x1.999999999999a times 2^-4. The "a" at the end means the digit 10 - in other words, 0.1 in binary floating point is very slightly larger than the "exact" value of 0.1 (because the final 0x0.99 is rounded up to 0x0.a). When you multiply this by 4, a power of two, the exponent shifts up (from 2^-4 to 2^-2) but the number is otherwise unchanged, so 4*0.1 == 0.4.
However, when you multiply by 3, the little tiny difference between 0x0.99 and 0x0.a0 (0x0.07) magnifies into a 0x0.15 error, which shows up as a one-digit error in the last position. This causes 0.1*3 to be very slightly larger than the rounded value of 0.3.
Python 3's float repr is designed to be round-trippable, that is, the value shown should be exactly convertible into the original value. Therefore, it cannot display 0.3 and 0.1*3 exactly the same way, or the two different numbers would end up the same after round-tripping. Consequently, Python 3's repr engine chooses to display one with a slight apparent error.


Input: Sending HTML email using Python How can I send the HTML content in an email using Python? I can send simple text.

Output:
From Python v2.6.2 documentation - 19.1.11. email: Examples:

Hereâs an example of how to create an HTML message with an alternative plain text version:

#! /usr/bin/python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()


Input: Python __str__ versus __unicode__ Is there a python convention for when you should implement __str__() versus __unicode__().  I've seen classes override __unicode__() more frequently than __str__() but it doesn't appear to be consistent.  Are there specific rules when it is better to implement one versus the other?  Is it necessary/good practice to implement both?

Output:
__str__() is the old method -- it returns bytes. __unicode__() is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in __unicode__(), and create a stub __str__() method:
def __str__(self):
    return unicode(self).encode('utf-8')

In 3.0, str contains characters, so the same methods are named __bytes__() and __str__(). These behave as expected.


Input:
Reimport a module in python while interactive I know it can be done, but I never remember how.
How can you reimport a module in python?
The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ?

Output:
This should work:
reload(my.module)

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.


Input:
Django: Why do some model fields clash with each other? I want to create an object that contains 2 links to Users. For example:
class GameClaim(models.Model):
    target = models.ForeignKey(User)
    claimer = models.ForeignKey(User)
    isAccepted = models.BooleanField()

but I am getting the following errors when running the server:

Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.

Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.

Can you please explain why I am getting the errors and how to fix them?

Output:
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually gameclaim_set. However, because you have two FKs, you would have two gameclaim_set attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation.
Use the related_name attribute in the FK definition.  e.g.
class GameClaim(models.Model):
    target = models.ForeignKey(User, related_name='gameclaim_targets')
    claimer = models.ForeignKey(User, related_name='gameclaim_users')
    isAccepted = models.BooleanField()


Input:
numpy: access an array by column Suppose I have:
test = numpy.array([[1, 2], [3, 4], [5, 6]])

test[i] gets me ith line of the array (eg [1, 2]). How can I access the ith column? (eg [1, 3, 5]). Also, would this be an expensive operation?

Output:
>>> test[:,0]
array([1, 3, 5])

Similarly,
>>> test[1,:]
array([3, 4])

lets you access rows.  This is covered in Section 1.4 (Indexing) of the NumPy reference.  This is quick, at least in my experience.  It's certainly much quicker than accessing each element in a loop.


Input:
how to get row count of pandas dataframe? I'm trying to get the number of rows of dataframe df with Pandas, and here is my code
Method 1:
total_rows = df.count
print total_rows +1

Method 2:
total_rows = df['First_columnn_label'].count
print total_rows +1

both the code snippets give me this error:

TypeError: unsupported operand type(s) for +: 'instancemethod' and 'int'

I'd be grateful for any suggestions what I'm doing wrong.
EDIT: According to the answer given by root the best (the fastest) way to check df length is to call:
len(df.index)

Output:
You can use the .shape property or just len(DataFrame.index) as there are notable performance differences:
In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: df = pd.DataFrame(np.arange(9).reshape(3,3))

In [4]: df
Out[4]:
   0  1  2
0  0  1  2
1  3  4  5
2  6  7  8

In [5]: df.shape
Out[5]: (3, 3)

In [6]: timeit df.shape
1000000 loops, best of 3: 1.17 us per loop

In [7]: timeit df[0].count()
10000 loops, best of 3: 56 us per loop

In [8]: len(df.index)
Out[8]: 3

In [9]: timeit len(df.index)
1000000 loops, best of 3: 381 ns per loop

EDIT: As @Dan Allen noted in the comments len(df.index) and df[0].count() are not interchangeable as count excludes NaNs,


Input:
How to check version of python modules? I just installed the python modules: construct and statlib with setuptools like this:
# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

I want to be able to (programmatically) check their versions.  Is there an equivalent to python --version I can run from the command line?
My python version is 2.7.3.

Output:
I suggest using pip in place of easy_install. With pip, you can list all installed packages and their versions with
pip freeze

For an individual module, you can try __version__ attribute, however there are modules without it:
$ pip freeze | grep lxml
lxml==2.3
$ python -c "import lxml; print lxml.__version__"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'

Last, as you run your command with sudo prefix, I guess you're installing to global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper


Input:
Using Django time/date widgets in custom form How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view?
I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it?
Here is my template that I want it applied on.
<form action="." method="POST">

        {% for f in form %}

  {{ f.name }}	 {{ f }}

        {% endfor %}

    <input type="submit" name="submit" value="Add Product">
</form>

Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py:
(r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}),

And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...

Output:
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that.
That said, here's what you have to do if you're determined to make this work:

Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model):
from django import forms
from my_app.models import Product
from django.contrib.admin import widgets

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.fields['mydate'].widget = widgets.AdminDateWidget()
        self.fields['mytime'].widget = widgets.AdminTimeWidget()
        self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()

Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean "from my_app.forms import ProductForm" instead of "from my_app.models import Product", of course).
In the head of your template, include {{ form.media }} to output the links to the Javascript files.
And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically.  So in your template above {{ form.media }} you'll need:
<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>

You may also wish to use the following admin CSS (thanks Alex for mentioning this):
<link rel="stylesheet" type="text/css" href="/media/admin/css/forms.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/global.css"/>
<link rel="stylesheet" type="text/css" href="/media/admin/css/widgets.css"/>

This implies that Django's admin media (ADMIN_MEDIA_PREFIX) is at /media/admin/ - you can change that for your setup.  Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question.
This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N).  You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out).  Sample code for your URLconf:
(r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'),

Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media:
{% load adminmedia %} /* At the top of the template. */

/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>

Thanks lupefiasco for this addition.


Input:
How do I convert local time to UTC in Python? How do I convert a datetime string in local time to a string in UTC time?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
Clarification:  For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00.
Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.

Output:
First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See documentation for datetime.strptime for information on parsing the date string.
Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.
Finally, use datetime.astimezone() method to convert the datetime to UTC.
Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":
import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone (pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:
utc_dt.strftime ("%Y-%m-%d %H:%M:%S")


Input:
Choosing Java vs Python on Google App Engine Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!
Edit:
http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1
Edit:
By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.

Output:
I'm biased (being a Python expert but pretty rusty in Java) but I think the Python runtime of GAE is currently more advanced and better developed than the Java runtime -- the former has had one extra year to develop and mature, after all.
How things will proceed going forward is of course hard to predict -- demand is probably stronger on the Java side (especially since it's not just about Java, but other languages perched on top of the JVM too, so it's THE way to run e.g. PHP or Ruby code on App Engine); the Python App Engine team however does have the advantage of having on board Guido van Rossum, the inventor of Python and an amazingly strong engineer.
In terms of flexibility, the Java engine, as already mentioned, does offer the possibility of running JVM bytecode made by different languages, not just Java -- if you're in a multi-language shop that's a pretty large positive. Vice versa, if you loathe Javascript but must execute some code in the user's browser, Java's GWT (generating the Javascript for you from your Java-level coding) is far richer and more advanced than Python-side alternatives (in practice, if you choose Python, you'll be writing some JS yourself for this purpose, while if you choose Java GWT is a usable alternative if you loathe writing JS).
In terms of libraries it's pretty much a wash -- the JVM is restricted enough (no threads, no custom class loaders, no JNI, no relational DB) to hamper the simple reuse of existing Java libraries as much, or more, than existing Python libraries are similarly hampered by the similar restrictions on the Python runtime.
In terms of performance, I think it's a wash, though you should benchmark on tasks of your own -- don't rely on the performance of highly optimized JIT-based JVM implementations discounting their large startup times and memory footprints, because the app engine environment is very different (startup costs will be paid often, as instances of your app are started, stopped, moved to different hosts, etc, all trasparently to you -- such events are typically much cheaper with Python runtime environments than with JVMs).
The XPath/XSLT situation (to be euphemistic...) is not exactly perfect on either side, sigh, though I think it may be a tad less bad in the JVM (where, apparently, substantial subsets of Saxon can be made to run, with some care). I think it's worth opening issues on the Appengine Issues page with XPath and XSLT in their titles -- right now there are only issues asking for specific libraries, and that's myopic: I don't really care HOW a good XPath/XSLT is implemented, for Python and/or for Java, as long as I get to use it. (Specific libraries may ease migration of existing code, but that's less important than being able to perform such tasks as "rapidly apply XSLT transformation" in SOME way!-). I know I'd star such an issue if well phrased (especially in a language-independent way).
Last but not least: remember that you can have different version of your app (using the same datastore) some of which are implemented with the Python runtime, some with the Java runtime, and you can access versions that differ from the "default/active" one with explicit URLs. So you could have both Python and Java code (in different versions of your app) use and modify the same data store, granting you even more flexibility (though only one will have the "nice" URL such as foobar.appspot.com -- which is probably important only for access by interactive users on browsers, I imagine;-).


Input: Using sphinx with Markdown instead of RST I hate RST but love sphinx. Is there a way that sphinx reads markdown instead of reStructuredText?

Output:
The "proper" way to do that would be to write a docutils parser for markdown.  (Plus a Sphinx option to choose the parser.)  The beauty of this would be instant support for all docutils output formats (but you might not care about that, as similar markdown tools already exist for most).  Ways to approach that without developing a parser from scratch:

You could cheat and write a "parser" that uses Pandoc to convert markdown to RST and pass that to the RST parser :-).
You can use an existing markdown->XML parser and transform the result (using XSLT?) to the docutils schema.
You could take some existing python markdown parser that lets you define a custom renderer and make it build docutils node tree.
You could fork the existing RST reader, ripping out everything irrelevant to markdown and changing the different syntaxes (this comparison might help)...
EDIT: I don't recommend this route unless you're prepared to heavily test it.  Markdown already has too many subtly different dialects and this will likely result in yet-another-one...

UPDATE: https://github.com/sgenoud/remarkdown is a markdown reader for docutils.  It didn't take any of the above shortcuts but uses a Parsley PEG grammar inspired by peg-markdown. Doesn't yet support directives.
UPDATE: https://github.com/rtfd/recommonmark and is another docutils reader, natively supported on ReadTheDocs.  Derived from remarkdown but uses the CommonMark-py parser.  Doesn't support directives, but can convert more or less natural Markdown syntaxes to appropriate structures e.g. list of links to a toctree.  For other needs, an ```eval_rst fenced block lets you embed any rST directive.

In all cases, you'll need to invent extensions of Markdown to represent Sphinx directives and roles.  While you may not need all of them, some like .. toctree:: are essential.
This I think is the hardest part.  reStructuredText before the Sphinx extensions was already richer than markdown.  Even heavily extended markdown, such as pandoc's, is mostly a subset of rST feature set.  That's a lot of ground to cover!
Implementation-wise, the easiest thing is adding a generic construct to express any docutils role/directive.  The obvious candidates for syntax inspiration are:

Attribute syntax, which pandoc and some other implementations already allow on many inline and block constructs.  For example `foo`{.method} -> `foo`:method:.
HTML/XML.  From foo to the kludgiest approach of just inserting docutils internal XML!
Some kind of YAML for directives?

But such a generic mapping will not be the most markdown-ish solution...
Currently most active places to discuss markdown extensions are https://groups.google.com/forum/#!topic/pandoc-discuss, https://github.com/scholmd/scholmd/
This also means you can't just reuse a markdown parser without extending it somehow.  Pandoc again lives up to its reputation as the swiss army knife of document conversion by supporting custom filtes.  (In fact, if I were to approach this I'd try to build a generic bridge between docutils readers/transformers/writers and pandoc readers/filters/writers.  It's more than you need but the payoff would be much wider than just sphinx/markdown.)

Alternative crazy idea: instead of extending markdown to handle Sphinx, extend reStructuredText to support (mostly) a superset of markdown!  The beauty is you'll be able to use any Sphinx features as-is, yet be able to write most content in markdown.
There is already considerable syntax overlap; most notably link syntax is incompatible.  I think if you add support to RST for markdown links, and ###-style headers, and change default `backticks` role to literal, and maybe change indented blocks to mean literal (RST supports > ... for quotations nowdays), you'll get something usable that supports most markdown.


Input:
Django datetime issues (default=datetime.now()) I have such db model:
from datetime import datetime

class TermPayment(models.Model):
    # cut out some fields, non relevant to the question
    date = models.DateTimeField(default=datetime.now(), blank=True)

And when new instance is added:
tp = TermPayment.objects.create(**kwargs)

I've an issue: all records in database have the same value in date field - the date of the first payment. After server restart - one record have new date and others have the same as the first. It's look like some data cache is used but I can't find where.
database: mysql 5.1.25
django v1.1.1

Output:
it looks like datetime.now() is being evaluated when the model is defined, and not each time you add a record.
Django has a feature to accomplish what you are trying to do already:
date = models.DateTimeField(auto_now_add=True, blank=True)

or
date = models.DateTimeField(default=datetime.now, blank=True)

The difference between the second example and what you currently have is the lack of parentheses. By passing datetime.now without the parentheses, you are passing the actual function, which will be called each time a record is added. If you pass it datetime.now(), then you are just evaluating the function and passing it the return value.
More information is available at Django's model field reference


Input:
Multiple variables in Python 'with' statement Is it possible to declare more than one variable using a with statement in Python?
Something like:
from __future__ import with_statement

with open("out.txt","wt"), open("in.txt") as file_out, file_in:
    for line in file_in:
        file_out.write(line)

... or is cleaning up two resources at the same time the problem?

Output:
It is possible in Python 3 since v3.1 and  Python 2.7. The new with syntax supports multiple context managers:
with A() as a, B() as b, C() as c:
    doSomething(a,b,c)

Unlike the contextlib.nested, this guarantees that a and b will have their __exit__()'s called even if C() or it's __enter__() method raises an exception.


Input:
Python date string to date object How do I convert a string to a date object in python?
The string would be: "24052010" (corresponding to the format: "%d%m%Y")
I don't want a datetime.datetime object, but rather a datetime.date

Output:
You can use strptime in the datetime package of Python:
>>> datetime.datetime.strptime('24052010', "%d%m%Y").date()
datetime.date(2010, 5, 24)