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 |
|---|---|---|---|---|---|---|---|---|---|
Pairwise Kullback Leibler (or Jensen-Shannon) divergence distance matrix in Python | 10,602,811 | 2 | 2012-05-15T14:20:40Z | 10,603,292 | 11 | 2012-05-15T14:48:32Z | [
"python",
"matrix",
"distance",
"metrics"
] | I have two matrices X and Y (in most of my cases they are similar) Now I want to calculate the pairwise KL divergence between all rows and output them in a matrix. E.g:
```
X = [[0.1, 0.9], [0.8, 0.2]]
```
The function should then take `kl_divergence(X, X)` and compute the pairwise Kl divergence distance for each pai... | Note that [KL divergence](http://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) is essentially a dot product of P(i) and log(P(i)/Q(i)). So, one option is to form a list of [numpy](http://numpy.scipy.org/) arrays for P(i) and another for log(P(i)/Q(i)), one row for each KL divergence you want to calculate),... |
Is there an implementation of 'expect' or an expect-like library that works in python3? | 10,603,596 | 10 | 2012-05-15T15:04:22Z | 10,635,713 | 8 | 2012-05-17T12:25:33Z | [
"python",
"python-3.x",
"expect",
"fabric",
"pexpect"
] | I would like to use an expect-like module in python3. As far as I know, neither pexpect nor fabric work with python3. Is there any similar package I can use? (If no, does anyone know if py3 support is on any project's roadmap?)
A perfectly overlapping feature set isn't necessary. I don't think my use case is necessary... | As Niek mentioned, I ported pexpect, and called it pexpect-u (u for unicode):
> <http://pypi.python.org/pypi/pexpect-u/>
It uses 2to3, but I had to make some changes to the code as well before it worked.
I'm not very interested in maintaining it, but I couldn't get in touch with the author of pexpect, and I felt it ... |
Can't connect to MongoDB 2.0.5 database with pymongo 2.2 | 10,603,754 | 8 | 2012-05-15T15:14:03Z | 10,667,145 | 14 | 2012-05-19T16:52:59Z | [
"python",
"mongodb",
"pymongo",
"bson"
] | I've been stuck with diagnosing this for a few hours now and thought I'd see if any pymongo experts out there have any ideas:
**The following line of code:**
connection = pymongo.Connection('localhost', 27017)
**Generates the following error:**
/usr/local/Cellar/python/2.7.3/bin/python2.7 /Users/danwilson/Dropbox/P... | The solution to this problem was not good news for pip: I had to uninstall pymongo and bson, then reinstall bson, then pymongo. So it looks like the order of installation is actually important! |
python isdigit() function return true for non digit character u'\u2466' | 10,604,074 | 8 | 2012-05-15T15:32:38Z | 10,604,095 | 18 | 2012-05-15T15:33:56Z | [
"python",
"unicode",
"digit"
] | I come across a strange problem dealing with python isdigit function.
For example:
```
>>> a = u'\u2466'
>>> a.isdigit()
Out[1]: True
>>> a.isnumeric()
Out[2]: True
```
Why this character is a digit?
Any way to make this return False instead, thanks?
---
Edit, If I don't want to treat it as a digit, then how to f... | U+2466 is the [CIRCLED DIGIT SEVEN](http://www.fileformat.info/info/unicode/char/2466/index.htm) (â¦), so yes, it's a digit.
If your definition of what is a digit differs from that of the [Unicode Consortium](http://unicode.org/), you might have to write your own `isdigit()` method.
> Edit, If I don't want to treat ... |
python isdigit() function return true for non digit character u'\u2466' | 10,604,074 | 8 | 2012-05-15T15:32:38Z | 10,604,236 | 8 | 2012-05-15T15:41:49Z | [
"python",
"unicode",
"digit"
] | I come across a strange problem dealing with python isdigit function.
For example:
```
>>> a = u'\u2466'
>>> a.isdigit()
Out[1]: True
>>> a.isnumeric()
Out[2]: True
```
Why this character is a digit?
Any way to make this return False instead, thanks?
---
Edit, If I don't want to treat it as a digit, then how to f... | If you're going to convert something to `int` you need [`isdecimal`](http://docs.python.org/library/stdtypes.html#unicode.isdecimal) rather than `isdigit`.
Note that "decimal" is not just 0, 1, 2, ... 9, there are [number of characters](http://www.fileformat.info/info/unicode/category/Nd/list.htm) that can be interpre... |
Sublime Text 2 console input | 10,604,409 | 31 | 2012-05-15T15:51:42Z | 10,605,079 | 41 | 2012-05-15T16:30:59Z | [
"python",
"ruby",
"sublimetext2"
] | I use Sublime Text 2 but it won't let me enter any value when my code asks for user input. (In other words: `input()` in Python and `gets` in Ruby fail to correctly prompt me for input).
Python throws an `EOFError` error (what you get when user doesn't enter anything).
Simply USER INPUT isn't working in Sublime Text ... | Sublime text doesn't support that. But you can get around it (at least in python) by using [SublimeREPL](https://github.com/wuub/SublimeREPL), I use this for everything, it works pretty great. Its a little cooky though, as the tab is still editable like a normal sublime tab (which is good and bad)...
It also allows yo... |
opencv VideoWriter under OSX producing no output | 10,605,163 | 13 | 2012-05-15T16:36:44Z | 19,212,323 | 35 | 2013-10-06T18:27:29Z | [
"python",
"opencv"
] | I am trying to create a video from the python wrapper for OpenCV under OSX. I am using python 2.7.1, opencv 2.3.1a, and the python wrappers from willowgarage that come with that version of opencv. I have:
```
import cv,cv2
w = cv2.VideoWriter('foo.avi', cv.FOURCC('M','J','P','G'), 25, (100,100))
for i in range(100):
... | There are many outdated and incorrect online guides on this topic-- I think I tried almost every one. After looking at the source QTKit-based implementation of VideoWriter on Mac OSX, I was finally able to get VideoWriter to output valid video files using the following code:
```
fps = 15
capSize = (1028,720) # this is... |
Pythonic and concise way to construct this list? | 10,605,536 | 5 | 2012-05-15T17:02:55Z | 10,605,558 | 7 | 2012-05-15T17:04:48Z | [
"python",
"list-comprehension"
] | How can I write the following code more concisely?
```
scores = []
for f in glob.glob(path):
score = read_score(f, Normalize = True)
scores.append(score)
```
I know this can be written in one or two lines without using `append`, but I'm a Python newbie. | Oh, I got it while browsing a [related question](http://stackoverflow.com/questions/3830727/is-there-a-more-elegant-pythonic-way-to-express-this-construct):
```
scores = [read_score(f, normalize=True) for f in glob.glob(path)]
``` |
Sending "User-agent" using Requests library in Python | 10,606,133 | 100 | 2012-05-15T17:48:44Z | 10,606,260 | 149 | 2012-05-15T17:58:21Z | [
"python",
"web-crawler",
"python-requests"
] | I want to send a value for `"User-agent"` while requesting a webpage using Python Requests. I am not sure is if it is okay to send this as a part of the header, as in the code below:
```
debug = {'verbose': sys.stderr}
user_agent = {'User-agent': 'Mozilla/5.0'}
response = requests.get(url, headers = user_agent, confi... | Your code is correct, you do send the `"User-Agent"` as part of the HTTP header.
Here is a [list of HTTP header fields](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields), and you'd probably be interested in [request-specific fields](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields), whic... |
Import Error for User Model | 10,606,843 | 7 | 2012-05-15T18:39:13Z | 10,621,914 | 10 | 2012-05-16T15:37:32Z | [
"python",
"google-app-engine"
] | I have this piece of code which is running perfectly on localhost but throws up this obscure error on GAE:
`import_string() failed for 'webapp2_extras.appengine.auth.models.User' . Possible reasons are: - missing __init__.py in a package; - package or module`
My import statements:
```
from webapp2_extras import auth... | Look similar to this [issue](http://code.google.com/p/webapp-improved/issues/detail?id=42) which was already fixed by webapp 2.5.1
Make sure you import the latest version of webapp2, by adding those line to your app.yaml file:
```
libraries:
- name: webapp2
version: latest
```
As a workaround you can add the follo... |
How can I access the form submit button value in Django? | 10,607,091 | 8 | 2012-05-15T18:57:03Z | 10,607,273 | 17 | 2012-05-15T19:10:39Z | [
"python",
"django",
"forms"
] | I have a Django project that, on one page, has multiple forms (in different tags) that can be submitted to have different effects. In all cases I want the user to be redirected back to the same page, so I use in my view the pattern of submitting the form and then redirecting to the original page. In at least one case, ... | `Submit` is an HTML Form structure... You must use name attribute of form objects as follows... In your template:
```
<form>
...
<input type="submit" name="list" value="List Objects" />
</form>
<form>
...
<input type="submit" name="do-something-else" value="Do Something Else" />
</form>
```
In your view:
```
if 'lis... |
Nested arguments in python not compiling | 10,607,293 | 11 | 2012-05-15T19:12:25Z | 10,607,353 | 16 | 2012-05-15T19:16:59Z | [
"python",
"python-3.x",
"compatibility"
] | I'm trying to compile the code found here:
<http://semprog.com/psw/chapter2/simpletriple.py>
...into a python3 module.
It runs fine when I choose 'run module' in IDLE, but receive the following syntax error when I try to create a distribution:
```
File "/usr/local/lib/python3.2/dist-packages/simpletriple.py", line 9
... | [PEP 3113](http://www.python.org/dev/peps/pep-3113/) explains why this feature, "tuple parameter unpacking", was removed in Python 3. It also explains how to port code that uses them. In this case you'd need to change a function like:
```
def add(self, (sub, pred, obj)):
self._addToIndex(self._spo, sub, pred, obj)... |
How to reduce the image file size using PIL | 10,607,468 | 20 | 2012-05-15T19:26:01Z | 13,211,834 | 32 | 2012-11-03T17:48:56Z | [
"python",
"image",
"compression",
"python-imaging-library"
] | I am using PIL to resize the images there by converting larger images to smaller ones. Are there any standard ways to reduce the file size of the image without losing the quality too much, lets say the original size of the image is 100KB, i want to get it down to like 5 or 10 KB especially for png and jpeg formats. | A built-in parameter for saving JPEGs and PNGs is optimize.
```
# My image is a 200x374 jpeg that is 102kb large
>>> foo = Image.open("path\\to\\image.jpg")
>>> foo.size
(200,374)
# I downsize the image with an ANTIALIAS filter (gives the highest quality)
>>> foo = foo.resize((160,300),Image.ANTIALIAS)
>>> foo... |
Python multiprocessing queue: what to do when the receiving process quits? | 10,607,553 | 4 | 2012-05-15T19:32:36Z | 10,638,480 | 10 | 2012-05-17T15:14:40Z | [
"python",
"queue",
"multiprocessing"
] | Basically I have the following code:
```
import multiprocessing
import time
class MyProcess(multiprocessing.Process):
def __init__(self, ):
multiprocessing.Process.__init__(self)
self.queue = multiprocessing.Queue()
def run(self):
print "Subprocess starting!"
time.sleep(4)
... | I'm answering my own question since not everybody reads comments. After the hint from user mata in the comments, I tested the sample code in the question adding a call to `time.sleep(0.01)` inside the loop that adds object to the queue, so I could limit the number of objects that would be added to the queue:
```
def a... |
A simple website with python using SimpleHTTPServer and SocketServer, how to only display the html file and not the whole directory? | 10,607,621 | 4 | 2012-05-15T19:37:21Z | 10,607,829 | 9 | 2012-05-15T19:53:15Z | [
"python",
"networking",
"webpage"
] | How do I only display `simplehttpwebsite_content.html` when I visit `localhost:8080`? So that I can't see my filetree, only the webpage. All these files are in the same directory btw.
simplehttpwebsite.py
```
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPReque... | you should call your file `index.html`, that's the page that gets served automatically instead of listing the directory.
the other possibility would be to override the handlers `list_directory(self, path)` method. |
A simple website with python using SimpleHTTPServer and SocketServer, how to only display the html file and not the whole directory? | 10,607,621 | 4 | 2012-05-15T19:37:21Z | 10,607,946 | 14 | 2012-05-15T20:01:06Z | [
"python",
"networking",
"webpage"
] | How do I only display `simplehttpwebsite_content.html` when I visit `localhost:8080`? So that I can't see my filetree, only the webpage. All these files are in the same directory btw.
simplehttpwebsite.py
```
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPReque... | You can extend `SimpleHTTPServer.SimpleHTTPRequestHandler` and override the `do_GET` method to replace `self.path` with `simplehttpwebpage_content.html` if `/` is requested.
```
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def... |
how to create a file name with the current date & time in python? | 10,607,688 | 38 | 2012-05-15T19:42:01Z | 10,607,768 | 80 | 2012-05-15T19:48:07Z | [
"python"
] | Here is a functional code (Create file with success)
```
sys.stdout = open('filename1.xml', 'w')
```
Now I'm trying to name the file with the current Date Time (I'm not an expert in python)
```
filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')
```
I want to write out a ... | While not using `datetime`, this solves your problem (answers your question) of getting a string with the current time and date format you specify:
```
import time
timestr = time.strftime("%Y%m%d-%H%M%S")
print timestr
```
yields:
```
20120515-155045
```
so your filename could append or use this string. |
how to create a file name with the current date & time in python? | 10,607,688 | 38 | 2012-05-15T19:42:01Z | 10,607,838 | 18 | 2012-05-15T19:53:53Z | [
"python"
] | Here is a functional code (Create file with success)
```
sys.stdout = open('filename1.xml', 'w')
```
Now I'm trying to name the file with the current Date Time (I'm not an expert in python)
```
filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')
```
I want to write out a ... | [`now`](http://docs.python.org/library/datetime.html#datetime.datetime.now) is a class method in the class `datetime` in the module `datetime`. So you need
```
datetime.datetime.now()
```
Or you can use a different import
```
from datetime import datetime
```
Done this way allows you to use `datetime.now` as per th... |
how to create a file name with the current date & time in python? | 10,607,688 | 38 | 2012-05-15T19:42:01Z | 10,607,854 | 10 | 2012-05-15T19:55:09Z | [
"python"
] | Here is a functional code (Create file with success)
```
sys.stdout = open('filename1.xml', 'w')
```
Now I'm trying to name the file with the current Date Time (I'm not an expert in python)
```
filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
sys.stdout = open(filename1 + '.xml', 'w')
```
I want to write out a ... | Change this line
```
filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")
```
To
```
filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
```
Note the extra `datetime`. Alternatively, change your
`import datetime` to `from datetime import datetime` |
Python list transpose and fill | 10,610,445 | 10 | 2012-05-16T00:05:16Z | 10,610,569 | 7 | 2012-05-16T00:29:08Z | [
"python",
"list",
"fill",
"transpose"
] | I have a list of lists such that the length of each inner list is either 1 or n (assume n > 1).
```
>>> uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]]
```
I want to transpose the list, but instead of truncating the longer list (as with `zip`) or filling the shorter lists with `None`, I want to fill the shorter ... | You can repeat one element list forever:
```
uneven = [[1], [47, 17, 2, 3], [3], [12, 5, 75, 33]]
from itertools import repeat
print zip(*(repeat(*x) if len(x)==1 else x for x in uneven))
``` |
Python: shortcut for writing decorators which accept arguments? | 10,610,824 | 9 | 2012-05-16T01:14:37Z | 10,610,830 | 7 | 2012-05-16T01:17:20Z | [
"python",
"decorator"
] | Does the Python standard library have a shortcut for writing decorators which accept arguments?
For example, if I want to write a decorator like `with_timeout(timeout)`:
```
@with_timeout(10.0)
def cook_eggs(eggs):
while not eggs.are_done():
eggs.cook()
```
I have to write something like:
```
def with_t... | I tend to write my decorators as classes to be honest
```
class TestWithArgs(object):
def __init__(self, *deco_args, **deco_kwargs):
self.deco_args = deco_args
self.deco_kwargs = deco_kwargs
def __call__(self, func):
def _wrap(self, *args, **kwargs):
print "Blah blah blah"
... |
Consumer Connection error with django and celery+rabbitmq? | 10,610,991 | 9 | 2012-05-16T01:48:38Z | 12,630,492 | 9 | 2012-09-27T21:46:13Z | [
"python",
"django",
"rabbitmq",
"celery",
"django-celery"
] | I'm trying to set up celeryd with django and rabbit-mq. So far, I've done the following:
* Installed celery from pip
* Installed rabbitmq via the debs available from their repository
* Added a user and vhost to rabbitmq via rabbitmqctl, as well as permissions for that user
* Started the rabbitmq-server
* Installed dja... | Your problem is in the `BROKER_URL`.
With an additional `VHOST`, the right config would be:
```
BROKER_URL='amqp://celeryuser@localhost:5672//'
BROKER_VHOST='/celeryhost'
``` |
Why isn't the "object" parent class for new-style classes in Python2.x written as "Object"? | 10,611,228 | 2 | 2012-05-16T02:23:51Z | 10,611,251 | 9 | 2012-05-16T02:27:45Z | [
"python",
"class",
"inheritance",
"object",
"styles"
] | Maybe I have the wrong impression, but wouldn't the parent class of a `class` object be a class?
If so, why didn't the authors of Python follow good style convention and capitalize the `object` class to `Object` to denote it as a class object? [Is it a class at all](http://stackoverflow.com/a/7375621/881224)? | It follows the convention of built-in types (`str`, `int`, `float`, `complex`, `file`, `type`, etc.) *not* having the initial letter capitalized. |
How to access List elements | 10,613,131 | 4 | 2012-05-16T06:29:56Z | 10,613,191 | 9 | 2012-05-16T06:33:54Z | [
"python",
"list"
] | I have a list
```
list = [['vegas','London'],['US','UK']]
```
How to access each element of this list? | I'd start by not calling it `list`, since that's the name of the constructor for Python's built in `list` type.
But once you've renamed it to `cities` or something, you'd do:
```
print(cities[0][0], cities[1][0])
print(cities[0][1], cities[1][1])
``` |
accessing request headers on django/python | 10,613,315 | 10 | 2012-05-16T06:45:24Z | 10,613,348 | 18 | 2012-05-16T06:47:54Z | [
"python",
"django",
"http",
"header",
"request"
] | I need to create a secure restFUL api using sencha and django. I am fairly new to python. So far i am able to send request from sencha to server using basic authentication as below
```
new Ext.data.Store({
proxy: {
type: "ajax",
headers: {
"Authorization": "Basic asdjksdfsksf="
}
}
})
```... | You can access them within a view using request.META, which is a dictionary.
If you wanted the Authorization header, you could do request.META['HTTP\_AUTHORIZATION']
If you're creating a restful API from scratch, you might want to take a look at using [tastypie](https://github.com/toastdriven/django-tastypie). |
A simple python server using SimpleHTTPServer and SocketServer, how do I close the socket down before rerunning .py file? | 10,613,977 | 9 | 2012-05-16T07:35:49Z | 10,614,360 | 11 | 2012-05-16T08:04:44Z | [
"python",
"http",
"sockets",
"networking"
] | When I run my python server file `simplehttpwebsite.py` in the linux shell and I do control+c and run it again I get `socket.error: [Errno 98] Address already in use`.
How do I make sure the socket closes down when I do ctrl+c?
*simplehttpwebsite.py*
```
#!/usr/bin/env python
import SimpleHTTPServer
import SocketSer... | Here is how you do it
```
#!/usr/bin/env python
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
class MyTCPServer(SocketServer.TCPServer):
allow_reuse_address = True
server = MyTCPServer(('0.0.0.0', 8080), Handler)
server.serve_forever()
```
IMHO this isn't very w... |
How to remove negative values from a list using lambda functions by python | 10,614,069 | 4 | 2012-05-16T07:42:12Z | 10,614,113 | 8 | 2012-05-16T07:45:08Z | [
"python",
"list",
"lambda"
] | I have implemented a lambda function to sort a list. now i want to remove all the negative objects from the list by using lambda functions .
```
dto_list.sort(key=lambda x: x.count, reverse=True)
```
any one know a way to write the lambda expression to do it? I could not find a proper tutorial | Not very pythonic but here is how to do it with a lambda
```
>>> L = list(range(-10,10))
>>> L
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x >= 0, L)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
```
Most people would use a list comprehension
```
>>> [x for x in L if x >= 0]
[0,... |
iterating over a range of rows using ws.iter_rows in the optimised reader of openpyxl | 10,614,518 | 6 | 2012-05-16T08:17:05Z | 13,962,583 | 13 | 2012-12-19T22:49:55Z | [
"python",
"excel",
"xlsx",
"openpyxl"
] | I need to read an xlsx file of 10x5324 cells
This is the gist of what i was trying to do:
```
from openpyxl import load_workbook
filename = 'file_path'
wb = load_workbook(filename)
ws = wb.get_sheet_by_name('LOG')
col = {'Time':0 ...}
for i in ws.columns[col['Time']][1:]:
print i.value.hour
```
The code was t... | The simplest solution with a lower bound would be something like this:
```
# Your code:
from openpyxl import load_workbook
filename = 'file_path'
wb = load_workbook(filename, use_iterators=True)
ws = wb.get_sheet_by_name('LOG')
# Solution 1:
for row in ws.iter_rows(row_offset=1):
# code to execute per row...
```
... |
Check how many elements from a list fall within a specified range (Python) | 10,615,196 | 5 | 2012-05-16T09:00:54Z | 10,615,351 | 8 | 2012-05-16T09:10:33Z | [
"python",
"list",
"range"
] | I have a list of elements (integers) and what I need to do is to quickly check how many elements from this list fall within a specified range. The example is below.
range is from 34 to 566
l = [9,20,413,425]
The result is 2.
I can of course use a simple for loop for the purpose and compare each element with the min... | `len([x for x in l if x > 34 and x < 566])` |
Check how many elements from a list fall within a specified range (Python) | 10,615,196 | 5 | 2012-05-16T09:00:54Z | 10,615,426 | 12 | 2012-05-16T09:15:20Z | [
"python",
"list",
"range"
] | I have a list of elements (integers) and what I need to do is to quickly check how many elements from this list fall within a specified range. The example is below.
range is from 34 to 566
l = [9,20,413,425]
The result is 2.
I can of course use a simple for loop for the purpose and compare each element with the min... | ```
>>> l = [9,20,413,425]
>>> sum(34 < x < 566 for x in l)
2
``` |
Trim whitespace using PIL | 10,615,901 | 21 | 2012-05-16T09:40:39Z | 10,616,717 | 49 | 2012-05-16T10:32:13Z | [
"python",
"imagemagick",
"python-imaging-library"
] | Is there a simple solution to trim whitespace on the image in PIL?
ImageMagick has easy support for it in following way:
```
convert test.jpeg -fuzz 7% -trim test_trimmed.jpeg
```
I found a solution for PIL:
```
from PIL import Image, ImageChops
def trim(im, border):
bg = Image.new(im.mode, im.size, border)
... | I don't think there is anything built in to PIL that can do this. But I've modified your code so it will do it.
* It gets the border colour from the top left pixel, using `getpixel`, so you don't need to pass the colour.
* Subtracts a scalar from the differenced image, this is a quick way of saturating all values unde... |
Matplotlib: Add strings as custom x-ticks but also keep existing (numeric) tick labels? Alternatives to matplotlib.pyplot.annotate? | 10,615,960 | 13 | 2012-05-16T09:44:25Z | 10,616,433 | 10 | 2012-05-16T10:13:13Z | [
"python",
"matplotlib",
"annotate",
"axis-labels"
] | I am trying to produce a graph and I am having some issues annotating it.
My graph has a log scale on the x-axis, showing time. What I want to be able to do is keep the existing (but not predictable) numeric tick labels at 100 units, 1000 units, 10000 units, etc but also add custom tick labels to the x-axis that make ... | From <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks>:
```
# return locs, labels where locs is an array of tick locations and
# labels is an array of tick labels.
locs, labels = xticks()
```
So all you should need to do is obtain the `locs` and `labels` and then modify `labels` to your... |
Matplotlib: Add strings as custom x-ticks but also keep existing (numeric) tick labels? Alternatives to matplotlib.pyplot.annotate? | 10,615,960 | 13 | 2012-05-16T09:44:25Z | 10,616,436 | 16 | 2012-05-16T10:13:32Z | [
"python",
"matplotlib",
"annotate",
"axis-labels"
] | I am trying to produce a graph and I am having some issues annotating it.
My graph has a log scale on the x-axis, showing time. What I want to be able to do is keep the existing (but not predictable) numeric tick labels at 100 units, 1000 units, 10000 units, etc but also add custom tick labels to the x-axis that make ... | If you really want to add extra ticks, you can get the existing ones using `axis.xaxis.get_majorticklocs()`, add whatever you want to add, and then set the ticks using `axis.xaxis.set_ticks(<your updated array>)`.
An alternative would be to add vertical lines [using `axvline`](http://matplotlib.org/api/pyplot_api.html... |
How to create a fix size list in python? | 10,617,045 | 14 | 2012-05-16T10:54:03Z | 10,617,221 | 15 | 2012-05-16T11:05:21Z | [
"python",
"list"
] | In C++, I can create a array like...
```
int* a = new int[10];
```
in python,I just know that I can declare a list,than append some items,or like..
```
l = [1,2,3,4]
l = range(10)
```
Can I initialize a list by a given size,like c++,and do not do any assignment? | (tl;dr: The exact answer to your question is `numpy.empty` or `numpy.empty_like`, but you likely don't care and can get away with using `myList = [None]*10000`.)
# Simple methods
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an err... |
Pip creates build/ directories | 10,617,198 | 8 | 2012-05-16T11:04:15Z | 10,618,122 | 22 | 2012-05-16T12:05:21Z | [
"python",
"virtualenv",
"pip"
] | I use virtualenv to create isolated environments for my Python projects. Then i install dependencies with pip - Python package manager. Sometimes i forget to do `source venv/bin/activate`, and then pip creates `build/` directories inside my projects. Why does pip create them? May i delete them, and if not, may i put th... | The `build` directory is where a packages gets unpacked into and build from. When the package is installed successfully, pip removes the unpacked dir from `build`, unless you've removed `pip-delete-this-directory.txt`. As described in `pip-delete-this-directory.txt`:
```
This file is placed here by pip to indicate the... |
hex string to character in python | 10,618,586 | 11 | 2012-05-16T12:31:56Z | 10,618,668 | 14 | 2012-05-16T12:35:45Z | [
"python",
"hex"
] | I have a hex string like:
```
data = "437c2123"
```
I want to convert this string to a sequence of characters according to the ASCII table.
The result should be like:
```
data_con = "C|!#"
```
Can anyone tell me how to do this? | ```
In [17]: data = "437c2123"
In [18]: ''.join(chr(int(data[i:i+2], 16)) for i in range(0, len(data), 2))
Out[18]: 'C|!#'
```
Here:
* `for i in range(0, len(data), 2)` iterates over every second position in `data`: `0`, `2`, `4` etc.
* `data[i:i+2]` looks at every pair of hex digits `'43'`, `'7c'`, etc.
* `chr(int(... |
hex string to character in python | 10,618,586 | 11 | 2012-05-16T12:31:56Z | 10,619,257 | 33 | 2012-05-16T13:08:44Z | [
"python",
"hex"
] | I have a hex string like:
```
data = "437c2123"
```
I want to convert this string to a sequence of characters according to the ASCII table.
The result should be like:
```
data_con = "C|!#"
```
Can anyone tell me how to do this? | In Python2
```
>>> "437c2123".decode('hex')
'C|!#'
```
In Python3 (also works in Python2, for <2.6 you can't have the `b` prefixing the string)
```
>>> import binascii
>>> binascii.unhexlify(b"437c2123")
b'C|!#'
``` |
Assigning NoneType to Dict | 10,619,600 | 4 | 2012-05-16T13:28:16Z | 10,619,632 | 8 | 2012-05-16T13:30:10Z | [
"python",
"list",
"dictionary",
"typeerror",
"nonetype"
] | I am trying to assign None to a key in a dict, but I am getting a TypeError:
```
self._rooms[g[0]] = None
TypeError: 'NoneType' object does not support item assignment
```
My code is here:
```
r = open(filename, 'rU')
for line in r:
g = line.strip().split(',')
if len(g) > 1:
r1 = g[0]... | The exception clearly states `TypeError: 'NoneType' object does not support item assignment` this suggests that `self._rooms` is actually `None`
Edit:
As you said yourself
```
self._rooms = {}
```
or
```
self._rooms = dict()
```
Will do what you need to clear the dict |
Efficiently removing subdirectories in dirnames from os.walk | 10,620,737 | 3 | 2012-05-16T14:30:07Z | 10,620,948 | 13 | 2012-05-16T14:41:23Z | [
"python",
"python-2.7",
"os.walk"
] | On a mac in python 2.7 when walking through directories using os.walk my script goes through 'apps' i.e. appname.app, since those are really just directories of themselves. Well later on in processing I am hitting errors when going through them. I don't want to go through them anyways so for my purposes it would be bes... | You can do something like this (assuming you want to ignore directories containing '.'):
```
subdirs[:] = [d for d in subdirs if '.' not in d]
```
The slice assignment (rather than just `subdirs = ...`) is necessary because you need to modify the same list that `os.walk` is using, not create a new one.
Note that you... |
What is the simplest way to create an empty iterable using yield in Python? | 10,621,615 | 12 | 2012-05-16T15:20:35Z | 10,621,647 | 11 | 2012-05-16T15:22:12Z | [
"python",
"iterator",
"yield"
] | I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass:
```
def test():
for x in my_iterable():
pass
```
The... | You can use the lambda and iter functions to create an empty iterable in Python.
```
my_iterable = lambda: iter(())
``` |
What is the simplest way to create an empty iterable using yield in Python? | 10,621,615 | 12 | 2012-05-16T15:20:35Z | 10,621,658 | 11 | 2012-05-16T15:22:40Z | [
"python",
"iterator",
"yield"
] | I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass:
```
def test():
for x in my_iterable():
pass
```
The... | Yes, there is:
```
return iter([])
``` |
Twisted-PyQt4 segmentation faults | 10,621,804 | 5 | 2012-05-16T15:30:38Z | 10,683,746 | 9 | 2012-05-21T10:41:18Z | [
"python",
"pyqt",
"segmentation-fault",
"twisted",
"multiple-instances"
] | I'm using PyQt 4.9.1 on Ubuntu 12.04 (amd64) (tried with both python 2.6 and 2.7) to make a headless browser, but i'm getting: Program received signal SIGSEGV, Segmentation fault.
Here is a simplified version of the program (still long a bit):
```
# -*- coding: utf-8 -*-
from pyvirtualdisplay import Display
display = ... | I apologize for the late response, finally I got the time to post the solution for my problem. Basically the segfault happened because the qt objects were not deleted before the last reference to the instance of the browser was deleted. Here is the fixed code:
```
# -*- coding: utf-8 -*-
from pyvirtualdisplay import D... |
Test if file under version control in pysvn (python subversion) | 10,622,214 | 4 | 2012-05-16T15:56:55Z | 10,782,740 | 7 | 2012-05-28T10:01:01Z | [
"python",
"svn",
"pysvn"
] | In [pysvn](http://pysvn.tigris.org/docs/pysvn_prog_ref.html), how do I test if a file is under version control? | Use `client.status()` and check the `text_status` attribute of the returned status object. Example:
```
>>> import pysvn
>>> c = pysvn.Client()
>>> out = c.status("versioned.cpp")[0] # .status() returns a list
>>> out.text_status
<wc_status_kind.normal>
```
That shows the file is versioned and unmodified.
```
>>> c... |
Accessing variables from IPython interactive namespace in a script | 10,622,268 | 11 | 2012-05-16T16:00:05Z | 10,622,883 | 16 | 2012-05-16T16:36:46Z | [
"python",
"ipython"
] | Is there an easy way to access variables in the IPython interactive namespace. While implementing a project that has a slow load command, I would like to run a script to load the data into the interactive work space, then call a second script that uses the data, like is possible with MATLAB.
In this simple case, what ... | Try using the -i option on IPython's magic run command; it makes the script run using the current interactive namespace, e.g. with
load.py:
```
a = 5
```
tst.py:
```
print a
```
From IPython I get;
```
In [1]: from load import *
In [2]: run -i tst
5
``` |
How do I sort a dictionary? | 10,622,597 | 5 | 2012-05-16T16:19:35Z | 10,622,626 | 10 | 2012-05-16T16:21:27Z | [
"python",
"dictionary"
] | The problem is a list of room numbers and guest details I ripped straight from a txt file that needs to be put into a dictionary with the room number as the keys and the details as the values.
The guest list is literally a list, each item represents room number, guest name, arrival, departure dates. Rooms without anyt... | Standard Python dictionaries are inherently unordered.
One possibility is to use [`OrderedDict`](http://docs.python.org/dev/library/collections.html#collections.OrderedDict). It will preserve the *insertion order*, meaning that you have to insert entries in the order in which you then wish to retrieve them.
Another p... |
python: UnboundLocalError: local variable 'open' referenced before assignment | 10,623,093 | 3 | 2012-05-16T16:50:12Z | 10,623,110 | 10 | 2012-05-16T16:51:11Z | [
"python"
] | ```
def read_lines():
readFileName = "readfile.txt"
f = open(readFileName, 'r+')
contents = f.read()
... # and so on
read_lines()
```
When I run this, I get an error:
```
f = open(readFileName, 'r+')
UnboundLocalError: local variable 'open' referenced before assignment
``` | This means that further down in your function you create a variable called `open`:
```
open = ...
```
Rename it so that it doesn't clash with the built-in function. |
How assignment works with python list slice | 10,623,302 | 32 | 2012-05-16T17:05:14Z | 10,623,352 | 43 | 2012-05-16T17:09:24Z | [
"python"
] | Python doc says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following doubts related to "Assignment to slices"
```
a = [1, 2, 3]
a[0:2] = [4, 5]
print a
```
Now the output would be:
```
[4, 5, 3]
```
1. How can something that is returning something come on the left side of... | You are confusing two distinct operation that use very similar syntax:
**1) slicing:**
```
b = a[0:2]
```
This makes a copy of the slice of `a` and assigns it to `b`.
**2) slice assignment:**
```
a[0:2] = b
```
This *replaces* the slice of `a` with the contents of `b`.
Although the syntax is similar (I imagine b... |
How assignment works with python list slice | 10,623,302 | 32 | 2012-05-16T17:05:14Z | 10,623,383 | 21 | 2012-05-16T17:12:12Z | [
"python"
] | Python doc says that slicing a list returns a new list.
Now if a "new" list is being returned I've the following doubts related to "Assignment to slices"
```
a = [1, 2, 3]
a[0:2] = [4, 5]
print a
```
Now the output would be:
```
[4, 5, 3]
```
1. How can something that is returning something come on the left side of... | When you specify `a` on the left side of the `=` operator, you are using python's **normal assignment**, which changes the name `a` in the current context to point to the new value. This does not change the previous value to which `a` was pointing.
By specifying `a[0:2]` on the left side of the `=` operator, you are t... |
converting a 2d dictionary to a numpy matrix | 10,623,592 | 13 | 2012-05-16T17:27:20Z | 10,623,813 | 7 | 2012-05-16T17:42:56Z | [
"python",
"numpy"
] | I have a huge dictionary something like this:
```
d[id1][id2] = value
```
example:
```
books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20
```
and so on..
Each of the "auth" keys can have any set of "genres" associated wtih them. The value for a keyed item is the number of book... | Use a list comprehension to turn a dict into a list of lists and/or a numpy array:
```
np.array([[books[author][genre] for genre in sorted(books[author])] for author in sorted(books)])
```
*EDIT*
Apparently you have an irregular number of keys in each sub-dictionary. Make a list of all the genres:
```
genres = ['hu... |
converting a 2d dictionary to a numpy matrix | 10,623,592 | 13 | 2012-05-16T17:27:20Z | 10,628,728 | 19 | 2012-05-17T01:12:16Z | [
"python",
"numpy"
] | I have a huge dictionary something like this:
```
d[id1][id2] = value
```
example:
```
books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20
```
and so on..
Each of the "auth" keys can have any set of "genres" associated wtih them. The value for a keyed item is the number of book... | [pandas](http://pandas.pydata.org/) do this very well:
```
books = {}
books["auth1"] = {}
books["auth2"] = {}
books["auth1"]["humor"] = 20
books["auth1"]["action"] = 30
books["auth2"]["comedy"] = 20
from pandas import *
df = DataFrame(books).T.fillna(0)
```
The output is:
```
action comedy humor
auth1 ... |
Python spacing and aligning strings | 10,623,727 | 22 | 2012-05-16T17:37:19Z | 10,623,851 | 35 | 2012-05-16T17:45:17Z | [
"python",
"string",
"alignment"
] | I am trying to add spacing to align text in between two strings vars without using " " to do so
Trying to get the text to look like this, with the second column being aligned.
```
Location: 10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
```
Curren... | You should be able to use the format method:
```
"Location: {0:20} Revision {1}".format(Location,Revision)
```
You will have to figure out the of the format length for each line depending on the length of the label. The User line will need a wider format width than the Location or District lines. |
Python spacing and aligning strings | 10,623,727 | 22 | 2012-05-16T17:37:19Z | 10,623,866 | 16 | 2012-05-16T17:46:40Z | [
"python",
"string",
"alignment"
] | I am trying to add spacing to align text in between two strings vars without using " " to do so
Trying to get the text to look like this, with the second column being aligned.
```
Location: 10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
```
Curren... | Try `%*s` and `%-*s` and prefix each string with the column width:
```
>>> print "Location: %-*s Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10 Revision: 1
>>> print "District: %-*s Date: %s" % (20,"Tower","May 16, 2012")
District: Tower Date: May 16, 2012
``` |
Python spacing and aligning strings | 10,623,727 | 22 | 2012-05-16T17:37:19Z | 10,623,883 | 12 | 2012-05-16T17:47:51Z | [
"python",
"string",
"alignment"
] | I am trying to add spacing to align text in between two strings vars without using " " to do so
Trying to get the text to look like this, with the second column being aligned.
```
Location: 10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
```
Curren... | You can use `expandtabs` to specify the tabstop, like this:
```
>>> print ('Location:'+'10-10-10-10'+'\t'+ 'Revision: 1').expandtabs(30)
>>> print ('District: Tower'+'\t'+ 'Date: May 16, 2012').expandtabs(30)
#Output:
Location:10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
``` |
Convert datetime in Python list to year only | 10,624,360 | 4 | 2012-05-16T18:20:22Z | 10,624,389 | 8 | 2012-05-16T18:22:40Z | [
"python",
"pyodbc"
] | So I'm using pyodbc to take a Date Time field from MS Access add to a Python list. When I do this, it pyodbc instantly converts the data to this format `datetime.datetime(2012, 1, 1,0,0)`. I'm only interested in obtaining the year `2012` in this case. How can I parse the year out of my List when it uses this format? Ma... | ```
>>> dt = datetime.datetime(2012, 1, 1,0,0)
>>> dt.year
2012
```
Just for the record, `datetime.datetime` is not a "list of values", it's a class. |
Upgrade python without breaking yum | 10,624,511 | 41 | 2012-05-16T18:30:20Z | 11,196,864 | 119 | 2012-06-25T20:30:08Z | [
"python",
"centos",
"yum"
] | I recently installed Python 2.7.3 on a CentOS machine by compiling from source. Python 2.7.3 is installed at /opt/python2.7 and when I installed it I just changed /usr/bin/python to point to the new version. This apparently is wrong though because when I did it it broke yum. I would get the following.
```
There was a ... | I wrote a [quick guide](http://toomuchdata.com/2012/06/25/how-to-install-python-2-7-3-on-centos-6-2/) on how to install Python 2.7.3 (and 3.3.0) on CentOS 6. You are not supposed to change the system version of Python because it will break the system (as you found out).
Installing other versions works fine as long as ... |
Upgrade python without breaking yum | 10,624,511 | 41 | 2012-05-16T18:30:20Z | 16,557,202 | 13 | 2013-05-15T04:59:20Z | [
"python",
"centos",
"yum"
] | I recently installed Python 2.7.3 on a CentOS machine by compiling from source. Python 2.7.3 is installed at /opt/python2.7 and when I installed it I just changed /usr/bin/python to point to the new version. This apparently is wrong though because when I did it it broke yum. I would get the following.
```
There was a ... | ```
vim `which yum`
modify #/usr/bin/python to #/usr/bin/python2.4
``` |
Convert datetime object to a String of date only in Python | 10,624,937 | 89 | 2012-05-16T19:00:02Z | 10,624,968 | 156 | 2012-05-16T19:01:39Z | [
"python",
"datetime"
] | I see a lot on converting a `datetime` string to an `datetime` object in Python, but I want to go the other way.
I've got `datetime.datetime(2012, 2, 23, 0, 0)` and I would like to convert it to string like `'2/23/2012'`. | You can use [strftime](http://docs.python.org/2/library/time.html#time.strftime) to help you format your date.
E.g.,
```
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')
```
will yield:
```
'02/23/2012'
```
More information about formatting see [here](http://docs.python.org/library/datetime.html#str... |
Convert datetime object to a String of date only in Python | 10,624,937 | 89 | 2012-05-16T19:00:02Z | 10,625,003 | 9 | 2012-05-16T19:04:05Z | [
"python",
"datetime"
] | I see a lot on converting a `datetime` string to an `datetime` object in Python, but I want to go the other way.
I've got `datetime.datetime(2012, 2, 23, 0, 0)` and I would like to convert it to string like `'2/23/2012'`. | You could use simple string formatting methods:
```
>>> dt = datetime.datetime(2012, 2, 23, 0, 0)
>>> '{0.month}/{0.day}/{0.year}'.format(dt)
'2/23/2012'
>>> '%s/%s/%s' % (dt.month, dt.day, dt.year)
'2/23/2012'
``` |
Convert datetime object to a String of date only in Python | 10,624,937 | 89 | 2012-05-16T19:00:02Z | 35,780,962 | 18 | 2016-03-03T19:11:43Z | [
"python",
"datetime"
] | I see a lot on converting a `datetime` string to an `datetime` object in Python, but I want to go the other way.
I've got `datetime.datetime(2012, 2, 23, 0, 0)` and I would like to convert it to string like `'2/23/2012'`. | `date` and `datetime` objects (and `time` as well) support a [mini-language to specify output](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior), and there are two ways to access it:
* direct method call: `dt.strftime('format here')`; and
* new format method: `'{:format here}'.format(dt)`... |
Extracting first n columns of a numpy matrix | 10,625,096 | 11 | 2012-05-16T19:09:29Z | 10,625,149 | 18 | 2012-05-16T19:13:40Z | [
"python",
"numpy"
] | I have an array like this:
```
array([[-0.57098887, -0.4274751 , -0.38459931, -0.58593526],
[-0.22279713, -0.51723555, 0.82462029, 0.05319973],
[ 0.67492385, -0.69294472, -0.2531966 , 0.01403201],
[ 0.41086611, 0.26374238, 0.32859738, -0.80848795]])
```
Now I want to extract the foll... | If `a` is your array:
```
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
``` |
How do I pass tuples elements to a function as arguments in python? | 10,625,220 | 9 | 2012-05-16T19:18:56Z | 10,625,231 | 21 | 2012-05-16T19:19:39Z | [
"python",
"list",
"arguments",
"tuples"
] | I have a list consisting of tuples, I want to pass each tuple's elements to a function as arguments:
```
mylist = [(a, b), (c, d), (e, f)]
myfunc(a, b)
myfunc(c, d)
myfunc(e, f)
```
How do I do it?
Best Regards | This is actually very simple to do in Python, simply loop over the list and use the splat operator (`*`) to unpack the tuple as arguments for the function:
```
mylist = [(a, b), (c, d), (e, f)]
for args in mylist:
myfunc(*args)
```
E.g:
```
>>> numbers = [(1, 2), (3, 4), (5, 6)]
>>> for args in numbers:
... ... |
abbreviating a double comparison in python | 10,625,746 | 7 | 2012-05-16T19:55:47Z | 10,625,755 | 13 | 2012-05-16T19:56:36Z | [
"python"
] | Is there a way to abbreviate a comparison statement in python so that I don't have to write the whole thing out again? For example, instead of :
```
a=3
if a==3 or a==2:
print "hello world"
```
could I do something like:
if a==(3 or 2):
print "hello world"
I know the above example won't work but is there another... | ```
if a in (2, 3):
print "hello world"
``` |
abbreviating a double comparison in python | 10,625,746 | 7 | 2012-05-16T19:55:47Z | 10,625,765 | 9 | 2012-05-16T19:57:07Z | [
"python"
] | Is there a way to abbreviate a comparison statement in python so that I don't have to write the whole thing out again? For example, instead of :
```
a=3
if a==3 or a==2:
print "hello world"
```
could I do something like:
if a==(3 or 2):
print "hello world"
I know the above example won't work but is there another... | Possible solutions, depending on what exactly you want:
* `if a in (2,3)`
* `if a in xrange(2, 4)`
* `if 2 <= a <= 3` |
abbreviating a double comparison in python | 10,625,746 | 7 | 2012-05-16T19:55:47Z | 10,625,979 | 9 | 2012-05-16T20:11:46Z | [
"python"
] | Is there a way to abbreviate a comparison statement in python so that I don't have to write the whole thing out again? For example, instead of :
```
a=3
if a==3 or a==2:
print "hello world"
```
could I do something like:
if a==(3 or 2):
print "hello world"
I know the above example won't work but is there another... | See [Python 3.2 Optimizations](http://docs.python.org/py3k/whatsnew/3.2.html#optimizations) regarding the reason for the answer below.
```
a = 3
if a in {2, 3}:
print('Hello, world!')
``` |
python randomly sort items of the same value | 10,626,087 | 6 | 2012-05-16T20:19:27Z | 10,626,114 | 7 | 2012-05-16T20:21:44Z | [
"python"
] | This is a bit tricky and I couldn't come up with anything concise.
I have a list of tuples sorted by an item of the tuple. It's possible for these items to have the same value, so something like this:
```
a = [(a,1), (b,1), (c, 1), (d,2), (e,2), (f,2)]
```
What I'm looking for, is a way to randomize the order of all... | You could sort items by a tuple consisting of themselves and then a random number. If `v_1 < v_2`, `(v_1, random.random()) < (v_2, random.random())`; if `v_1 == v_2`, it'll fall back to comparing on the random number.
```
sorted(a, key=lambda v: (v, random.random()))
``` |
Minimax explanation "for dummies" | 10,626,766 | 9 | 2012-05-16T21:10:07Z | 10,638,736 | 7 | 2012-05-17T15:29:14Z | [
"python",
"algorithm"
] | I'm quite new to algorithms and i was trying to understand the minimax, i read a lot of articles,but i still can't get how to implement it into a tic-tac-toe game in python.
Can you try to explain it to me as easy as possible maybe with some pseudo-code or some python code?.
I just need to understand how it works. i r... | the idea of "minimax" is that there in a two-player game, one player is trying to maximize some form of score and another player is trying to minimize it. For example, in Tic-Tac-Toe the win of X might be scored as +1 and the win of O as -1. X would be the max player, trying to maximize the final score and O would be t... |
When is it best to use a class in Python? | 10,627,232 | 7 | 2012-05-16T21:49:23Z | 10,627,275 | 11 | 2012-05-16T21:52:52Z | [
"python",
"oop",
"class",
"function"
] | I'm new to python and programming in general, so would really appreciate any clarification on this point.
For example, in the following code:
```
#Using a class
class Monster(object):
def __init__(self, level, damage, duration):
print self
self.level = level
self.damage = damage
... | Your example is rather simplified.
In a more complete example fighting wouldn't just display the current state - it would also modify that state. Your monster might get hurt and that would change its hit points and morale. This state has to be stored somewhere. If you use a class it would be natural to add instance va... |
Inserting image into IPython notebook markdown | 10,628,262 | 70 | 2012-05-16T23:52:03Z | 10,628,360 | 73 | 2012-05-17T00:08:24Z | [
"python",
"ipython"
] | I am starting to depend heavily on the IPython notebook app to develop and document algorithms. It is awesome; but there is something that seems like it should be possible, but I can't figure out how to do it:
I would like to insert a local image into my (local) IPython notebook markdown to aid in documenting an algor... | Files inside the notebook dir are available under a "files/" url. So if it's in the base path, it would be `<img src="files/image.png">`, and subdirs etc. are also available: `<img src="files/subdir/image.png">`, etc.
*Update*: starting with IPython 2.0, the `files/` prefix is no longer needed (cf. [release notes](htt... |
Inserting image into IPython notebook markdown | 10,628,262 | 70 | 2012-05-16T23:52:03Z | 23,220,934 | 41 | 2014-04-22T13:23:24Z | [
"python",
"ipython"
] | I am starting to depend heavily on the IPython notebook app to develop and document algorithms. It is awesome; but there is something that seems like it should be possible, but I can't figure out how to do it:
I would like to insert a local image into my (local) IPython notebook markdown to aid in documenting an algor... | I am using ipython 2.0, so just two line.
```
from IPython.display import Image
Image(filename='output1.png')
``` |
Inserting image into IPython notebook markdown | 10,628,262 | 70 | 2012-05-16T23:52:03Z | 37,057,341 | 24 | 2016-05-05T18:05:06Z | [
"python",
"ipython"
] | I am starting to depend heavily on the IPython notebook app to develop and document algorithms. It is awesome; but there is something that seems like it should be possible, but I can't figure out how to do it:
I would like to insert a local image into my (local) IPython notebook markdown to aid in documenting an algor... | Most of the answeres given so far go in the wrong direction, suggest to load additional libraries and use the code instead of markup. In Ipython/Jupyter Notebooks it is very simple. Make sure the cell is indeed in markup and to display a image use:
```

```
Further advantage compared... |
python recursive pascal triangle | 10,628,788 | 3 | 2012-05-17T01:24:13Z | 10,628,872 | 7 | 2012-05-17T01:41:19Z | [
"python",
"recursion",
"pascals-triangle"
] | After completing an assignment to create pascal's triangle using an iterative function, I have attempted to recreate it using a recursive function. I have gotten to the point where I can get it to produce the individual row corresponding to the number passed in as an argument. But several attempts to have it produce th... | You just need to pass a list of lists through the recursion, and pick off the last element of the list (i.e. the last row of the triangle) to build your new row. Like so:
```
def triangle(n):
if n == 0:
return []
elif n == 1:
return [[1]]
else:
new_row = [1]
result = triangl... |
Handle multiple window in Python | 10,629,815 | 11 | 2012-05-17T04:26:16Z | 10,632,032 | 10 | 2012-05-17T08:11:22Z | [
"python",
"selenium",
"webdriver",
"ui-automation"
] | I am working in **selenium automation project**. Here i am using python language for selenium automation instead of Java.
I am facing an issue,handling multiple windows
Scenario is when I click a link in home page a new window opens.In the newly opened window I cannot perform any actions because the control is still ... | [`window_handles`](http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.window_handles) should give you the references to all open windows.
[this](http://seleniumhq.org/docs/03_webdriver.html#moving-between-windows-and-frames) is what the docu has to say about switching windows. |
No module named Image tk | 10,630,736 | 16 | 2012-05-17T06:14:51Z | 21,342,211 | 35 | 2014-01-24T20:47:36Z | [
"python"
] | I am new to python can any body please Help
D:\python\sub>python app.py
Traceback (most recent call last):
File "app.py", line 2, in
import ImageTk
ImportError: No module named ImageTk | This says that python is installed in non-standard location so the OS can not find ImageTk as it look in standard locations. You can re-install Python in a standard location, and where that is depends on which operating system and which installer you are using, or append this location to sys.path.
I'm using Ubuntu 13.0... |
Python GIL: is django save() blocking? | 10,631,419 | 4 | 2012-05-17T07:14:07Z | 10,631,846 | 7 | 2012-05-17T07:55:13Z | [
"python",
"django",
"multithreading",
"transactions",
"gil"
] | My django app saves django models to a remote database. Sometimes the saves are bursty. In order to free the main thread (\*thread\_A\*) of the application from the time toll of saving multiple objects to the database, I thought of transferring the model objects to a separate thread (\*thread\_B\*) using [`collections.... | Django's `save()` does nothing special to the GIL. In fact, there is hardly anything you can do with the GIL in Python code -- when it is executed, the thread must hold the GIL.
There are only two ways the GIL could get released in `save()`:
* Python decides to switch threads (after [`sys.getcheckinterval()`](http://... |
'str' object does not support item assignment in Python | 10,631,473 | 34 | 2012-05-17T07:18:41Z | 10,631,478 | 30 | 2012-05-17T07:19:38Z | [
"python",
"string"
] | I would like to read some characters from a string and put it into other string (Like we do in C).
So my code is like below
```
import string
import re
str = "Hello World"
j = 0
srr = ""
for i in str:
srr[j] = i #'str' object does not support item assignment
j = j + 1
print (srr)
```
In C the code may be
`... | In Python, strings are immutable, so you can't change their characters in-place.
You can, however, do the following:
```
for i in str:
srr += i
```
The reasons this works is that it's a shortcut for:
```
for i in str:
srr = srr + i
```
The above *creates a new string* with each iteration, and stores the re... |
'str' object does not support item assignment in Python | 10,631,473 | 34 | 2012-05-17T07:18:41Z | 18,006,499 | 22 | 2013-08-01T23:44:02Z | [
"python",
"string"
] | I would like to read some characters from a string and put it into other string (Like we do in C).
So my code is like below
```
import string
import re
str = "Hello World"
j = 0
srr = ""
for i in str:
srr[j] = i #'str' object does not support item assignment
j = j + 1
print (srr)
```
In C the code may be
`... | The other answers are correct, but you can, of course, do something like:
```
>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>
```
if you really want to. |
Adding a custom filter to jinja2 under pyramid | 10,632,232 | 3 | 2012-05-17T08:30:56Z | 10,632,586 | 9 | 2012-05-17T08:57:32Z | [
"python",
"pyramid",
"jinja2"
] | This question has been asked [before](http://stackoverflow.com/questions/8339899/jinja2-custom-filter-templateassertionerror-no-filter-named-format-number) but the accepted solution (given by the question poster himself) says that we can add the new filter to jinja2.filter.FILTER straightaway.
But in the [jinja2 docum... | Assuming you are using [`pyramid_jinja2`](http://docs.pylonsproject.org/projects/pyramid_jinja2/en/latest/?awesome), you can use `pyramid_jinja2.get_jinja2_environment()` via the `configurator` instance to access the environment.
However, apparently you can also [register them via the pyramid config file](http://docs.... |
Python: transform "list of tuples" in to 1 flat list, or 1 matrix | 10,632,839 | 18 | 2012-05-17T09:16:58Z | 10,636,583 | 46 | 2012-05-17T13:22:37Z | [
"python",
"sqlite",
"list",
"tuples"
] | With Sqlite, a "select..from" command returns the results "output", which prints (in python):
```
>>print output
[(12.2817, 12.2817), (0, 0), (8.52, 8.52)]
```
It seems to be a list of tuples. I would like to either convert "output" in a simple 1D array (=list in Python I guess):
```
[12.2817, 12.2817, 0, 0, 8.52, 8... | By far the fastest (and shortest) solution posted:
```
list(sum(output, ()))
```
About 50% faster than the `itertools` solution, and about 70% faster than the `map` solution. |
Python 2.x return values for cmp | 10,635,002 | 12 | 2012-05-17T11:37:53Z | 10,635,142 | 11 | 2012-05-17T11:46:22Z | [
"python",
"python-2.x"
] | Quoted from the [docs](http://docs.python.org/library/functions.html#cmp):
> `cmp(x, y)`
>
> Compare the two objects x and y and return an integer according to the outcome. The return value is negative if `x < y`, zero if `x == y` and strictly positive if `x > y`.
I was under the assumption that the return values are... | No, the docs explicitly say that yalues can be anything. The only value that is specified is `0` if the compared objects are equal. Don't trust the fact that you only see the values `-1`, `0` and `1`, that's an implementation detail and could change\*, so always check for `<` and `>` 0.
\*: note - actually, it won't r... |
insert or update keys in a python dictionary | 10,635,052 | 6 | 2012-05-17T11:40:58Z | 10,635,287 | 7 | 2012-05-17T11:55:26Z | [
"python",
"algorithm",
"dictionary"
] | I have a python dictionary `dict1` with more than 20,000 keys and I want to `update` it with another dictionary `dict2`. The dictionaries look like this:
```
dict1
key11=>[value11]
key12=>[value12]
...
...
keyxyz=>[value1x] //common key
...... so on
dict2
key21=>[value21]
key22=>[value22]
...
... | Use [`defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict) from the collections module.
```
>>> from collections import defaultdict
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> my_dict = defaultdict(list)
>>> for k in dict1:
... my_dict[k].append(... |
How to write manipulated raster values to ASCII grid with GDAL? | 10,635,107 | 4 | 2012-05-17T11:43:59Z | 10,725,993 | 8 | 2012-05-23T18:44:45Z | [
"python",
"gis",
"geospatial",
"raster",
"gdal"
] | I am trying to manipulate raster values in a grid (ASCII Grid) with GDAL. But before proceeding with this, I have trouble writing the new values into the file. I get these error messages when slopeband.WriteArray(s) is called.
ERROR 6: slope.asc, band 1: WriteBlock() not supported for this dataset.
ERROR 1: slope.asc... | Unfortunately, GDAL cannot read and write to the same degrees across all filetypes. Arc ASCII grid happens to be one of those filetypes that GDAL cannot write to. As your error message says: `WriteBlock() not supported for this dataset.`, so you can't write to Arc ASCII grids.
As alternative, you could convert your ex... |
How do I make multiple celery workers run the same tasks? | 10,635,733 | 5 | 2012-05-17T12:27:07Z | 10,636,900 | 7 | 2012-05-17T13:43:31Z | [
"python",
"django",
"rabbitmq",
"celery",
"amqp"
] | I have one task that is checking a url speed, but i want that to be executed by multiple celery workers in different servers. I want the same url to be checked by multiple workers.
How can I do that? | If you could set `ignore_result=True` . Try [Broadcast](http://docs.celeryproject.org/en/master/userguide/routing.html#broadcast)
If you couldn't, check [Routing Tasks](http://docs.celeryproject.org/en/master/userguide/routing.html#id2) and send the task multiple times to different queues, for different IDC for exampl... |
Python / Pandas - GUI for viewing a DataFrame or Matrix | 10,636,024 | 22 | 2012-05-17T12:48:00Z | 12,036,847 | 10 | 2012-08-20T11:30:18Z | [
"python",
"user-interface",
"pandas"
] | I'm using the Pandas package and it creates a DataFrame object, which is basically a labeled matrix. Often I have columns that have long string fields, or dataframes with many columns, so the simple print command doesn't work well. I've written some text output functions, but they aren't great.
What I'd really love is... | I use `QTableWidget` from PyQt to display a `DataFrame`. I create a `QTableWidgetObject` and then populate with `QTableWidgetItems` created with `DataFrame` values.
Following is the snippet of code that reads a CSV file ,create a `DataFrame`, then display in a GUI:
```
df = read_csv(filename, index_col = 0,header = 0... |
Python / Pandas - GUI for viewing a DataFrame or Matrix | 10,636,024 | 22 | 2012-05-17T12:48:00Z | 16,884,805 | 7 | 2013-06-02T16:27:16Z | [
"python",
"user-interface",
"pandas"
] | I'm using the Pandas package and it creates a DataFrame object, which is basically a labeled matrix. Often I have columns that have long string fields, or dataframes with many columns, so the simple print command doesn't work well. I've written some text output functions, but they aren't great.
What I'd really love is... | You could use the to\_html() dataframe method to convert the dataframe to html and display it in your browser. Here is an example assuming you have a dataframe called df. You should check the documentation to see what other options are available in the to\_html() method.
```
# Format floating point numbers with 2 deci... |
Python / Pandas - GUI for viewing a DataFrame or Matrix | 10,636,024 | 22 | 2012-05-17T12:48:00Z | 37,447,530 | 8 | 2016-05-25T21:01:08Z | [
"python",
"user-interface",
"pandas"
] | I'm using the Pandas package and it creates a DataFrame object, which is basically a labeled matrix. Often I have columns that have long string fields, or dataframes with many columns, so the simple print command doesn't work well. I've written some text output functions, but they aren't great.
What I'd really love is... | I wasn't fully satisfied with some other GUIs, so I created my own, which I'm now maintaining [on Github](https://github.com/bluenote10/PandasDataFrameGUI). Example:
[](http://i.stack.imgur.com/rtB25.png)
Apart from the basic table + plot functionalit... |
replacing while loop with list comprehension | 10,637,037 | 2 | 2012-05-17T13:51:22Z | 10,637,141 | 9 | 2012-05-17T13:57:47Z | [
"python",
"while-loop",
"list-comprehension"
] | It is common to express for loops as list comprehensions:
```
mylist=[]
for i in range(30):
mylist.append(i**2)
```
This is equivalent to:
```
mylist = [i**2 for i in range(30)]
```
Is there any sort of mechanism by which this sort of iteration could be done with a while loop?
```
mylist=[]
i=0
while i<30:
... | If your while loop justs checks a local variable that is being incremented, you should convert it to a for loop or the equivalent list comprehension.
You should only use a while loop only if you can **not** express the loop as iterating over something. An example of a typical use case are checks for the state of an [E... |
Flask: IOError when saving uploaded files | 10,637,352 | 6 | 2012-05-17T14:11:16Z | 10,638,095 | 9 | 2012-05-17T14:51:10Z | [
"python",
"flask"
] | I am learning Flask and am attempting to work through the uploading files pattern documented here: <http://flask.pocoo.org/docs/patterns/fileuploads/>. I am working in Firefox 12 on Windows 7, and am running my app in debug mode on my local machine.
I am copying the example verbatim, except for the value of the UPLOAD... | The slash at the beginning of '/uploads' makes the path specification absolute: the leading slash represents the root of the filesystem hierarchy. While that might not be exactly how things work on Windows, it makes sense for Python to understand it this way as its path-handling functions are cross-platform.
The forms... |
Flask: IOError when saving uploaded files | 10,637,352 | 6 | 2012-05-17T14:11:16Z | 20,257,725 | 21 | 2013-11-28T04:29:01Z | [
"python",
"flask"
] | I am learning Flask and am attempting to work through the uploading files pattern documented here: <http://flask.pocoo.org/docs/patterns/fileuploads/>. I am working in Firefox 12 on Windows 7, and am running my app in debug mode on my local machine.
I am copying the example verbatim, except for the value of the UPLOAD... | Why not try this, it works for me.
```
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(APP_ROOT, 'static/uploads')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
``` |
Minimum Edit Distance Reconstruction | 10,638,597 | 3 | 2012-05-17T15:21:22Z | 10,641,240 | 18 | 2012-05-17T18:13:39Z | [
"python",
"matrix",
"nlp",
"dynamic-programming"
] | I know there are similar answer to this on stack, as well as online, but I feel I'm missing something. Given the code below, we need to reconstruct the sequence of events that led to the resulting minimum edit distance. For the code below, we need to write a function that outputs:
```
Equal, L, L
Delete, E
Equal, A, A... | It's my opinion that understanding the algorithm more deeply is important in this case. Rather than giving you some pseudocode, I'll walk you through the essential steps of the algorithm, and show you how the data you want is "encoded" in the final matrix that results. Of course, if you don't need to roll your own algo... |
Python prime generator in one-line | 10,639,861 | 5 | 2012-05-17T16:41:19Z | 10,640,037 | 8 | 2012-05-17T16:52:00Z | [
"python",
"math",
"integer",
"primes"
] | I'm trying to create prime number generator in one-line of Python just as a fun exercise.
The following code works as expected, but it is too slow:
```
primes = lambda q: (i for i in xrange(1,q) if i not in [j*k for j in xrange(1,i) for k in xrange(1,i)])
for i in primes(10):
print i,
```
So I I tried to do it by... | That's not the Sieve of Eratosthenes, even though it looks like it is. It is in fact much worse. The Sieve is the best algorithm for finding primes.
See <http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes>
**edit**: I've modified <http://stackoverflow.com/a/9302299/711085> to be a one-liner (originally it was not the... |
Reading and writing files python | 10,640,493 | 2 | 2012-05-17T17:26:40Z | 10,640,512 | 8 | 2012-05-17T17:27:55Z | [
"python",
"file"
] | I am trying to write three separate line in a text document based on input obtained from a dialogue window. I am sure this is a simple fix but I can't seem to write the three lines as separate lines. Would someone mind telling me what's wrong with this bit of code?
```
file = open('file.txt', 'wb')
file.write('input1... | Try this:
```
file = open('file.txt', 'wb')
file.write('input1\n')
file.write('input2\n')
file.write('input3\n')
```
You are appending the newline character `'\n'` to advance to the next line.
If you use the `with` construct, it will automatically close the file for you:
```
with open('file.txt', 'wb') as file:
... |
Python database WITHOUT using Django (for Heroku) | 10,640,532 | 12 | 2012-05-17T17:29:17Z | 10,644,101 | 17 | 2012-05-17T21:59:50Z | [
"python",
"database",
"django",
"heroku"
] | To my surprise, I haven't found this question asked elsewhere. Short version, I'm writing an app that I plan to deploy to the cloud (probably using Heroku), which will do various web scraping and data collection. The reason it'll be in the cloud is so that I can have it be set to run on its own every day and pull the d... | You can get a database provided from Heroku without requiring your app to use Django. To do so:
```
heroku addons:add heroku-postgresql:dev
```
If you need a larger more dedicated database, you can examine the plans at [Heroku Postgres](http://postgres.heroku.com/)
Within your requirements.txt you'll want to add:
`... |
Is there a decent way of creating a copy constructor in python? | 10,640,642 | 8 | 2012-05-17T17:36:13Z | 10,640,886 | 14 | 2012-05-17T17:52:38Z | [
"python",
"copy-constructor",
"deep-copy"
] | I realize questions quite similar to this have been asked, though not exactly this way.
I'd like to have an optional argument for the constructor of my class that, if it is an instance of my class, will be copied. For example, something like (*I know this code does not work!*):
```
class Foo(object):
def __init__... | I think this is the most pythonic way of doing it - a copy factory method.
```
import copy
class Foo(object):
def __init__(self):
self.x = None
self.y = None
self.z = None
def copy(self):
return copy.deepcopy(self)
a = Foo()
a.x = 1
a.y = 2
a.z = 3
b = a.copy()
print b.x
prin... |
How to get the cumulative distribution function with NumPy? | 10,640,759 | 8 | 2012-05-17T17:44:34Z | 10,642,100 | 9 | 2012-05-17T19:15:18Z | [
"python",
"numpy",
"histogram"
] | I want to create a CDF with NumPy, my code is the next:
```
histo = np.zeros(4096, dtype = np.int32)
for x in range(0, width):
for y in range(0, height):
histo[data[x][y]] += 1
q = 0
cdf = list()
for i in histo:
q = q + i
cdf.append(q)
```
I am walking by the array but take a long ti... | I'm not really sure what your code is doing, but if you have `hist` and `bin_edges` arrays returned by `numpy.histogram` you can use `numpy.cumsum` to generate a cumulative sum of the histogram contents.
```
>>> import numpy as np
>>> hist, bin_edges = np.histogram(np.random.randint(0,10,100), normed=True)
>>> bin_edg... |
How to get the cumulative distribution function with NumPy? | 10,640,759 | 8 | 2012-05-17T17:44:34Z | 30,460,089 | 18 | 2015-05-26T13:33:11Z | [
"python",
"numpy",
"histogram"
] | I want to create a CDF with NumPy, my code is the next:
```
histo = np.zeros(4096, dtype = np.int32)
for x in range(0, width):
for y in range(0, height):
histo[data[x][y]] += 1
q = 0
cdf = list()
for i in histo:
q = q + i
cdf.append(q)
```
I am walking by the array but take a long ti... | Using a histogram is one solution but it involves binning the data. This is not necessary for plotting a CDF of empirical data. Let `F(x)` be the count of how many entries are less than `x` then it goes up by one, exactly where we see a measurement. Thus, if we sort our samples then at each point we increment the count... |
Django workflow to convert model superclass to subclass | 10,640,789 | 3 | 2012-05-17T17:46:21Z | 10,641,305 | 10 | 2012-05-17T18:18:37Z | [
"python",
"django",
"django-models"
] | I have a Django project with two models: Applicant and Client, where Client is a subclass of Applicant. I would like some way of allowing a user to add an existing Applicant instance as a Client. I already have a view for Applicant instances, so I thought that having a Client model form on that page would do this, but ... | You can create a `Client` instance from an existing `Applicant` instance with the following code:
```
client = Client(applicant_ptr=applicant)
client.save_base(raw=True)
``` |
how to add lines to existing file using python | 10,640,804 | 16 | 2012-05-17T17:47:24Z | 10,640,823 | 21 | 2012-05-17T17:49:06Z | [
"python",
"file"
] | I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing additional lines in the file in a later part of the program. (The lines will be written from user input obtained later on.)
```
with open('file.txt'... | If you want to append to the file, open it with `'a'`. If you want to seek through the file to find the place where you should insert the line, use `'r+'`. ([docs](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files)) |
how to add lines to existing file using python | 10,640,804 | 16 | 2012-05-17T17:47:24Z | 10,640,840 | 17 | 2012-05-17T17:50:19Z | [
"python",
"file"
] | I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing additional lines in the file in a later part of the program. (The lines will be written from user input obtained later on.)
```
with open('file.txt'... | Open the file for 'append' rather than 'write'.
```
with open('file.txt', 'a') as file:
file.write('input')
``` |
how to add lines to existing file using python | 10,640,804 | 16 | 2012-05-17T17:47:24Z | 10,640,855 | 7 | 2012-05-17T17:50:59Z | [
"python",
"file"
] | I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing additional lines in the file in a later part of the program. (The lines will be written from user input obtained later on.)
```
with open('file.txt'... | Use `'a'`, `'a'` means `append`. Anything written to a file opened with `'a'` attribute is written at the end of the file.
```
with open('file.txt', 'a') as file:
file.write('input')
``` |
ValueError: unsupported format character '{' (0x7b) in defining dictionary | 10,640,904 | 5 | 2012-05-17T17:53:37Z | 10,640,967 | 7 | 2012-05-17T17:56:36Z | [
"python"
] | I'm writing some code for web development using Google Python Appengine. In my code I have to concatenate strings using % and dictionary Here's the code I've written.
```
def print_form(self, unameError='', passwdError='', verpasswdError='', emailError='', unameValue='', emailValue='' ):
self.response.out.write( f... | It sounds like you may have the sequence "%{" in the value of `form3`. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.