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
Efficient Alternative to "in"
6,509,647
4
2011-06-28T16:14:44Z
6,509,723
7
2011-06-28T16:20:08Z
[ "python", "list", "optimization", "memory" ]
I'm writing a web crawler with the ultimate goal of creating a map of the path the crawler has taken. While I haven't a clue at what rate other, and most definitely better crawlers pull down pages, mine clocks about 2,000 pages per minute. The crawler works on a recursive backtracking algorithm which I have limited to...
Simply replace your 'list of crawled URLS" with a "`set` of crawled urls". Sets are optimised for random access (using the same hashing algorithms that dictionaries use) and they're a heck of a lot faster. A lookup operation for lists is done using a linear search so it's not particularly fast. You won't need to change...
How to get Registry().settings during Pyramid app startup time?
6,509,856
18
2011-06-28T16:30:41Z
6,517,508
12
2011-06-29T08:06:38Z
[ "python", "paste", "pyramid" ]
I am used to develop web applications on Django and gunicorn. In case of Django, any application modules in a Django application can get deployment settings through *django.conf.settings*. The "settings.py" is written in Python, so that any arbitrary settings and pre-processing can be defined **dynamically**. In case...
The pattern that I use is to pass the `Configurator` to modules that need to be initialized. Pyramid doesn't use any global variables because a design goal is to be able to run multiple instances of Pyramid in the same process. The threadlocals are global, but they are local to the current request, so different Pyramid...
How to get Registry().settings during Pyramid app startup time?
6,509,856
18
2011-06-28T16:30:41Z
6,517,725
14
2011-06-29T08:29:33Z
[ "python", "paste", "pyramid" ]
I am used to develop web applications on Django and gunicorn. In case of Django, any application modules in a Django application can get deployment settings through *django.conf.settings*. The "settings.py" is written in Python, so that any arbitrary settings and pre-processing can be defined **dynamically**. In case...
Another option, if you enjoy global configuration via Python, create a settings.py file. If it needs values from the ini file, parse the ini file and grab them out (at module scope, so it runs at import time): ``` from paste.deploy.loadwsgi import appconfig config = appconfig('config:development.ini', 'myapp', relativ...
How to Find a String in a Text File And Replace Each Time With User Input in a Python Script?
6,512,131
2
2011-06-28T19:35:27Z
6,512,210
8
2011-06-28T19:43:25Z
[ "python", "replace" ]
I am new to python so excuse my ignorance. Currently, I have a text file with some words marked as <>. My goal is to essentially build a script which runs through a text file with such marked words. Each time the script finds such a word, it would ask the user for what it wants to replace it with. For example, if I ...
``` import re with open('in.txt') as infile: text = infile.read() search = re.compile('<<([^>]*)>>') text = search.sub(lambda m: raw_input(m.group(1) + '? '), text) with open('out.txt', 'w') as outfile: outfile.write(text) ```
Accept a range of numbers in the form of 0-5 using Python's argparse?
6,512,280
10
2011-06-28T19:49:31Z
6,512,320
7
2011-06-28T19:52:18Z
[ "python", "argparse" ]
Using argparse, is there a way to accept a range of numbers and convert them into a list? For example: ``` python example.py --range 0-5 ``` Is there some way input a command line argument in that form and end up with: ``` args.range = [0,1,2,3,4,5] ``` And also have the possibility to input `--range 2 = [2]`?
You can just use a string argument and then parse it with `range(*rangeStr.split(','))`.
Accept a range of numbers in the form of 0-5 using Python's argparse?
6,512,280
10
2011-06-28T19:49:31Z
6,512,463
16
2011-06-28T20:05:44Z
[ "python", "argparse" ]
Using argparse, is there a way to accept a range of numbers and convert them into a list? For example: ``` python example.py --range 0-5 ``` Is there some way input a command line argument in that form and end up with: ``` args.range = [0,1,2,3,4,5] ``` And also have the possibility to input `--range 2 = [2]`?
You could just write your own parser in the `type` argument, e.g. ``` from argparse import ArgumentParser, ArgumentTypeError import re def parseNumList(string): m = re.match(r'(\d+)(?:-(\d+))?$', string) # ^ (or use .split('-'). anyway you like.) if not m: raise ArgumentTypeError("'" + string + "'...
How would you create a comma-delimited string from a pyodbc result row?
6,513,588
9
2011-06-28T21:57:57Z
6,514,174
10
2011-06-28T23:17:05Z
[ "python" ]
I have a resultset of rows stored in cursor.rows which are returned from a pyodbc.cursor.execute command. What is the fastest way to unpack this data and place it into a list of comma-seperated strings (or unpack into a custom object)? Currently I am doing the following: ``` cursor.execute(query_str) f = open(out_fil...
I'd use the `csv` module: ``` import csv cursor.execute(query_str) with open(out_file, 'w') as f: csv.writer(f, quoting=csv.QUOTE_NONE).writerows(cursor) ``` Beware that if you `csv.QUOTE_NONE` a `csv.Error` is raised if there's a comma in a data field. The sane way would be to `csv.QUOTE_MINIMAL` at least.
Running Python script from IDLE on Windows 7 64 bit
6,513,967
2
2011-06-28T22:45:44Z
6,514,219
14
2011-06-28T23:25:43Z
[ "python", "python-idle" ]
I'm trying to figure out how to successfully use Python 2.7.1 on windows 7. So far, I'm having to use the shell (IDLE) to create scripts and then run them from the cmd prompt. I feel this is slowing down the learning process and I was wondering if there was a way to run it from IDLE (I'm not able to create a pathway,...
1. Run IDLE. You will be presented with the "Python Shell" window and a `>>>` prompt. 2. Click File, New Window. You will be presented with an "Untitled" window for editing a script. 3. Enter your script in the "Untitled" window. 4. In the "Untitled" window, select Run, Run Module (or press F5) to run your script. 5. A...
How do you escape strings for SQLite table/column names in Python?
6,514,274
40
2011-06-28T23:33:51Z
6,515,315
15
2011-06-29T03:02:15Z
[ "python", "sqlite", "sqlite3" ]
The standard approach for using variable values in SQLite queries is the "question mark style", like this: ``` import sqlite3 with sqlite3.connect(":memory:") as connection: connection.execute("CREATE TABLE foo(bar)") connection.execute("INSERT INTO foo(bar) VALUES (?)", ("cow",)) print(list(connection.ex...
If you're quite certain that you need to specify column names dynamically, you should use a library that can do so safely (and complains about things that are wrong). SQLAlchemy is very good at that. ``` >>> import sqlalchemy >>> from sqlalchemy import * >>> metadata = MetaData() >>> dynamic_column = "cow" >>> foo_tab...
How do you escape strings for SQLite table/column names in Python?
6,514,274
40
2011-06-28T23:33:51Z
6,515,471
24
2011-06-29T03:32:04Z
[ "python", "sqlite", "sqlite3" ]
The standard approach for using variable values in SQLite queries is the "question mark style", like this: ``` import sqlite3 with sqlite3.connect(":memory:") as connection: connection.execute("CREATE TABLE foo(bar)") connection.execute("INSERT INTO foo(bar) VALUES (?)", ("cow",)) print(list(connection.ex...
The `psycopg2` documentation explicitly recommends using normal python % or {} formatting to substitute in table and column names (or other bits of dynamic syntax), and then using the parameter mechanism to substitute values into the query. I disagree with everyone who is saying "don't ever use dynamic table/column na...
How do you escape strings for SQLite table/column names in Python?
6,514,274
40
2011-06-28T23:33:51Z
6,701,665
24
2011-07-15T00:58:40Z
[ "python", "sqlite", "sqlite3" ]
The standard approach for using variable values in SQLite queries is the "question mark style", like this: ``` import sqlite3 with sqlite3.connect(":memory:") as connection: connection.execute("CREATE TABLE foo(bar)") connection.execute("INSERT INTO foo(bar) VALUES (?)", ("cow",)) print(list(connection.ex...
To convert any string into a SQLite identifier: * Ensure the string can be encoded as UTF-8. * Ensure the string does not include any NUL characters. * Replace all `"` with `""`. * Wrap the entire thing in double quotes. ### Implementation ``` import codecs def quote_identifier(s, errors="strict"): encodable = ...
GUI interface for sqlite data entry in Python
6,514,680
16
2011-06-29T00:55:57Z
6,522,854
9
2011-06-29T15:04:01Z
[ "python", "sqlite", "user-interface", "ms-access" ]
I am making a simple sqlite database for storing some non-sensitive client information. I am very familiar with python+sqlite and would prefer to stick with this combo on this project. I would like to create an simple GUI interface for data entry and searching of the database... something very similar to what MS Access...
Since you're interested in future integration with a web application, you might consider using a Python web framework and running the app locally on your machine, using your web browser as the interface. In that case, one easy option would be [web2py](http://www.web2py.com). Just [download](http://www.web2py.com/exampl...
Django: Redirect to previous page *with query string* after login
6,515,096
10
2011-06-29T02:18:56Z
6,515,265
9
2011-06-29T02:51:36Z
[ "python", "django", "django-authentication" ]
I am using `django.contrib.auth` and would like to redirect to the previous page after logging in. I would like something like the following: [Django: Redirect to previous page after login](http://stackoverflow.com/questions/806835/django-redirect-to-previous-page-after-login) *except* the redirected-to URL can contain...
How about escaping the get parameters and then unquoting them in the view? ### html ``` <a href="{% url user_login %}?next={{ request.get_full_path|urlencode }}">Login</a> ``` ### login view ``` if successful_login: url_with_get = urllib2.unquote(request.GET.get('next')) return http.HttpResponseRedirect(url...
Need more efficient way to parse out csv file in Python
6,515,120
2
2011-06-29T02:23:17Z
6,515,172
12
2011-06-29T02:32:42Z
[ "python", "csv" ]
Here's a sample csv file ``` id, serial_no 2, 500 2, 501 2, 502 3, 600 3, 601 ``` This is the output I'm looking for (list of serial\_no withing a list of ids): ``` [2, [500,501,502]] [3, [600, 601]] ``` I have implemented my solution but it's too much code and I'm sure there are better solutions out there. Still l...
``` from collections import defaultdict records = defaultdict(list) file = 'test.csv' data = csv.reader(open(file)) fields = data.next() for row in data: records[row[0]].append(row[1]) #sorting by ids since keys don't maintain order results = sorted(records.items(), key=lambda x: x[0]) print results ``` If th...
Get key from dictionary
6,517,793
4
2011-06-29T08:35:37Z
6,517,820
9
2011-06-29T08:37:37Z
[ "python", "dictionary" ]
I just started with Python, Is there some iteration in dictionary like in PHP ``` foreach(aData as key=>value) ```
It looks like something like this : ``` my_dict = {"key1": 1, "key2":2} my_dict.items() # in python < 3 , you should use iteritems() >>> ("key1", 1), ("key2", 2) ``` so you can iterate on it : ``` for key, value in my_dict.items(): do_the_stuff(key, value) ```
Clear all items from the queue
6,517,953
24
2011-06-29T08:48:39Z
6,518,011
47
2011-06-29T08:53:18Z
[ "python", "queue" ]
How can I clear a queue. For example I have datas in a queue, but for some reason I don't need the existing data, and just want to clear the queue. Is there any way? Will this work: ``` oldQueue = Queue.Queue() ```
``` q = Queue.Queue() q.queue.clear() ``` **EDIT** I omitted the issue of thread safety for clarity and brevity, but @Dan D is quite correct, the following is better. ``` q = Queue.Queue() with q.mutex: q.queue.clear() ```
Clear all items from the queue
6,517,953
24
2011-06-29T08:48:39Z
18,873,213
13
2013-09-18T13:11:50Z
[ "python", "queue" ]
How can I clear a queue. For example I have datas in a queue, but for some reason I don't need the existing data, and just want to clear the queue. Is there any way? Will this work: ``` oldQueue = Queue.Queue() ```
You just can not clear the queue, because every put also add the unfinished\_tasks member. The join method depends on this value. And all\_tasks\_done needs to be notified also. ``` q.mutex.acquire() q.queue.clear() q.all_tasks_done.notify_all() q.unfinished_tasks = 0 q.mutex.release() ``` or in decent way, use get a...
Python, remove duplicates from list of tuples
6,518,071
3
2011-06-29T08:59:51Z
6,518,140
14
2011-06-29T09:06:08Z
[ "python", "list", "items" ]
I have the following list: ``` [('mail', 167, datetime.datetime(2010, 9, 29)) , ('name', 1317, datetime.datetime(2011, 12, 12)), ('mail', 1045, datetime.datetime(2010, 8, 13)), ('name', 3, datetime.datetime(2011, 11, 3))] ``` And I want to remove items from the list with coinciding first item in a tuple where d...
You can use a dictionary to store the highest value found for a given key so far: ``` temp = {} for key, number, date in input_list: if key not in temp: # we see this key for the first time temp[key] = (key, number, date) else: if temp[key][2] < date: # the new date is larger than the old one ...
How to check if all items in the list are None?
6,518,394
24
2011-06-29T09:25:47Z
6,518,435
66
2011-06-29T09:28:07Z
[ "python" ]
``` In [27]: map( lambda f,p: f.match(p), list(patterns.itervalues()), vatids ) Out[27]: [None, <_sre.SRE_Match object at 0xb73bfdb0>, None] ``` The list can be all `None` or one of it is an re.Match instance. What one liner check can I do on the returned list to tell me that the contents are all `None`?
``` all(v is None for v in l) ``` will return `True` if all of the elements of `l` are `None` Note that `l.count(None) == len(l)` is a lot faster but requires that `l` be an actual `list` and not just an iterable.
How to check if all items in the list are None?
6,518,394
24
2011-06-29T09:25:47Z
6,518,492
15
2011-06-29T09:32:03Z
[ "python" ]
``` In [27]: map( lambda f,p: f.match(p), list(patterns.itervalues()), vatids ) Out[27]: [None, <_sre.SRE_Match object at 0xb73bfdb0>, None] ``` The list can be all `None` or one of it is an re.Match instance. What one liner check can I do on the returned list to tell me that the contents are all `None`?
``` not any(my_list) ``` returns `True` if all items of `my_list` are falsy. **Edit**: Since match objects are always trucy and `None` is falsy, this will give the same result as `all(x is None for x in my_list)` for the case at hand. As demonstrated in [gnibbler's answer](http://stackoverflow.com/questions/6518394/h...
Interpolate NaN values in a numpy array
6,518,811
23
2011-06-29T09:58:44Z
6,519,053
14
2011-06-29T10:19:56Z
[ "python", "numpy", "interpolation" ]
Is there a quick way of replacing all NaN values in a numpy array with (say) the linearly interpolated values? For example, ``` [1 1 1 nan nan 2 2 nan 0] ``` would be converted into ``` [1 1 1 1.3 1.6 2 2 1 0] ```
I came up with this code: ``` import numpy as np nan = np.nan A = np.array([1, nan, nan, 2, 2, nan, 0]) ok = -np.isnan(A) xp = ok.ravel().nonzero()[0] fp = A[-np.isnan(A)] x = np.isnan(A).ravel().nonzero()[0] A[np.isnan(A)] = np.interp(x, xp, fp) print A ``` It prints ``` [ 1. 1.33333333 1.66666667 ...
Interpolate NaN values in a numpy array
6,518,811
23
2011-06-29T09:58:44Z
6,520,696
30
2011-06-29T12:34:30Z
[ "python", "numpy", "interpolation" ]
Is there a quick way of replacing all NaN values in a numpy array with (say) the linearly interpolated values? For example, ``` [1 1 1 nan nan 2 2 nan 0] ``` would be converted into ``` [1 1 1 1.3 1.6 2 2 1 0] ```
Lets define first a simple helper function in order to make it more straightforward to handle indices and logical indices of [NaNs](http://en.wikipedia.org/wiki/NaN): ``` import numpy as np def nan_helper(y): """Helper to handle indices and logical indices of NaNs. Input: - y, 1d numpy array with pos...
scoped_session(session_maker()) or plain session_maker() in sqlalchemy?
6,519,546
17
2011-06-29T10:58:29Z
6,519,855
17
2011-06-29T11:24:52Z
[ "python", "django", "orm", "sqlalchemy" ]
I am using SQlAlchemy in my web project. What should i use scoped\_session(session\_maker()) or plain session\_maker() and Why ?. Or should i use something else ? ``` ## model.py from sqlalchemy import * from sqlalchemy.orm import * engine = create_engine('mysql://dbUser:dbPassword@dbServer:dbPort/dbName', pool_recyc...
Reading the [documentation](http://www.sqlalchemy.org/docs/06/orm/session.html?highlight=scoped_session#unitofwork-contextual) is recommended: > the scoped\_session() function is provided which produces a thread-managed registry of Session objects. It is commonly used in web applications so that a single global variab...
scoped_session(session_maker()) or plain session_maker() in sqlalchemy?
6,519,546
17
2011-06-29T10:58:29Z
6,520,068
7
2011-06-29T11:41:40Z
[ "python", "django", "orm", "sqlalchemy" ]
I am using SQlAlchemy in my web project. What should i use scoped\_session(session\_maker()) or plain session\_maker() and Why ?. Or should i use something else ? ``` ## model.py from sqlalchemy import * from sqlalchemy.orm import * engine = create_engine('mysql://dbUser:dbPassword@dbServer:dbPort/dbName', pool_recyc...
Scoped\_session at every method since will give you a thread of local session which you cannot obtain beforehand (like at the module level).It's not needed to open a new session in every method, You can use a global session , Create a session only when the global session is not available. i.e you can write a method whi...
Logical paradox in python?
6,520,193
11
2011-06-29T11:52:17Z
6,520,216
21
2011-06-29T11:53:59Z
[ "python" ]
I came over this, where "not None" equals both True and False simultaneously. ``` >>> not None True >>> not None == True True >>> not None == False True ``` At first I expected that this would be because of the order of operators, but however when testing a similar expression: ``` >>> not False True >>> not False...
This *is* due to operator precedence. `not none == True` means `not (None == True)` means `None != True`, which is true. Similarly, `None != False` is also true. The value `None` is distinct from the booleans. Your last two expressions mean `False != False`, which is false, and `False != True`, which is true.
Running "wc -l <filename>" within Python Code
6,520,761
5
2011-06-29T12:40:28Z
6,521,584
8
2011-06-29T13:40:58Z
[ "python" ]
I want to do 10-fold cross-validation for huge files ( running into hundreds of thousands of lines each). I want to do a "wc -l " each time i start reading a file, then generate random numbers a fixed number of times, each time writing that line number into a separate file . I am using this: ``` import os for i in fi...
Let's compare: ``` from subprocess import check_output def wc(filename): return int(check_output(["wc", "-l", filename]).split()[0]) def native(filename): c = 0 with open(filename) as file: while True: chunk = file.read(10 ** 7) if chunk == "": return c ...
How to access a dictionary key value present inside a list?
6,521,892
11
2011-06-29T14:01:57Z
6,521,916
16
2011-06-29T14:04:00Z
[ "python" ]
Suppose I have the following list: ``` list = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}] ``` How do I access a particular value of key say `d`?
Index the list then the dict. ``` print L[1]['d'] ```
How to delete documentation from PyPi
6,521,931
4
2011-06-29T14:05:02Z
6,531,582
9
2011-06-30T07:50:06Z
[ "python", "pypi" ]
I just noticed that there is some ancient version of documentation accessible directly at <http://pypi.python.org/pypi/gensim> (right at the top, under [Package Documentation](http://packages.python.org/gensim)). I may have tested that feature when first trying PyPi, ages ago. Now real documentation for my package is ...
Just create a new `index.html` file with a link to the new documentation or even a redirect: ``` <html> <head> <title>A web page that points a browser to a different page after 2 seconds</title> <meta http-equiv="refresh" content="2; URL=http://www.example.com"> <meta name="keywords" conten...
How to change database dynamically in Django?
6,522,161
2
2011-06-29T14:17:32Z
6,522,273
8
2011-06-29T14:23:53Z
[ "python", "database", "django" ]
Is it possible to change active database dynamically in Django? For example, use one DB for inserts and updates and switch to other for readonly operations.
This is possible by configuring multiple databases in your settings and then using a router to specify which database configuration should be used for read and write. Go to <https://docs.djangoproject.com/en/1.3/topics/db/multi-db/#database-routers> and look for "MasterSlaveRouter", which has example code for exactly ...
unrar archive while downloading it
6,522,281
4
2011-06-29T14:24:18Z
6,527,691
7
2011-06-29T21:49:27Z
[ "python", "download", "archive", "rar", "unrar" ]
I've got a program that downloads part01, then part02 etc of a rar file split across the internet. My program downloads part01 first, then part02 and so on. After some tests, I found out that using, on example, UnRAR2 for python I can extract the first part of the file (an .avi file) contained in the archive and I'm ab...
You are talking about an .avi file inside the rar archives. Are you sure the archives are actually compressed? [Video files released by the warez scene do not use compression:](http://en.wikipedia.org/wiki/Standard_%28warez%29#Packaging) > Ripped movies are still packaged due to the large filesize, but compression is ...
List of tuples to dictionary
6,522,446
30
2011-06-29T14:35:26Z
6,522,469
51
2011-06-29T14:36:56Z
[ "python", "list", "hash", "dictionary", "tuples" ]
Here's how I'm currently converting a list of tuples to dictionary in Python: ``` l = [('a',1),('b',2)] h = {} [h.update({k:v}) for k,v in l] > [None, None] h > {'a': 1, 'b': 2} ``` Is there a better way? It seems like there should be a one-liner to do this.
(Note: a "hash" is called a "dictionary" in Python.) ``` >>> my_list = [('a', 1), ('b', 2)] >>> dict(my_list) {'a': 1, 'b': 2} ```
List of tuples to dictionary
6,522,446
30
2011-06-29T14:35:26Z
6,522,475
14
2011-06-29T14:37:15Z
[ "python", "list", "hash", "dictionary", "tuples" ]
Here's how I'm currently converting a list of tuples to dictionary in Python: ``` l = [('a',1),('b',2)] h = {} [h.update({k:v}) for k,v in l] > [None, None] h > {'a': 1, 'b': 2} ``` Is there a better way? It seems like there should be a one-liner to do this.
The `dict` constructor accepts input exactly as you have it (key/value tuples). ``` >>> l = [('a',1),('b',2)] >>> d = dict(l) >>> d {'a': 1, 'b': 2} ``` From the [documentation](http://docs.python.org/library/stdtypes.html#mapping-types-dict): > For example, these all return a > dictionary equal to {"one": 1, "two":...
Why is Python running my module when I import it, and how do I stop it?
6,523,791
56
2011-06-29T16:11:12Z
6,523,852
89
2011-06-29T16:15:59Z
[ "python", "module", "python-import" ]
I have a Python program I'm building that can be run in either of 2 ways: the first is to call "python main.py" which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call "python batch.py *-file-*" which will pass over all the friendly input gatherin...
Because this is just how Python works - keywords such as `class` and `def` are *not declarations*. Instead, they are *real live statements* which are executed. If they were not executed your module would be .. empty :-) Anyway, the idiomatic approach is: ``` # stuff to run always here such as class/def def main(): ...
Why is Python running my module when I import it, and how do I stop it?
6,523,791
56
2011-06-29T16:11:12Z
6,523,855
11
2011-06-29T16:16:09Z
[ "python", "module", "python-import" ]
I have a Python program I'm building that can be run in either of 2 ways: the first is to call "python main.py" which prompts the user for input in a friendly manner and then runs the user input through the program. The other way is to call "python batch.py *-file-*" which will pass over all the friendly input gatherin...
Due to the way Python works, it is necessary for it to run your modules when it imports them. To prevent code in the module from being executed when imported, but only when run directly, you can guard it with this `if`: ``` if __name__ == "__main__": # this won't be run when imported ``` You may want to put this...
Find and Replace Values in XML using Python
6,523,886
12
2011-06-29T16:18:35Z
6,524,105
17
2011-06-29T16:33:57Z
[ "python", "xml", "replace", "find" ]
I am looking to edit XML files using python. I want to find and replace keywords in the tags. In the past, a co-worker had set up template XML files and used a "find and replace" program to replace these key words. I want to use python to find and replace these key words with values. I have been teaching myself the Ele...
The basics: ``` from xml.etree import ElementTree as et tree = et.parse(datafile) tree.find('idinfo/timeperd/timeinfo/rngdates/begdate').text = '1/1/2011' tree.find('idinfo/timeperd/timeinfo/rngdates/enddate').text = '1/1/2011' tree.write(datafile) ``` You can shorten the path if the tag name is unique. This syntax f...
python regex to replace all windows newlines with spaces
6,523,893
5
2011-06-29T16:19:02Z
6,523,923
9
2011-06-29T16:20:49Z
[ "python", "regex" ]
I did this: ``` from urllib import urlopen import nltk url = http://myurl.com html = urlopen(url).read() cleanhtml = nltk.clean_html(html) ``` I now have a long string in python which is full of text interrupted periodically by windows newlines `/r/n`, and I simply want to remove all of the occurrences of /r/n from t...
Just a small syntax error: ``` htmlspaced = re.sub(r"\r\n", " ", html) ``` should work.
python regex to replace all windows newlines with spaces
6,523,893
5
2011-06-29T16:19:02Z
6,523,927
20
2011-06-29T16:20:59Z
[ "python", "regex" ]
I did this: ``` from urllib import urlopen import nltk url = http://myurl.com html = urlopen(url).read() cleanhtml = nltk.clean_html(html) ``` I now have a long string in python which is full of text interrupted periodically by windows newlines `/r/n`, and I simply want to remove all of the occurrences of /r/n from t...
There's no need to use regular expressions, just ``` htmlspaced = html.replace('\r\n', ' ') ``` Your program didn't work since you added additional quotes, you only need one set.
Using self in Django Model classes
6,524,251
6
2011-06-29T16:45:08Z
6,524,640
7
2011-06-29T17:13:15Z
[ "python", "django", "django-models", "self" ]
While adding model class to models.py in Django, why don't we use self with the field variables which we define? Shouldn't not using self field variables make them class variables instead,which "may" cause a problem.
Django uses [metaclasses](http://www.python.org/download/releases/2.2/descrintro/#metaclasses) to create the actual class based on the class definition your provide. In brief, upon instantiation of your model class, the metaclass will run through your model field definitions and return a corresponding class with the ap...
Stopping a thread after a certain amount of time
6,524,459
29
2011-06-29T16:59:14Z
6,524,542
76
2011-06-29T17:05:06Z
[ "python", "multithreading" ]
I'm looking to terminate some threads after a certain amount of time. These threads will be running an infinite while loop and during this time they can stall for a random, large amount of time. The thread cannot last longer than time set by the duration variable. How can I make it so after the length set by duration, ...
This will work **if** you are not blocking. If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use `time.sleep()` your thread will only stop *after* it wakes up. ...
Stopping a thread after a certain amount of time
6,524,459
29
2011-06-29T16:59:14Z
6,524,564
7
2011-06-29T17:06:32Z
[ "python", "multithreading" ]
I'm looking to terminate some threads after a certain amount of time. These threads will be running an infinite while loop and during this time they can stall for a random, large amount of time. The thread cannot last longer than time set by the duration variable. How can I make it so after the length set by duration, ...
If you want the threads to stop when your program exits (as implied by your example), then make them [daemon threads](http://stackoverflow.com/questions/190010/daemon-threads-explanation). If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a che...
Writing to a file with multiprocessing
6,524,635
5
2011-06-29T17:12:38Z
6,524,704
11
2011-06-29T17:18:37Z
[ "python", "file-io", "queue", "multiprocessing" ]
I'm having the following problem in python. I need to do some calculations in parallel whose results I need to be written sequentially in a file. So I created a function that receives a `multiprocessing.Queue` and a file handle, do the calculation and print the result in the file: ``` import multiprocessing from mult...
You really should use two queues and three separate kinds of processing. 1. Put stuff into Queue #1. 2. Get stuff out of Queue #1 and do calculations, putting stuff in Queue #2. You can have many of these, since they get from one queue and put into another queue safely. 3. Get stuff out of Queue #2 and write it to a f...
How to modify pythonpath for a WSGI application in alwaysdata.net
6,525,243
3
2011-06-29T18:07:59Z
6,528,518
11
2011-06-29T23:44:20Z
[ "python", "hosting", "mod-wsgi", "wsgi", "flask" ]
I've created a small Python web application using Flask, and I wanted to host it in alwaysdata.net. I already installed mod\_wsgi in my subdomain, but when I try to import the main module of my app it fails because it can't be found. All the files are in the /www folder. Should I place my files somewhere else? I tried...
The current working directory under mod\_wsgi will not be where the WSGI script is located, so you shouldn't be using os.getcwd(). See: <http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Application_Working_Directory> To do what you want, use: ``` sys.path.append(os.path.dirname(__file__)) ``` This is calcula...
How to delete a s3 version from a bucket using boto and python
6,525,270
9
2011-06-29T18:11:22Z
6,627,277
17
2011-07-08T16:12:03Z
[ "python", "amazon-s3", "boto", "versions" ]
When I try to delete a bucket using the lines: ``` conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) print conn.delete_Bucket('BucketNameHere').message ``` It tells me the bucket I tried to delete is not empty. The bucket has no keys in it. But it does have versions. How can I delete the versions? ...
Boto does support versioned buckets after version 1.9c. Here's how it works: ``` import boto s3 = boto.connect_s3() #Create a versioned bucket bucket = s3.create_bucket("versioned.example.com") bucket.configure_versioning(True) #Create a new key and make a few versions key = new_key("versioned_object") key.set_cont...
Getting file extension using pattern matching in python
6,525,334
3
2011-06-29T18:16:50Z
6,525,387
13
2011-06-29T18:21:50Z
[ "python", "regex" ]
I am trying to find the extension of a file, given its name as a string. I know I can use the function `os.path.splitext` but it does not work as expected in case my file extension is `.tar.gz` or `.tar.bz2` as it gives the extensions as `gz` and `bz2` instead of `tar.gz` and `tar.bz2` respectively. So I decided to f...
``` root,ext = os.path.splitext('a.tar.gz') if ext in ['.gz', '.bz2']: ext = os.path.splitext(root)[1] + ext ``` Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
How can I make a deepcopy of a function in Python?
6,527,633
10
2011-06-29T21:44:20Z
6,528,148
18
2011-06-29T22:46:04Z
[ "python", "function", "copy", "deep-copy" ]
I would like to make a deepcopy of a function in Python. The *copy* module is not helpful, according to the [documentation](http://docs.python.org/library/copy.html), which says: > This module does not copy types like module, method, stack trace, stack frame, file, > socket, window, array, or any similar types. It doe...
The FunctionType constructor is used to make a deep copy of a function. ``` import types def copy_func(f, name=None): return types.FunctionType(f.func_code, f.func_globals, name or f.func_name, f.func_defaults, f.func_closure) def A(): """A""" pass B = copy_func(A, "B") B.__doc__ = """B""" ```
Speed up python code for computing matrix cofactors
6,527,641
7
2011-06-29T21:45:35Z
6,528,024
11
2011-06-29T22:31:48Z
[ "python", "matrix", "performance", "numpy", "linear-algebra" ]
As part of a complex task, I need to compute [matrix cofactors](http://en.wikipedia.org/wiki/Cofactor_%28linear_algebra%29). I did this in a straightforward way using this [nice code for computing matrix minors](http://stackoverflow.com/questions/3858213/numpy-routine-for-computing-matrix-minors). Here is my code: ```...
If your matrix is invertible, the cofactor is related to the inverse: ``` def matrix_cofactor(matrix): return np.linalg.inv(matrix).T * np.linalg.det(matrix) ``` This gives large speedups (~ 1000x for 50x50 matrices). The main reason is fundamental: this is an `O(n^3)` algorithm, whereas the minor-det-based one i...
Python config parser that supports section inheritance?
6,528,137
9
2011-06-29T22:45:16Z
6,532,314
9
2011-06-30T08:53:47Z
[ "python", "config", "ini" ]
I'm looking for an ini style config parser in Python that supports section inheritance similar to what [Zend\_Config\_Ini](http://framework.zend.com/manual/en/zend.config.adapters.ini.html) does in PHP. Does such a module exist or will I need to roll my own?
Python's ConfigParser can load multiple files. Files read later on can override settings from the first file. For example, my application has database settings in its internal default configuration file: ``` [database] server = 127.0.0.1 port = 1234 ... ``` I override these on a different server with a "environment....
Improving performance of raytracing hit function
6,528,214
13
2011-06-29T22:54:43Z
6,528,506
7
2011-06-29T23:42:46Z
[ "python", "performance" ]
I have a simple raytracer in python. rendering an image 200x200 takes 4 minutes, which is definitely too much for my taste. I want to improve the situation. Some points: I shoot multiple rays per each pixel (to provide antialiasing) for a grand total of 16 rays per pixel. 200x200x16 is a grand total of 640000 rays. Ea...
1) Ray tracing is fun but if you care at all about performance, dump python and switch to C. Not C++ unless you are some kind of super expert, just C. 2) The big win in scenes with multiple (20 or more) objects is to use a spatial index to reduce the number of intersection tests. Popular options are kD-trees, OctTrees...
Change value of currently iterated element in list in python
6,528,848
8
2011-06-30T00:38:45Z
6,528,907
19
2011-06-30T00:52:05Z
[ "python" ]
problem: when you use construction > for a in *list*: > print a it prints every item in array. But you can't alter array. Is it possible to alter value of array (something like a=123, but that ain't working) I know it's possible (for example in while loop), but I want to do it this way (more elegant) In PHP it would...
``` for idx, a in enumerate(foo): foo[idx] = a + 42 ``` Note though, that if you're doing this, you probably should look into list comprehensions (or `map`), unless you really want to mutate in place (just don't insert or remove items from iterated-on list). The same loop written as a list comprehension looks lik...
How are lambda expressions bound to a class?
6,530,110
7
2011-06-30T04:59:40Z
6,530,189
15
2011-06-30T05:10:41Z
[ "python" ]
If I set up a class like below in Python, as I expect the lambda expressions created should be bound to the class A. I don't understand why when I put a lambda inside a list like in `g` it isn't bound. ``` class A(object): f = lambda x,y: (x + y) g = [lambda x,y: (x + y)] a = A() #a.f bound print a.f <bound met...
`f` is bound because it's a part of the class as per the definition. `g` is not a method. `g` is a list. The first element of this list incidentally happens to be a lambda expression. That's got nothing to do with whether `g` is defined inside a class definition or not.
Get the version of Django for application
6,530,231
18
2011-06-30T05:17:42Z
6,530,280
18
2011-06-30T05:25:20Z
[ "python", "django", "django-admin", "django-templates", "mod-python" ]
I am starting a new (actually very old) project which I know is in Django. I am getting lost knowing the exact version of Django it has been build upon. Is there a way I can know the version of Django my application is running?
The only way is to take a guess. I would start by looking at the created date of the settings.py file (or other base project files) Release dates for versions: * 1.0: September 2008. (?) * 1.1: July 29, 2009 [[1](https://docs.djangoproject.com/en/dev/releases/1.1/)] * 1.2: May 17, 2010 [[2](https://docs.djangoproject...
Get the version of Django for application
6,530,231
18
2011-06-30T05:17:42Z
6,530,586
10
2011-06-30T06:06:38Z
[ "python", "django", "django-admin", "django-templates", "mod-python" ]
I am starting a new (actually very old) project which I know is in Django. I am getting lost knowing the exact version of Django it has been build upon. Is there a way I can know the version of Django my application is running?
You can guess based on the way settings.py is laid out. Your first hint would be from [database settings](https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs#databases). The old way prior to Django 1.2 was: ``` DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3'...
How to check if a string contains an element from a list in Python
6,531,482
48
2011-06-30T07:41:19Z
6,531,661
9
2011-06-30T07:57:13Z
[ "if-statement", "python" ]
I have something like this: ``` extensionsToCheck = ['.pdf', '.doc', '.xls'] for extension in extensionsToCheck: if extension in url_string: print(url_string) ``` I am wondering what would be the more elegant way to do this in python (without using the for loop)? I was thinking of something like this (li...
It is better to parse the URL properly - this way you can handle `http://.../file.doc?foo` and `http://.../foo.doc/file.exe` correctly. ``` from urlparse import urlparse import os path = urlparse(url_string).path ext = os.path.splitext(path)[1] if ext in extensionsToCheck: print(url_string) ```
How to check if a string contains an element from a list in Python
6,531,482
48
2011-06-30T07:41:19Z
6,531,678
11
2011-06-30T07:57:58Z
[ "if-statement", "python" ]
I have something like this: ``` extensionsToCheck = ['.pdf', '.doc', '.xls'] for extension in extensionsToCheck: if extension in url_string: print(url_string) ``` I am wondering what would be the more elegant way to do this in python (without using the for loop)? I was thinking of something like this (li...
``` extensionsToCheck = ('.pdf', '.doc', '.xls') 'test.doc'.endswith(extensionsToCheck) # returns True 'test.jpg'.endswith(extensionsToCheck) # returns False ```
How to check if a string contains an element from a list in Python
6,531,482
48
2011-06-30T07:41:19Z
6,531,704
108
2011-06-30T08:00:47Z
[ "if-statement", "python" ]
I have something like this: ``` extensionsToCheck = ['.pdf', '.doc', '.xls'] for extension in extensionsToCheck: if extension in url_string: print(url_string) ``` I am wondering what would be the more elegant way to do this in python (without using the for loop)? I was thinking of something like this (li...
Use a generator together with `any`, which short-circuits on the first True: ``` if any(ext in url_string for ext in extensionsToCheck): print(url_string) ``` **EDIT:** I see this answer has been accepted by OP. Though my solution may be "good enough" solution to his particular problem, and is a good general way ...
Separate number/letter tokens in Python
6,532,065
3
2011-06-30T08:30:11Z
6,532,247
7
2011-06-30T08:47:04Z
[ "python", "regex", "split" ]
I'm using `re.split()` to separate a string into tokens. Currently the pattern I'm using as the argument is `[^\dA-Za-z]`, which retrieves alphanumeric tokens from the string. However, what I need is to also split tokens that have both numbers and letters into tokens with only one or the other, eg. ``` re.split(patte...
Try the findall method instead. ``` >>> print re.findall ('[^\d ]+', "my t0kens"); ['my', 't', 'kens'] >>> print re.findall ('[\d]+', "my t0kens"); ['0'] >>> ``` Edit: Better way from Bart's comment below. ``` >>> print re.findall('[a-zA-Z]+|\\d+', "my t0kens") ['my', 't', '0', 'kens'] >>> ```
Can I have some code constantly run inside Django like a daemon
6,532,744
13
2011-06-30T09:31:31Z
6,532,835
13
2011-06-30T09:38:24Z
[ "python", "django", "daemon", "daemons", "python-daemon" ]
I'm using mod\_wsgi to serve a django site through Apache. I also have some Python code that runs as a background process (dameon?). It keeps polling a server and inserts data into one of the Django models. This works fine but can I have this code be a part of my Django application and yet able to constantly run in the...
You could either set up a cron job that runs some function you have defined, or - the more advanced and probably recommended method, integrate [celery](http://celeryproject.org/) in your project (which is quite easy, actually).
Can I have some code constantly run inside Django like a daemon
6,532,744
13
2011-06-30T09:31:31Z
6,533,128
9
2011-06-30T10:05:01Z
[ "python", "django", "daemon", "daemons", "python-daemon" ]
I'm using mod\_wsgi to serve a django site through Apache. I also have some Python code that runs as a background process (dameon?). It keeps polling a server and inserts data into one of the Django models. This works fine but can I have this code be a part of my Django application and yet able to constantly run in the...
You could create a background thread from the WSGI script when it is first being imported. ``` import threading import time def do_stuff(): time.sleep(60) ... do periodic job _thread = threading.Thread(target=do_stuff) _thread.setDaemon(True) _thread.start() ``` For this to work though you would have to be ...
How to make a copy of a 2D array in Python?
6,532,881
17
2011-06-30T09:43:40Z
6,532,908
19
2011-06-30T09:46:36Z
[ "python", "arrays", "object", "copy", "variable-assignment" ]
`X` is a 2D array. I want to have a new variable `Y` that which has the same value as the array `X`. Moreover, **any further manipulations with Y should not influence the value of the X.** It seems to me so natural to use `y = x`. But it does not work with arrays. If I do it this way and then changes y, the x will be ...
Try this: ``` from copy import copy, deepcopy y = deepcopy(x) ``` I'm not sure, maybe [`copy()`](http://docs.python.org/library/copy.html) is sufficient.
How to make a copy of a 2D array in Python?
6,532,881
17
2011-06-30T09:43:40Z
6,533,065
28
2011-06-30T09:59:33Z
[ "python", "arrays", "object", "copy", "variable-assignment" ]
`X` is a 2D array. I want to have a new variable `Y` that which has the same value as the array `X`. Moreover, **any further manipulations with Y should not influence the value of the X.** It seems to me so natural to use `y = x`. But it does not work with arrays. If I do it this way and then changes y, the x will be ...
Using deepcopy() or copy() is a good solution. For a simple 2D-array case ``` y = [row[:] for row in x] ```
When should the save method be called in Django?
6,534,038
5
2011-06-30T11:31:03Z
6,534,097
7
2011-06-30T11:36:13Z
[ "python", "django" ]
Should the save method be called after every `create` method or does calling the `create` method automatically call the `save` method? If the `save` method is called automatically after creating an object then what would be a good use-case for the `save` method? Thanks.
No `save()` does not need to be called after `create()`. from the [docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/#create) for create: > A convenience method for creating an object and saving it all in one step its to be used in place of creating an object the normal way then saving with object.sav...
Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)
6,534,430
44
2011-06-30T12:03:17Z
6,534,808
13
2011-06-30T12:34:38Z
[ "python", "algorithm", "language-design", "permutation" ]
It is universally agreed that a list of n *distinct* symbols has n! permutations. However, when the symbols are not distinct, the most common convention, in mathematics and elsewhere, seems to be to count only distinct permutations. Thus the permutations of the list `[1, 1, 2]` are usually considered to be `[1, 1, 2]...
It's fairly easy to get the behavior you prefer by wrapping `itertools.permutations`, which might have influenced the decision. As described in the documentation, `itertools` is designed as a collection of building blocks/tools to use in building your own iterators. ``` def unique(iterable): seen = set() for x...
Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)
6,534,430
44
2011-06-30T12:03:17Z
6,534,998
25
2011-06-30T12:47:46Z
[ "python", "algorithm", "language-design", "permutation" ]
It is universally agreed that a list of n *distinct* symbols has n! permutations. However, when the symbols are not distinct, the most common convention, in mathematics and elsewhere, seems to be to count only distinct permutations. Thus the permutations of the list `[1, 1, 2]` are usually considered to be `[1, 1, 2]...
I can't speak for the designer of `itertools.permutations` (Raymond Hettinger), but it seems to me that there are a couple of points in favour of the design: First, if you used a `next_permutation`-style approach, then you'd be restricted to passing in objects that support a linear ordering. Whereas `itertools.permuta...
Why does Python's itertools.permutations contain duplicates? (When the original list has duplicates)
6,534,430
44
2011-06-30T12:03:17Z
6,571,976
14
2011-07-04T13:10:02Z
[ "python", "algorithm", "language-design", "permutation" ]
It is universally agreed that a list of n *distinct* symbols has n! permutations. However, when the symbols are not distinct, the most common convention, in mathematics and elsewhere, seems to be to count only distinct permutations. Thus the permutations of the list `[1, 1, 2]` are usually considered to be `[1, 1, 2]...
I'm accepting the answer of Gareth Rees as the most appealing explanation (short of an answer from the Python library designers), namely, that Python's `itertools.permutations` doesn't compare the values of the elements. Come to think of it, this is what the question asks about, but I see now how it could be seen as an...
Creating a simple scripting language in Python
6,535,748
10
2011-06-30T13:46:19Z
6,535,797
16
2011-06-30T13:49:58Z
[ "python", "xml", "scripting" ]
I'm creating a GUI application that can monitor and manipulate a stream of messages. I'm trying to create a simple means to let the user script some of this functionality and I'm looking for possible candidates. Initially I wanted to use XML since it can naturally take care of embedded code: ``` <if> <condition> ...
How about Python [itself](http://docs.python.org/py3k/library/code.html)? For example: ``` >>> import code >>> def host_func(): ... print("Hello old chap!") ... >>> c = code.compile_command("print(\"Script says hello!\"); host_func()") >>> exec(c) Script says hello! Hello old chap! ``` [`exec`](http://docs.pytho...
Python: Inherit the superclass __init__
6,535,832
36
2011-06-30T13:51:37Z
6,535,884
29
2011-06-30T13:55:24Z
[ "python", "inheritance", "constructor", "init" ]
I have a base class with a lot of `__init__` arguments: ``` def BaseClass(object): def __init__(self, a, b, c, d, e, f, ...): self._a=a+b self._b=b if b else a ... ``` All the inheriting classes should run `__init__` method of the base class. I can write a `__init__()` method in each of t...
``` super(SubClass, self).__init__(...) ``` Consider using \*args and \*\*kw if it helps solving your variable nightmare.
Python: Inherit the superclass __init__
6,535,832
36
2011-06-30T13:51:37Z
6,535,962
17
2011-06-30T14:01:01Z
[ "python", "inheritance", "constructor", "init" ]
I have a base class with a lot of `__init__` arguments: ``` def BaseClass(object): def __init__(self, a, b, c, d, e, f, ...): self._a=a+b self._b=b if b else a ... ``` All the inheriting classes should run `__init__` method of the base class. I can write a `__init__()` method in each of t...
You have to write it explicitly, but on the other hand, if you have lots of args, you should probably use \*args for positional args and \*\*kwargs for keyword args. ``` class SubClass(BaseClass): def __init__(self, *args, **kwargs): super(SubClass, self).__init__(*args, **kwargs) # SubClass initia...
Python: Inherit the superclass __init__
6,535,832
36
2011-06-30T13:51:37Z
6,536,135
10
2011-06-30T14:12:52Z
[ "python", "inheritance", "constructor", "init" ]
I have a base class with a lot of `__init__` arguments: ``` def BaseClass(object): def __init__(self, a, b, c, d, e, f, ...): self._a=a+b self._b=b if b else a ... ``` All the inheriting classes should run `__init__` method of the base class. I can write a `__init__()` method in each of t...
If the derived classes don't implement anything beyond what the base class `__init__()` already does, just omit the derived classes `__init__()` methods - the base class `__init__()` is then called automatically. If, OTOH, your derived classes add some extra work in their `__init__()`, and you don't want them to expli...
Multithreading performance overhead
6,537,448
3
2011-06-30T15:44:53Z
6,537,497
9
2011-06-30T15:48:08Z
[ "python", "multithreading" ]
So basically I created this program that adds values to redis. So far I get this timing: ``` real 0m27.759s user 0m18.129s sys 0m5.580s ``` However when I tried to run multiple threads: ``` if __name__ == '__main__': try: for x in range(0, NUM_THREADS): Thread(None, startProgram, None, ...
The result depends on the Python implementation, cpython's [GIL](http://wiki.python.org/moin/GlobalInterpreterLock) prevents parallel computations from being faster than sequential ones. Consider using the [`multiprocessing`](http://docs.python.org/library/multiprocessing.html) module, which executes each thread in it...
Python: Making a beep noise
6,537,481
34
2011-06-30T15:47:09Z
6,537,563
55
2011-06-30T15:53:13Z
[ "python", "audio", "serial-port" ]
I'm trying to get the program to give me a beeping noise. I'm on a windows machine. I've looked at <http://docs.python.org/library/winsound.html> But not sure how I can program this with a barcode scanner. Here is my code for the serial barcode scanner. ``` ser = serial.Serial() ser.baudrate = 9600 #for windows ser...
If you want to just make the computer make a beep sound: ``` import winsound Freq = 2500 # Set Frequency To 2500 Hertz Dur = 1000 # Set Duration To 1000 ms == 1 second winsound.Beep(Freq,Dur) ``` The winsound.Beep can be used wherever you want the Beep to occur.
Python: Making a beep noise
6,537,481
34
2011-06-30T15:47:09Z
6,537,650
60
2011-06-30T15:59:30Z
[ "python", "audio", "serial-port" ]
I'm trying to get the program to give me a beeping noise. I'm on a windows machine. I've looked at <http://docs.python.org/library/winsound.html> But not sure how I can program this with a barcode scanner. Here is my code for the serial barcode scanner. ``` ser = serial.Serial() ser.baudrate = 9600 #for windows ser...
The cross-platform way to do this is to `print '\a'`. This will send the ASCII Bell character to stdout, and will hopefully generate a beep (a for 'alert'). Note that many modern terminal emulators provide the option to ignore bell characters. Since you're on Windows, you'll be happy to hear that Windows has its own (...
python scipy Delaunay plotting point cloud
6,537,657
5
2011-06-30T16:00:11Z
6,541,755
12
2011-06-30T22:19:29Z
[ "python", "scipy", "triangulation", "delaunay" ]
I have a pointlist=[p1,p2,p3...] where p1 = [x1,y1],p2=[x2,y2] ... I want to use scipy.spatial.Delaunay to do trianglation on these point clouds and then plot it How can i do this ? The documentation for the Delaunay is really scarce so far i have this code ``` from subprocess import Popen, PIPE import os os.env...
**EDIT**: plot also the convex hull ``` import numpy as np from scipy.spatial import Delaunay points = np.random.rand(30, 2) # 30 points in 2-d tri = Delaunay(points) # Make a list of line segments: # edge_points = [ ((x1_1, y1_1), (x2_1, y2_1)), # ((x1_2, y1_2), (x2_2, y2_2)), # ......
Breaking at a member function in the Python debugger
6,537,662
2
2011-06-30T16:00:34Z
6,537,986
7
2011-06-30T16:27:14Z
[ "python", "debugging" ]
This should be a trivial question, but my search so far has been fruitless: I'm using the Python debugger (pdb) for the first time, and was quite pleased to find most of the commands familiar from using gdb. However, when I went to set a breakpoint in the *parse*() member of class *JamParser* with the statement: ```...
You need to import names before you can refer to them in the debugger. ``` (Pdb) from jam2dot import JamParser (Pdb) b JamParser.parse ```
Am I using super() correctly?
6,538,147
6
2011-06-30T16:41:39Z
6,538,193
8
2011-06-30T16:45:03Z
[ "python", "oop", "inheritance", "super" ]
I made a small chunk of code because I'm still trying to figure out the specifics of using `super()`. Why does this chunk run to this `TypeError`? ``` a = SecondClass() TypeError: __init__() takes exactly 2 arguments (1 given) ``` Then, the `SecondClass.meth()` function is supposed to print the string, but I'm clear...
This isn't anything to do with `super`. You don't define an `__init__` for `SecondClass` explicitly - but, because it inherits from `FirstClass`, it inherits `FirstClass`'s `__init__`. So you can't instantiate the object without passing in the `value` parameter. **Edit** OK. The first point, as others have mentioned, ...
Installing Pygame for Python 3.1.2 in Ubuntu
6,539,472
6
2011-06-30T18:35:32Z
10,227,363
8
2012-04-19T11:48:08Z
[ "python", "ubuntu", "pygame" ]
I'm reading the book *Introduction to Computer Science Using Python and Pygame* by Paul Craven (note: legally available for free online). In the book, he uses a combination of Python 3.1.3 and Pygame 1.9.1 . In my Linux Ubuntu machine, I have Python 3.1.2 but even after I sudo apt-get installed python-pygame (version 1...
PyGame on Python 3 remains experimental, but these steps worked for me on Ubuntu 11.10: ``` sudo apt-get install mercurial python3-dev libjpeg-dev libpng12-dev libportmidi-dev libsdl-image1.2-dev libsdl-mixer1.2-dev libsdl-ttf2.0-dev libsdl1.2-dev libsmpeg-dev libx11-dev ttf-freefont libavformat-dev libswscale-dev hg ...
Python: Converting from ISO-8859-1/latin1 to UTF-8
6,539,881
53
2011-06-30T19:12:46Z
6,539,919
69
2011-06-30T19:16:11Z
[ "python", "character-encoding" ]
I have this string that has been decoded from Quoted-printable to ISO-8859-1 with the email module. This gives me strings like "\xC4pple" which would correspond to "Äpple" (Apple in Swedish). However, I can't convert those strings to UTF-8. ``` >>> apple = "\xC4pple" >>> apple '\xc4pple' >>> apple.encode("UTF-8") Tra...
Try decoding it first, then encoding: ``` apple.decode('iso-8859-1').encode('utf8') ```
Python: Converting from ISO-8859-1/latin1 to UTF-8
6,539,881
53
2011-06-30T19:12:46Z
6,539,920
9
2011-06-30T19:16:31Z
[ "python", "character-encoding" ]
I have this string that has been decoded from Quoted-printable to ISO-8859-1 with the email module. This gives me strings like "\xC4pple" which would correspond to "Äpple" (Apple in Swedish). However, I can't convert those strings to UTF-8. ``` >>> apple = "\xC4pple" >>> apple '\xc4pple' >>> apple.encode("UTF-8") Tra...
Decode to Unicode, encode the results to UTF8. apple.decode('latin1').encode('utf8')
Python: Converting from ISO-8859-1/latin1 to UTF-8
6,539,881
53
2011-06-30T19:12:46Z
6,539,952
100
2011-06-30T19:18:30Z
[ "python", "character-encoding" ]
I have this string that has been decoded from Quoted-printable to ISO-8859-1 with the email module. This gives me strings like "\xC4pple" which would correspond to "Äpple" (Apple in Swedish). However, I can't convert those strings to UTF-8. ``` >>> apple = "\xC4pple" >>> apple '\xc4pple' >>> apple.encode("UTF-8") Tra...
This is a common problem, so here's a relatively thorough illustration. For non-unicode strings (i.e. those without `u` prefix like `u'\xc4pple'`), one must decode from the native encoding (`iso8859-1`/`latin1`, unless [modified with the enigmatic `sys.setdefaultencoding`](http://stackoverflow.com/q/2276200/19212) fun...
Color matplotlib plot_surface command with surface gradient
6,539,944
12
2011-06-30T19:18:18Z
6,543,777
33
2011-07-01T05:03:54Z
[ "python", "matlab", "matplotlib" ]
I would like to convert surf command from **MATLAB** to plot\_surface command in **matplotlib**. The challenge I am facing is when using *cmap* function in plot\_surface command to color the surface with gradient. Here is the **matlab** script ``` % Matlab Commands x = -5:.25:5; y = x [x,y] = meshgrid(x); R = sqrt(x...
First, it looks like you want the colors mapped from gradient magnitude. You are trying to use the gradient vectors which is why you are getting the 'list' error. Second, you can supply a cmap, but it only defines how you want the Z values mapped to a color. If you want new face colors then use the [`facecolors` argum...
(Are there) PERFORMANCE advantages of python socketserver over regular socket object?
6,540,284
10
2011-06-30T19:47:55Z
6,570,488
8
2011-07-04T10:54:01Z
[ "python", "sockets", "asynchronous", "synchronous", "socketserver" ]
thanks for the interesting responses thus far. In light of said responses I have changed my question a bit. guess what I really need to know is, is socketserver as opposed to the straight-up socket library designed to handle both periods of latency and stress, i.e. **does it have additional mechanisms or features that...
The socket module is a very low-level module for sending and receiving packets. As said in the documentation, it "provides access to the BSD socket interface". If you want something more elaborate, there is "socketserver" that takes care of the gory details for you, *but* it is still relatively low level. On top of t...
Multiple splits on a single line in Python
6,540,957
2
2011-06-30T20:49:44Z
6,540,988
7
2011-06-30T20:53:17Z
[ "python", "split" ]
I would like to know if there is a more compact (or Pythonic) way of doing several splits of some input string. Now I'm doing: ``` [a,bc,de] = 'a,b:c,d/e'.split(',') [b,c] = bc.split(':') [d,e] = de.split('/') ```
I'd use the regular expression library. You don't need to use lists for unpacking, you can use tuples as below. ``` import re regex = re.compile(r'[,:/]') a, b, c, d, e = regex.split('a,b:c,d/e') ```
Improve subplot size/spacing with many subplots in matplotlib
6,541,123
97
2011-06-30T21:09:11Z
6,541,454
94
2011-06-30T21:45:11Z
[ "python", "matplotlib" ]
Very similar to [this question](http://stackoverflow.com/questions/2418125/matplotlib-subplots-adjust-hspace-so-titles-and-xlabels-dont-overlap) but with the difference that my figure can be as large as it needs to be. I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved...
You can use plt.subplots\_adjust to change the spacing between the subplots [Link](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.subplots_adjust) ``` subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) left = 0.125 # the left side of the subplots of the ...
Improve subplot size/spacing with many subplots in matplotlib
6,541,123
97
2011-06-30T21:09:11Z
9,827,668
29
2012-03-22T17:43:54Z
[ "python", "matplotlib" ]
Very similar to [this question](http://stackoverflow.com/questions/2418125/matplotlib-subplots-adjust-hspace-so-titles-and-xlabels-dont-overlap) but with the difference that my figure can be as large as it needs to be. I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved...
I found that subplots\_adjust(hspace = 0.001) is what ended up working for me. When I use space = None, there is still white space between each plot. Setting it to something very close to zero however seems to force them to line up. What I've uploaded here isn't the most elegant piece of code, but you can see how the h...
Improve subplot size/spacing with many subplots in matplotlib
6,541,123
97
2011-06-30T21:09:11Z
9,827,848
140
2012-03-22T17:55:12Z
[ "python", "matplotlib" ]
Very similar to [this question](http://stackoverflow.com/questions/2418125/matplotlib-subplots-adjust-hspace-so-titles-and-xlabels-dont-overlap) but with the difference that my figure can be as large as it needs to be. I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved...
Try using [`plt.tight_layout`](http://matplotlib.sourceforge.net/users/tight_layout_guide.html) As a quick example: ``` import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=4, ncols=4) fig.tight_layout() # Or equivalently, "plt.tight_layout()" plt.show() ``` --- Without Tight Layout ![enter image desc...
Improve subplot size/spacing with many subplots in matplotlib
6,541,123
97
2011-06-30T21:09:11Z
15,086,636
19
2013-02-26T10:25:19Z
[ "python", "matplotlib" ]
Very similar to [this question](http://stackoverflow.com/questions/2418125/matplotlib-subplots-adjust-hspace-so-titles-and-xlabels-dont-overlap) but with the difference that my figure can be as large as it needs to be. I need to generate a whole bunch of vertically-stacked plots in matplotlib. The result will be saved...
``` import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,60)) plt.subplots_adjust( ... ) ``` The **plt.subplots\_adjust** method: ``` def subplots_adjust(*args, **kwargs): """ call signature:: subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) Tune t...
Is POS tagging deterministic?
6,541,141
8
2011-06-30T21:11:03Z
6,541,296
8
2011-06-30T21:26:59Z
[ "python", "nlp", "machine-learning", "nltk" ]
I have been trying to wrap my head around why this is happening but am hoping someone can shed some light on this. I am trying to tag the following text: ``` ae0.475 X mod ae0.842 X mod ae0.842 X mod ae0.775 X mod ``` using the following code: ``` import nltk file = open("test", "r") for ...
My best effort to understand uncovered [this](http://nltk.googlecode.com/svn/trunk/doc/howto/tag.html) from someone not using the whole Brown corpus: > Note that words that the tagger has > not seen before, such as decried, > receive a tag of None. So, I guess something that looks like `ae1.111` must appear in the co...
UnicodeDecodeError: 'ascii' codec can't decode
6,541,256
8
2011-06-30T21:21:46Z
6,541,289
15
2011-06-30T21:26:13Z
[ "python", "file", "encoding", "decoding", "representation" ]
I'm reading a file that contains Romanian words in Python with file.readline(). I've got problem with many characters because of encoding. Example : ``` >>> a = "aberație" #type 'str' >>> a -> 'abera\xc8\x9bie' >>> print sys.stdin.encoding UTF-8 ``` I've tried encode() with utf-8, cp500 etc, but it doesn't work. ...
What are you trying to do? This is a set of bytes: ``` BYTES = 'abera\xc8\x9bie' ``` It's a set of bytes which represents a `utf-8` encoding of the string "aberație". You *decode* the bytes to get your unicode string: ``` >>> BYTES 'abera\xc8\x9bie' >>> print BYTES aberaÈ›ie >>> abberation = BYTES.decode('utf...
Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'
6,541,767
7
2011-06-30T22:21:17Z
6,542,236
30
2011-06-30T23:39:59Z
[ "python", "python-3.x", "urllib" ]
Note: This is Python 3, there is no urllib2. Also, I've tried using json.loads(), and I get this error: ``` TypeError: can't use a string pattern on a bytes-like object ``` I get this error if I use json.loads() and remove the .read() from response: ``` TypeError: expected string or buffer ``` > ``` import urllib....
Try this: ``` jsonResponse = json.loads(response.decode('utf-8')) ```
Fullscreen with pyqt4?
6,541,771
9
2011-06-30T22:22:05Z
6,541,995
18
2011-06-30T22:56:03Z
[ "python", "pyqt", "fullscreen" ]
I'm new to pyqt and I've been looking for some docs about pyqt and fullscreen mode. but I couldn't find nothing. So here is my question: is there any way to run a PyQT 4 application on fullscreen?
use **showFullScreen()** on your widget.
Basic question about string joining in python
6,541,900
3
2011-06-30T22:41:54Z
6,541,927
11
2011-06-30T22:45:47Z
[ "python", "string" ]
I want to join strings `my_string = "I am good."` such that it should be printing the same my\_string 3 times, as in `my_string*3` with a space in between each full sentence. How do I do it? something like `str.join(' ',my_string*3)`? I know this a basic question, but I want to know this. Thank you in advance, Sammed
You're pretty close. Try this: ``` >>> my_string = "I am good." >>> " ".join([my_string]*3) 'I am good. I am good. I am good.' ``` You need `[my_string]*3` instead of `my_string*3` because you want a list containing the string three times (that can then be joined) instead of having a single big string containing the ...
Check to ensure a string does not contain multiple values
6,542,801
5
2011-07-01T01:36:53Z
6,542,815
14
2011-07-01T01:39:58Z
[ "python", "algorithm", "string" ]
\*\*Note- I will not just be testing at the end of a string-- need to locate particular substrings anywhere in the string What is the fastest way to check to make sure a string does not contain multiple values. My current method is inefficient and unpythonic: ``` if string.find('png') ==-1 and sring.find('jpg') ==-1 ...
Try: ``` if not any(extension in string for extension in ('jpg', 'png', 'gif')): ``` which is basically the same as your code, but more elegantly written.
Querying a many-to-many relationship in SQLAlchemy
6,542,967
14
2011-07-01T02:16:12Z
6,543,089
18
2011-07-01T02:42:23Z
[ "python", "sqlalchemy" ]
I have a pretty standard many-to-many relationship, similar to the Blog -> Keyword relationship in the ORM tutorial. I would like to query for a list of Keywords, returning Blog posts where any of them match. However, I can't work out if there is a simple way to do this. If I add multiple filters, repeatedly doing ``...
I think you just want ``` .filter(Blog.keywords.any(Keyword.name.in_(['keyword1', 'keyword2', ...]))) ``` I'm using <http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators> for reference
Setting LD_LIBRARY_PATH from inside Python
6,543,847
8
2011-07-01T05:16:00Z
25,457,751
7
2014-08-23T01:57:14Z
[ "python", "linux", "fontforge" ]
Is there a way to set specify *during runtime* where Python looks for shared libraries? I have `fontforge.so` located in `fontforge_bin` and tried the following ``` os.environ['LD_LIBRARY_PATH']='fontforge_bin' sys.path.append('fontforge_bin') import fontforge ``` and get ``` ImportError: fontforge_bin/fontforge.so...
Your script can check for the existence/properness of the environment variable before you import your module, then set it in os.environ if it is missing, and then call [os.execv()](https://docs.python.org/2/library/os.html#os.execv) to restart the python interpreter using the same command line arguments but an updated ...
How do I find the numbers that are not listed or missing?
6,544,403
5
2011-07-01T06:30:41Z
6,544,439
12
2011-07-01T06:35:19Z
[ "python", "bash" ]
I'll have a list of numbers, each on its own line (say 0 -100). How do I find the numbers that are not listed or missing?
Add them all to a set. Then subtract from a set filled with 1-100. Here's an example for 0-9: ``` >>> set(range(10)) - set([1, 4, 5, 6, 8, 2]) set([0, 9, 3, 7]) >>> ``` I had `[1, 4, 5, 6, 8, 2]` listed. To find out which numbers in range 0-9 are missing, I created a set with all of 0-9 and then subtracted the set wi...
How to sort IP addresses stored in dictionary in Python?
6,545,023
8
2011-07-01T07:40:49Z
6,545,088
7
2011-07-01T07:48:51Z
[ "python", "sorting", "dictionary", "ip" ]
I have a piece of code that looks like this: ``` ipCount = defaultdict(int) for logLine in logLines: date, serverIp, clientIp = logLine.split(" ") ipCount[clientIp] += 1 for clientIp, hitCount in sorted(ipCount.items), key=operator.itemgetter(0)): print(clientIp) ``` and it kind of sorts IP's, but like ...
Use the key parameter of sorted to convert your ip to an integer, for example: ``` list_of_ips = ['192.168.204.111', '192.168.99.11', '192.168.102.105'] sorted(list_of_ips, key=lambda ip: long(''.join(["%02X" % long(i) for i in ip.split('.')]), 16)) ``` EDIT: Gryphius proposes a solution with the socket module, and ...
How to sort IP addresses stored in dictionary in Python?
6,545,023
8
2011-07-01T07:40:49Z
6,545,090
18
2011-07-01T07:49:12Z
[ "python", "sorting", "dictionary", "ip" ]
I have a piece of code that looks like this: ``` ipCount = defaultdict(int) for logLine in logLines: date, serverIp, clientIp = logLine.split(" ") ipCount[clientIp] += 1 for clientIp, hitCount in sorted(ipCount.items), key=operator.itemgetter(0)): print(clientIp) ``` and it kind of sorts IP's, but like ...
You can use a custom `key` function to return a sortable representation of your strings: ``` def split_ip(ip): """Split a IP address given as string into a 4-tuple of integers.""" return tuple(int(part) for part in ip.split('.')) def my_key(item): return split_ip(item[0]) items = sorted(ipCount.items(), ...
Get index of recently appended item
6,545,426
6
2011-07-01T08:25:53Z
6,545,463
12
2011-07-01T08:29:24Z
[ "python", "list" ]
Is there a straightforward way to get the index of an item I just appended to a list? I need to keep track of the last added item. I came up with two possible solutions: ``` # Workaround 1 # The last added is the one at index len(li) - 1 >> li = ['a', 'b', 'c',] >> li.append('d') >> last_index = len(li) - 1 >> last_i...
`li[-1]` is the last item in the list, and hence the one that was most recently appended to its end: ``` >>> li = [1, 2, 3] >>> li.append(4) >>> li[-1] 4 ``` If you need the index, not the item, then `len(li) - 1` is just fine, and very efficient (since `len(li)` is computed in constant time - see below) --- In the...
how to create uncollectable garbage in python?
6,546,823
6
2011-07-01T10:34:51Z
6,546,909
11
2011-07-01T10:43:40Z
[ "python", "garbage-collection" ]
I have a large long-running server, and, over weeks the memory usage steadily climbs. Generally, as pointed out below, its unlikely that leaks are my problem; however, I have not got a lot to go on so I want to see if there are any leaks. Getting at console output is tricky so I'm not running with `gc.set_debug()`. T...
Any cycle of finalizable objects (that is, objects with a `__del__` method) is uncollectable (because the garbage collector does not know which order to run the finalizers in): ``` >>> class Finalizable: ... def __del__(self): pass ... >>> a = Finalizable() >>> b = Finalizable() >>> a.x = b >>> b.x = a >>> del a >...
Initializing object variables - a Java approach, a Python approach?
6,547,649
8
2011-07-01T11:58:39Z
6,547,813
9
2011-07-01T12:15:05Z
[ "python" ]
I have an object that needs to have some 4-5 values passed to it. To illustrate: ``` class Swoosh(): spam = '' eggs = '' swallow = '' coconut = '' [... methods ...] ``` Right now, the way to use `Swoosh` is: ``` swoosh = Swoosh() swoosh.set_spam('Spam!') swoosh.set_eggs('Eggs!') swoosh.set_swall...
First of all, this: ``` class Swoosh(): spam = '' eggs = '' swallow = '' coconut = '' ``` sets *class* attributes `spam`, `eggs`, etc. Your set\_spam method would then presumably go ahead and create *object* attributes of the same name that hide the class attributes. In other words, defining these att...
Initializing object variables - a Java approach, a Python approach?
6,547,649
8
2011-07-01T11:58:39Z
6,547,818
14
2011-07-01T12:15:25Z
[ "python" ]
I have an object that needs to have some 4-5 values passed to it. To illustrate: ``` class Swoosh(): spam = '' eggs = '' swallow = '' coconut = '' [... methods ...] ``` Right now, the way to use `Swoosh` is: ``` swoosh = Swoosh() swoosh.set_spam('Spam!') swoosh.set_eggs('Eggs!') swoosh.set_swall...
Firstly you're using old style classes. You **really, really** should be using [new style classes that inherit from `object`](http://docs.python.org/glossary.html#term-new-style-class): ``` class Swoosh(object): ``` Defining an `__init__` method that takes arguments is definitely the Pythonic way of doing things: ``...