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 |
|---|---|---|---|---|---|---|---|---|---|
Safely create a file if and only if it does not exist with python | 10,978,869 | 51 | 2012-06-11T11:03:11Z | 18,474,773 | 26 | 2013-08-27T20:26:09Z | [
"python"
] | I wish to write to a file based on whether that file already exists or not, only writing if it doesn't already exist (in practice, I wish to keep trying files until I find one that doesn't exist).
The following code shows a way in which a potentially attacker could insert a symlink, as suggested in [this post](http://... | For reference, Python 3.3 implements a new `'x'` mode in the [`open()`](http://docs.python.org/3/library/functions.html#open) function to cover this use-case (create only, fail if file exists). |
How to check if some text is present on a web page using selenium 2? | 10,978,923 | 3 | 2012-06-11T11:07:29Z | 17,209,508 | 13 | 2013-06-20T09:03:44Z | [
"python",
"automated-tests",
"selenium-webdriver"
] | Hi I am using selenium to automate test on web pages.
I am using selenium 2 and python and would like to have answers in this framework only.
SO how do I check whether some text is present or not? I have tried asset equals but it is not working?
```
assertEquals(driver.getPageSource().contains("email"), true);
``` | You can use `driver.page_source` and a simple regular expression to check if the text exists:
```
import re
src = driver.page_source
text_found = re.search(r'text_to_search', src)
self.assertNotEqual(text_found, None)
``` |
Showing line numbers in IPython/Jupyter Notebooks | 10,979,667 | 52 | 2012-06-11T11:59:15Z | 10,986,483 | 67 | 2012-06-11T19:41:15Z | [
"python",
"ipython",
"jupyter"
] | Error reports from most language kernels running in IPython/Jupyter Notebooks indicate the line on which the error occurred; but (at least by default) no line numbers are indicated in Notebooks.
Is it possibile to add the line numbers to IPython/Jupyter Notebooks? | `CTRL` - `M``L` toggles line numbers in the CodeMirror area. See the QuickHelp for other keyboard shortcuts. |
Showing line numbers in IPython/Jupyter Notebooks | 10,979,667 | 52 | 2012-06-11T11:59:15Z | 26,174,059 | 52 | 2014-10-03T06:11:45Z | [
"python",
"ipython",
"jupyter"
] | Error reports from most language kernels running in IPython/Jupyter Notebooks indicate the line on which the error occurred; but (at least by default) no line numbers are indicated in Notebooks.
Is it possibile to add the line numbers to IPython/Jupyter Notebooks? | On IPython 2.2.0, just typing l (lowercase L) on command mode (activated by typing Esc) works. See [Help] - [Keyboard Shortcuts] for other shortcuts.
Also, you can set default behavior to display line numbers by [editing `custom.js`.](http://stackoverflow.com/questions/20197471/how-to-display-line-numbers-in-ipython-n... |
Functional programming - for and while loops | 10,981,037 | 3 | 2012-06-11T13:26:40Z | 10,981,487 | 7 | 2012-06-11T13:53:02Z | [
"python",
"functional-programming"
] | I'm trying to write for and while loops in python - functional programming style.
I think `for` construct is fine but `while` doesn't work, it runs infinitely.
```
# for loop
lst = [1, 2, 3]
def fun(e):
return e
print map(fun, lst)
# while loop
i = 1
def whileloop():
global i
print i
i = i+1
while_FP... | FP-style don't uses global state (global variables) and minimizes the side effects (IO for ex.). While-loop shout look like this:
```
fp_while = lambda pred, fun, acc: (lambda val: fp_while(pred, fun, val) if pred(val) else val)(fun(acc))
print fp_while(lambda x: x < 5, lambda x: x + 1, 1)
```
if you need a side eff... |
How to shift a column in Pandas DataFrame | 10,982,089 | 27 | 2012-06-11T14:28:49Z | 10,982,198 | 47 | 2012-06-11T14:35:02Z | [
"python",
"pandas",
"dataframe"
] | I would like to shift a column in a Pandas DataFrame, but I haven't been able to find a method to do it from the documentation without rewriting the whole DF. Does anyone know how to do it?
DataFrame:
```
## x1 x2
##0 206 214
##1 226 234
##2 245 253
##3 265 272
##4 283 291
```
Desired output:
```
## ... | ```
In [18]: a
Out[18]:
x1 x2
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
In [19]: a.x2 = a.x2.shift(1)
In [20]: a
Out[20]:
x1 x2
0 0 NaN
1 1 5
2 2 6
3 3 7
4 4 8
``` |
for - else vs for elif | 10,983,394 | 8 | 2012-06-11T15:44:48Z | 10,983,437 | 8 | 2012-06-11T15:47:02Z | [
"python",
"for-loop",
"python-2.7",
"if-statement"
] | i thought that elif: was the shorthand for
```
else:
if:
```
but it's not possible to use
for - elif:
only
for - else: if:
in this code:
```
for line in source:
change_next = False
for dataset,artnr,revision in datasets:
if dataset in line:
change_next = True
print " ... | Correct. The same goes for `else` in `try .. except .. else`. |
for - else vs for elif | 10,983,394 | 8 | 2012-06-11T15:44:48Z | 10,983,450 | 9 | 2012-06-11T15:47:56Z | [
"python",
"for-loop",
"python-2.7",
"if-statement"
] | i thought that elif: was the shorthand for
```
else:
if:
```
but it's not possible to use
for - elif:
only
for - else: if:
in this code:
```
for line in source:
change_next = False
for dataset,artnr,revision in datasets:
if dataset in line:
change_next = True
print " ... | The [`for` `else`](http://docs.python.org/reference/compound_stmts.html#the-for-statement) is a special case usage, not the same as the [`if` `elif`](http://docs.python.org/reference/compound_stmts.html#the-if-statement) structure. `elif` doesn't really make sense in the context of `for` anyway, as the meaning of the `... |
for - else vs for elif | 10,983,394 | 8 | 2012-06-11T15:44:48Z | 10,983,459 | 10 | 2012-06-11T15:48:17Z | [
"python",
"for-loop",
"python-2.7",
"if-statement"
] | i thought that elif: was the shorthand for
```
else:
if:
```
but it's not possible to use
for - elif:
only
for - else: if:
in this code:
```
for line in source:
change_next = False
for dataset,artnr,revision in datasets:
if dataset in line:
change_next = True
print " ... | `elif:` isn't a macro that expands to `else: if`, it is a syntactical element that is valid only in the context of an [`if:` statement](http://docs.python.org/reference/compound_stmts.html#the-if-statement). Ordinarily, `else: if` would open a new `if` block; however, `elif:` doesn't do that. |
How to get the newest directory in Python | 10,983,705 | 3 | 2012-06-11T16:03:45Z | 10,983,925 | 8 | 2012-06-11T16:20:02Z | [
"python",
"operating-system",
"directory"
] | I'm looking for a method that can find the newest directory created inside another directory
The only method i have is `os.listdir()` but it shows all files and directories inside. How can I list only directories and how can I access to the attributes of the directory to find out the newest created?
Thanks | ```
import os
dirs = [d for d in os.listdir('.') if os.path.isdir(d)]
sorted(dirs, key=lambda x: os.path.getctime(x), reverse=True)[:1]
```
**Update:**
Maybe some more explanation:
`[d for d in os.listdir('.') if os.path.isdir(d)]`
is a list comprehension. You can read more about them [here](http://docs.activestate... |
Automatically Rescale ylim and xlim in Matplotlib | 10,984,085 | 14 | 2012-06-11T16:32:43Z | 11,039,268 | 21 | 2012-06-14T18:34:45Z | [
"python",
"matplotlib"
] | I'm plotting data in Python using matplotlib. I am updating the data of the plot based upon some calculations and want the ylim and xlim to be rescaled automatically. Instead what happens is the scale is set based upon the limits of the initial plot. A MWE is
```
import random
import matplotlib.pyplot as pyplot
pyplo... | You will need to update the axes' dataLim, then subsequently update the axes' viewLim based on the dataLim. The approrpiate methods are axes.relim() and ax.autoscale\_view() method.
Your example then looks like:
```
import random
import matplotlib.pyplot as pyplot
pyplot.ion()
x = range(10)
y = lambda m: [m*random.r... |
OpenCV 2.4.1 - computing SURF descriptors in Python | 10,984,313 | 15 | 2012-06-11T16:49:24Z | 10,987,035 | 32 | 2012-06-11T20:23:31Z | [
"python",
"opencv",
"computer-vision"
] | I'm trying to update my code to use `cv2.SURF()` as opposed to `cv2.FeatureDetector_create("SURF")` and `cv2.DescriptorExtractor_create("SURF")`. However I'm having trouble getting the descriptors after detecting the keypoints. What's the correct way to call `SURF.detect`?
I tried following the OpenCV documentation, b... | I am not sure whether i understand your questions correctly. But if you are looking for a sample of matching SURF keypoints, a very simple and basic one is below, which is similar to template matching:
```
import cv2
import numpy as np
# Load the images
img =cv2.imread('messi4.jpg')
# Convert them to grayscale
imgg ... |
numpy array of chars to string | 10,984,471 | 6 | 2012-06-11T17:02:00Z | 10,984,878 | 9 | 2012-06-11T17:37:24Z | [
"python",
"arrays",
"string",
"numpy",
"char"
] | I have a 2D numpy char array (from a NetCDF4 file) which actually represents a list of strings. I want to convert it into a list of strings.
I know I can use join() to concatenate the chars into a string, but I can only find a way to do this one string at a time:
```
data = np.array([['a','b'],['c','d']])
for row in ... | The list comprehension is the most "pythonic" way.
The most "numpythonic" way would be:
```
>>> data = np.array([['a','b'],['c','d']])
# a 2D view
>>> data.view('S2')
array([['ab'],
['cd']],
dtype='|S2')
# or maybe a 1D view ...fastest solution:
>>> data.view('S2').ravel()
array(['ab', 'cd'],
dty... |
Loop through dates except for weekends | 10,984,741 | 6 | 2012-06-11T17:25:39Z | 10,984,848 | 8 | 2012-06-11T17:35:09Z | [
"python",
"datetime",
"loops"
] | So I have a script that has date arguments for different functions and I want it to loop through `01-01-2012` to `06-09-2012` not including weekends. Im trying to figure out a way I can use time delta because my script outputs files with the date used in the name of the file for example:
```
items = (functions.getItem... | Use the [`datetime.weekday()`](http://docs.python.org/library/datetime.html#datetime.date.weekday) method. It returns values between zero and six, related to the weekdays. Saturday value is 5 and Sunday value is 6; so, if you skip the operation when these values appear, you skip weekdends:
```
start = datetime(2012, 1... |
Sockets between computers | 10,985,112 | 7 | 2012-06-11T17:55:12Z | 10,985,254 | 7 | 2012-06-11T18:06:06Z | [
"python",
"sockets",
"python-3.x",
"pygame"
] | So far I have been able to work out a basic socket in python **3.2**. The client sends some data, an X and a Y coordinate, to the server, and the server takes the data and sends back a confirmation message. But the trouble I'm having is getting it to listen between computers. My server and client work perfect when I ru... | Don't bind to localhost. This means that your server will only listen to itself. If you bind to `0.0.0.0`, this will ensure that your server is listening to every computer that can reach it. (**Warning**: potentially insecure.)
An overzealous firewall rule could also be to blame.
Make sure you are connecting to your ... |
parsing date string in python (convert string to date) | 10,985,312 | 5 | 2012-06-11T18:09:53Z | 10,985,348 | 23 | 2012-06-11T18:11:37Z | [
"python"
] | I have a datetime string in the form of a string as:
```
2011-10-23T08:00:00-07:00
```
How do i parse this string as the datetime object.
I did the following reading the documentation:
```
date = datetime.strptime(data[4],"%Y-%m-%d%Z")
```
BUt I get the error
```
ValueError: time data '2011-10-23T08:00:00-07:00... | Standard datetime.datetime.strptime has problems with timezone definitions. Use [dateutil.parser](http://labix.org/python-dateutil)
```
>>> from dateutil import parser
>>> parser.parse("2011-10-23T08:00:00-07:00")
datetime.datetime(2011, 10, 23, 8, 0, tzinfo=tzoffset(None, -25200))
```
If you care about the date part... |
How to represent a jar file as a network graph? | 10,985,576 | 3 | 2012-06-11T18:29:11Z | 10,985,578 | 8 | 2012-06-11T18:29:12Z | [
"java",
"python",
"graph",
"jar",
"networkx"
] | As a result of trying to answer the question [Graph isomorphism for jar files](http://stackoverflow.com/q/10916159/1290420), the debate naturally arose as to how to represent a jar file as a graph using Python.
The problem: given a jar file, read the files contained within it and create a representation of the content... | ## The Solution
Given that jar files are basically zipped archives, use [the `zipfile` module](http://docs.python.org/library/zipfile.html) from the standard library in Python to read the contents and prepare textual and graphic representation of the relations of the contents of the jar.
## Textual Representation
Fo... |
Multi line string with arguments. How to declare? | 10,985,603 | 13 | 2012-06-11T18:31:37Z | 10,985,648 | 14 | 2012-06-11T18:34:28Z | [
"python"
] | Let's say I have an extremely long string with arguments that I want to create.
I know you can create a multiline string with
```
cmd = """line 1
line 2
line 3"""
```
But now lets say I want to pass 1, 2, and 3 as arguments.
This works
```
cmd = """line %d
line %d
line %d""" % (1, 2, 3)
```
... | You could abuse the line continuation properties of the parenthesis `(` and the comma `,`.
```
cmd = """line %d
line %d
line %d""" % (
1,
2,
3)
``` |
Multi line string with arguments. How to declare? | 10,985,603 | 13 | 2012-06-11T18:31:37Z | 10,986,239 | 24 | 2012-06-11T19:22:13Z | [
"python"
] | Let's say I have an extremely long string with arguments that I want to create.
I know you can create a multiline string with
```
cmd = """line 1
line 2
line 3"""
```
But now lets say I want to pass 1, 2, and 3 as arguments.
This works
```
cmd = """line %d
line %d
line %d""" % (1, 2, 3)
```
... | You could use the `str.format()` function, that allows named arguments. So,
```
'''line {0}
line {1}
line {2}'''.format(1,2,3)
```
You could of course extend this using Python's `*args` syntax to allow you to pass in a `tuple` or `list`.
```
args = (1,2,3)
'''line {0}
line {1}
line {2}'''.format(*args)
```
If you c... |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,986,983 | 13 | 2012-06-11T20:19:37Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | you can use the mod (`%`) operator.
```
count = 0 # initialize count once
```
then
```
count = (count + 1) % 2
```
will toggle the value of count between 0 and 1 each time this statement is executed. The *advantage* of this approach is that you can cycle through a sequence of values (if needed) from `0 - (n-1)` wh... |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,987,000 | 40 | 2012-06-11T20:21:18Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | You can accomplish that with a generator like this:
```
>>> def alternate():
... while True:
... yield 0
... yield 1
...
>>>
>>> alternator = alternate()
>>>
>>> alternator.next()
0
>>> alternator.next()
1
>>> alternator.next()
0
``` |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,987,025 | 49 | 2012-06-11T20:23:03Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | Use `itertools.cycle()`:
```
from itertools import cycle
myIterator = cycle(range(2))
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next() # or next(myIterator) which works in Python 3.x. Yields 1
# etc.
```
Note that if you need a more complicated cycle than `[0, 1]`, th... |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,987,046 | 9 | 2012-06-11T20:24:23Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | In python, True and False *are integers* (1 and 0 respectively). You could use a boolean (True or False) and the not operator:
```
var = not var
```
Of course, if you want to iterate between other numbers than 0 and 1, this trick becomes a little more difficult.
To pack this into an admittedly ugly function:
```
de... |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,987,098 | 7 | 2012-06-11T20:29:59Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | ```
from itertools import cycle
alternator = cycle((0,1))
next(alternator) # yields 0
next(alternator) # yields 1
next(alternator) # yields 0
next(alternator) # yields 1
#... forever
``` |
Python: How to toggle between two values | 10,986,970 | 23 | 2012-06-11T20:18:35Z | 10,987,177 | 16 | 2012-06-11T20:36:58Z | [
"python",
"toggle"
] | I want to toggle between two values in Python, that is, between 0 and 1.
For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.
Sorry if this doesn't make sense, but does anyone know a way to do this? | You may find it useful to create a function alias like so:
```
import itertools
myfunc = itertools.cycle([0,1]).next
```
then
```
myfunc() # -> returns 0
myfunc() # -> returns 1
myfunc() # -> returns 0
myfunc() # -> returns 1
``` |
Xvfb multiple displays for parallel processing? | 10,987,246 | 8 | 2012-06-11T20:42:25Z | 10,987,416 | 7 | 2012-06-11T20:56:54Z | [
"python",
"parallel-processing",
"rendering",
"xvfb"
] | Curious about running multiple xvfb displays: I have between 10-50 instances of a script running in parallel that connect to an xvfb display. Is is advantageous to run the same number of xvfb displays and connect 1 to 1? Or can multiple processes share the same display? RAM is not an issue, neither is processing power. | One Xvfb server should be able to handle lots of connections quite well. One thing you want to make sure you do is run the server with the `-noreset` option. Without it, it has a memory leak every time a client disconnects.
The only time multiple Xvfb servers is helpful is if you have more than one processor available... |
Creating QuerySet object from last 7 days | 10,987,778 | 4 | 2012-06-11T21:29:02Z | 10,987,912 | 14 | 2012-06-11T21:40:36Z | [
"python",
"django"
] | `posts = Post.objects.filter(author=member.user, xyz=xyz_id, pub_date >= datetime.datetime.now()-7)`
I want to extract all posts by those requires of author and xyz which will be from last 7 days. Results only from last 7 days. I ofc know that this is wrong but I do not have idea how to code it. | ```
from datetime import datetime, timedelta
posts = Post.objects.filter(author=member.user, xyz=xzy_id, pub_date__gte=datetime.now()-timedelta(days=7))
``` |
"ImportError: No module named cv2" when running Django project from PyCharm IDE | 10,987,834 | 2 | 2012-06-11T21:33:27Z | 10,992,173 | 8 | 2012-06-12T07:26:23Z | [
"python",
"django",
"opencv",
"pycharm"
] | I'm running a Django project from PyCharm with the configuration set up to use the Python interpreter from a virtualenv which has a dependency on opencv. The site works fine locally when I run `django-admin.py runserver`, however I keep getting an "`ImportError: No module named cv2`" error when I try to run the project... | In the end I ended up having to set an environment variable directly in the Pycharm Edit Configurations -> Run/Debug Configurations -> Environment Variables panel. I added the following option after you hit the edit button: set name to `PYTHONPATH` and value to `/usr/local/lib/python2.7/site-packages:$PYTHONPATH` which... |
Iterating Through List by 3's | 10,988,036 | 4 | 2012-06-11T21:51:22Z | 10,988,055 | 14 | 2012-06-11T21:53:37Z | [
"python",
"list"
] | ```
a = [3,5,8,3,9,5,0,3,2,7,5,4]
for o in a[::3]:
print o
```
This gets me the first and every 3 item.
3,3,0,7
is there a way i can retrieve the next two items as well?
```
a = [3,5,8,3,9,5,0,3,2,7,5,4]
for o in a[::3]:
if o == 0:
print o
print o + 1
print o + 2
```
output 0 3 2
I know that's no... | You can do this using the "grouper" recipe from the [`itertools` documentation](http://docs.python.org/library/itertools.html#recipes):
```
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
```
... |
What are the URL parameters? (element at position #3 in urlparse result) | 10,988,614 | 22 | 2012-06-11T23:02:59Z | 10,988,756 | 12 | 2012-06-11T23:30:50Z | [
"python",
"url",
"url-parameters",
"urlparse"
] | I've taken a look to `urlparse.urlparse` method documentation and I'm a little bit confused about what is the `parameters` part (not to be confused with the more familiar `query` part, that is what goes after the question mark and before the fragment part).
Wikipedia entry on URL's structure doesn't say anything about... | fascinating, this is the first time I've encounter them, found this
<http://doriantaylor.com/policy/http-url-path-parameter-syntax> I also found this
<http://tools.ietf.org/html/rfc3986#section-3.3> (last paragraph before query) and this
<http://www.jtmelton.com/2011/02/02/beware-the-http-path-parameter/>
their rare... |
What are the URL parameters? (element at position #3 in urlparse result) | 10,988,614 | 22 | 2012-06-11T23:02:59Z | 10,988,764 | 20 | 2012-06-11T23:31:24Z | [
"python",
"url",
"url-parameters",
"urlparse"
] | I've taken a look to `urlparse.urlparse` method documentation and I'm a little bit confused about what is the `parameters` part (not to be confused with the more familiar `query` part, that is what goes after the question mark and before the fragment part).
Wikipedia entry on URL's structure doesn't say anything about... | Wow... I was not aware of that, see example:
```
>>> urlparse.urlparse("http://some.page.pl/nothing.py;someparam=some;otherparam=other?query1=val1&query2=val2#frag")
ParseResult(scheme='http', netloc='some.page.pl', path='/nothing.py', params='someparam=some;otherparam=other', query='query1=val1&query2=val2', fragment... |
Using Django's new i18n_patterns: How to fall back to the default language specified in the settings module? | 10,988,882 | 7 | 2012-06-11T23:46:58Z | 10,989,971 | 11 | 2012-06-12T02:47:08Z | [
"python",
"django",
"internationalization",
"url-routing",
"urlconf"
] | I'm using the new `i18n_patterns` of Django 1.4:
```
from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns += i18n_patterns('',
url(r'^admin/', include(admin.site.urls)),
)
```
It works for every acti... | It looks like you did not [enable django.middleware.locale.LocaleMiddleware](https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-url-patterns). |
Differences between Jython and Python | 10,989,098 | 5 | 2012-06-12T00:18:41Z | 15,779,076 | 13 | 2013-04-03T04:47:32Z | [
"python",
"syntax",
"jython"
] | I know Jython converts Python code into Java byte code, but are there any syntax changes between the two? and as a side question is Jython 3.x usable yet or is it still being ported? | In a nutshell
## Differences of - Python & Jython
### Python
1. C
2. Multi-platform
3. Compiles to .pyc
4. Extend with C
5. GIL 1\*
6. Python Garbage Collection
1\*. Global Interpreter Lock, explained in [Documentation](https://docs.python.org/3/) Python documentation, chapter 8.1 (1)
### Jython
1. 100% Java
2. A... |
Python regex negation within regex | 10,989,198 | 4 | 2012-06-12T00:35:33Z | 10,989,385 | 7 | 2012-06-12T01:06:22Z | [
"python",
"regex"
] | Given:
```
ABC
content 1
123
content 2
ABC
content 3
XYZ
```
Is it possible to create a regex that matches the shortest version of "ABC[\W\w]+?XYZ"
Essentially, I'm looking for "ABC followed by any characters terminating with XYZ, but don't match if I encounter ABC in between" (but think of ABC as a potential regex ... | A regex solution would be `ABC(?:(?!ABC).)*?XYZ` with the `DOTALL` flag. |
Python creating a list with itertools.product? | 10,989,585 | 3 | 2012-06-12T01:40:11Z | 10,989,693 | 8 | 2012-06-12T02:00:05Z | [
"python",
"itertools"
] | I'm creating a list with itertools from a list of ranges, so far I have this:
```
start_list = [xrange(0,201,1),xrange(0,201,2),xrange(0,201,5),xrange(0,201,10),xrange(0,201,20),xrange(0,201,50),xrange(0,201,100),xrange(0,201,200)]
```
Now, I know that if I were to try to run this next line it will kill my python int... | Better to just use a list comprehension
```
new_list = [item for item in itertools.product(*start_list) if sum(item) == 200]
``` |
Pygame mouse clicking detection | 10,990,137 | 6 | 2012-06-12T03:18:49Z | 10,992,212 | 13 | 2012-06-12T07:29:18Z | [
"python",
"mouseevent",
"pygame"
] | I was wondering how to write code that would detect the mouse clicking on a sprite. For example:
```
if #Function that checks for mouse clicked on Sprite:
print ("You have opened a chest!")
``` | I assume your game has a main loop, and all your sprites are in a list called `sprites`.
In your main loop, get all events, and check for the `MOUSEBUTTONDOWN` or `MOUSEBUTTONUP` event.
```
while ... # your main loop
# get all events
ev = pygame.event.get()
# proceed events
for event in ev:
# handle MOU... |
Gevent monkey unpatch | 10,990,151 | 3 | 2012-06-12T03:21:07Z | 10,991,918 | 7 | 2012-06-12T07:07:37Z | [
"python",
"monkeypatching",
"gevent"
] | I'm doing my program in many steps. One of them is to use gevent + monkey patch
```
from gevent import monkey; monkey.patch_all()
```
Everything works great. But can i unpatch it after i'm done using it ? I want to return to my default socket functions. | ```
reload(socket)
```
This blog post has a pretty good write up of the solution here: <http://emptysquare.net/blog/undoing-gevents-monkey-patching/> |
One loop? python | 10,991,311 | 3 | 2012-06-12T06:06:17Z | 10,991,376 | 9 | 2012-06-12T06:13:32Z | [
"python"
] | So I wrote this function that is given possible numbers, and it has to find the two numbers inside the possible numbers that make up the given number. However, I am still learning Python (a very wonderful language) so I can only use a limited set of functions.
I created this function:
```
def sumPair(theList, n):
... | Instructor is probably unhappy that your algorithm takes longer than it has to. Try this:
```
for each element x in theList
if there exists an element y in theList such that x+y = n, you have a match
```
You need to make the "if exists" test fast, which is what you use a dictionary for. One loop will build up this ... |
Django: Get current user in model save | 10,991,460 | 28 | 2012-06-12T06:22:35Z | 10,993,961 | 17 | 2012-06-12T09:34:15Z | [
"python",
"django",
"django-models"
] | I want to get current logged in user(request.user) in save method of models.py. I want to check the role of the user and perform some operations based on his role. I have given the models.py code below.
**models.py**
```
class TimeSheet(models.Model):
check_in_time = models.TimeField()
check_out... | You can tackle this problem from another angle. Instead of changing the models save method you should override the AdminSites `save_model` method. There you'll have the request object and can access the logged in user data as you already pointed out.
Have a look at this chapter of the docs: [Django ModelAdmin document... |
Django: Get current user in model save | 10,991,460 | 28 | 2012-06-12T06:22:35Z | 13,205,194 | 8 | 2012-11-03T01:45:21Z | [
"python",
"django",
"django-models"
] | I want to get current logged in user(request.user) in save method of models.py. I want to check the role of the user and perform some operations based on his role. I have given the models.py code below.
**models.py**
```
class TimeSheet(models.Model):
check_in_time = models.TimeField()
check_out... | I don't think that save\_model method override is the best option. Imagine, for instance, that you want to save the user info or validate the model based on user info and that save() does not come from a view or the adminsite itself.
What people are asking are constructions like those one:
```
def save(..)
self.u... |
PySide: Easier way of updating GUI from another thread | 10,991,991 | 14 | 2012-06-12T07:12:58Z | 12,127,115 | 16 | 2012-08-26T02:06:05Z | [
"python",
"multithreading",
"qt",
"signals-slots",
"pyside"
] | I have a PySide (Qt) GUI which spawns multiple threads. The threads sometimes need to update the GUI. I have solved this in the following way:
```
class Signaller(QtCore.QObject) :
my_signal = QtCore.Signal(QListWidgetItem, QIcon)
signaller = Signaller()
class MyThread(threading.Thread):
def __init__(self):
... | I started coding with PySide recently and I needed a equivalent of PyGObject's `GLib.idle_add` behaviour. I based the code off of your answer ( <http://stackoverflow.com/a/11005204/1524507> ) but this one uses events instead of using a queue ourselves.
```
from PySide import QtCore
class InvokeEvent(QtCore.QEvent):
... |
Python: Importing Module | 10,993,156 | 6 | 2012-06-12T08:42:15Z | 10,993,202 | 9 | 2012-06-12T08:46:11Z | [
"python"
] | Lets say i have a python model fibo.py defined as below:
```
#Fibonacci numbers module
print "This is a statement"
def fib(n):
a,b = 0,1
while b < n:
print b
a, b = b, a+b
def fib2(n):
a,b = 0,1
result= []
while(b < n):
result.append(b)
a, b = b, a+b
return resu... | This is expected behavior. When you import with `from X import Y`, the module is still loaded and executed, as documented in the [Language Reference](http://docs.python.org/reference/simple_stmts.html#the-import-statement). In fact, when you do
```
from fibo import fib
print("foo")
import fibo
```
will print `This is... |
Python: Removing \xa0 from string? | 10,993,612 | 74 | 2012-06-12T09:12:32Z | 11,566,398 | 92 | 2012-07-19T17:42:44Z | [
"python",
"parsing",
"unicode"
] | I am currently using Beautiful Soup to parse an HTML file and calling `get_text()`, but it seems like I'm being left with a lot of \xa0 Unicode representing spaces. Is there an efficient way to remove all of them in Python 2.7, and change them into spaces? I guess the more generalized question would be, is there a way ... | \xa0 is actually non-breaking space in Latin1 (ISO 8859-1), also chr(160). You should replace it with a space.
`string = string.replace(u'\xa0', u' ')`
When .encode('utf-8'), it will encode the unicode to utf-8, that means every unicode could be represented by 1 to 4 bytes. For this case, \xa0 is represented by 2 byt... |
Python: Removing \xa0 from string? | 10,993,612 | 74 | 2012-06-12T09:12:32Z | 13,828,161 | 11 | 2012-12-11T20:39:35Z | [
"python",
"parsing",
"unicode"
] | I am currently using Beautiful Soup to parse an HTML file and calling `get_text()`, but it seems like I'm being left with a lot of \xa0 Unicode representing spaces. Is there an efficient way to remove all of them in Python 2.7, and change them into spaces? I guess the more generalized question would be, is there a way ... | I ran into this same problem pulling some data from a sqlite3 database with python. The above answers didn't work for me (not sure why), but this did: `line = line.decode('ascii', 'ignore')` However, my goal was deleting the \xa0s, rather than replacing them with spaces.
I got this from [this super-helpful unicode tut... |
Python: Removing \xa0 from string? | 10,993,612 | 74 | 2012-06-12T09:12:32Z | 34,669,482 | 23 | 2016-01-08T04:24:55Z | [
"python",
"parsing",
"unicode"
] | I am currently using Beautiful Soup to parse an HTML file and calling `get_text()`, but it seems like I'm being left with a lot of \xa0 Unicode representing spaces. Is there an efficient way to remove all of them in Python 2.7, and change them into spaces? I guess the more generalized question would be, is there a way ... | There's many useful things in Python's `unicodedata` library. One of them is the [`.normalize()`](https://docs.python.org/2/library/unicodedata.html#unicodedata.normalize) function.
Try:
```
new_str = unicodedata.normalize("NFKD", unicode_str)
```
Replacing NFKD with any of the other methods listed in the link above... |
How do I create a 404 page? | 10,994,195 | 7 | 2012-06-12T09:50:51Z | 10,995,088 | 17 | 2012-06-12T10:46:15Z | [
"python",
"flask",
"jinja2"
] | My application catches all url requests with an `@app.route`, but occasionally I bump into a bad url for which I have no matching jinja file (bu it does match an existing `@app.route`). So I want to redirect such requests to a 404 page for that bad url.
How to discriminate between "a jinja file exists" and "a jinja fi... | Jinja will throw an exception if the template is not found: `TemplateNotFound`
So instead of:
```
def myview():
return render_template(...)
```
you could do something like this:
```
def myview():
try:
return render_template(...)
except TemplateNotFound:
abort(404)
```
And then handle th... |
How to make an object properly hashable? | 10,994,229 | 20 | 2012-06-12T09:53:46Z | 10,994,240 | 26 | 2012-06-12T09:55:13Z | [
"python",
"python-3.x"
] | Here is my code:
```
class Hero:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + str(self.age)
def __hash__(self):
print(hash(str(self)))
return hash(str(self))
heroes = set()
heroes.add(Hero('Zina Portnova', 1... | You also need to define `__eq__()` in a compatible way with [`__hash__()`](http://docs.python.org/reference/datamodel.html#object.__hash__) â otherwise, equality will be based on object identity. |
Something like pyHook on OS X | 10,994,750 | 4 | 2012-06-12T10:26:20Z | 11,004,560 | 9 | 2012-06-12T20:42:09Z | [
"python",
"osx",
"keylogger",
"pyhook"
] | I am actually working with **pyHook**, but I'd like to write my program for OS X too.
If someone know such a module ... I've been looking on the internet for a while, but nothing really relevant.
-> The idea is to be able to record keystrokes outside the python app. My application is a *community statistics* builder, ... | As far as I know, there is no Python library for this, so you're going to be calling native APIs. The good news is that PyObjC (which comes with the built-in Python on recent OS releases) often makes that easy.
There are two major options. For either of these to work, your app has to have a Cocoa/CoreFoundation runloo... |
Python check if list of keys exist in dictionary | 10,995,172 | 26 | 2012-06-12T10:51:20Z | 10,995,203 | 63 | 2012-06-12T10:52:50Z | [
"python"
] | I have a dictionary that looks like that:
```
grades = {
'alex' : 11,
'bob' : 10,
'john' : 14,
'peter': 7
}
```
and a list of names `students = ('alex', 'john')`
I need to check that all the names in `students` exist as keys in `grades` dict.
`grades` can have more names, but... | Use [`all()`](https://docs.python.org/2/library/functions.html#all):
```
if all(name in grades for name in students):
# whatever
``` |
Python check if list of keys exist in dictionary | 10,995,172 | 26 | 2012-06-12T10:51:20Z | 10,995,204 | 8 | 2012-06-12T10:52:53Z | [
"python"
] | I have a dictionary that looks like that:
```
grades = {
'alex' : 11,
'bob' : 10,
'john' : 14,
'peter': 7
}
```
and a list of names `students = ('alex', 'john')`
I need to check that all the names in `students` exist as keys in `grades` dict.
`grades` can have more names, but... | ```
>>> grades = {
'alex' : 11,
'bob' : 10,
'john' : 14,
'peter': 7
}
>>> names = ('alex', 'john')
>>> set(names).issubset(grades)
True
```
Calling it `class` is invalid so I changed it to `names`. |
How to remove specific elements in a numpy array | 10,996,140 | 65 | 2012-06-12T11:54:37Z | 10,996,196 | 98 | 2012-06-12T11:58:06Z | [
"python",
"arrays",
"numpy"
] | How can I remove some specific elements from a numpy array? Say I have
```
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
```
I then want to remove `3,4,7` from `a`. All I know is the index of the values (`index=[2,3,6]`). | Use [numpy.delete()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html) - returns a *new* array with sub-arrays along an axis deleted
```
numpy.delete(a, index)
```
For your specific question:
```
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
index = [2, 3, 6]
new_a = np.delete(a... |
How to remove specific elements in a numpy array | 10,996,140 | 65 | 2012-06-12T11:54:37Z | 10,996,272 | 16 | 2012-06-12T12:03:02Z | [
"python",
"arrays",
"numpy"
] | How can I remove some specific elements from a numpy array? Say I have
```
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
```
I then want to remove `3,4,7` from `a`. All I know is the index of the values (`index=[2,3,6]`). | A Numpy array is [immutable](http://en.wikipedia.org/wiki/Immutable_object), meaning you technically cannot delete an item from it. However, you can construct a *new* array without the values you don't want, like this:
```
b = np.delete(a, [2,3,6])
``` |
How to remove specific elements in a numpy array | 10,996,140 | 65 | 2012-06-12T11:54:37Z | 36,460,734 | 7 | 2016-04-06T19:33:32Z | [
"python",
"arrays",
"numpy"
] | How can I remove some specific elements from a numpy array? Say I have
```
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9])
```
I then want to remove `3,4,7` from `a`. All I know is the index of the values (`index=[2,3,6]`). | There is a numpy built-in function to help with that.
```
import numpy as np
>>> a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = np.array([3,4,7])
>>> c = np.setdiff1d(a,b)
>>> c
array([1, 2, 5, 6, 8, 9])
``` |
Pixel neighbors in 2d array (image) using Python | 10,996,769 | 3 | 2012-06-12T12:34:48Z | 10,998,027 | 8 | 2012-06-12T13:46:47Z | [
"python",
"numpy",
"computer-vision",
"scipy",
"nearest-neighbor"
] | I have a numpy array like this:
```
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
```
I need to create a function let's call it "neighbors" with the following input parameter:
* x: a numpy 2d array
* (i,j): the index of an element in a 2d array
* d: neighborhood radius
As output I want to get the neighbors of the cell `i... | Have a look at [`scipy.ndimage.generic_filter`.](http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.filters.generic_filter.html)
As an example:
```
import numpy as np
import scipy.ndimage as ndimage
def test_func(values):
print values
return values.sum()
x = np.array([[1,2,3],[4,5,6],... |
"Converting" Numpy arrays to Matlab and vice versa | 10,997,254 | 15 | 2012-06-12T13:02:26Z | 10,997,335 | 28 | 2012-06-12T13:07:06Z | [
"python",
"matlab",
"numpy"
] | I am looking for a way to pass NumPy arrays to Matlab.
I've managed to do this by storing the array into an image using `scipy.misc.imsave` and then loading it using `imread`, but this of course causes the matrix to contain values between 0 and 256 instead of the 'real' values.
Taking the product of this matrix divid... | Sure, just use `scipy.io.savemat`
As an example:
```
import numpy as np
import scipy.io
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
scipy.io.savemat('test.mat', dict(x=x, y=y))
```
Similarly, there's `scipy.io.loadmat`.
You then load this in matlab with `load test`.
Alteratively, as @JAB suggested, you coul... |
Python Timezone conversion | 10,997,577 | 15 | 2012-06-12T13:20:38Z | 10,997,718 | 31 | 2012-06-12T13:28:32Z | [
"python",
"timezone"
] | I am looking for a quick way to type in a time and then python convert it into other timezones ( maybe up to 10 different timezones )
Sorry. I am not fimilar with time in python at all, if someone could put me in the right direction I would really appreciate it. | Using [pytz](http://pytz.sourceforge.net/)
```
from datetime import datetime
from pytz import timezone
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
timezonelist = ['UTC','US/Pacific','Europe/Berlin']
for zone in timezonelist:
now_time = datetime.now(timezone(zone))
print now_time.strftime(fmt)
``` |
Python Timezone conversion | 10,997,577 | 15 | 2012-06-12T13:20:38Z | 18,646,797 | 28 | 2013-09-05T22:13:24Z | [
"python",
"timezone"
] | I am looking for a quick way to type in a time and then python convert it into other timezones ( maybe up to 10 different timezones )
Sorry. I am not fimilar with time in python at all, if someone could put me in the right direction I would really appreciate it. | I have found that the best approach is to first convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).
Then you can use [astimezone](http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone) to convert to the... |
How to read lines from a CSV variable into a multidimensional array in python? | 10,998,413 | 3 | 2012-06-12T14:09:15Z | 10,998,514 | 8 | 2012-06-12T14:14:07Z | [
"python",
"csv",
"multidimensional-array",
"python-2.7"
] | The string looks like this:
```
x = '''"High";"10";"Assigned";"2012/06/12 10:11:02"
"Low";"20";"Assigned";"2012/06/12 10:11:02"
"Medium";"30";"Assigned";"2012/06/12 10:11:02"'''
```
I want it to be like this:
```
x = [
[High, 10, Assigned, 2012/06/12 10:11:02],
[Low, 20, Assigned, 2012/06/12 10:11:02],
[Medium, 30, ... | ```
>>> import csv
>>> result = [row for row in csv.reader(x.splitlines(), delimiter=';')]
>>> import pprint
>>> pprint.pprint(result)
[['High', '10', 'Assigned', '2012/06/12 10:11:02'],
['Low', '20', 'Assigned', '2012/06/12 10:11:02'],
['Medium', '30', 'Assigned', '2012/06/12 10:11:02']]
``` |
Square braces not required in list comprehensions when used in a function | 10,998,521 | 6 | 2012-06-12T14:14:32Z | 10,998,554 | 15 | 2012-06-12T14:17:05Z | [
"python",
"syntax",
"list-comprehension"
] | I submitted a pull request with this code:
```
my_sum = sum([x for x in range(10)])
```
One of the reviewers suggested this instead:
```
my_sum = sum(x for x in range(10))
```
(the difference is just that the square braces are missing).
I was surprised that the second form seems to be identical. But when I tried t... | This is a generator expression. To get it to work in the standalone case, use braces:
```
y = (x for x in range(10))
```
and y becomes a generator. You can iterate over generators, so it works where an iterable is expected, such as the `sum` function.
**Usage examples and pitfalls:**
```
>>> y = (x for x in range(1... |
Rotate axis text in python matplotlib | 10,998,621 | 33 | 2012-06-12T14:20:34Z | 10,998,872 | 39 | 2012-06-12T14:34:35Z | [
"python",
"matplotlib"
] | I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception t... | Try pyplot.setp. I think you could do something like this:
```
x = range(len(time))
plt.xticks(x, time)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.plot(x, delay)
``` |
Rotate axis text in python matplotlib | 10,998,621 | 33 | 2012-06-12T14:20:34Z | 10,999,118 | 26 | 2012-06-12T14:48:56Z | [
"python",
"matplotlib"
] | I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception t... | I came up with a similar example. Again, the rotation keyword is.. well, it's key.
```
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;
``` |
Rotate axis text in python matplotlib | 10,998,621 | 33 | 2012-06-12T14:20:34Z | 23,009,503 | 39 | 2014-04-11T10:04:49Z | [
"python",
"matplotlib"
] | I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception t... | **Easy way**
As [described here](http://matplotlib.org/1.3.1/users/recipes.html), there is an existing method in the `matplotlib.pyplot` `figure` class that automatically rotates dates appropriately for you figure.
You can call it after you plot your data (i.e.`ax.plot(dates,ydata)` :
```
fig.autofmt_xdate()
```
If... |
Rotate axis text in python matplotlib | 10,998,621 | 33 | 2012-06-12T14:20:34Z | 32,478,701 | 7 | 2015-09-09T11:45:41Z | [
"python",
"matplotlib"
] | I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception t... | My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:
```
for tick in ax.get_xticklabels():
tick.set_rotation(45)
``` |
Rotate axis text in python matplotlib | 10,998,621 | 33 | 2012-06-12T14:20:34Z | 37,708,190 | 10 | 2016-06-08T16:36:15Z | [
"python",
"matplotlib"
] | I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception t... | This works for me:
```
plt.xticks(rotation=90)
``` |
How to convert GMT time to EST time using python | 10,999,021 | 7 | 2012-06-12T14:42:23Z | 10,999,098 | 17 | 2012-06-12T14:47:25Z | [
"python",
"timezone",
"timestamp"
] | I want convert GMT time to EST time and get a timestamp. I tried the following but don't know how to set timezone.
```
time = "Tue, 12 Jun 2012 14:03:10 GMT"
timestamp2 = time.mktime(time.strptime(time, '%a, %d %b %Y %H:%M:%S GMT'))
``` | Time zones aren't built into standard Python - you need to use another library. [pytz](http://pytz.sourceforge.net/) is a good choice.
```
>>> gmt = pytz.timezone('GMT')
>>> eastern = pytz.timezone('US/Eastern')
>>> time = "Tue, 12 Jun 2012 14:03:10 GMT"
>>> date = datetime.datetime.strptime(time, '%a, %d %b %Y %H:%M:... |
tee function from itertools library | 10,999,039 | 5 | 2012-06-12T14:43:42Z | 10,999,092 | 13 | 2012-06-12T14:47:00Z | [
"python",
"itertools"
] | Both list and islice objects are iterable but why this difference in result.
```
r = [1, 2, 3, 4]
i1, i2 = tee(r)
print [e for e in r if e < 3]
print [e for e in i2]
#[1, 2]
#[1, 2, 3, 4]
r = islice(count(), 1, 5)
i1, i2 = tee(r)
print [e for e in r if e < 3]
print [e for e in i2]
#[1, 2]
#[... | The issue here is that `tee()` needs to consume the values from the original iterator, if you start consuming them from the original iterator, it will be unable to function correctly. In your list example, the iteration simply begins again. In the generator example, it is exhausted and no more values are produced.
Thi... |
Get raw POST body in Python Flask regardless of Content-Type header | 10,999,990 | 55 | 2012-06-12T15:37:10Z | 11,000,778 | 22 | 2012-06-12T16:25:25Z | [
"python",
"flask",
"wsgi"
] | So, while ago I asked similar question:
[How to get whole request POST body in Python (Flask)](http://stackoverflow.com/questions/10434599/how-to-get-whole-request-post-body-in-python-flask)
And I got an answer that actually `flask.request.data` is the raw POST BODY. But that seems to work only if the request has few ... | There's `request.stream` when the mime type is not recognized.
```
data = request.stream.read()
``` |
Get raw POST body in Python Flask regardless of Content-Type header | 10,999,990 | 55 | 2012-06-12T15:37:10Z | 11,163,649 | 13 | 2012-06-22T20:29:43Z | [
"python",
"flask",
"wsgi"
] | So, while ago I asked similar question:
[How to get whole request POST body in Python (Flask)](http://stackoverflow.com/questions/10434599/how-to-get-whole-request-post-body-in-python-flask)
And I got an answer that actually `flask.request.data` is the raw POST BODY. But that seems to work only if the request has few ... | I just had this issue, and I think a few of you might be able to benefit from my solution. I created a WSGI middleware class that saves the raw POST body from the socket. I saved the value in the WSGI variable 'environ' so I could refer to it as request.environ['body\_copy'] within my Flask app.
You need to be careful... |
Get raw POST body in Python Flask regardless of Content-Type header | 10,999,990 | 55 | 2012-06-12T15:37:10Z | 23,898,949 | 80 | 2014-05-27T21:06:57Z | [
"python",
"flask",
"wsgi"
] | So, while ago I asked similar question:
[How to get whole request POST body in Python (Flask)](http://stackoverflow.com/questions/10434599/how-to-get-whole-request-post-body-in-python-flask)
And I got an answer that actually `flask.request.data` is the raw POST BODY. But that seems to work only if the request has few ... | I'm using Flask 0.10.1, and if you look at the source code, it turns out that you can call
```
request.get_data()
```
To get the raw data, regardless of content type. The request data is then cached, and you can subsequently access `request.data, request.json, request.form` at will.
However, if you access `request.d... |
Python overloading multiple getitems / index requests | 11,000,623 | 6 | 2012-06-12T16:16:27Z | 11,000,765 | 10 | 2012-06-12T16:24:33Z | [
"python",
"operator-overloading"
] | I have a `Grid` class which I want to access using `myGrid[1][2]`. I know I can overload the first set of square brackets with the `__getitem__()` method, but what about the second.
I thought I could achieve this by having a helper class which also implements `__getitem__` and then:
```
class Grid:
def __init__(... | ```
class Grid:
def __init__(self):
self.list = [[1,2], [3,4]]
def __getitem__(self, index):
return self.list[index]
g = Grid();
print g[0]
print g[1]
print g[0][1]
```
prints
```
[1, 2]
[3, 4]
2
``` |
Fastest way to split a concatenated string into a tuple and ignore empty strings | 11,001,247 | 7 | 2012-06-12T16:56:32Z | 11,001,298 | 7 | 2012-06-12T16:59:39Z | [
"python",
"split"
] | I have a concatenated string like this:
```
my_str = 'str1;str2;str3;'
```
and I would like to apply `split` function to it and then convert the resulted list to a tuple, and get rid of any empty string resulted from the `split` (notice the last ';' in the end)
So far, I am doing this:
```
tuple(filter(None, my_str... | That is a very reasonable way to do it. Some alternatives:
* `foo.strip(";").split(";")` (if there won't be any empty slices inside the string)
* `[ x.strip() for x in foo.split(";") if x.strip() ]` (to strip whitespace from each slice)
The "fastest" way to do this will depend on a lot of things⦠but you can easily... |
Argparse - Custom Action With No Argument? | 11,001,678 | 6 | 2012-06-12T17:24:14Z | 11,002,123 | 13 | 2012-06-12T17:55:07Z | [
"python",
"argparse"
] | ```
class StartAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Hello"
start.add_argument('-s', '--start', action=StartAction)
```
I know normally having the action be something like 'store\_true' would prevent the requirement of an argument, but is there ... | Try adding `nargs=0` to your `start.add_argument`:
```
start.add_argument('-s', '--start', action=StartAction, nargs=0)
``` |
Downloading file with Python mechanize | 11,002,014 | 7 | 2012-06-12T17:47:36Z | 11,019,266 | 26 | 2012-06-13T16:27:18Z | [
"python",
"web-scraping",
"mechanize"
] | I am trying to download a file from a website using python and mechanize. My current code successfully logs on to the website and opens the page that contains the download link.
The download link is: <https://www.lendingclub.com/browse/browseNotesRawDataV2.action>
The info for the link is:
```
Link(base_url='https:/... | For anyone who's interested, this was the solution:
```
br.retrieve('https://www.lendingclub.com/browse/browseNotesRawDataV2.action','lââoans.csv')[0]
``` |
How To Reduce Python Script Memory Usage | 11,002,247 | 12 | 2012-06-12T18:03:33Z | 11,002,926 | 20 | 2012-06-12T18:50:18Z | [
"python",
"optimization",
"module",
"package",
"organization"
] | I have a very large python script, 200K, that I would like to use as little memory as possible. It looks something like:
```
# a lot of data structures
r = [34, 78, 43, 12, 99]
# a lot of functions that I use all the time
def func1(word):
return len(word) + 2
# a lot of functions that I rarely use
def func1(word... | **Organzing:**
Your python script seems indeed to be huge, maybe you should consider reorganizing your code first, to split in into several [modules or packages](http://docs.python.org/tutorial/modules.html). It will probably make easier the code profiling and the optimization tasks.
You may want to have a look there... |
Using/importing Beautiful Soup 4 without installation | 11,002,846 | 2 | 2012-06-12T18:44:07Z | 11,002,892 | 7 | 2012-06-12T18:47:27Z | [
"python",
"beautifulsoup"
] | As the Beautiful Soup documentation says:
> If all else fails, the license for Beautiful Soup allows you to package the entire library with your application. You can download the tarball, copy its bs4 directory into your applicationâs codebase, and use Beautiful Soup without installing it at all.
This is exactly wh... | That 'bunch of python scripts' is called a [python package](http://docs.python.org/tutorial/modules.html#packages); there should be a `__init__.py` file in there somewhere. Together they form a coherent whole, a namespaced set of modules.
You can just import the `BeautifulSoup` class from the `bs4` package:
```
from ... |
Hiding command-line dialog in py2exe | 11,003,040 | 3 | 2012-06-12T18:59:26Z | 11,003,201 | 13 | 2012-06-12T19:08:47Z | [
"python",
"tkinter",
"py2exe"
] | Hi When I compile my python script with py2exe, everything works well except a usless command-line dialog appears as well as my GUI. Any way to fix this? I have python 2.7 and my setup script looks like this:
```
from distutils.core import setup
import py2exe
setup(console=['Main.py'])
```
Please help! | Using `setup(windows=['Main.py'])` should remove the command line dialog and use Main.py as your console, instead. |
How can I get Bottle to restart on file change? | 11,004,204 | 20 | 2012-06-12T20:18:41Z | 11,004,294 | 32 | 2012-06-12T20:24:38Z | [
"python",
"cherrypy",
"bottle"
] | I'm really enjoying [Bottle](http://bottlepy.org/) so far, but the fact that I have to CTRL+C out of the server and restart it every time I make a code change is a big hit on my productivity. I've thought about using [Watchdog](http://packages.python.org/watchdog/) to keep track of files changing then restarting the se... | Check out from the tutorial a section entitled ["Auto Reloading"](http://bottlepy.org/docs/dev/tutorial.html#auto-reloading)
> During development, you have to restart the server a lot to test your
> recent changes. The auto reloader can do this for you. Every time you
> edit a module file, the reloader restarts the se... |
find the docs page for function "in" | 11,005,277 | 2 | 2012-06-12T21:39:50Z | 11,005,329 | 7 | 2012-06-12T21:43:54Z | [
"python"
] | i'm trying to find the docs for the function
```
in
```
Inside python. It is very hard because the search engine can't function with a word like in. | "`in`" is not a function. Its a built-in keyword. Using it can trigger the target objects `__contains__()`
[http://docs.python.org/reference/datamodel.html#object.**contains**](http://docs.python.org/reference/datamodel.html#object.__contains__)
```
>>> l = ['a']
>>> l.__contains__('a')
True
>>> 'a' in l
True
```
I ... |
Shuffling SQLAlchemy results? | 11,005,391 | 2 | 2012-06-12T21:49:40Z | 11,007,820 | 7 | 2012-06-13T03:27:13Z | [
"python",
"database",
"django",
"sqlalchemy",
"flask"
] | The code in question:
```
random_items = random.shuffle(Item.query.all())[20:30]
```
It's in a Flask/SQLAlchemy app.`Item` is the model.
That's what I'm doing right now and it works but I foresee a disaster when I start using a real dataset.
How do I do this properly? | I'm not entirely sure of your concern. Is it that you'll be returning a large dataset, so large lists will be manipulated in memory?
If so, you can do it within the SQL statement if you're not overly worried about portability; i.e., if you are using MySQL, you can do:
```
Item.query.order_by(func.rand()).offset(20).l... |
How do I remove/delete a virtualenv? | 11,005,457 | 152 | 2012-06-12T21:54:54Z | 11,005,505 | 139 | 2012-06-12T21:58:56Z | [
"python",
"virtualenv",
"virtualenv-commands"
] | I created an environment with the following command: `virtualenv venv --distribute`
I cannot remove it with the following command: `rmvirtualenv venv`
I do an `ls`on 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 ru... | 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. |
How do I remove/delete a virtualenv? | 11,005,457 | 152 | 2012-06-12T21:54:54Z | 18,624,789 | 80 | 2013-09-04T22:23:57Z | [
"python",
"virtualenv",
"virtualenv-commands"
] | I created an environment with the following command: `virtualenv venv --distribute`
I cannot remove it with the following command: `rmvirtualenv venv`
I do an `ls`on 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 ru... | Just to echo what @skytreader had previously commented, `rmvirtualenv` is a command provided by `virtualenvwrapper`, not `virtualenv`. Maybe you didn't have `virtualenvwrapper` installed?
See [VirtualEnvWrapper Command Reference](http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html) for more details. |
how can i append in reverse? python | 11,005,814 | 2 | 2012-06-12T22:32:22Z | 11,005,995 | 13 | 2012-06-12T22:52:23Z | [
"python"
] | `.append`
Function adds elements to the list.
How can I add elements to the list? In reverse? So that index zero is new value, and the old values move up in index?
What append does
```
[a,b,c,d,e]
```
what I would like.
```
[e,d,c,b,a]
```
Thank you very much. | Suppose you have a list `a`, `a = [1, 2, 3]`
Now suppose you wonder what kinds of things you can do to that list:
```
dir(a)
```
Hmmmm... wonder what this `insert` thingy does...
```
help(a.insert)
```
Insert object before index, you say? Why, that sounds a lot like what I want to do! If I want to insert something... |
Elegant Format for a MAC Address in Python 3.2 | 11,006,702 | 7 | 2012-06-13T00:29:27Z | 11,006,780 | 10 | 2012-06-13T00:39:26Z | [
"python"
] | I am looking for a more elegant solution to formatting a MAC address with colons. I am using Python 3.2. A fancy list comprehension perhaps?
```
s=""
h="00233a990c21"
for i in range(0,12,2):
s += h[i:i+2] + ":"
s=s[:-1]
print("s=",s)
``` | Your code is easily converted to a comprehension form:
```
':'.join(h[i:i+2] for i in range(0,12,2))
``` |
Python variable declaration | 11,007,627 | 34 | 2012-06-13T02:54:08Z | 11,007,895 | 13 | 2012-06-13T03:38:41Z | [
"python"
] | Learning python, and has some basic doubts.
1.I have seen variable declaration (path here) as
```
class writer:
path = ""
```
sometimes, no explicit declaration but initialize through `__init__`.
```
def __init__(self, name):
self.name = name
```
I understand the purpose of `__init__`, but is it advisable ... | There's no need to declare new variables in Python. If we're talking about variables in functions or modules, no declaration is needed. Just assign a value to a name where you need it: `mymagic = "Magic"`. Variables in Python can hold values of any type, and you can't restrict that.
Your question specifically asks abo... |
Python variable declaration | 11,007,627 | 34 | 2012-06-13T02:54:08Z | 11,008,311 | 98 | 2012-06-13T04:43:20Z | [
"python"
] | Learning python, and has some basic doubts.
1.I have seen variable declaration (path here) as
```
class writer:
path = ""
```
sometimes, no explicit declaration but initialize through `__init__`.
```
def __init__(self, name):
self.name = name
```
I understand the purpose of `__init__`, but is it advisable ... | Okay, first things first.
**There is no such thing as "variable declaration" or "variable initialization" in Python.**
There is simply what we call "assignment", but should probably just call "naming".
Assignment means "this name on the left-hand side now refers to the result of evaluating the right-hand side, regar... |
Why is Geopy Distance.Distance wrong? | 11,008,380 | 3 | 2012-06-13T04:52:02Z | 11,008,455 | 7 | 2012-06-13T05:02:00Z | [
"python",
"geopy"
] | From GeoDjango Point Field, I get the following points:
```
object1.point = "POINT(-113.4741271000000040 53.4235217000000020)"
object2.point = "POINT(-113.5013688000000229 53.5343457999999970)"
```
Then I calculate the distance using `geopy`:
```
from geopy import distance
from geopy import Point
p1 = Point("-113.4... | You've got lat/long the wrong way round. Try:
```
p1 = Point("53.4235217000000020 -113.4741271000000040")
p2 = Point("53.5343457999999970 -113.5013688000000229")
```
Gives me result = 12.466096663282977 |
how to split a string on the first instance of delimiter in python | 11,009,155 | 10 | 2012-06-13T06:12:45Z | 11,009,205 | 24 | 2012-06-13T06:17:09Z | [
"python",
"regex",
"string"
] | I need to split a string using python but only on the first instance of the delimiter in the string.
My code:
```
for line in conf.readlines():
if re.search('jvm.args',line):
key,value= split('=',line)
default_args=val
```
The problem is `line`, which contains `jvm.args` looks like this:
```
'jv... | This is what [`str.partition`](http://docs.python.org/library/stdtypes.html#str.partition) is for:
```
>>> 'jvm.args= -Dappdynamics.com=true, -Dsomeotherparam=false,'.partition('=')
('jvm.args', '=', ' -Dappdynamics.com=true, -Dsomeotherparam=false,')
```
From the docs:
> **str.partition(sep)**
>
> Split the string ... |
how to split a string on the first instance of delimiter in python | 11,009,155 | 10 | 2012-06-13T06:12:45Z | 11,009,314 | 9 | 2012-06-13T06:26:46Z | [
"python",
"regex",
"string"
] | I need to split a string using python but only on the first instance of the delimiter in the string.
My code:
```
for line in conf.readlines():
if re.search('jvm.args',line):
key,value= split('=',line)
default_args=val
```
The problem is `line`, which contains `jvm.args` looks like this:
```
'jv... | From the [`split` documentation](http://docs.python.org/library/stdtypes.html#str.split)
> str.split([sep[, maxsplit]])
>
> Return a list of the words in the string, using sep as the delimiter string.
> If maxsplit is given, at most maxsplit splits are done (thus, the list will have at
> most maxsplit+1 elements)
```... |
Exiting the child process after os.fork() | 11,009,567 | 6 | 2012-06-13T06:50:00Z | 11,010,413 | 7 | 2012-06-13T07:52:37Z | [
"python",
"fork"
] | Which is the correct function to call to exit the child process after `os.fork()`?
The documentation for `os._exit()` [states](http://docs.python.org/library/os.html#os._exit):
> The standard way to exit is `sys.exit(n)`.
>
> `_exit()` should normally only be used in the child process after a `fork()`.
It does not s... | [The unix way](http://www.unixguide.net/unix/programming/1.1.3.shtml) is that if you are a child of a `fork` then you call [\_exit](http://linux.die.net/man/2/_exit). The main difference between [exit](http://linux.die.net/man/3/exit) and `_exit` is that `exit` tidies up more - calls the `atexit` handlers, flushes `std... |
Distributing a shared library and some C code with a Cython extension module | 11,010,151 | 27 | 2012-06-13T07:33:58Z | 13,602,504 | 16 | 2012-11-28T10:05:59Z | [
"python",
"cython",
"distutils"
] | I'm trying to take some functions from a large C++ shared library (libbig.so) and expose them to Python via Cython. To do so, I've got a little C++ file (small.cpp) that provides a thin wrapper around the functionality from the shared library that I need, in a way that makes it easy to call via Cython (pysmall.pyx).
l... | 1) Distributing libbig.so
This is a problem that python isn't going to help you with. Who are you targeting? If it's linux, can you request that they install it with their package manager? If libbig isn't distributed through a package manager or it's not linux and you're targeting multiple architectures, you might hav... |
How to have negative zero always formatted as positive zero in a python string? | 11,010,683 | 5 | 2012-06-13T08:11:37Z | 11,010,791 | 23 | 2012-06-13T08:18:35Z | [
"python"
] | I have the following to format a string:
```
'%.2f' % n
```
If `n` is a negative zero (`-0`, `-0.000` etc) the output will be `-0.00`.
How do I make the output always `0.00` for both negative and positive zero values of `n`?
(It is fairly straight forward to achieve this but I cannot find what I would call a succin... | Add zero:
```
>>> a = -0.0
>>> a + 0
0.0
```
which you can format:
```
>>> '{0:.3f}'.format(a + 0)
'0.000'
``` |
PyQT Reading a text file | 11,011,294 | 3 | 2012-06-13T08:50:15Z | 11,011,453 | 9 | 2012-06-13T08:59:40Z | [
"python",
"qt",
"pyqt"
] | I've been searching all over google and have found no solution, which is unbelievable! It should be simple. I'm trying to make my PyQT UI open a text file into a QTextBrowser or a QTextEdit.
But QTextEdit can't 'setSource' and QTextBrowser can not display anything but HTML, if I open the text file it doesn't have any ... | ```
text_edit = QPlainTextEdit()
...
text=open('file.txt').read()
text_edit.setPlainText(text)
```
Doesn't seem hard to me. |
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? | 11,011,756 | 321 | 2012-06-13T09:17:28Z | 11,011,846 | 665 | 2012-06-13T09:22:27Z | [
"python",
"dictionary"
] | For example I have two dicts:
```
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
```
I need a pythonic way of 'combining' two dicts such that the result is :
```
{'a':1, 'b':5, 'c':7, 'd':5}
```
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its v... | Use [`collections.Counter`](http://docs.python.org/library/collections.html#collections.Counter):
```
>>> from collections import Counter
>>> A = Counter({'a':1, 'b':2, 'c':3})
>>> B = Counter({'b':3, 'c':4, 'd':5})
>>> A + B
Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1})
```
Counters are basically a subclass of `dict`, s... |
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? | 11,011,756 | 321 | 2012-06-13T09:17:28Z | 11,011,911 | 49 | 2012-06-13T09:25:28Z | [
"python",
"dictionary"
] | For example I have two dicts:
```
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
```
I need a pythonic way of 'combining' two dicts such that the result is :
```
{'a':1, 'b':5, 'c':7, 'd':5}
```
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its v... | ```
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
``` |
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? | 11,011,756 | 321 | 2012-06-13T09:17:28Z | 11,012,181 | 92 | 2012-06-13T09:41:10Z | [
"python",
"dictionary"
] | For example I have two dicts:
```
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
```
I need a pythonic way of 'combining' two dicts such that the result is :
```
{'a':1, 'b':5, 'c':7, 'd':5}
```
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its v... | A more generic solution, which works for non-numeric values as well:
```
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
r = dict(a.items() + b.items() +
[(k, a[k] + b[k]) for k in set(b) & set(a)])
```
or even more generic:
```
def combine_dicts(a, b, op=operator.add):
ret... |
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? | 11,011,756 | 321 | 2012-06-13T09:17:28Z | 14,930,843 | 37 | 2013-02-18T06:45:45Z | [
"python",
"dictionary"
] | For example I have two dicts:
```
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
```
I need a pythonic way of 'combining' two dicts such that the result is :
```
{'a':1, 'b':5, 'c':7, 'd':5}
```
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its v... | **Intro:**
There are the (probably) best solutions. But you have to know it and remember it and sometimes you have to hope that your Python version isn't too old or whatever the issue could be.
Then there are the most 'hacky' solutions. They are great and short but sometimes are hard to understand, to read and to reme... |
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)? | 11,011,756 | 321 | 2012-06-13T09:17:28Z | 24,571,813 | 9 | 2014-07-04T10:06:27Z | [
"python",
"dictionary"
] | For example I have two dicts:
```
Dict A: {'a':1, 'b':2, 'c':3}
Dict B: {'b':3, 'c':4, 'd':5}
```
I need a pythonic way of 'combining' two dicts such that the result is :
```
{'a':1, 'b':5, 'c':7, 'd':5}
```
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its v... | ```
myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
myDict[k] = A.get(k, 0)+B.get(k, 0)
``` |
Finding locations where two strings differ | 11,013,196 | 2 | 2012-06-13T10:43:24Z | 11,013,405 | 7 | 2012-06-13T10:57:11Z | [
"python",
"string",
"algorithm",
"pattern-matching",
"nltk"
] | I have two extremely long sequences of words.
I need to find places where they differ. For example, if the input is
```
1st sequence: A B C D E F G
2nd sequence: A X D Y Z W G
```
(each character here represents a word)
The output should be:
```
B C -> X
E F -> Y Z W
```
What I have thought of: I could have an in... | `difflib.SequenceMatcher.get_opcodes` can do this.
```
import difflib
def diff(a, b):
for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b).get_opcodes():
if tag!='equal':
yield a[i1:i2], b[j1:j2]
>>> d = list(diff('A B C D E F G'.split(), 'A X D Y Z W G'.split()))
>>> d
[(['B', 'C'], ... |
How to use template inheritance with Chameleon? | 11,013,452 | 10 | 2012-06-13T11:00:13Z | 11,034,341 | 15 | 2012-06-14T13:38:55Z | [
"python",
"pyramid",
"chameleon",
"template-metal"
] | I am using latest Pyramid to build a web app. Somehow we have started using Chameleon as the template engine. I have used Mako before and it was extremely simple to create a base template. Is this possible with chameleon as well?
I have tried to look through the docs but I can not seem to find an easy solution. | With Chameleon >= 2.7.0 you can use the "load" TALES expression. Example:
main.pt:
```
<html>
<head>
<div metal:define-slot="head"></div>
</head>
<body>
<ul id="menu">
<li><a href="">Item 1</a></li>
<li><a href="">Item 2</a></li>
<li><a href="">Item 3</a></li>
</ul>
<div metal:... |
Speeding up build process with distutils | 11,013,851 | 16 | 2012-06-13T11:25:21Z | 13,176,803 | 18 | 2012-11-01T12:11:31Z | [
"c++",
"python",
"distutils"
] | I am programming a C++ extension for Python and I am using distutils to compile the project. As the project grows, rebuilding it takes longer and longer. Is there a way to speed up the build process?
I read that parallel builds (as with `make -j`) are not possible with distutils. Are there any good alternatives to dis... | 1. Try building with environment variable `CC="ccache gcc"`, that will speed up build significantly when the source has not changed. (strangely, distutils uses `CC` also for c++ source files). Install the ccache package, of course.
2. Since you have a single extension which is assembled from multiple compiled object fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.