title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Allowing <br> tags with Google App Engine and Jinja2
10,436,458
7
2012-05-03T17:30:33Z
10,611,713
21
2012-05-16T03:43:28Z
[ "python", "escaping", "whitespace", "jinja2", "webapp2" ]
In my web app, the user can make blog posts. When I display the blog post, newlines aren't shown because I didn't replace the new lines with `<br>` tags. The problem is that I've turned autoescaping on in Jinja, so `<br>` tags are escaped. I don't want to temporarily disable autoescaping, I want to specifically allow `...
I have another answer that I think is the best. Initially I was just displaying my variable `post.content` as-is, and the newlines weren't being preserved. None of the solutions here worked (well), and my pre solution was just a quick fix and had major issues. This is the real solution: ``` {% for line in post.content...
Python script to remove all comments from XML file
10,436,695
4
2012-05-03T17:47:20Z
10,437,575
8
2012-05-03T18:51:33Z
[ "python", "xml", "dom", "xpath" ]
I am trying to build a python script that will take in an XML document and remove all of the comment blocks from it. I tried something along the lines of: ``` tree = ElementTree() tree.parse(file) commentElements = tree.findall('//comment()') for element in commentElements: element.parentNode.remove(element) ```...
`comment()` is an XPath node test that is not supported by ElementTree. You can use `comment()` with **[lxml](http://lxml.de/index.html)**. This library is quite similar to ElementTree and it has full support for XPath 1.0. Here is how you can remove comments with lxml: ``` from lxml import etree XML = """<root> ...
save pylint message to a file
10,439,481
4
2012-05-03T21:20:06Z
10,444,160
8
2012-05-04T06:57:37Z
[ "python", "pylint" ]
Is there a built in way to save the pylint report to a file? It seems it might be useful to do this in order to log progress on a project and compare elements of reports across multiple files as changes are made.
Note: [**This option is deprecated and it will be removed in Pylint 2.0.**](https://docs.pylint.org/en/latest/whatsnew/changelog.html#what-s-new-in-pylint-2-0) You can use the `--file-output=y` command line option. Quoting the man page: ``` --files-output=<y_or_n> Put messages in a separate file for each...
Efficiently create a density plot for high-density regions, points for sparse regions
10,439,961
9
2012-05-03T22:05:17Z
10,452,333
11
2012-05-04T16:04:23Z
[ "python", "matplotlib" ]
I need to make a plot that functions like a density plot for high-density regions on the plot, but below some threshold uses individual points. I couldn't find any existing code that looked similar to what I need in the matplotlib thumbnail gallery or from google searches. I have a working code I wrote myself, but it i...
This should do it: ``` import matplotlib.pyplot as plt, numpy as np, numpy.random, scipy #histogram definition xyrange = [[-5,5],[-5,5]] # data range bins = [100,100] # number of bins thresh = 3 #density threshold #data definition N = 1e5; xdat, ydat = np.random.normal(size=N), np.random.normal(1, 0.6, size=N) # h...
Find which lines in a file contain certain characters
10,440,219
5
2012-05-03T22:33:01Z
10,440,232
9
2012-05-03T22:34:40Z
[ "python", "string", "search" ]
Is there a way to find out if a string contains any one of the characters in a set with python? It's straightforward to do it with a single character, but I need to check and see if a string contains any one of a set of bad characters. Specifically, suppose I have a string: ``` s = 'amanaplanacanalpanama~012345' ```...
``` any((c in badChars) for c in yourString) ``` or ``` any((c in yourString) for c in badChars) # extensionally equivalent, slower ``` or ``` set(yourString) & set(badChars) # extensionally equivalent, slower ``` "so long as one is encountered that is enough to end the search." - This will be true if you use th...
What effect has a statement like 'var and do_something_with(var)' in Python?
10,440,491
11
2012-05-03T23:00:18Z
10,440,512
15
2012-05-03T23:03:46Z
[ "python" ]
While looking for some answers in a package source code (*colander* to be specific) I stumbled upon a string that I cannot comprehend. Also my *PyCharm* frowns on it with 'statement seems to have no effect'. Here's the code abstract: ``` ... for path in e.paths(): keyparts = [] msgs = [] for exc in path: ...
If keyname evaluates to False, the `and` statement will return false immediately and not evaluate the second part. Otherwise, it will evaluate the second part (not that the return value matters in this case). So it's basically equivalent to: ``` if keyname: keyparts.append(keyname) ``` I'm not sure that it's ver...
Python for loops (novice)
10,440,493
6
2012-05-03T23:00:33Z
10,440,559
10
2012-05-03T23:08:13Z
[ "python", "loops", "for-loop", "increment" ]
I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format `for x in y`, where `y` is just some list. The for-each loop `for (int n: someArray)` becomes `for n in someArray`, And the for loop `for (i = 0; i < 9; i-=2)` can be ...
As you say, a `for` loop iterates through the elements of a list. The list can contain anything you like, so you can construct a list beforehand that contains each step. A `for` loop can also iterate over a ["generator"](http://wiki.python.org/moin/Generators), which is a small piece of code instead of an actual list....
Python for loops (novice)
10,440,493
6
2012-05-03T23:00:33Z
10,440,632
8
2012-05-03T23:15:18Z
[ "python", "loops", "for-loop", "increment" ]
I recently started learning Python, and the concept of for loops is still a little confusing for me. I understand that it generally follows the format `for x in y`, where `y` is just some list. The for-each loop `for (int n: someArray)` becomes `for n in someArray`, And the for loop `for (i = 0; i < 9; i-=2)` can be ...
You can use a [generator expression](https://www.youtube.com/watch?v=t85uBptTDYY) to do this efficiently and with little excess code: ``` for i in (2**x for x in range(10)): #In Python 2.x, use `xrange()`. ... ``` Generator expressions work just like defining a manual generator (as in [Greg Hewgill's answer](http...
Why does "[] == False" evaluate to False when "if not []" succeeds?
10,440,792
22
2012-05-03T23:33:35Z
10,440,825
46
2012-05-03T23:37:48Z
[ "python" ]
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `Fal...
The `if` statement evaluates everything in a Boolean context, it is like there is an implicit call to the [`bool()`](http://docs.python.org/library/functions.html#bool) built-in function. Here is how you would actually check how things will be evaluated by an `if` statement: ``` >>> bool([]) False >>> bool([]) == Fal...
Why does "[] == False" evaluate to False when "if not []" succeeds?
10,440,792
22
2012-05-03T23:33:35Z
10,440,830
13
2012-05-03T23:38:50Z
[ "python" ]
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `Fal...
Empty containers are "falsy," that is, they evaluate to `False` *in a Boolean context*. That doesn't mean they are literally equal to the constant `False`. In other words, the following is `True`: ``` bool([]) == False ``` The truth value of an object is determined by its `__nonzero__()` or its `__len__()` method. (...
Why does "[] == False" evaluate to False when "if not []" succeeds?
10,440,792
22
2012-05-03T23:33:35Z
10,440,835
7
2012-05-03T23:40:01Z
[ "python" ]
I'm asking this because I know that the pythonic way to check whether a list is empty or not is the following: ``` my_list = [] if not my_list: print "computer says no" else: # my_list isn't empty print "computer says yes" ``` will print `computer says no`, etc. So this leads me to identify `[]` with `Fal...
Built-in types in Python have a truth value which allows you to test them for truthfulness. See *[Truth Value Testing](http://docs.python.org/library/stdtypes.html#truth-value-testing)*. This is different than saying `object == False` which is doing an actual value test (equality test). It is using the objects `__eq__...
Boost Python : Having problems importing a module
10,441,851
3
2012-05-04T02:21:06Z
10,442,642
8
2012-05-04T04:14:25Z
[ "c++", "python", "boost", "boost-python" ]
I'm currently trying to use Boost Python to export a class, and then use it in the corresponding the program. ``` /** main.cpp */ #define BOOST_PYTHON_STATIC_LIB #include <Resource\ZipResourceFile.hpp> #include <Resource\ResourceCache.hpp> #include <Windows.h> #include <boost/python.hpp> #include <iostream> /* a ...
The convention for naming the module initialization function is: * `init***` for Python 2.x (no underscore). * `PyInit_***` for Python 3.x. Boost.Python's `BOOST_PYTHON_MODULE` macro follows these conventions. Since you're using Python 3.2, the initialization function of your `PyBackend` module will therefore be cal...
Why is matrix multiplication faster with numpy than with ctypes in Python?
10,442,365
28
2012-05-04T03:36:22Z
10,442,941
12
2012-05-04T05:01:05Z
[ "python", "c", "benchmarking", "matrix-multiplication" ]
I was trying to figure out the fastest way to do matrix multiplication and tried 3 different ways: * Pure python implementation: no surprises here. * Numpy implementation using `numpy.dot(a, b)` * Interfacing with C using `ctypes` module in Python. This is the C code that is transformed into a shared library: ``` #i...
I'm not too familiar with Numpy, but the source is on Github. Part of dot products are implemented in <https://github.com/numpy/numpy/blob/master/numpy/core/src/multiarray/arraytypes.c.src>, which I'm assuming is translated into specific C implementations for each datatype. For example: ``` /**begin repeat * * #name...
Why is matrix multiplication faster with numpy than with ctypes in Python?
10,442,365
28
2012-05-04T03:36:22Z
10,443,821
8
2012-05-04T06:30:48Z
[ "python", "c", "benchmarking", "matrix-multiplication" ]
I was trying to figure out the fastest way to do matrix multiplication and tried 3 different ways: * Pure python implementation: no surprises here. * Numpy implementation using `numpy.dot(a, b)` * Interfacing with C using `ctypes` module in Python. This is the C code that is transformed into a shared library: ``` #i...
The language used to implement a certain functionality is a bad measure of performance by itself. Often, using a more suitable algorithm is the deciding factor. In your case, you're using the naive approach to matrix multiplication as taught in school, which is in O(n^3). However, you can do much better for certain ki...
Why is matrix multiplication faster with numpy than with ctypes in Python?
10,442,365
28
2012-05-04T03:36:22Z
12,031,765
20
2012-08-20T02:48:41Z
[ "python", "c", "benchmarking", "matrix-multiplication" ]
I was trying to figure out the fastest way to do matrix multiplication and tried 3 different ways: * Pure python implementation: no surprises here. * Numpy implementation using `numpy.dot(a, b)` * Interfacing with C using `ctypes` module in Python. This is the C code that is transformed into a shared library: ``` #i...
NumPy uses a highly-optimized, carefully-tuned BLAS method for matrix multiplication (see also: [ATLAS](http://math-atlas.sourceforge.net/)). The specific function in this case is GEMM (for generic matrix multiplication). You can look up the original by searching for `dgemm.f` (it's in Netlib). The optimization, by th...
How to iterate over space-separated ASCII file in Python
10,443,073
3
2012-05-04T05:21:15Z
10,443,092
10
2012-05-04T05:23:37Z
[ "python", "for-loop", "loops" ]
Strange question here. I have a `.txt` file that I want to iterate over. I can get all the words into an array from the file, which is good, but what I want to know how to do is, how do I iterate over the whole file, but not the individual letters, but the words themselves. I want to be able to go through the array w...
This code reads the space separated file.txt ``` f = open("file.txt", "r") words = f.read().split() for w in words: print w ```
Combine 3 separate numpy arrays to an RGB image in Python
10,443,295
13
2012-05-04T05:46:14Z
10,445,502
20
2012-05-04T08:40:13Z
[ "python", "image", "image-processing", "numpy" ]
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image. I tried 'Image' to do the job but it requires 'mode' to be attributed. I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' ...
I don't really understand your question but here is an example of something similar I've done recently that seems like it might help: ``` # r, g, and b are 512x512 float arrays with values >= 0 and < 1. from PIL import Image import numpy as np rgbArray = np.zeros((512,512,3), 'uint8') rgbArray[..., 0] = r*256 rgbArray...
Combine 3 separate numpy arrays to an RGB image in Python
10,443,295
13
2012-05-04T05:46:14Z
10,463,090
14
2012-05-05T15:06:24Z
[ "python", "image", "image-processing", "numpy" ]
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image. I tried 'Image' to do the job but it requires 'mode' to be attributed. I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F' ...
``` rgb = np.dstack((r,g,b)) # stacks 3 h x w arrays -> h x w x 3 ``` To also convert floats 0 .. 1 to uint8 s, ``` rgb_uint8 = (np.dstack((r,g,b)) * 255.999) .astype(np.uint8) # right, Janna, not 256 ```
Remove leading and trailing spaces?
10,443,400
27
2012-05-04T05:56:34Z
10,443,548
75
2012-05-04T06:10:06Z
[ "python" ]
I'm having a hard time trying to use .strip with the following line of code. Thanks for the help. ``` f.write(re.split("Tech ID:|Name:|Account #:",line)[-1]) ```
You can use the strip() to remove trailing and leading spaces. ``` s = ' abd cde ' s.strip() 'ab cde' ``` Note: the internal spaces are preserved
Pylint: Relative import should be
10,444,360
9
2012-05-04T07:13:33Z
10,444,888
9
2012-05-04T07:55:26Z
[ "python", "pylint" ]
I'm checking a module with Pylint. The project has this structure: ``` /builder __init__.py entity.py product.py ``` Within product I import entity like this: ``` from entity import Entity ``` but Pylint laments that: ``` ************* Module builder.product W: 5,0: Relative import 'entity', should be...
``` from .entity import Entity ``` if your Python is new enough.
Overriding __contains__ method for a class
10,445,819
5
2012-05-04T09:01:56Z
10,446,010
11
2012-05-04T09:14:21Z
[ "python", "python-3.x" ]
I need to simulate enums in Python, and did it by writing classes like: ``` class Spam(Enum): k = 3 EGGS = 0 HAM = 1 BAKEDBEANS = 2 ``` Now I'd like to test if some constant is a valid choice for a particular Enum-derived class, with the following syntax: ``` if (x in Foo): print("seems legit") `...
> Why that? When you use special syntax like `a in Foo`, the `__contains__` method is looked up on the type of `Foo`. However, your `__contains__` implementation exists on `Foo` itself, not its type. `Foo`'s type is `type`, which doesn't implement this (or iteration), thus the error. The same situation occurs if you ...
Does dictionary's clear() method delete all the item related objects from memory?
10,446,839
15
2012-05-04T10:13:50Z
10,447,948
22
2012-05-04T11:29:22Z
[ "python", "memory", "dictionary" ]
If a dictionary contains mutable objects or objects of custom classes (say a queryset, or a even a DateTime), then will calling `clear()` on the dictionary delete these objects from memory? Does it behave differently than looping through the dict and `del`eting them? eg. consider ``` class MyClass(object): '''Tes...
[Python documentation on dicts](http://docs.python.org/library/stdtypes.html?highlight=dict#dict) states that `del d[key]` removes `d[key]` from the dictionary while `d.clear()` removes every key, so basically their behavior is the same. On the memory issue, in Python when you "delete" you are basically removing a ref...
Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way?
10,448,122
2
2012-05-04T11:38:51Z
10,448,181
8
2012-05-04T11:43:16Z
[ "python", "list" ]
The following code works just fine. But it seems so verbose, surely there is a more elegant way to calculate this? The idea is that I have a list of 100 incrementing timestamps, I want to look at those timestamps and calculate the mean time between each time-stamp. The code below functions, but I'm sure it's really i...
If you have numpy: ``` >>> import numpy as np >>> np.diff([1,4,6,10]).mean() 3.0 ```
How to parse multiple sub-commands using python argparse?
10,448,200
28
2012-05-04T11:44:04Z
10,579,924
17
2012-05-14T08:36:57Z
[ "python", "command-line-arguments", "argparse" ]
I am implementing a command line program which has interface like this: ``` cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...] ``` I have gone through the [argparse documentation](http://docs.python.org/dev/library/argparse.html). I can implement `GLOBAL_OPTIONS` as optional argument using `...
@mgilson has a nice [answer](http://stackoverflow.com/a/10449310/446386) to this question. But problem with splitting sys.argv myself is that i lose all the nice help message Argparse generates for the user. So i ended up doing this: ``` import argparse ## This function takes the 'extra' attribute from global namespa...
How to parse multiple sub-commands using python argparse?
10,448,200
28
2012-05-04T11:44:04Z
19,476,216
11
2013-10-20T10:15:50Z
[ "python", "command-line-arguments", "argparse" ]
I am implementing a command line program which has interface like this: ``` cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...] ``` I have gone through the [argparse documentation](http://docs.python.org/dev/library/argparse.html). I can implement `GLOBAL_OPTIONS` as optional argument using `...
I came up with the same qustion, and it seems i have got a better answer. the solution is we shall not simply nest subparser with anothor subparser, but we can add subparser following with a parser fllowing anothor subparser. Code tell you how: ``` parent_parser = argparse.ArgumentParser(add_help=False) ...
When`starmap` could be preferred over `List Comprehension`
10,448,486
6
2012-05-04T12:02:50Z
10,448,628
8
2012-05-04T12:12:36Z
[ "python", "list-comprehension", "itertools" ]
While answering the question [Clunky calculation of differences between an incrementing set of numbers, is there a more beautiful way?](http://stackoverflow.com/questions/10448122/clunky-calculation-of-differences-between-an-incrementing-set-of-numbers-is-the), I came up with two solutions, one with `List Comprehension...
The difference I normally see is `map()`/`starmap()` are most appropriate where you are literally just calling a function on every item in a list. In this case, they are a little clearer: ``` (f(x) for x in y) map(f, y) # itertools.imap(f, y) in 2.x (f(*x) for x in y) starmap(f, y) ``` As soon as you start needing t...
string into a list in Python
10,449,484
2
2012-05-04T13:09:28Z
10,449,618
8
2012-05-04T13:18:06Z
[ "python", "string", "list" ]
I have a str that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python? ``` for i in in_data.splitlines(): print i.split('Counter3...
Given your data as ``` >>> data="""IF-MIB::ifInOctets.1 = Counter32: 12576810 IF-MIB::ifInOctets.2 = Counter32: 1917472404 IF-MIB::ifInOctets.3 = Counter32: 3104185795""" ``` You can use regex where the intent is more clear ``` >>> import re >>> [re.findall("\d+$",e)[0] for e in data.splitlines()] ['12576810', '1917...
Can not activate a virtualenv in GIT bash mingw32 for Windows
10,450,992
18
2012-05-04T14:40:37Z
10,451,017
25
2012-05-04T14:42:20Z
[ "python", "git", "bash", "virtualenv", "git-bash" ]
When I try to activate my virtualenv from GIT bash mingw32 I do not get the expected response. NOTE: `py` is the folder for Python projects in my Google Drive folder. `hy` is the virtualenv folder that was made when I ran `virtualenv --distribute hy`. ``` s3z@s3z ~/Google Drive/py/hy $ Scripts/activate ``` So you se...
Doing `Scripts/activate` runs the script in a new instance of the shell, which is destroyed after the script execution. To run the script in your current shell, use either `. Scripts/activate` or `source Scripts/activate`. `Scripts/activate.bat` does not work here because it is written in Batch, Windows `cmd.exe` lang...
Python lambda's binding to local values
10,452,770
21
2012-05-04T16:33:52Z
10,452,819
42
2012-05-04T16:36:46Z
[ "python", "closures", "lambda" ]
The following code spits out `1` twice, I expect to see `0` and then `1` ``` def pv(v) : print v def test() : value = [] value.append(0) value.append(1) x=[] for v in value : x.append(lambda : pv(v)) return x x = test() for xx in x: xx() ``` I expected python lambdas to bind to the reference a ...
Change `x.append(lambda : pv(v))` to `x.append(lambda v=v: pv(v))`. You expect "python lambdas to bind to the reference a local variable is pointing to, behind the scene", but that is not how Python works. Python looks up the variable name at the time the function is called, not when it is created. Using a default arg...
Python lambda's binding to local values
10,452,770
21
2012-05-04T16:33:52Z
10,452,866
9
2012-05-04T16:41:17Z
[ "python", "closures", "lambda" ]
The following code spits out `1` twice, I expect to see `0` and then `1` ``` def pv(v) : print v def test() : value = [] value.append(0) value.append(1) x=[] for v in value : x.append(lambda : pv(v)) return x x = test() for xx in x: xx() ``` I expected python lambdas to bind to the reference a ...
The lambda's closure holds a reference to the variable being used, not its value, so if the value of the variable later changes, the value in the closure also changes. That is, the closure variable's value is resolved when the function is called, not when it is created. (Python's behavior here is not unusual in the fun...
O(1) indexable deque of integers in Python
10,453,176
5
2012-05-04T17:05:35Z
10,453,347
7
2012-05-04T17:19:50Z
[ "python", "collections" ]
what are my options there? I need to call a lot of `append`s (to the right end) and `popleft`s (from the left end, naturally), but also to read from the middle of the storage, which will steadily grow, by the nature of the algorithm. I would like to have all these operations in `O(1)`. I could implement it in C easy e...
You can get an amortized O(1) data structure by using two python lists, one holding the left half of the deque and the other holding the right half. The front half is stored reversed so the left end of the deque is at the back of the list. Something like this: ``` class mydeque(object): def __init__(self): self...
matplotlib, define size of a grid on a plot
10,453,770
16
2012-05-04T17:53:43Z
10,453,861
18
2012-05-04T18:00:40Z
[ "python", "matplotlib" ]
I am plotting using matplotlib in python. I want create plot with grid, here is an [example](http://www.scipy.org/Plotting_Tutorial) from plotting tutorial. In my plot range if the y axe is from 0 to 14 and if use `pylab.grid(True)` then it makes grid with size of square of two, but I want the size to be 1. How can I f...
Try using `ax.grid(True, which='both')` to position your grid lines on both major and minor ticks, as suggested [here](http://matplotlib.sourceforge.net/api/axis_api.html). EDIT: Or just set your ticks manually, like this: ``` import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,...
How to project and resample a grid to match another grid with GDAL python?
10,454,316
11
2012-05-04T18:34:32Z
10,538,634
19
2012-05-10T16:42:04Z
[ "python", "gis", "raster", "gdal", "osgeo" ]
Clarification: I somehow left out the key aspect: not using os.system or subprocess - just the python API. I'm trying to convert a section of a NOAA GTX offset grid for vertical datum transformations and not totally following how to do this in GDAL with python. I'd like to take a grid (in this case a Bathymetry Attrib...
Thanks to Jamie for the answer. ``` #!/usr/bin/env python from osgeo import gdal, gdalconst # Source src_filename = 'MENHMAgome01_8301/mllw.gtx' src = gdal.Open(src_filename, gdalconst.GA_ReadOnly) src_proj = src.GetProjection() src_geotrans = src.GetGeoTransform() # We want a section of source that matches this: m...
Python lambda with regex
10,454,359
5
2012-05-04T18:37:37Z
10,454,406
8
2012-05-04T18:41:43Z
[ "python", "regex", "lambda", "python-2.7" ]
When using re.sub() part of re for python, a function can be used for sub if I am not mistaken. To my knowledge it passes in the match to whatever function is passed for example: ``` r = re.compile(r'([A-Za-z]') r.sub(function,string) ``` Is there a smarter way to have it pass in a second arg other than with a lambda...
You can use `functools.partial`: ``` >>> from functools import partial >>> def foo(x, y): ... print x+y ... >>> partial(foo, y=3) <functools.partial object at 0xb7209f54> >>> f = partial(foo, y=3) >>> f(2) 5 ``` In your example: ``` def function(x, y): pass # ... r.sub(functools.partial(function, y=arg),st...
Can Selenium web driver have access to javascript global variables?
10,455,130
7
2012-05-04T19:41:26Z
10,455,320
13
2012-05-04T19:56:23Z
[ "javascript", "python", "django", "selenium" ]
Hi: I'm writing tests for django with javascript and I was wondering if the Selenium webdriver can access a javascript global variable. `mypage` has a script that has a global variable I'd like to access. Is it possible? Thanks! ``` from django.test import LiveServerTestCase from selenium.webdriver.firefox.webdriver i...
Yes, you should be able to that with code similar to the below: ``` browser.execute_script("return globalVar;") ```
Django template datetime.weekday name
10,455,518
4
2012-05-04T20:13:05Z
10,455,636
10
2012-05-04T20:22:24Z
[ "python", "django", "datetime", "django-templates" ]
Is there a way to display the weekday of a datetime object in a template as the actual name of the weekday? Basically I want it to print `Friday` instead of `5`.
See the documentation for the [built-in `date` filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#date). From there you'll see you need to use: > l Day of the week, textual, long. 'Friday'
DELIMITER / Creating a trigger in SQLAlchemy
10,455,547
7
2012-05-04T20:14:34Z
10,456,217
10
2012-05-04T21:13:47Z
[ "python", "mysql", "sqlalchemy", "flask" ]
I need to create a BEFORE INSERT [trigger](http://dev.mysql.com/doc/refman/5.6/en/create-trigger.html) in SQLAlchemy: ``` DELIMITER | CREATE TRIGGER set_rank BEFORE INSERT ON authors FOR EACH ROW BEGIN IF NEW.rank = 0 THEN SET NEW.rank = (SELECT IFNULL(MAX(a.rank),0) + 1 FROM author...
You really honestly don't need the `DELIMITER`. Thats only for the command line client. You as a programmer will be dividing up statements, so the delimiters are otherwise ignored. ``` >>> from sqlalchemy import * >>> >>> trigger_text = """ ... CREATE TRIGGER set_rank BEFORE INSERT ON authors ... FOR EACH ROW BEGIN ....
Making a Dictionary List with cx_Oracle
10,455,863
11
2012-05-04T20:40:26Z
10,456,001
18
2012-05-04T20:53:25Z
[ "python", "oracle", "cx-oracle" ]
I've been using the following function to make a "more readable" (supposedly) format for fetching data from Oracle. Here is the function: ``` def rows_to_dict_list(cursor): """ Create a list, each item contains a dictionary outlined like so: { "col1_name" : col1_data } Each item in the list is technic...
There are other improvements to make, but this really jumped out at me: ``` for col in columns: # Create a new dictionary with field names as the key, # row data as the value. # # Then add this dictionary to the new_list row_dict[col] = row[columns.index(col)] ``` In addit...
Making a Dictionary List with cx_Oracle
10,455,863
11
2012-05-04T20:40:26Z
18,520,122
7
2013-08-29T20:09:13Z
[ "python", "oracle", "cx-oracle" ]
I've been using the following function to make a "more readable" (supposedly) format for fetching data from Oracle. Here is the function: ``` def rows_to_dict_list(cursor): """ Create a list, each item contains a dictionary outlined like so: { "col1_name" : col1_data } Each item in the list is technic...
For a clean way to avoid the memory usage of dumping everything in a list upfront, you could wrap the cursor in a generator function: ``` def rows_as_dicts(cursor): """ returns cx_Oracle rows as dicts """ colnames = [i[0] for i in cursor.description] for row in cursor: yield dict(zip(colnames, row)...
How do Homebrew, PIP, easy_install etc. work so that I can clean up
10,455,947
16
2012-05-04T20:48:03Z
10,506,281
22
2012-05-08T20:50:04Z
[ "python", "macports", "pip", "homebrew", "easy-install" ]
I have a problem that comes from me following tutorials without really understanding what I'm doing. The root of the problem I think is the fact that I don't understand how the OS X filesystem works. The problem is bigger than Python but it was when I started learning about Python that I realized how little I really u...
Homebrew installs its software inside the `/usr/local` subdirectory on your Mac. OS X doesn't install anything there on its own; in fact, `/usr/local` is reserved for user-installed stuff. Since Homebrew never installs files outside `/usr/local` (and doesn't even have the ability to, unless you run `brew` using `sudo` ...
matplotlib, can plot but not scatter
10,456,088
7
2012-05-04T21:02:24Z
10,456,372
11
2012-05-04T21:27:38Z
[ "python", "matplotlib" ]
I have weird behaviour of matplotlib.pyplot. I have two array x and y. I want scatter these point. so I use scatter function: ``` ax.scatter(x, y, 'r') plt.xlabel('average revsion size') plt.ylabel('time (seconds)') plt.savefig('time.png', format='png') ``` this piece of code give me error `otImplementedError: Not im...
The thing is that `scatter` and `plot` don't take the arguments in the same order. Try using `scatter(x, y, c='r')` instead (assuming it was the coloring you intended to set). Take a look at the [documentation for `scatter`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.scatter) as well. ``` ...
Python setuptools: how to include a config file for distribution into <prefix>/etc
10,456,279
16
2012-05-04T21:20:39Z
13,476,594
7
2012-11-20T15:33:28Z
[ "python", "setuptools" ]
How can I write `setup.py` so that: 1. The binary egg distribution (`bdist_egg`) includes a sample configuration file and 2. Upon installation puts it into the `{prefix}/etc` directory? A sample project source directory looks like this: ``` bin/ myapp etc/ myapp.cfg myapp/ __init__.py [...] setup.py ``...
I was doing some research on this issue and I think the answer is in the setuptools documentation: <http://peak.telecommunity.com/DevCenter/setuptools#non-package-data-files> Next, I quote the extract that I think has the answer: > Non-Package Data Files > > The distutils normally install general "data files" to a > ...
Extra line in output when printing inside a loop
10,456,293
5
2012-05-04T21:21:40Z
10,456,341
9
2012-05-04T21:24:51Z
[ "python" ]
I can't figure out why the code #1 returns an extra empty line while code #2 doesn't. Could somebody explain this? The difference is an extra comma at the end of the code #2. ``` # Code #1 file = open('tasks.txt') for i, text in enumerate(filer, start=1): if i >= 2 and i <= 4: print "(%d) %s" % (i, text) ...
The trailing `,` in the print statement will surpress a line feed. Your first print statement doesn't have one, your second one does. The input you read still contains the `\n` which causes the extra linefeed. One way to compensate for it is to prevent print from issuing a linefeed of its own by using the trailing com...
Python for iOS (like RubyMotion)
10,456,648
22
2012-05-04T21:57:40Z
10,506,539
22
2012-05-08T21:08:08Z
[ "python", "rubymotion" ]
[RubyMotion](http://www.rubymotion.com/) has been released, and I am wondering, if a similar solution is available, or coming for Python?
RubyMotion isn't a new cross-platform framework (like Kivy, Papaya, Rhodes, etc.) but rather an implementation of the Ruby programming language ON TOP OF the native iOS language Objective-C. Because of this, a RubyMotion object *IS* an Obj-C Object, but you get to use the dynamic Ruby syntax and idioms to deal with it,...
Error 'failed to load external entity' when using Python lxml
10,457,564
10
2012-05-04T23:57:54Z
10,469,748
8
2012-05-06T10:14:39Z
[ "python", "xml", "lxml", "elementtree" ]
I'm trying to parse an XML document I retrieve from the web, but it crashes after parsing with this error: ``` ': failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="GreenButtonDataStyleSheet.xslt"?> ``` That is the second line in the XML that is downloaded. I...
[`etree.parse(source)`](http://lxml.de/api/lxml.etree-module.html#parse) expects `source` to be one of * a file name/path * a file object * a file-like object * a URL using the HTTP or FTP protocol The problem is that you are supplying the XML content as a string. You can also do without `urllib2.urlopen()`. Just us...
Error 'failed to load external entity' when using Python lxml
10,457,564
10
2012-05-04T23:57:54Z
12,984,394
14
2012-10-20T01:13:14Z
[ "python", "xml", "lxml", "elementtree" ]
I'm trying to parse an XML document I retrieve from the web, but it crashes after parsing with this error: ``` ': failed to load external entity "<?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="GreenButtonDataStyleSheet.xslt"?> ``` That is the second line in the XML that is downloaded. I...
In concert with what mzjn said, if you do want to pass a string to etree.parse(), just wrap it in a StringIO object. Example: ``` from lxml import etree from StringIO import StringIO myString = "<html><p>blah blah blah</p></html>" tree = etree.parse(StringIO(myString)) ``` This method is used in the [lxml document...
Redefining the Index in a Pandas DataFrame object
10,457,584
53
2012-05-05T00:00:12Z
10,458,386
131
2012-05-05T02:44:12Z
[ "python", "pandas" ]
I am trying to re-index a pandas DataFrame object, like so, ``` From: a b c 0 1 2 3 1 10 11 12 2 20 21 22 To : b c 1 2 3 10 11 12 20 21 22 ``` I am going about this as shown below and am getting the wrong answer. Any clues on...
Why don't you simply use [`set_index`](http://pandas.pydata.org/pandas-docs/stable/indexing.html#add-an-index-using-dataframe-columns) method? ``` In : col = ['a','b','c'] In : data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col) In : data Out: a b c 0 1 2 3 1 10 11 12 2 20 21 22 In : d...
How do I install wxPython in virtualenv
10,457,647
7
2012-05-05T00:10:51Z
27,436,070
7
2014-12-12T02:51:25Z
[ "python", "windows", "osx", "wxpython", "virtualenv" ]
I'm on a Mac OSX Lion machine, and I've downloaded wxPython-src-2.9.3.1.tar.bz2. I then did the following (*note: output messages have been removed*): ``` $ tar -xjf wxPython-src-2.9.3.1.tar.bz2 $ cd wxPython-src-2.9.3.1 $ mkdir bld $ cd bld $ source /path/to/myvirtualenv/bin/activate (myvirtualenv)$ cross_compiling=y...
For others, here is what worked for me: On Mac OSX, I installed wxpython with Homebrew using: ``` brew install wxpython ``` Change into your virtualenv site-packages directory: ``` cd /venv/lib/python2.7/site-packages ``` then link the wx.pth ``` ln -s /usr/local/Frameworks/Python.framework/Versions/2.7/lib/pytho...
How to compare inheritance with several classes?
10,458,093
5
2012-05-05T01:43:53Z
10,458,106
17
2012-05-05T01:45:42Z
[ "python" ]
I want to check if an object is an instance of any class in a list/group of Classes, but I can't find if there is even a pythonic way of doing so without doing ``` if isinstance(obj, Class1) or isinstance(obj, Class2) ... or isinstance(obj, ClassN): # proceed with some logic ``` I mean, comparing class by class. ...
You can pass a tuple of classes as 2nd argument to isinstance. ``` >>> isinstance(u'hello', (basestring, str, unicode)) True ``` Looking up the docstring would have also told you that though ;) ``` >>> help(isinstance) Help on built-in function isinstance in module __builtin__: isinstance(...) isinstance(object...
python setup.py configuration to install files in custom directories
10,458,158
10
2012-05-05T01:57:03Z
10,458,620
7
2012-05-05T03:35:28Z
[ "python", "configuration", "installation", "setup.py" ]
I want to create a setup.py which would install my files into custom directories. I have a certain prefix, where I would like to get the following result: ``` /my/prefix/ bin/ script.sh libexec/ one.py two.py ... lib/pythonX.Y/site-packages/ package/... ``` My initial project is following: ...
The scripts are handled by use of the `scripts` parameter to the setup function. For libexec you can treat them as data files and use a data options. ``` setup(... scripts=glob("bin/*"), data_files=[(os.path.join(sys.prefix, 'libexec', 'mypackage'), glob("libexec/*"))], ... ) ``` I'm not sure how that wou...
What is the difference between dict.items() and dict.iteritems()?
10,458,437
349
2012-05-05T02:58:27Z
10,458,452
51
2012-05-05T03:00:52Z
[ "python", "dictionary" ]
Are there any applicable differences between [`dict.items()`](http://docs.python.org/library/stdtypes.html#dict.items) and [`dict.iteritems()`](http://docs.python.org/library/stdtypes.html#dict.iteritems)? From the Python docs: > `dict.items()`: Return a **copy** of the dictionary’s list of (key, value) pairs. > > ...
`dict.items()` returns a list of 2-tuples (`[(key, value), (key, value), ...]`), whereas `dict.iteritems()` is a generator that yields 2-tuples. The former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating e...
What is the difference between dict.items() and dict.iteritems()?
10,458,437
349
2012-05-05T02:58:27Z
10,458,567
430
2012-05-05T03:26:27Z
[ "python", "dictionary" ]
Are there any applicable differences between [`dict.items()`](http://docs.python.org/library/stdtypes.html#dict.items) and [`dict.iteritems()`](http://docs.python.org/library/stdtypes.html#dict.iteritems)? From the Python docs: > `dict.items()`: Return a **copy** of the dictionary’s list of (key, value) pairs. > > ...
It's part of an evolution. Originally, Python `items()` built a real list of tuples and returned that. That could potentially take a lot of extra memory. Then, generators were introduced to the language in general, and that method was reimplemented as an iterator-generator method named `iteritems()`. The original rem...
What is the difference between dict.items() and dict.iteritems()?
10,458,437
349
2012-05-05T02:58:27Z
10,459,488
23
2012-05-05T06:29:57Z
[ "python", "dictionary" ]
Are there any applicable differences between [`dict.items()`](http://docs.python.org/library/stdtypes.html#dict.items) and [`dict.iteritems()`](http://docs.python.org/library/stdtypes.html#dict.iteritems)? From the Python docs: > `dict.items()`: Return a **copy** of the dictionary’s list of (key, value) pairs. > > ...
You asked: 'Are there any applicable differences between dict.items() and dict.iteritems()' This may help (for Python 2.x): ``` >>> d={1:'one',2:'two',3:'three'} >>> type(d.items()) <type 'list'> >>> type(d.iteritems()) <type 'dictionary-itemiterator'> ``` You can see that `d.items()` returns a list of tuples of the...
What is the difference between dict.items() and dict.iteritems()?
10,458,437
349
2012-05-05T02:58:27Z
20,329,606
34
2013-12-02T13:33:29Z
[ "python", "dictionary" ]
Are there any applicable differences between [`dict.items()`](http://docs.python.org/library/stdtypes.html#dict.items) and [`dict.iteritems()`](http://docs.python.org/library/stdtypes.html#dict.iteritems)? From the Python docs: > `dict.items()`: Return a **copy** of the dictionary’s list of (key, value) pairs. > > ...
## In Py2.x The commands `dict.items()`, `dict.keys()` and `dict.values()` return a **copy** of the dictionary's **list** of `(k, v)` pair, keys and values. This could take a lot of memory if the copied list is very large. The commands `dict.iteritems()`, `dict.iterkeys()` and `dict.itervalues()` return an **iterator...
How to convert my bytearray('b\x9e\x18K\x9a') to something like this--> '\x9e\x18K\x9a'<---just str ,not array
10,459,067
4
2012-05-05T05:14:07Z
10,459,136
10
2012-05-05T05:25:04Z
[ "python", "string", "bytearray" ]
How to convert my `bytearray('b\x9e\x18K\x9a')` to something like this --> `\x9e\x18K\x9a` <---just str, not array! ``` >> uidar = bytearray() >> uidar.append(tag.nti.nai.uid[0]) >> uidar.append(tag.nti.nai.uid[1]) >> uidar.append(tag.nti.nai.uid[2]) >> uidar.append(tag.nti.nai.uid[3]) >> uidar bytearray('b\x9e\x18...
In 2.x, strings are bytestrings. ``` >>> str(bytearray('b\x9e\x18K\x9a')) 'b\x9e\x18K\x9a' ``` Latin-1 maps the first 256 characters to their bytevalue equivalents, so in Python 3.x: ``` 3>> bytearray(b'b\x9e\x18K\x9a').decode('latin-1') 'b\x9e\x18K\x9a' ```
Concatenating Tuple
10,459,324
8
2012-05-05T06:04:04Z
10,459,348
24
2012-05-05T06:07:53Z
[ "python" ]
Suppose I have a list: ``` a=[1,2,3,4,5] ``` Now I want to convert this list into a tuple. I thought coding something like this would do: ``` state=() for i in a: state=state+i ``` and it gave an error. It's quite obvious why, I *am* trying to concatenate an integer with a tuple. But tuples don't have the ...
~~Tuples are immutable, you cannot append, delete, or edit them at all. If you want to turn a list into a tuple, you can just use the tuple function:~~ ``` tuple(a) ``` If, for some reason, you feel the need to append to a tuple (You should never do this), you can always turn it back into a list, append, then turn it...
Concatenating Tuple
10,459,324
8
2012-05-05T06:04:04Z
28,011,324
8
2015-01-18T15:21:50Z
[ "python" ]
Suppose I have a list: ``` a=[1,2,3,4,5] ``` Now I want to convert this list into a tuple. I thought coding something like this would do: ``` state=() for i in a: state=state+i ``` and it gave an error. It's quite obvious why, I *am* trying to concatenate an integer with a tuple. But tuples don't have the ...
``` state=() for i in a: state=state+(i,) ``` The above code will work out to concatenate each time a new `tuple (i,)` into tuple state. I am using python 2.7.9.
Error when trying to Increment a db.IntegerProperty: TypeError: can only concatenate tuple (not "int") to tuple
10,459,402
2
2012-05-05T06:15:55Z
10,460,071
8
2012-05-05T08:11:30Z
[ "python", "google-app-engine", "gae-datastore" ]
I am playing around with Google App Engine and I am simply trying to increment a value by 1 (player.number\_requests -- see code below). However, when I do so, I am getting the following error: "TypeError: can only concatenate tuple (not "int") to tuple". Any idea why this is happening? ``` class Player(db.Model): ...
The properties in your model have a comma (,) at the end. They shouldn't. In python writing ``` foo = bar, ``` is the same as if you'd put ``` foo = (bar,) ``` which creates a tuple.
find indexes of sequence in list in python
10,459,493
3
2012-05-05T06:31:13Z
10,459,561
8
2012-05-05T06:42:15Z
[ "python", "list" ]
I am quite new and I hope it's not too obvious, but I just can't seem to find a short and precise answer to the following problem. I have two lists: ``` a = [2,3,5,2,5,6,7,2] b = [2,5,6] ``` I would like to find when all the indexes of the second list (`b`) are in the first list (`a`), so that I get something like t...
With a list comprehension: ``` >>> [(i, i+len(b)) for i in range(len(a)) if a[i:i+len(b)] == b] [(3, 6)] ``` Or with a for-loop: ``` >>> indexes = [] >>> for i in range(len(a)): ... if a[i:i+len(b)] == b: ... indexes.append((i, i+len(b))) ... >>> indexes [(3, 6)] ```
Efficiency of line by line file reading in Python
10,460,453
7
2012-05-05T09:18:31Z
10,460,468
8
2012-05-05T09:20:41Z
[ "python", "performance", "file" ]
Right now I am writing some Python code to deal with massive twitter files. These files are so big that they can't fit into memory. To work with them, I basically have two choices. 1. I could split the files into smaller files that can fit into memory. 2. I could process the big file line by line so I never need to fi...
For really fast file reading, have a look at the [mmap](http://docs.python.org/library/mmap.html) module. This will make the entire file appear as a big chunk of virtual memory, even if it's much larger than your available RAM. If your file is bigger than 3 or 4 gigabytes, then you'll want to be using a 64-bit OS (and ...
Is it costly in Python to put classes in different files?
10,460,682
6
2012-05-05T09:50:53Z
10,460,741
8
2012-05-05T09:58:01Z
[ "python", "performance", "python-2.7" ]
I am a Java programmer and I have always created separate files for Classes, I am attempting to learn python and I want to learn it right. Is it costly in python to put Classes in different files, meaning one file contains only one class. I read in a blog that it is costly because resolution of `.` operator happens at ...
It is slightly more costly, but not to an extent you are likely to care. You can negate this extra cost by doing: ``` from module import Class ``` As then the class will be assigned to a variable in the local namespace, meaning it doesn't have to do the lookup through the module. In reality, however, this is unlikel...
Merge and sum of two dictionaries
10,461,531
17
2012-05-05T11:45:52Z
10,461,916
48
2012-05-05T12:38:47Z
[ "python", "dictionary" ]
I have the following dictionary. And i want to add to another dictionary with same or different elements and merge it's results. Is there any build in function or should i have to make my own. ``` {'6d6e7bf221ae24e07ab90bba4452267b05db7824cd3fd1ea94b2c9a8': 6, '7c4a462a6ed4a3070b6d78d97c90ac230330603d24a58cafa79caf42'...
You didn't say how exactly you want to merge, so take your pick: ``` x = {'both1':1, 'both2':2, 'only_x': 100 } y = {'both1':10, 'both2': 20, 'only_y':200 } print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) } print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) & set(y) } print { k: x.get(k, 0) + y.get(k, 0) for k...
Merge and sum of two dictionaries
10,461,531
17
2012-05-05T11:45:52Z
10,461,952
11
2012-05-05T12:43:32Z
[ "python", "dictionary" ]
I have the following dictionary. And i want to add to another dictionary with same or different elements and merge it's results. Is there any build in function or should i have to make my own. ``` {'6d6e7bf221ae24e07ab90bba4452267b05db7824cd3fd1ea94b2c9a8': 6, '7c4a462a6ed4a3070b6d78d97c90ac230330603d24a58cafa79caf42'...
You could use [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict) for this: ``` from collections import defaultdict def dsum(*dicts): ret = defaultdict(int) for d in dicts: for k, v in d.items(): ret[k] += v return dict(ret) x = {'both1':1, 'both2'...
Merge and sum of two dictionaries
10,461,531
17
2012-05-05T11:45:52Z
30,950,164
7
2015-06-20T04:08:15Z
[ "python", "dictionary" ]
I have the following dictionary. And i want to add to another dictionary with same or different elements and merge it's results. Is there any build in function or should i have to make my own. ``` {'6d6e7bf221ae24e07ab90bba4452267b05db7824cd3fd1ea94b2c9a8': 6, '7c4a462a6ed4a3070b6d78d97c90ac230330603d24a58cafa79caf42'...
You can perform `+`, `-`, `&`, and `|` (intersection and union) on [`collections.Counter()`](https://docs.python.org/2/library/collections.html#collections.Counter). So we can do the following: ``` from collections import Counter x = {'both1':1, 'both2':2, 'only_x': 100 } y = {'both1':10, 'both2': 20, 'only_y':200 }...
How to pass values to templates in tornado
10,461,585
3
2012-05-05T11:54:21Z
10,462,734
9
2012-05-05T14:21:30Z
[ "python", "templates", "python-2.7", "tornado" ]
I have a template which displays a lot of values which are passed from a server, my question is how to i pass these values to the template file. My Handler code is as follows: class AdminHandler(tornado.web.RequestHandler): def get(self, \*args, \*\*kwargs): #respond to a get method #self.write("AdminHandler:: Inside G...
Here is a demonstration similar to what you seem to be doing. Look into the syntax of the template and see the different uses of `{% %}` and the `{{ }}` blocks. This code: ``` from tornado import template t = template.Template('''\ {% for user in users %} {{ user['userName'] }} {{ user['welcomeMessage'] }} ...
Zip function in python 3.2.3 not working as hoped
10,462,237
2
2012-05-05T13:17:00Z
10,462,250
7
2012-05-05T13:18:30Z
[ "python", "function", "matrix", "zip", "transpose" ]
I am trying to define a function that transposes a matrix. This is my code: ``` def Transpose (A): B = list(zip(*A)) return B ``` Now when I call the function somewhere in the program like such: ``` Matrix = [[1,2,3],[4,5,6],[7,8,9]] Transpose(Matrix) print(Matrix) ``` The matrix comes out unchanged. What a...
Your function returns a new value that does not affect your matrix (`zip` does not change it's parameters). You are not doing anything wrong, that is the correct way of doing things. Just change it to: ``` print(Transpose(Matrix)) ``` or ``` Matrix = Transpose(Matrix) ``` Note: You really should be using lower-case...
Creating a custom categorized corpus in NLTK and Python
10,463,898
8
2012-05-05T16:44:42Z
10,519,171
14
2012-05-09T15:24:46Z
[ "python", "regex", "nlp", "nltk" ]
I'm experiencing a bit of a problem which has to do with regular expressions and `CategorizedPlaintextCorpusReader` in Python. I want to create a custom categorized corpus and train a Naive-Bayes classifier on it. My issue is the following: I want to have two categories, "pos" and "neg". The positive files are all in ...
Here is the answer to my question. Since I was thinking about using two cases I think it's good to cover both in case someone needs the answer in the future. If you have the same setup as the movie\_review corpus - several folders labeled in the same way you would like your labels to be called and containing the traini...
Python: try-catch-else without handling the exception. Possible?
10,464,118
10
2012-05-05T17:09:09Z
10,464,124
24
2012-05-05T17:09:58Z
[ "python", "exception", "try-catch" ]
I am new to python and is wondering if I can make a try-catch-else statement without handling the exception? Like: ``` try: do_something() except Exception: else: print("Message: ", line) // complains about that else is not intended ```
The following sample code shows you how to catch and ignore an exception, using pass. ``` try: do_something() except RuntimeError: pass # does nothing else: print("Message: ", line) ```
How to use multiple versions of Python without uninstallation
10,464,301
6
2012-05-05T17:33:47Z
10,464,438
9
2012-05-05T17:48:33Z
[ "python", "python-3.x", "version", "nltk" ]
I am faced with a unique situation, slightly trivial but painful. I need to use Python 2.6.6 because NLTK is not ported to Python 3 (that's what I could gather). In a different code(which am working concurrently), there is a collections counter function which is available only in Python 3 but not in Python 2.6.6. So...
You simply install multiple versions in separate directories, and then you run the python program with the Python version you want to use. Like so: ``` C:\Python26\Python.exe thescript.py ``` Or similar. What virtualenv does is that it gives you many separate "virtual" installations of *the same python version*. Tha...
How to use multiple versions of Python without uninstallation
10,464,301
6
2012-05-05T17:33:47Z
10,464,628
11
2012-05-05T18:13:20Z
[ "python", "python-3.x", "version", "nltk" ]
I am faced with a unique situation, slightly trivial but painful. I need to use Python 2.6.6 because NLTK is not ported to Python 3 (that's what I could gather). In a different code(which am working concurrently), there is a collections counter function which is available only in Python 3 but not in Python 2.6.6. So...
**Install Python 3** Python 3.3 and higher put a `py.exe` into the windows folder. [[link](http://stackoverflow.com/questions/5087831/how-should-i-set-default-python-version)] This executable is used to determine the python version with the first line of the file: ``` #!/usr/bin/python2.7 ``` will be executed with P...
Interpolation on DataFrame in pandas
10,464,738
20
2012-05-05T18:25:59Z
10,465,162
29
2012-05-05T19:16:19Z
[ "python", "pandas" ]
I have a DataFrame, say a volatility surface with index as time and column as strike. How do I do two dimensional interpolation? I can reindex but how do i deal with `NaN`? I know we can `fillna(method='pad')` but it is not even linear interpolation. Is there a way we can plug in our own method to do interpolation?
You can use `DataFrame.apply` with `Series.interpolate` to get a linear interpolation. ``` In : df = pandas.DataFrame(numpy.random.randn(5,3), index=['a','c','d','e','g']) In : df Out: 0 1 2 a -1.987879 -2.028572 0.024493 c 2.092605 -1.429537 0.204811 d 0.767215 1.077814 0.565666 e -1....
Decompress zip file with password fails - bug in Python?
10,464,913
4
2012-05-05T18:46:25Z
10,465,517
8
2012-05-05T20:04:15Z
[ "python", "exception", "zip" ]
I get a strange error in python. When I try to extract a password protected file using the zip module, I get an exception when trying to set "oy" as password. Everything else seems to work. A bug in ZipFile module? ``` import zipfile zip = zipfile.ZipFile("file.zip", "r") zip.setpassword("oy".encode('utf-8')) zip....
If there's a problem with the password, usually you get the following exception: ``` RuntimeError: ('Bad password for file', <zipfile.ZipInfo object at 0xb76dec2c>) ``` Since your exception complains about block type, most probably your .zip archive is corrupted, have you tried to unpack it with standalone unzip util...
Tk grid won't resize properly
10,464,928
5
2012-05-05T18:48:11Z
10,465,176
12
2012-05-05T19:17:47Z
[ "python", "grid", "resize", "tkinter" ]
I'm trying to write a simple ui with Tkinter in python and I cannot get the widgets within a grid to resize. Whenever I resize the main window the entry and button widgets do not adjust at all. Here is my code: ``` class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master, ...
Add a root window and columnconfigure it so that your Frame widget expands too. That's the problem, you've got an implicit root window if you don't specify one and the frame itself is what's not expanding properly. ``` root = Tk() root.columnconfigure(0, weight=1) app = Application(root) ```
Data rearrangement in R
10,465,062
3
2012-05-05T19:03:54Z
10,465,325
8
2012-05-05T19:37:29Z
[ "python", "dataframe", "data.table" ]
I have several CSV files like so: ``` site,run,id,payload,dir 1,1,1,528,1 1,1,1,540,2 1,1,3,532,1 # ... thousands more rows ... ``` (In the actual case I'm working with, there are three files with a grand total of 1,408,378 rows.) For plotting, I want to reshuffle them into this format: ``` label,stream,dir,i,payloa...
R code to accomplish the desired steps: --"where 'label' is derived from the name of the CSV file; " ``` filvec <- list.files(<path>) for (fil in filvec) { #all the statements will be in the loop body dat <- read.csv(fil) dat$label <- fil # recycling will make all the elements the same character value ``` --"...
What are the pythonic way to replace a specific set element?
10,465,390
3
2012-05-05T19:45:56Z
10,465,403
9
2012-05-05T19:47:22Z
[ "python" ]
I have a python set set([1, 2, 3]) and always want to replace the third element of the set with another value. It can be done like below: ``` def change_last_elemnent(data): result = [] for i,j in enumerate(list(data)): if i == 2: j = 'C' result.append(j) return set(result) ```...
Sets are unordered, so the 'third' element doesn't really mean anything. This will remove an arbitrary element. If that is what you want to do, you can simply do: ``` data.pop() data.add(new_value) ``` If you wish to remove an item from the set by value and replace it, you can do: ``` data.remove(value) #data.disca...
Driver python for postgresql
10,465,393
4
2012-05-05T19:46:06Z
10,465,407
12
2012-05-05T19:49:03Z
[ "python", "postgresql", "driver" ]
Which is the best driver in python to connect to postgresql? There are a few possibilities, <http://wiki.postgresql.org/wiki/Python> but I don't know which is the best choice Any idea?
psycopg2 is the one everyone uses with CPython. For PyPy though, you'd want to look at the pure Python ones.
Driver python for postgresql
10,465,393
4
2012-05-05T19:46:06Z
10,465,649
8
2012-05-05T20:20:30Z
[ "python", "postgresql", "driver" ]
Which is the best driver in python to connect to postgresql? There are a few possibilities, <http://wiki.postgresql.org/wiki/Python> but I don't know which is the best choice Any idea?
I would recommend [sqlalchemy](http://www.sqlalchemy.org/) - it offers great flexibility and has a sophisticated inteface. Futhermore it's not bound to postgresql alone. Shameless c&p from the [tutorial](http://docs.sqlalchemy.org/en/rel_0_7/orm/session.html): ``` from sqlalchemy import create_engine from sqlalchemy...
Class attribute or argument's default value
10,466,207
3
2012-05-05T21:40:16Z
10,466,250
12
2012-05-05T21:47:57Z
[ "python" ]
I've found the following open source code in Python: ``` class Wait: timeout = 9 def __init__(self, timeout=None): if timeout is not None: self.timeout = timeout ... ``` I'm trying to understand if there are advantages of the code above vs using default argument's value: ``` class Wait: de...
It's possible to change the default value this way: ``` Wait.timeout = 20 ``` Will mean that, if unset, the default will be 20. E.g: ``` >>> class Wait: ... timeout = 9 ... def __init__(self, timeout=None): ... if timeout is not None: ... self.timeout = timeout ... >>> a = Wait() >>> b ...
Add separate colors for two (or more) specific values in color plot and color bar
10,466,730
4
2012-05-05T23:12:54Z
10,467,546
8
2012-05-06T02:03:54Z
[ "python", "numpy", "matplotlib" ]
I want to show a matrix in color plot and give specific colors to two or more special values. ``` import numpy as np from pylab import * np.random.seed(10) a=np.random.randint(-1,10, size=(5, 5)) print a fig, ax = plt.subplots() mat=ax.matshow(a, cmap=cm.jet, vmin=1, vmax=10) colorbar(mat) show() ``` Here are t...
You can use ListedColormap: ``` import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt N = 10 np.random.seed(10) a=np.random.randint(-1, N, size=(5, 5)) print a fig, ax = plt.subplots() colors = [(0.0,0.0,0.0),(1.0,1.0,1.0)] colors.extend(mpl.cm.jet(np.linspace(0, 1, N-1))) cmap = mpl...
How do I create my own NLTK text from a text file?
10,467,024
16
2012-05-06T00:13:23Z
10,467,054
25
2012-05-06T00:22:14Z
[ "python", "nltk" ]
I'm a Literature grad student, and I've been going through the O'Reilly book in Natural Language Processing (nltk.org/book). It looks incredibly useful. I've played around with all the example texts and example tasks in Chapter 1, like concordances. I now know how many times Moby Dick uses the word "whale." The problem...
Found the answer myself. That's embarrassing. Or awesome. From Ch. 3: ``` f=open('my-file.txt','rU') raw=f.read() tokens = nltk.word_tokenize(raw) text = nltk.Text(tokens) ``` Does the trick.
What algorithm is used when using the in operator in python to search a list?
10,468,467
4
2012-05-06T05:54:02Z
10,468,483
8
2012-05-06T05:56:52Z
[ "python", "algorithm", "search", "operators" ]
When using the 'in' operator to search for an item in a list e.g. ``` if item in list: print item ``` What algorithm is used to search for this item. Is it a straight search of the list from beginning to end or does it use something like binary search?
`list`s can't be assumed to be in sorted order (or any order at all), so binary search won't work. Nor can the keys be assumed to be hashable, so unlike a `dict` or `set` a hash-table lookup can't be used to accelerate the search At a guess it's a straight-through check of every element from first to last. I'll try a...
Filter items that only occurs once in a very large list
10,468,974
6
2012-05-06T07:42:27Z
10,468,989
17
2012-05-06T07:45:53Z
[ "python", "performance", "algorithm", "list", "filter" ]
I have a large list(over 1,000,000 items), which contains english words: ``` tokens = ["today", "good", "computer", "people", "good", ... ] ``` I'd like to get all the items that occurs only once in the list now I'm using: ``` tokens_once = set(word for word in set(tokens) if tokens.count(word) == 1) ``` but it's ...
You iterate over a list and then for each element you do it again, which makes it O(N²). If you replace your `count` by a `Counter`, you iterate once over the list and then once again over the list of unique elements, which makes it, in the worst case, O(2N), i.e. O(N). ``` from collections import Counter tokens = [...
apply mask to color image
10,469,235
11
2012-05-06T08:32:57Z
10,469,945
22
2012-05-06T10:49:02Z
[ "python", "opencv" ]
How can I apply mask to a color image in latest python binding (cv2)? In previous python binding the simplest way was to use `cv.Copy` e.g. `cv.Copy(dst, src, mask)` But this function is not available in cv2 binding. Is there any workaround without using boilerplate code?
Here, you could use `cv2.bitwise_and` function if you already have the mask image. For check the below code: ``` img = cv2.imread('lena.jpg') mask = cv2.imread('mask.png',0) res = cv2.bitwise_and(img,img,mask = mask) ``` The output will be as follows for a lena image, and for rectangular mask. ![enter image descrip...
making two strings into one
10,469,960
13
2012-05-06T10:52:45Z
10,470,033
15
2012-05-06T11:05:09Z
[ "python", "string", "algorithm" ]
Let's say I have 2 strings ``` AAABBBCCCCC ``` and ``` AAAABBBBCCCC ``` to make these strings as similar as possible, given that I can only remove characters I should * delete the last C from the first string * delete the last A and the last B from the second string, so that they become ``` AAABBBCCCC ``` What ...
[Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) can calculate how many changes you need to convert one string into another. A small change to the source, and you may get not only distance, but the conversions needed.
making two strings into one
10,469,960
13
2012-05-06T10:52:45Z
10,470,049
14
2012-05-06T11:06:51Z
[ "python", "string", "algorithm" ]
Let's say I have 2 strings ``` AAABBBCCCCC ``` and ``` AAAABBBBCCCC ``` to make these strings as similar as possible, given that I can only remove characters I should * delete the last C from the first string * delete the last A and the last B from the second string, so that they become ``` AAABBBCCCC ``` What ...
How about using `difflib`? ``` import difflib s1 = 'AAABBBCCCCC' s2 = 'AAAABBBBCCCC' for difference in difflib.ndiff(s1, s2): print difference, if difference[0] == '+': print 'remove this char from s2' elif difference[0] == '-': print 'remove this char from s1' else: print 'no...
Unicode, regular expressions and PyPy
10,471,016
7
2012-05-06T13:49:21Z
10,474,730
7
2012-05-06T22:13:13Z
[ "python", "regex", "string", "unicode", "pypy" ]
I wrote a program to add (limited) [unicode support](http://stackoverflow.com/q/1832893/520779) to Python regexes, and while it's working fine on CPython 2.5.2 it's not working on PyPy (1.5.0-alpha0 1.8.0, implementing Python 2.7.1 2.7.2), both running on Windows XP (*Edit:* as seen in the comments, @dbaupp could run i...
Why aren’t you simply using [Matthew Barnett’s super-recommended `regexp` module](http://pypi.python.org/pypi/regex) instead? It works on both Python 3 and legacy Python 2, is a drop-in replacement for `re`, handles all the Unicode stuff you could want, and a whole lot more.
What does the character `S` stand for in nosetest output
10,471,696
4
2012-05-06T15:23:49Z
10,471,776
7
2012-05-06T15:33:00Z
[ "python", "unit-testing", "nose", "nosetests" ]
I am running python nosetests on a foreign module. The dots mean that a test passed. What does S stand for? ``` c:\vendor\test>nosetests ................................................................................ ........................................SS......S.S............................. .........SSSSSSSSSSS...
`S` means skipped, `.` means success. <http://readthedocs.org/docs/nose/en/latest/plugins/skip.html> > This plugin installs a SKIP error class for the SkipTest exception. When SkipTest is raised, the exception will be logged in the skipped attribute of the result, **‘S’ or ‘SKIP’ (verbose) will be output**, a...
Child class doesn't recognize module imports of parent class?
10,471,970
3
2012-05-06T16:00:26Z
10,471,992
10
2012-05-06T16:02:36Z
[ "python", "python-module" ]
I've got two classes in two different modules: * `animal.py` * `monkey.py` **animal.py:** ``` import json class Animal(object): pass ``` **monkey:** ``` import animal class Monkey(animal.Animal): def __init__(self): super(Monkey, self).__init__() # Do some json stuff... ``` When I try ...
It is loaded, but its name is not available in the scope of `monkey.py`. You could type `animal.json` to get at it (but why would you), or just type ``` import json ``` in `monkey.py` as well. Python will ensure that the module is not loaded twice.
how to store scrapy images on Amazon S3?
10,472,274
8
2012-05-06T16:42:36Z
10,535,957
8
2012-05-10T14:17:14Z
[ "python", "amazon-s3", "scrapy" ]
I've been using scrapy for about 1 week now, and want to store the images to amazon s3, and they mentioned that they support images uploading to amazon s3 but it's not documented. So does anyone know how to use amazon s3 with scrapy ? Here's their documentation : <http://readthedocs.org/docs/scrapy/en/latest/topics/im...
You need 3 settings: ``` AWS_ACCESS_KEY_ID = "xxxxxx" AWS_SECRET_ACCESS_KEY = "xxxxxx" IMAGES_STORE = "s3://bucketname/base-key-dir-if-any/" ``` that's all, ie. images will be stored using same directory structured described at <http://readthedocs.org/docs/scrapy/en/latest/topics/images.html#file-system-storage>, ie:...
How to convert dictionary into string
10,472,907
8
2012-05-06T18:08:54Z
10,473,054
17
2012-05-06T18:26:59Z
[ "python", "string" ]
I'm trying to use the solution provided [here](http://stackoverflow.com/questions/5192753/how-to-get-the-number-of-occurrences-of-each-character-using-python) Instead of getting a dictionary, how can I get a string with the same output i.e. character followed by the number of occurrences Example:d2m2e2s3
To convert from the dict to the string in the format you want: ``` ''.join('{}{}'.format(key, val) for key, val in adict.items()) ``` if you want them alphabetically ordered by key: ``` ''.join('{}{}'.format(key, val) for key, val in sorted(adict.items())) ```
Why does Python's dis dislike lists?
10,473,744
17
2012-05-06T19:53:21Z
10,473,946
18
2012-05-06T20:21:29Z
[ "python", "python-2.x" ]
In Python (2.7.2),why does ``` import dis dis.dis("i in (2, 3)") ``` works as expected whereas ``` import dis dis.dis("i in [2, 3]") ``` raises: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dis.py", line 45, in dis disassemble_string(x) File "/usr/lib/python...
`dis.dis` expects bytecode as an argument, not python source code. Although your first example "works", it doesn't provide any meaningful output. You probably want: ``` import compiler, dis code = compiler.compile("i in [2, 3]", '', 'single') dis.dis(code) ``` This works as expected. (I tested in 2.7 only).
Why does Python's dis dislike lists?
10,473,744
17
2012-05-06T19:53:21Z
10,474,097
27
2012-05-06T20:39:00Z
[ "python", "python-2.x" ]
In Python (2.7.2),why does ``` import dis dis.dis("i in (2, 3)") ``` works as expected whereas ``` import dis dis.dis("i in [2, 3]") ``` raises: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dis.py", line 45, in dis disassemble_string(x) File "/usr/lib/python...
## Short Answer In Python 2.x, the `str` type holds raw bytes, so `dis` assumes that if you pass it a string it is getting compiled bytecode. It tries to disassemble the string you pass it as bytecode and -- purely due to the implementation details of Python bytecode -- succeeds for `i in (2,3)`. Obviously, though, it...
Why does Python's dis dislike lists?
10,473,744
17
2012-05-06T19:53:21Z
10,474,278
9
2012-05-06T21:03:23Z
[ "python", "python-2.x" ]
In Python (2.7.2),why does ``` import dis dis.dis("i in (2, 3)") ``` works as expected whereas ``` import dis dis.dis("i in [2, 3]") ``` raises: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/dis.py", line 45, in dis disassemble_string(x) File "/usr/lib/python...
If you are just trying to get bytecode for a simple expression, passing it to dis as a lambda with your expression as the lambda's body is the simplest: ``` >>> import dis >>> dis.dis(lambda i : i in [3,2]) 1 0 LOAD_FAST 0 (i) 3 LOAD_CONST 2 ((3, 2)) ...
Convert Latitude and Longitude to point in 3D space
10,473,852
12
2012-05-06T20:07:34Z
10,475,267
11
2012-05-06T23:48:34Z
[ "python", "math", "3d", "latitude-longitude", "data-conversion" ]
I need to convert latitude and longitude values to a point in the 3-dimensional space. I've been trying this for about 2 hours now, but I do not get the correct results. The **Equirectangular** coordinates come from [openflights.org](http://openflights.org/data.html). I've tried several combinations of *cos* and *sin*...
you're not doing what wikipedia suggests. read it again carefully. they say: ``` x = r cos(phi) sin(theta) y = r sin(phi) sin(theta) z = r cos(theta) ``` and then: ``` theta == latitude phi == longitude ``` and, in your case, r = radius + altitude so you should be using: ``` r = radius + altitude x = r cos(long)...
Convert Latitude and Longitude to point in 3D space
10,473,852
12
2012-05-06T20:07:34Z
20,360,045
9
2013-12-03T19:34:26Z
[ "python", "math", "3d", "latitude-longitude", "data-conversion" ]
I need to convert latitude and longitude values to a point in the 3-dimensional space. I've been trying this for about 2 hours now, but I do not get the correct results. The **Equirectangular** coordinates come from [openflights.org](http://openflights.org/data.html). I've tried several combinations of *cos* and *sin*...
I've reformatted the code that was previously mentioned here, but more importantly you have left out some of the equations mentioned in the link provided by **Niklas R** ``` def LLHtoECEF(lat, lon, alt): # see http://www.mathworks.de/help/toolbox/aeroblks/llatoecefposition.html rad = np.float64(6378137.0) ...
How do I find the angle between 2 points in pygame?
10,473,930
2
2012-05-06T20:18:39Z
10,474,341
19
2012-05-06T21:11:13Z
[ "python", "geometry", "line", "pygame" ]
I am writing a game in Python with Pygame. The co-ords (of my display window) are `( 0 , 0 )` at the top left and `(640,480)` at the bottom right. The angle is `0°` when pointing up, `90°` when pointing to the right. I have a player sprite with a centre position and I want the turret on a gun to point tow...
First, `math` has a handy `atan2(denominator, numerator)` function. Normally, you'd use `atan2(dy,dx)` but because Pygame flips the y-axis relative to Cartesian coordinates (as you know), you'll need to make `dy` negative and then avoid negative angles. ("dy" just means "the change in y".) ``` from math import atan2, ...
How to send a zip file as an attachment in python?
10,474,650
4
2012-05-06T21:58:39Z
10,474,798
7
2012-05-06T22:24:28Z
[ "python", "email", "zip" ]
I have looked through many tutorials, as well as other question here on stack overflow, and the documentation and explanation are at minimum, just unexplained code. I would like to send a file that I already have zipped, and send it as an attachment. I have tried copy and pasting the code provided, but its not working,...
I don't really see the problem. Just omit the part which creates the zip file and, instead, just load the zip file you have. Essentially, this part here ``` msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', f...
Boolean operations
10,474,882
7
2012-05-06T22:39:59Z
10,474,896
8
2012-05-06T22:42:36Z
[ "python", "python-2.7" ]
I'm confused on how Python evaluates boolean statements. For ex. ``` False and 2 or 3 ``` returns 3 How is this evaluated? I thought Python first looks at 'False and 2', and returns False without even looking at 'or 3'. What is the order of what Python sees here? Another is: ``` 1 or False and 2 or 2 and 0 or 0 `...
`and` has higher precedence than `or`. ``` False and 2 or 3 ``` is evaluated as ``` ((False and 2) or 3) ``` Since the first part `(False and 2)` is `False`, Python has to evaluated the second part to see whether the whole condition can still become `True` or not. It can, since `3` evaluates to `True` so this opera...
Bottle loading time for network server is extremely slow
10,474,993
4
2012-05-06T22:59:53Z
10,791,922
8
2012-05-29T00:56:11Z
[ "python", "html", "python-2.7", "bottle" ]
So i am currently working on a basic little website to run for my network. However, i am running into some problems. When i run the server, on the computer that is running the server, i can access the pages extremely quickly. However, when i try to access the same page on a different computer on my network, it loads EX...
I had the same delay issue while trying to test a Bottle app from another PC on the same network. The solution was to run Bottle using a better, multi-threaded server. cherrypy worked for me. 1. Install cherrypy: easy\_install cherrypy 2. Change Bottle to run using cherrypy: run(app, host='0.0.0.0', port=8080...
Bottle loading time for network server is extremely slow
10,474,993
4
2012-05-06T22:59:53Z
14,470,658
8
2013-01-23T00:44:54Z
[ "python", "html", "python-2.7", "bottle" ]
So i am currently working on a basic little website to run for my network. However, i am running into some problems. When i run the server, on the computer that is running the server, i can access the pages extremely quickly. However, when i try to access the same page on a different computer on my network, it loads EX...
I know that I am late to the party, but I encountered this same problem. The default bottle server (WSGIRef from wsgiref.simple\_server) does a reverse DNS lookup for every GET, POST, etc., so it can use the connecting hostname instead of its IP address in the web-log. This can unnecessarily slow things down, *even if*...