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 |
|---|---|---|---|---|---|---|---|---|---|
Key Order in Python Dictionaries | 5,629,023 | 24 | 2011-04-12T00:21:38Z | 5,629,050 | 25 | 2011-04-12T00:25:30Z | [
"python",
"dictionary"
] | Code:
```
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
```
This prints ['a', 'c', 'b']. I'm unsure of how the method **keys** determines the order of the keywords within **l**. However, I'd like to be able to retrive the keywords in the "proper" order. The proper order of course would create the list ['a', 'b',... | You could use [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) (requires Python 2.7) or higher.
Also, note that `OrderedDict({'a': 1, 'b':2, 'c':3})` won't work since the `dict` you create with `{...}` has already forgotten the order of the elements. Instead, you want to use `Orde... |
Getting Every File in a Directory, Python | 5,629,242 | 8 | 2011-04-12T00:59:20Z | 5,629,275 | 8 | 2011-04-12T01:04:31Z | [
"python",
"windows",
"folder"
] | I have a folder in Windows 7 which contains multiple .txt files. How would one go about getting every file in said directory as a list? | You can use [`os.listdir(".")`](http://docs.python.org/library/os.html#os.listdir) to list the contents of the current directory ("."):
```
for name in os.listdir("."):
if name.endswith(".txt"):
print(name)
```
If you want the whole list as a Python list, use a *list comprehension*:
```
a = [name for nam... |
Tkinter Option Menu Widget Changing Widths | 5,629,745 | 5 | 2011-04-12T02:27:50Z | 5,634,157 | 7 | 2011-04-12T11:03:10Z | [
"python",
"tkinter",
"optionmenu"
] | I have a snippet here which creates a Tkinter Option Menu widget. One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?
Snippet:
```
options = ... | When you use the `grid` command to place the widget in its parent, have the widget fill its cell (try `sticky="ew"`) |
Tkinter Option Menu Widget Changing Widths | 5,629,745 | 5 | 2011-04-12T02:27:50Z | 5,636,417 | 9 | 2011-04-12T13:58:41Z | [
"python",
"tkinter",
"optionmenu"
] | I have a snippet here which creates a Tkinter Option Menu widget. One problem I've encountered is every time a new option is selected, the width of the widget changes. I believe this is due to the text within the widget changing widths. How do I make the widget hold a consistent width?
Snippet:
```
options = ... | To the best of my knowledge you can use `optionmenu.config(width=width)` I know this works before packing the widget but have never tried it before grid.
*Edit:* I just tested it and it does work with grid. I placed it like this:
```
...
optionmenu = Tkinter.OptionMenu(par, var, *options)
optionmenu.config(width=widt... |
Python Regular Expressions, find Email Domain in Address | 5,629,907 | 6 | 2011-04-12T02:57:38Z | 5,630,275 | 13 | 2011-04-12T04:03:50Z | [
"python",
"regex",
"email",
"search",
"dns"
] | I know I'm an idiot, but I can't pull the domain out of this email address:
```
'blahblah@gmail.com'
```
My desired output:
```
'@gmail.com'
```
My current output:
```
.
```
(it's just a period character)
Here's my code:
```
import re
test_string = 'blahblah@gmail.com'
domain = re.search('@*?\.', test_string)
p... | Here's something I think might help
```
import re
s = 'My name is Conrad, and blahblah@gmail.com is my email.'
domain = re.search("@[\w.]+", s)
print domain.group()
```
outputs
```
@gmail.com
```
How the regex works:
`@` - scan till you see this character
`[\w.]` a set of characters to potentially match, so `\w` ... |
How do Rpy2, pyrserve and PypeR compare? | 5,630,441 | 46 | 2011-04-12T04:32:07Z | 5,638,613 | 12 | 2011-04-12T16:31:26Z | [
"python",
"rpy2",
"pyrserve",
"pyper"
] | I would like to access R from within a Python program. I am aware of Rpy2, pyrserve and PypeR.
What are the advantages or disadvantages of these three options? | From the paper in the [Journal of Statistical Software on PypeR](http://www.jstatsoft.org/v35/c02):
> RPy presents a simple and efficient way of accessing R from Python. It is robust and very
> convenient for frequent interaction operations between Python and R. This package allows
> Python programs to pass Python obj... |
How do Rpy2, pyrserve and PypeR compare? | 5,630,441 | 46 | 2011-04-12T04:32:07Z | 5,643,423 | 29 | 2011-04-13T01:19:17Z | [
"python",
"rpy2",
"pyrserve",
"pyper"
] | I would like to access R from within a Python program. I am aware of Rpy2, pyrserve and PypeR.
What are the advantages or disadvantages of these three options? | I know one of the 3 better than the others, but in the order given in the question:
rpy2:
* C-level interface between Python and R (R running as an embedded process)
* R objects exposed to Python without the need to copy the data over
* Conversely, Python's numpy arrays can be exposed to R without making a copy
* Low... |
SQLAlchemy: print the actual query | 5,631,078 | 51 | 2011-04-12T06:12:00Z | 5,698,357 | 33 | 2011-04-18T03:53:48Z | [
"python",
"sqlalchemy"
] | I'd really like to be able to print out valid SQL for my application, including values, rather than bind parameters, but it's not obvious how to do this in SQLAlchemy (by design, I'm fairly sure).
Has anyone solved this problem in a general way? | This works in python 2 and 3 and is a bit cleaner than before, but requires SA>=1.0.
```
from sqlalchemy.engine.default import DefaultDialect
from sqlalchemy.sql.sqltypes import String, DateTime, NullType
# python2/3 compatible.
PY3 = str is not bytes
text = str if PY3 else unicode
int_type = int if PY3 else (int, lo... |
SQLAlchemy: print the actual query | 5,631,078 | 51 | 2011-04-12T06:12:00Z | 9,898,141 | 7 | 2012-03-27T21:41:07Z | [
"python",
"sqlalchemy"
] | I'd really like to be able to print out valid SQL for my application, including values, rather than bind parameters, but it's not obvious how to do this in SQLAlchemy (by design, I'm fairly sure).
Has anyone solved this problem in a general way? | This code is based on brilliant [existing answer](http://stackoverflow.com/a/5698357/1296661) from @bukzor. I just added custom render for `datetime.datetime` type into Oracle's `TO_DATE()`.
Feel free to update code to suit your database:
```
import decimal
import datetime
def printquery(statement, bind=None):
"... |
SQLAlchemy: print the actual query | 5,631,078 | 51 | 2011-04-12T06:12:00Z | 23,835,766 | 45 | 2014-05-23T18:05:19Z | [
"python",
"sqlalchemy"
] | I'd really like to be able to print out valid SQL for my application, including values, rather than bind parameters, but it's not obvious how to do this in SQLAlchemy (by design, I'm fairly sure).
Has anyone solved this problem in a general way? | In the vast majority of cases, the "stringification" of a SQLAlchemy statement or query is as simple as:
```
print str(statement)
```
This applies both to an ORM `Query` as well as any `select()` or other statement.
**Note**: the following detailed answer is being maintained on the [sqlalchemy documentation](http://... |
Displaying graphs/charts in Django | 5,631,247 | 14 | 2011-04-12T06:33:59Z | 16,811,752 | 9 | 2013-05-29T10:42:07Z | [
"python",
"django",
"charts"
] | I'm making a report app in Django that involves plenty of graphs and charts.
Is there an easy graphing library/module that allows me to achieve this workflow:
1. Execute my SQL queries
2. Parse the returned data to the graphing library/module
3. Graphing library/module manipulates the data into a chart/graph which I ... | You might want to look at
[Django Graphos](https://github.com/agiliq/django-graphos)
It supports lot of backends, and integrates well with Django orm, but can work with other data sources too.
### Chart types supported
Flot
* Line chart
* Bar Chart
* Point Chart
Google Charts
* Line chart
* Column chart
* Bar ch... |
How to get exit code when using Python subprocess communicate method? | 5,631,624 | 99 | 2011-04-12T07:11:02Z | 5,631,819 | 135 | 2011-04-12T07:29:23Z | [
"python",
"subprocess"
] | How do I retrieve the exit code when using Python's `subprocess` module and the `communicate()` method?
Relevant code:
```
import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
```
Should I be doing this another way? | `Popen.communicate` will set the `returncode` attribute when it's done(\*). Here's the relevant documentation section:
```
Popen.returncode
The child return code, set by poll() and wait() (and indirectly by communicate()).
A None value indicates that the process hasnât terminated yet.
A negative value -N in... |
What is the difference between sqlite3 and sqlalchemy? | 5,632,677 | 6 | 2011-04-12T08:54:45Z | 5,632,745 | 13 | 2011-04-12T09:01:22Z | [
"python",
"sqlite",
"sqlalchemy"
] | Beginner question- what is the difference between sqlite and sqlalchemy? | They're apples and oranges.
Sqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retrieve structured data from files.
SQLAlchemy is a Python library that provides an object relational mapper (ORM). It does what it suggests... |
Getting n most recent emails using IMAP and Python | 5,632,713 | 6 | 2011-04-12T08:58:05Z | 5,641,178 | 8 | 2011-04-12T20:22:19Z | [
"python",
"email",
"imap"
] | I'm looking to return the n (most likely 10) most recent emails from an email accounts inbox using IMAP.
So far I've cobbled together:
```
import imaplib
from email.parser import HeaderParser
M = imaplib.IMAP4_SSL('my.server')
user = 'username'
password = 'password'
M.login(user, password)
M.search(None, 'ALL')
for ... | The sort command is available, but it is not guaranteed to be supported by the IMAP server. For example, Gmail does not support the SORT command.
To try the sort command, you would replace:
`M.search(None, 'ALL')`
with
`M.sort(search_critera, 'UTF-8', 'ALL')`
Then `search_criteria` would be a string like:
```
... |
Google App Engine Datastore multiline entries not displayed as multiline in HTML | 5,633,265 | 4 | 2011-04-12T09:45:51Z | 5,634,098 | 8 | 2011-04-12T10:57:56Z | [
"python",
"google-app-engine",
"multiline"
] | Using the Google App Store guestbook demo as an example, when entering a entry over multiple lines and storing it, when read back and displayed it appears on one single line.
How can we make it appear excactly as it was originally entered, over multiple lines?
The databasemodel is like this:
```
class Greeting(db.M... | Html ignores EOL special characters like `\r\n` or `\n`.
Here are some options:
1. Replace the special characters with the proper html `<br>` tag
2. Wrap the multiline text inside a `<pre>` tag
3. In case you are using webapp templating, try with `{{greeting.content|linebreaks}}` as suggested by *@wooble*
4. Set `whi... |
In python, super() is always called first in a method. Are there situations where it should be called later? | 5,634,221 | 12 | 2011-04-12T11:09:21Z | 5,634,272 | 14 | 2011-04-12T11:15:24Z | [
"python",
"super"
] | Are there situations where you want to do some processing before you call super()?
This is a contrived example. Are there better examples? Is this considered pythonic?
```
class Base(object):
def __init__(self, name):
print "Base %s created" % name
self._name = name
class UpperBase(A):
""" Si... | Sometimes you need to validate the arguments before calling `super()`:
```
class UpperBase(Base):
def __init__(self, name):
if not name_valid(name):
raise ValueError()
super(UpperBase, self).__init__(name)
```
I don't see why this wouldn't be pythonic, because it's the easiest way to d... |
python __init__ method in inherited class | 5,636,419 | 18 | 2011-04-12T13:58:47Z | 5,636,453 | 12 | 2011-04-12T14:00:56Z | [
"python",
"oop",
"inheritance"
] | I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an `__init__` type method which does not override the `__init__` method of the parent class?
I have written the code below purely to illustrate my question (hence ... | Just call the parent's `__init__` using `super`:
```
class inheritedclass(initialclass):
def __new__(self):
self.attr3 = 'three'
super(initialclass, self).__init__()
```
I strongly advise to follow Python's naming conventions and start a class with a Capital letter, e.g. `InheritedClass` and `Init... |
python __init__ method in inherited class | 5,636,419 | 18 | 2011-04-12T13:58:47Z | 5,636,463 | 30 | 2011-04-12T14:01:36Z | [
"python",
"oop",
"inheritance"
] | I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an `__init__` type method which does not override the `__init__` method of the parent class?
I have written the code below purely to illustrate my question (hence ... | As far as I know that's not possible, however you can call the init method of the superclass, like this:
```
class inheritedclass(initialclass):
def __init__(self):
initialclass.__init__(self)
self.attr3 = 'three'
``` |
Why does python thread consume so much memory? | 5,636,660 | 3 | 2011-04-12T14:14:51Z | 5,637,673 | 9 | 2011-04-12T15:24:35Z | [
"python",
"multithreading"
] | Why does python thread consumes so much memory?
I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process!
OS: Ubuntu 10.10
Edit: due to popular demand I'll give some extraneous examples, here it is:
```
from os import getpid
from time import sleep
from threading imp... | This is not Python-specific, and has to do with the separate stack that gets allocated by the OS for every thread. The default maximum stack size on your OS happens to be 8MB.
Note that the 8MB is simply a chunk of address space that gets set aside, with very little memory committed to it initially. Additional memory ... |
Tab completion in Python's raw_input() | 5,637,124 | 42 | 2011-04-12T14:44:09Z | 5,638,688 | 52 | 2011-04-12T16:38:07Z | [
"python",
"raw-input"
] | i know i can do this to get the effect of tab completion in python sure.
```
import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
'email', 'foobar', 'foo']
def complete(text, state):
for cmd in COMMANDS:
if cmd.startswith(text):
if not state:
return ... | Here is a quick example of how to perform incremental completion of file system paths. I've modified your example, organizing it into a class where methods named `complete_[name]` indicate top-level commands.
I've switched the completion function to use the internal readline buffer to determine the state of the overal... |
Django: using user.get_profile() | 5,637,620 | 2 | 2011-04-12T15:21:22Z | 5,637,850 | 10 | 2011-04-12T15:36:42Z | [
"python",
"django",
"django-authentication"
] | I have a very newbie question on using django auth. Here is my model:
```
class UserProfile(models.Model):
""" Main user profile used on a website """
user = models.ForeignKey(User, unique=True) # reference to built in django user
display_name = models.CharField(max_length=100, blank=True)
... | You should be able to use a `OneToOneField(User, related_name='profile')` in your UserProfile model and then do `Post.objects.select_related('author__profile')`. |
Only extract those words from a list that include no repeating letters, using regex | 5,637,963 | 2 | 2011-04-12T15:43:51Z | 5,638,110 | 7 | 2011-04-12T15:53:03Z | [
"python",
"regex",
"perl",
"grep"
] | I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.
```
INPUT:
abducts
abe
abeam
abel
abele
OUTPUT:
abducts
abe
abel
```
I'd like to do this using Regex (grep or perl or python). Is that possible? | It's much easier to write a regex that matches words that *do* have repeating letters, and then negate the match:
```
my @input = qw(abducts abe abeam abel abele);
my @output = grep { not /(\w).*\1/ } @input;
```
(This code assumes that `@input` contains one word per entry.) But this problem isn't necessarily best so... |
How to write Big files into Blobstore using experimental API? | 5,638,894 | 11 | 2011-04-12T16:56:22Z | 5,643,563 | 7 | 2011-04-13T01:45:27Z | [
"python",
"google-app-engine",
"blobstore",
"tipfy",
"scribd"
] | I have dilemma.. I'm uploading files both in scribd store and blobstore using tipfy as framework.
I have webform with action is not created by blobstore.create\_upload\_url (i'm just using url\_for('myhandler')). I did it because if i'm using blobstore handler the POST response parsed and I cannot use normal python-scr... | You need to make multiple, smaller calls to the file API, for instance like this:
```
with files.open(file_name, 'a') as f:
data = uploaded_file.read(65536)
while data:
f.write(data)
data = uploaded_file.read(65536)
```
Note that the payload size limit on regular requests to App Engine apps is 10M... |
Why NUMPY correlate and corrcoef return different values and how to "normalize" a correlate in "full" mode? | 5,639,280 | 13 | 2011-04-12T17:33:18Z | 5,639,626 | 17 | 2011-04-12T18:04:01Z | [
"python",
"numpy",
"normalization",
"time-series",
"correlation"
] | I'm trying to use some Time Series Analysis in Python, using Numpy.
I have two somewhat medium-sized series, with 20k values each and I want to check the sliding correlation.
The corrcoef gives me as output a Matrix of auto-correlation/correlation coefficients. Nothing useful by itself in my case, as one of the serie... | You are looking for normalized cross-correlation. This option isn't available yet in Numpy, but [a patch](http://projects.scipy.org/numpy/ticket/1714) is waiting for review that does just what you want. It shouldn't be too hard to apply it I would think. Most of the patch is just doc string stuff. The only lines of cod... |
array filter in python? | 5,640,630 | 23 | 2011-04-12T19:40:13Z | 5,640,665 | 9 | 2011-04-12T19:42:39Z | [
"python",
"list",
"filter"
] | For example, I have two lists
```
A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = [6, 9, 12]; # the subset of A
the result should be [7, 8, 10, 11]; the remaining elements
```
Is there a built-in function in python to do this? | Yes, the `filter` function:
```
filter(lambda x: x not in subset_of_A, A)
``` |
array filter in python? | 5,640,630 | 23 | 2011-04-12T19:40:13Z | 5,640,701 | 35 | 2011-04-12T19:45:09Z | [
"python",
"list",
"filter"
] | For example, I have two lists
```
A = [6, 7, 8, 9, 10, 11, 12]
subset_of_A = [6, 9, 12]; # the subset of A
the result should be [7, 8, 10, 11]; the remaining elements
```
Is there a built-in function in python to do this? | If the order is not important, you should use `set.difference`. However, if you want to retain order, a simple list comprehension is all it takes.
```
result = [a for a in A if a not in subset_of_A]
```
**EDIT:** As delnan says, performance will be substantially improved if `subset_of_A` is an actual `set`, since che... |
Sanitizing HTML in submitted form data | 5,641,901 | 23 | 2011-04-12T21:34:22Z | 5,642,146 | 22 | 2011-04-12T22:03:26Z | [
"python",
"django",
"forms",
"sanitization"
] | Is there a generic "form sanitizer" that I can use to ensure all html/scripting is stripped off the submitted form? form.clean() doesn't seem to do any of that - html tags are all still in cleaned\_data. Or actually doing this all manually (and override the clean() method for the form) is my only option? | Django comes with a template filter called [striptags](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#striptags), which you can use in a template:
```
value|striptags
```
It uses the function `strip_tags` which lives in `django.utils.html`. You can utilize it also to clean your form data:
... |
Sanitizing HTML in submitted form data | 5,641,901 | 23 | 2011-04-12T21:34:22Z | 7,159,905 | 35 | 2011-08-23T10:53:33Z | [
"python",
"django",
"forms",
"sanitization"
] | Is there a generic "form sanitizer" that I can use to ensure all html/scripting is stripped off the submitted form? form.clean() doesn't seem to do any of that - html tags are all still in cleaned\_data. Or actually doing this all manually (and override the clean() method for the form) is my only option? | strip\_tags actually removes the tags from the input, which may not be what you want.
To convert a string to a "safe string" with angle brackets, ampersands and quotes converted to the corresponding HTML entities, you can use the [escape](https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#escap... |
Sanitizing HTML in submitted form data | 5,641,901 | 23 | 2011-04-12T21:34:22Z | 30,528,160 | 8 | 2015-05-29T11:15:28Z | [
"python",
"django",
"forms",
"sanitization"
] | Is there a generic "form sanitizer" that I can use to ensure all html/scripting is stripped off the submitted form? form.clean() doesn't seem to do any of that - html tags are all still in cleaned\_data. Or actually doing this all manually (and override the clean() method for the form) is my only option? | Alternatively, there is a Python library called [bleach](https://bleach.readthedocs.org/en/latest/index.html):
> Bleach is a whitelist-based HTML sanitization and text linkification library. It is designed to take untrusted user input with *some* HTML.
>
> Because Bleach uses `html5lib` to parse document fragments the... |
Tool for automatically creating data for django model | 5,642,323 | 9 | 2011-04-12T22:23:00Z | 5,642,396 | 16 | 2011-04-12T22:31:38Z | [
"python",
"django",
"django-models",
"django-admin"
] | Is there a way to automatically create data for a django model? So I created a model with choices, text fields, foreign keys, and everything. Is there an automatic way to fill it with data? I don't really care if they are garbage values, just that it's valid within the schema.
It'd be really cool if there was a way to... | I haven't used it myself, but [django-autofixture](http://pypi.python.org/pypi/django-autofixture) looks pretty much like what you are after.
Other similar apps are listed in this grid: <https://www.djangopackages.com/grids/g/fixtures/> |
How does python numpy.where() work? | 5,642,457 | 58 | 2011-04-12T22:39:26Z | 5,642,497 | 14 | 2011-04-12T22:45:36Z | [
"python",
"numpy",
"magic-methods"
] | I am playing with `numpy` and digging through documentation and I have come across some magic. Namely I am talking about `numpy.where()`:
```
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
```
How do they achieve internally that you are able to pass something like `x > ... | **Old Answer**
it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.
so:
```
>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
... |
How does python numpy.where() work? | 5,642,457 | 58 | 2011-04-12T22:39:26Z | 5,642,525 | 54 | 2011-04-12T22:48:27Z | [
"python",
"numpy",
"magic-methods"
] | I am playing with `numpy` and digging through documentation and I have come across some magic. Namely I am talking about `numpy.where()`:
```
>>> x = np.arange(9.).reshape(3, 3)
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
```
How do they achieve internally that you are able to pass something like `x > ... | > How do they achieve internally that you are able to pass something like x > 5 into a method?
The short answer is that they don't.
Any sort of logical operation on a numpy array returns a boolean array. (i.e. `__gt__`, `__lt__`, etc all return boolean arrays where the given condition is true).
E.g.
```
x = np.aran... |
INSERT not working in cx_oracle when used with execute. How to get it working? | 5,642,708 | 2 | 2011-04-12T23:14:54Z | 16,689,730 | 8 | 2013-05-22T10:43:29Z | [
"python",
"cx-oracle",
"oracle11gr2"
] | I am new to cx\_oracle. I have established a connection and I am able to create and drop a table using execute.
Where I am failing is when I try to use "INSERT INTO ..." in execute. It doesn't show any error but it doesn't store any value either (I confirmed this by checking if the entry had taken place using sqlplus ... | How can `cursor.commit` work when the methods in Cursor do not have commit, connections has this method and hence it should be:
```
connection.commit()
```
Using `cursor.commit()` returns:
`AttributeError: 'cx_Oracle.Cursor' object has no attribute 'commit'` |
Write to a file | 5,643,206 | 2 | 2011-04-13T00:38:33Z | 5,643,237 | 9 | 2011-04-13T00:44:16Z | [
"python"
] | I have been trying to write to a file,but it kept writing them on a single line with commas, and square brackets at both ends. How do I write to a file without the square brackets, commas and newline for each rows or lines of the file. Column 6 must remained sorted in descending order.
This is the output from the code... | Each element of `lines` is *itself* an array. Try:
```
for i in lines:
outfile.write(" ".join(i) + "\n")
```
The `.join()` method takes an array `i` and concatenates all the elements together with a space `" "` between each element. Then a newline `"\n"` is added to make sure your output is broken up into separat... |
In Python, how does one catch warnings as if they were exceptions? | 5,644,836 | 34 | 2011-04-13T05:34:59Z | 5,645,133 | 16 | 2011-04-13T06:13:41Z | [
"python",
"exception",
"exception-handling",
"warnings"
] | A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the `try` `except` syntax to properly handle these warnings. Is there a way to do this? | To quote from the python handbook ([27.6.4. Testing Warnings](http://docs.python.org/library/warnings.html#testing-warnings)):
```
import warnings
def fxn():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnin... |
In Python, how does one catch warnings as if they were exceptions? | 5,644,836 | 34 | 2011-04-13T05:34:59Z | 7,207,340 | 8 | 2011-08-26T15:48:40Z | [
"python",
"exception",
"exception-handling",
"warnings"
] | A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the `try` `except` syntax to properly handle these warnings. Is there a way to do this? | Here's a variation that makes it clearer how to work with only your custom warnings.
```
import warnings
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Call some code that triggers a custom warning.
functionThatRaisesWarni... |
In Python, how does one catch warnings as if they were exceptions? | 5,644,836 | 34 | 2011-04-13T05:34:59Z | 30,368,735 | 9 | 2015-05-21T08:46:55Z | [
"python",
"exception",
"exception-handling",
"warnings"
] | A third-party library (written in C) that I use in my python code is issuing warnings. I want to be able to use the `try` `except` syntax to properly handle these warnings. Is there a way to do this? | To handle warnnings as errors simply use this:
```
import warnings
warnings.filterwarnings("error")
```
After this you will be able to catch warnnings same as errors, e.g. this will work:
```
try:
some_heavy_calculations()
except RuntimeWarning:
import ipdb; ipdb.set_trace()
```
P.S. Added this answer becau... |
How to run python script on my server? | 5,645,384 | 4 | 2011-04-13T06:43:26Z | 5,645,469 | 10 | 2011-04-13T06:52:45Z | [
"python"
] | I have a server hosting by Blueshot. I have been using php to get post variables from iPhone... But now I have to use python to get post variable from iPhone. I wrote something like this
```
import cgi
import cgitb; cgitb.enable() # for troubleshooting
print "Content-type: text/html"
print
print """
<html>
<head><... | Here's a small checklist of things to check when CGI scripts aren't working:
* Is it in a `cgi-bin` (or equivalent) folder?
* Is it executable?
* Is it readable?
* Does it have a hashbang?
* Is your server set up to process CGI scripts?
Here's a sample CGI script you can use for testing:
```
#!/usr/bin/env python
im... |
Python - suds - no module | 5,646,364 | 4 | 2011-04-13T08:24:17Z | 5,647,556 | 15 | 2011-04-13T10:14:00Z | [
"python",
"web-services",
"suds"
] | I've installed Python 2.7.1, setuptools and suds 0.4.
When running my script, I'm having the following error:
Traceback (most recent call last):
File "C:\Python27\test.py", line 5, in
from suds.client import Client # suds soap client
ImportError: No module named suds.client
It looks like Python can't find the suds l... | Sounds like suds is not actually installed.
Since you have setuptools, try:
```
easy_install https://fedorahosted.org/releases/s/u/suds/python-suds-0.4.tar.gz
``` |
Is it possible to do partial inheritance with Python? | 5,647,118 | 7 | 2011-04-13T09:31:53Z | 5,647,219 | 7 | 2011-04-13T09:41:43Z | [
"python",
"class",
"inheritance"
] | I'm creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single method. Is it possible for class0 to only inherit a single... | One path is to use the 'mixin' approach:
```
class Mixin(object):
def method(self):
pass
class C1(Mixin, ...parents...):
pass
class C2(Mixin, ...parents...):
pass
```
Another way is the composition:
```
class C1(object):
def method(self):
pass
class C2(object):
def __init__(sel... |
How hard is it to build an Email client? - Python | 5,647,487 | 9 | 2011-04-13T10:08:35Z | 5,648,907 | 20 | 2011-04-13T12:06:42Z | [
"python",
"email",
"smtp",
"imap",
"email-client"
] | I'm venturing in unknown territory here...
I am trying to work out how hard it could be to implement an Email client using Python:
* Email retrieval
* Email sending
* Email formatting
* Email rendering
Also I'm wondering if all protocols are easy/hard to support e.g. SMTP, IMAP, POP3, ...
---
Hopefully someone cou... | The Python language does offer raw support for the needed protocols in its standard library. Properly using then, and, properly parsing and assembling a "modern day" e-mail message, however can be tough to do.
Also, you didn't say if you want to create a graphical interface for your e-mail client -- if you want to hav... |
Scope in a python class surprising behaviour | 5,648,070 | 2 | 2011-04-13T11:00:23Z | 5,648,143 | 8 | 2011-04-13T11:06:41Z | [
"python",
"oop"
] | The following code will result in the print statement being executed
```
class C1(object):
print 'I am some code executing in C1'
def method1(self):
print 'I am method1'
def method2(self):
print 'I am method2'
pass
```
I am surprised by this as I would have thought it would only ... | I guess you mean that it prints 'I am some code executing in C1'?
It's printed when the class object is created, and in this case that happens when you load the file it's declared in. This is also the place where you put class variables (which can be used as Python's equivalent of static variables in other languages).... |
How to add an xml-stylesheet processing instruction node with Python 2.6 and minidom? | 5,648,343 | 4 | 2011-04-13T11:21:44Z | 5,651,055 | 7 | 2011-04-13T14:40:31Z | [
"python",
"xml",
"stylesheet",
"minidom",
"processing-instruction"
] | I'm creating an XML document using minidom - how do I ensure my resultant XML document contains a stylesheet reference like this:
```
<?xml-stylesheet type="text/xsl" href="mystyle.xslt"?>
```
Thanks ! | Use something like this:
```
from xml.dom import minidom
xml = """
<root>
<x>text</x>
</root>"""
dom = minidom.parseString(xml)
pi = dom.createProcessingInstruction('xml-stylesheet',
'type="text/xsl" href="mystyle.xslt"')
root = dom.firstChild
dom.insertBefore(pi, root)
print d... |
Unicode - String - list Manipulation | 5,648,532 | 3 | 2011-04-13T11:37:56Z | 5,648,725 | 9 | 2011-04-13T11:51:34Z | [
"python",
"string",
"unicode",
"operation"
] | I have a data `s = u"[u'38', u'36', u'34', u'32']"` which has data type unicode
i want to make this data as simple list of element like `s= ['38','36','32']`,
i try to use simplejson.loads but its not working simple json work with the ('["s"]') this type of string not ("['s']") so any buddy please guide me to get of ... | ```
>>> import ast
>>> s = u"[u'38', u'36', u'34', u'32']"
>>> [ item.encode('ascii') for item in ast.literal_eval(s) ]
['38', '36', '34', '32']
``` |
Python print unicode strings in arrays as characters, not code points | 5,648,573 | 26 | 2011-04-13T11:41:10Z | 5,648,769 | 42 | 2011-04-13T11:55:01Z | [
"python",
"unicode"
] | If I've got a dictionary of the form:
`a = {u"foo": u"ááá "}`
and I write
`>>> print a[u"foo"]`
I get
`ááá`
as expected. But if I write
`>>> print a`
I get
`{u'foo': u'\u10d1\u10d0\u10e0'}`, but I would prefer the characters themselves to be printed.
All the data will ultimately get dumped into a da... | This works in my terminal:
```
print repr(a).decode("unicode-escape")
``` |
Is there a python builtin to create tuples from multiple lists? | 5,648,794 | 7 | 2011-04-13T11:56:54Z | 5,648,826 | 15 | 2011-04-13T11:59:07Z | [
"python",
"transpose",
"list-manipulation",
"builtins"
] | Is there a python builtin that does the same as tupler for a set of lists, or something similar:
```
def tupler(arg1, *args):
length = min([len(arg1)]+[len(x) for x in args])
out = []
for i in range(length):
out.append(tuple([x[i] for x in [arg1]+args]))
return out
```
so, for example:
```
tu... | I think you're looking for [`zip()`](http://docs.python.org/library/functions.html#zip):
```
>>> zip([1,2,3,4],[5,6,7])
[(1, 5), (2, 6), (3, 7)]
``` |
End of nonblocking file | 5,648,969 | 18 | 2011-04-13T12:12:07Z | 5,896,830 | 14 | 2011-05-05T11:17:01Z | [
"python",
"file",
"nonblocking",
"eof"
] | How is end of file detected for a file in nonblocking mode? | At least on POSIX (including Linux), the obvious answer is that nonblocking regular files don't exist. Regular files ALWAYS block, and O\_NONBLOCK is silently ignored.
Similarly, poll()/select() et al. will always tell you that a fd pointing to a regular file is ready for I/O, regardless of whether the data is ready i... |
hexadecimal string to byte array in python | 5,649,407 | 53 | 2011-04-13T12:43:58Z | 5,682,984 | 81 | 2011-04-15T22:32:21Z | [
"python",
"bytearray"
] | I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type. | Suppose your hex string is something like
```
>>> hex_string = "deadbeef"
```
### Convert it to a string:
```
>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"
```
### Convert it to a byte array
```
>>> import array
>>> array.array('B', hex_data)
array.array('B', [0xDE, 0xAD, 0xBE, 0xEF])
```... |
hexadecimal string to byte array in python | 5,649,407 | 53 | 2011-04-13T12:43:58Z | 13,363,076 | 81 | 2012-11-13T15:01:18Z | [
"python",
"bytearray"
] | I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type. | There is a built-in function in bytearray that does what you intend.
```
bytearray.fromhex("de ad be ef 00")
```
It returns a bytearray and it reads hex strings with or without space separator. |
Setting Network settings from Python/Django on a Linux/Ubuntu machine | 5,650,965 | 4 | 2011-04-13T14:34:00Z | 5,651,243 | 7 | 2011-04-13T14:53:37Z | [
"python",
"django",
"networking",
"ubuntu",
"ip"
] | I'm working on a simple web interface for an embedded computer. The computer will ship with a static default ip that will then need to be updated by the install tech who may not be tech/linux savvy.
Basicly I need to change the following system settings from a Django app.
1. IP Addres
2. Subnet
3. Default Gateway
4. ... | Have a look at pynetlinux on Github:
<https://github.com/rlisagor/pynetlinux>
It is a good starting point and you can add the remaining functionality yourself quite easily I would imagine. |
How to raise Suds.WebFault from python code? | 5,651,623 | 5 | 2011-04-13T15:19:19Z | 5,679,346 | 7 | 2011-04-15T15:54:55Z | [
"python",
"suds",
"fault",
"raise"
] | I am trying to raise a Suds.WebFault from python code. The `__init__` method\constructor takes three arguments `__init__(self, fault, document)`. The fault has fault.faultcode and fault.detail members\attributes\properties. I could not find out what class fault belongs to no matte what I tried. How do I raise Suds.WebF... | Not sure what exactly you are asking but you can throw a web fault using:
```
import suds
try:
client.service.Method(parameter)
except suds.WebFault, e:
print e
``` |
Django Want to print the date & time for today | 5,651,763 | 3 | 2011-04-13T15:30:27Z | 5,652,026 | 36 | 2011-04-13T15:49:38Z | [
"python",
"django",
"datetime",
"date",
"views"
] | I want to print some sort of time stamp or some sort of function to tell what day and time it is in a template. In my views I have
```
time = datetime.now()
```
and in my template I have
```
{{time}}
```
All this does is prints out a `<type 'datetime.date'>` object. | if its just in the template, use [now](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#now)
```
It is {% now "f" %}
``` |
Receiving TypeError while trying to write to file in Python | 5,651,784 | 3 | 2011-04-13T15:31:43Z | 5,651,844 | 12 | 2011-04-13T15:35:46Z | [
"python",
"file-io",
"typeerror"
] | When I run this code:
```
tickers = re.findall(r'Process Name: (\w+)', s)
file = open("C:\Documents and Settings\jppavan\My Documents\My Dropbox\Python Scripts\Processes\GoodProcesses.txt","w")
file.write(tickers)
file.close()
```
It returns the common error:
> TypeError: expected a character buffer object
Any ide... | findall() as the name indicates returns a Python *list* and not a string/buffer.
You can not write a list to file handle - how should that work?
What do you expect?
```
file.write(str(tickers))
```
for the string representation of the list?
Or
```
file.write(', '.join(tickers))
```
for a comma-separated concaten... |
Python 2.7: How to check if a deque is empty? | 5,652,278 | 21 | 2011-04-13T16:11:42Z | 5,652,291 | 39 | 2011-04-13T16:12:45Z | [
"python"
] | Is try-catch the only method to do that? | If `d` is your deque, use
```
if d:
# not empty
else:
# empty
```
This will implicitly convert `d` to a `bool`, which yields `True` if the deque contains any items and `False` if it is empty. |
Using python how to find elements in a list of lists based on a key that is an element of the inner list? | 5,652,943 | 8 | 2011-04-13T17:08:07Z | 5,652,992 | 11 | 2011-04-13T17:12:39Z | [
"python"
] | Suppose I have a list of lists or a list of tuples, whichever can solve my problem more efficiently. Eg:
```
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
```
The task is to find an element in the main list based on a key that is any element of the inner list or tuple. Eg:
... | I would use `filter()` or a list comprehension.
```
def find_listcomp(students, value):
return [student for student in students if student[1] == value or student[2] == value]
def find_filter(students, value):
return filter(lambda s: s[1] == value or s[2] == value, students)
``` |
IndexError: list assignment index out of range | 5,653,533 | 77 | 2011-04-13T18:01:35Z | 5,653,546 | 13 | 2011-04-13T18:03:12Z | [
"python",
"list",
"exception"
] | Please consider the following code:
```
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
print j
```
The output (Python 2.6.6 on Win 7 32-bit) is:
```
> Traceback (most recent call last):
> j[k] = l IndexError: list assignment index out of range
```
I guess it's something simple I don... | Do `j.append(l)` instead of `j[k] = l` and avoid `k` at all. |
IndexError: list assignment index out of range | 5,653,533 | 77 | 2011-04-13T18:01:35Z | 5,653,549 | 128 | 2011-04-13T18:03:47Z | [
"python",
"list",
"exception"
] | Please consider the following code:
```
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
print j
```
The output (Python 2.6.6 on Win 7 32-bit) is:
```
> Traceback (most recent call last):
> j[k] = l IndexError: list assignment index out of range
```
I guess it's something simple I don... | `j` is an empty list, but you're attempting to write to element `[0]` in the first iteration, which doesn't exist yet.
Try the following instead, to add a new element to the end of the list:
```
for l in i:
j.append(l)
``` |
IndexError: list assignment index out of range | 5,653,533 | 77 | 2011-04-13T18:01:35Z | 9,028,197 | 22 | 2012-01-27T02:14:59Z | [
"python",
"list",
"exception"
] | Please consider the following code:
```
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
print j
```
The output (Python 2.6.6 on Win 7 32-bit) is:
```
> Traceback (most recent call last):
> j[k] = l IndexError: list assignment index out of range
```
I guess it's something simple I don... | Your other option is to initialize `j`:
```
j = [None]*max(i)
``` |
IndexError: list assignment index out of range | 5,653,533 | 77 | 2011-04-13T18:01:35Z | 9,029,759 | 7 | 2012-01-27T06:32:01Z | [
"python",
"list",
"exception"
] | Please consider the following code:
```
i = [1, 2, 3, 5, 8, 13]
j = []
k = 0
for l in i:
j[k] = l
k += 1
print j
```
The output (Python 2.6.6 on Win 7 32-bit) is:
```
> Traceback (most recent call last):
> j[k] = l IndexError: list assignment index out of range
```
I guess it's something simple I don... | For the example you posted, you could also use a list comprehension:
```
j = [l for l in i]
```
or just make a copy:
```
j = i[:]
``` |
Fastest way to update a dictionary & check for keys | 5,654,006 | 2 | 2011-04-13T18:46:27Z | 5,654,065 | 8 | 2011-04-13T18:52:11Z | [
"python",
"performance",
"dictionary",
"append"
] | I am building a dictionary of a very long string (~1G), where key is a fixed-length k-mer, and value is all the occurrence positions. When k is large (>9) it makes no sense to pre-build the k-mer dictionary, since not all values will occur & it inflates the table.
Currently I'm doing the task like this:
```
def hash_... | I would use [`collections.defaultdict`](http://docs.python.org/library/collections.html#collections.defaultdict):
```
import collections
...
hash = collections.defaultdict(list)
r = stsize-mersize+1
for i in range(0, r):
mer = st[i:i+mersize]
hash[mer].append(i)
```
though have never profiled it vs `if ... e... |
python: most elegant way to intersperse a list with an element | 5,655,708 | 17 | 2011-04-13T21:13:05Z | 5,655,803 | 9 | 2011-04-13T21:20:39Z | [
"python",
"list"
] | Input:
```
intersperse(666, ["once", "upon", "a", 90, None, "time"])
```
Output:
```
["once", 666, "upon", 666, "a", 666, 90, 666, None, 666, "time"]
```
What's the most elegant (read: Pythonic) way to write `intersperse`? | [**`itertools`**](http://docs.python.org/library/itertools.html) to the rescue
- or -
*How many itertools functions can you use in one line?*
```
from itertools import chain, izip, repeat, islice
def intersperse(delimiter, seq):
return islice(chain.from_iterable(izip(repeat(delimiter), seq)), 1, None)
```
Us... |
python: most elegant way to intersperse a list with an element | 5,655,708 | 17 | 2011-04-13T21:13:05Z | 5,656,097 | 21 | 2011-04-13T21:48:21Z | [
"python",
"list"
] | Input:
```
intersperse(666, ["once", "upon", "a", 90, None, "time"])
```
Output:
```
["once", 666, "upon", 666, "a", 666, 90, 666, None, 666, "time"]
```
What's the most elegant (read: Pythonic) way to write `intersperse`? | I would have written a generator myself, but like this:
```
def joinit(iterable, delimiter):
it = iter(iterable)
yield next(it)
for x in it:
yield delimiter
yield x
``` |
Refer to same input multiple times in string replacement? | 5,655,805 | 2 | 2011-04-13T21:20:53Z | 5,655,840 | 7 | 2011-04-13T21:24:19Z | [
"python",
"string"
] | I need to print something like this
```
"a=name1,b=name2,c=name1,d=name2"
```
While I have name1 and name2 in variable n1 n2
```
n1="name1"
n2="name2"
```
what I am trying to do
```
"a=%s,b=%s,c=%s,d=%s" % (n1,n2,n1,n2)
```
Is there a better way than this? way to avoid n1,n2,n1,n2 ?
with python 3 ?
and what if
... | ```
"a=%(name1)s,b=%(name2)s,c=%(name1)s,d=%(name2)s" % {'name1': n1, 'name2': n2}
``` |
How do I speed up iteration of large datasets in Django | 5,656,238 | 5 | 2011-04-13T22:03:54Z | 5,656,273 | 12 | 2011-04-13T22:09:16Z | [
"python",
"django"
] | I have a query set of approximately 1500 records from a Django ORM query. I have used the select\_related() and only() methods to make sure the query is tight. I have also used connection.queries to make sure there is only this one query. That is, I have made sure no extra queries are getting called on each iteration.
... | A QuerySet can get pretty heavy when it's full of model objects. In similar situations, I've used the .values method on the queryset to specify the properties I need as a list of dictionaries, which can be much faster to iterate over. <http://docs.djangoproject.com/en/1.3/ref/models/querysets/#values-list> |
Remove Max and Min values from python list of integers | 5,656,670 | 7 | 2011-04-13T22:56:23Z | 5,656,708 | 13 | 2011-04-13T23:00:42Z | [
"python",
"list",
"max",
"min"
] | I am not completely green to Python, but I am interested in learning/keeping good practices while I develop my skills.
I want to remove the high and low values from a list of numbers, which I know how to do, but am curious if there is a better/preferred way to do this.
```
mylist = [1, 4, 0, 3, 2]
mylist.sort() #[0, ... | Here's another way to do it if you don't want to change the order of the items:
```
mylist = [1, 4, 0, 3, 2]
mylist.remove(max(mylist))
mylist.remove(min(mylist))
```
Assumes that the high/low don't have any duplicates in the list, or if there are, that it's OK to remove only one of them.
This will need to do 2-4 pa... |
Python/Matplotlib - Is there a way to make a discontinuous axis? | 5,656,798 | 49 | 2011-04-13T23:13:54Z | 5,657,491 | 21 | 2011-04-14T01:11:30Z | [
"python",
"matplotlib"
] | I'm trying to create a plot using pyplot that has a discontinuous x-axis. The usual way this is drawn is that the axis will have something like this:
(values)----//----(later values)
where the // indicates that you're skipping everything between (values) and (later values).
I haven't been able to find any examples o... | I see many suggestions for this feature but no indication that it's been implemented. Here is a workable solution for the time-being. It applies a step-function transform to the x-axis. It's a lot of code, but it's fairly simple since most of it is boilerplate custom scale stuff. I have not added any graphics to indica... |
Python/Matplotlib - Is there a way to make a discontinuous axis? | 5,656,798 | 49 | 2011-04-13T23:13:54Z | 5,669,301 | 47 | 2011-04-14T20:31:42Z | [
"python",
"matplotlib"
] | I'm trying to create a plot using pyplot that has a discontinuous x-axis. The usual way this is drawn is that the axis will have something like this:
(values)----//----(later values)
where the // indicates that you're skipping everything between (values) and (later values).
I haven't been able to find any examples o... | Paul's answer is a perfectly fine method of doing this.
However, if you don't want to make a custom transform, you can just use two subplots to create the same effect.
Rather than put together an example from scratch, there's [an excellent example of this written by Paul Ivanov](https://github.com/matplotlib/matplotl... |
Which of these are immutable in Python? | 5,656,998 | 2 | 2011-04-13T23:49:09Z | 5,657,085 | 7 | 2011-04-13T23:59:45Z | [
"python",
"immutability"
] | I am trying to figure out whether the following are immutable in Sage (which is built on Python so I believe if it is immutable in python, I believe in most cases it will be immutable in Sage)
Below are objects e, f, g, i
```
class e: pass
f = e()
g = pi # (g's "type" in Sage is symbolic expression. It's supposed to ... | `e` is mutable. You can, for instance, add a new method on the class: `e.foo = lambda self,x: x`.
`f` is mutable. You can, for instance, add a new field to this class instance: `f.x = 99`.
`g` is immutable. You can't change anything about it.
`i` is not immutable. You can do all sorts of evil things to it: `i.func_c... |
Python : Tkinter widget background (buttons, entries etc) | 5,657,073 | 4 | 2011-04-13T23:58:30Z | 13,677,929 | 8 | 2012-12-03T05:57:26Z | [
"python",
"tkinter"
] | I'm having a bit of a problem in creating my GUI's. It's when changing backgrounds, I can change the whole background, and also the background of the labels and such, but when it comes to buttons and entry fields etc, there is a white area behind the button that i cannot seem to change :S
The problem can be seen in th... | I know it's been a while and you're certainly no longer working on this code, but I found a solution, and I'll post it here for everybody who has a similar issue. It's the same as the way you get the area around an entry to be your background color:
`highlightbackground=color` |
In python how can I match two lists of tuples by a tuple element? | 5,657,297 | 2 | 2011-04-14T00:33:23Z | 5,657,315 | 7 | 2011-04-14T00:35:51Z | [
"python",
"list",
"tuples"
] | Let's say I have `names` as a list of tuples that contain name tuples in arbitrary order:
```
names = [(1,"Alice"), (2,"Bob")]
```
and `genders` as another list of tuples that contain gender tuples in arbitrary order:
```
genders = [(2,"male"), (1,"female")]
```
How can I effectively match the two lists by using th... | Convert to dictionaries, gather the keys, and iterate. |
How do I convert a datetime.date object into a time.struct_time object? | 5,657,308 | 6 | 2011-04-14T00:34:58Z | 5,657,328 | 10 | 2011-04-14T00:38:42Z | [
"python",
"datetime",
"time"
] | I have a python script which I need to compare two dates. I have a list dates as time.struct\_time objects which I need to compare to a few datetime.date objects.
How do I convert the datetime.date objects into a time.struct\_time objects? Or can I just use them as is for comparison? | Try using [`date.timetuple()`](http://docs.python.org/library/datetime.html#datetime.date.timetuple). From the Python docs:
> Return a [`time.struct_time`](http://docs.python.org/library/time.html#time.struct_time) such as
> returned by `time.localtime()`. The
> hours, minutes and seconds are 0, and
> the DST flag is ... |
Python Timed-Script | 5,657,429 | 3 | 2011-04-14T00:59:35Z | 5,658,088 | 7 | 2011-04-14T03:05:56Z | [
"python"
] | How do I have a python script run everyday at a set-time. Say exactly at 2:00 P.M. every day.
Is there a way to have it run exactly twice a day?
Not really sure where to start with this. Thanks for the help. | Don't reinvent and use functionality existing for decades on any system: **cron**
Apart from that: PyPI lists a bunch of cron-related or cron-similar packages:
<http://pypi.python.org/pypi?%3Aaction=search&term=cron&submit=search>
In addition: Python provides a dedicated 'sched' module:
<http://docs.python.org/libr... |
What's the fastest way to convert an interleaved NumPy integer array to complex64? | 5,658,047 | 5 | 2011-04-14T02:57:37Z | 5,658,446 | 13 | 2011-04-14T04:14:07Z | [
"python",
"numpy",
"complex-numbers"
] | I have a stream of incoming data that has interleaved real and imaginary integers. Converting these to complex64 values is the slowest operation in my program. This is my current approach:
```
import numpy as np
a = np.zeros(1000000, dtype=np.int16)
b = np.complex64(a[::2]) + np.complex64(1j) * np.complex64(a[1::2])
... | ```
[~]
|1> import numpy as np
[~]
|2> a = np.zeros(1000000, dtype=np.int16)
[~]
|3> b = a.astype(np.float32).view(np.complex64)
[~]
|4> b.shape
(500000,)
[~]
|5> b.dtype
dtype('complex64')
``` |
How to input a regex in string.replace in python? | 5,658,369 | 90 | 2011-04-14T03:59:21Z | 5,658,377 | 21 | 2011-04-14T04:00:53Z | [
"python",
"regex",
"string",
"replace"
] | I need some help on declaring a regex. My inputs are like the following:
```
this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>
```
The required output is:
```
this is a par... | `str.replace()` does fixed replacements. Use [`re.sub()`](http://docs.python.org/library/re.html#re.sub) instead. |
How to input a regex in string.replace in python? | 5,658,369 | 90 | 2011-04-14T03:59:21Z | 5,658,439 | 181 | 2011-04-14T04:12:17Z | [
"python",
"regex",
"string",
"replace"
] | I need some help on declaring a regex. My inputs are like the following:
```
this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>
```
The required output is:
```
this is a par... | This tested snippet should do it:
```
import re
line = re.sub(r"</?\[\d+>", "", line)
```
**Edit:** Here's a commented version explaining how it works:
```
line = re.sub(r"""
(?x) # Use free-spacing mode.
< # Match a literal '<'
/? # Optionally match a '/'
\[ # Match a literal '['
\d+ # Match one o... |
How to input a regex in string.replace in python? | 5,658,369 | 90 | 2011-04-14T03:59:21Z | 16,548,014 | 10 | 2013-05-14T16:13:42Z | [
"python",
"regex",
"string",
"replace"
] | I need some help on declaring a regex. My inputs are like the following:
```
this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.
and there are many other lines in the txt files
with<[3> such tags </[3>
```
The required output is:
```
this is a par... | The easiest way
```
import re
txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. and there are many other lines in the txt files with<[3> such tags </[3>'
out = re.sub("(<[^>]+>)", '', txt)
print out
``` |
python subprocess Popen environment PATH? | 5,658,622 | 29 | 2011-04-14T04:39:49Z | 5,659,133 | 8 | 2011-04-14T05:55:19Z | [
"python",
"path",
"subprocess",
"environment",
"popen"
] | I'm confused about how `subprocess` searches for the executable when using `Popen()`. It works if given absolute paths to the child process, but I'm trying to use relative paths. I've found that if I set the environment variable PYTHONPATH then I can get imported modules from that path ok, and PYTHONPATH is there in `s... | You appear to be a little confused about the nature of `PATH` and `PYTHONPATH`.
`PATH` is an environment variable that tells the OS shell where to search for executables.
`PYTHONPATH` is an environment variable that tells the Python interpreter where to search for modules to import. It has nothing to do with `subproc... |
python subprocess Popen environment PATH? | 5,658,622 | 29 | 2011-04-14T04:39:49Z | 5,659,249 | 33 | 2011-04-14T06:08:30Z | [
"python",
"path",
"subprocess",
"environment",
"popen"
] | I'm confused about how `subprocess` searches for the executable when using `Popen()`. It works if given absolute paths to the child process, but I'm trying to use relative paths. I've found that if I set the environment variable PYTHONPATH then I can get imported modules from that path ok, and PYTHONPATH is there in `s... | (filling in details from a comment to make a separate answer)
First off, relative paths (paths containing slashes) never get checked in any PATH, no matter what you do. They are relative to the *current working directory* only. If you need to resolve relative paths, you will have to search the PATH manually, or munge ... |
Where has now() moved in DateTime 2.12 | 5,661,293 | 2 | 2011-04-14T09:43:26Z | 5,661,548 | 9 | 2011-04-14T10:01:58Z | [
"python",
"datetime"
] | I have a product which I'm supporting which uses the now() method from the DateTime module.
```
from DateTime import now
```
However, in DateTime 2.12 this method no longer exists.
Has it been moved to a new location, or is there a new/preferred idiom for getting the current time? | From [this](http://pypi.python.org/pypi/DateTime#downloads) page:
**If the function is called with no arguments, then the current date/ time is returned, represented in the timezone of the local machine.**
I browsed through the code of DateTime.py and I didn't see a now() method. So to answer your question, to get th... |
Packaging and shipping a python library and scripts, the professional way | 5,661,385 | 35 | 2011-04-14T09:49:24Z | 5,731,719 | 14 | 2011-04-20T14:12:20Z | [
"python"
] | I have the task of packaging and shipping a commercial application bundle, which will include:
1. a python library (developed by us)
2. some python programs depending on the library above
3. additional libraries not developed by us, but which are dependencies of our library.
4. a complete python installation (python 2... | This is not a complete answer but just a bunch of ideas. I wrote an installer for a client that incorporated some ideas that might be useful to you.
It was Linux only so I focussed on just that. We needed to ship specific custom versions of mySQL, lighttpd, python, memcached, a few 3rd party Python modules and some cu... |
format ints into string of hex | 5,661,725 | 19 | 2011-04-14T10:15:47Z | 5,661,753 | 26 | 2011-04-14T10:18:16Z | [
"python",
"formatting"
] | I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - "05", 16 - "10"...
e.g.
> input: [0,1,2,3,127,200,255],
>
> output: 000102037fc8ff
I've managed to come up with:
```
#!/usr/bin/env python
def format_me(nums):
result = ""... | ```
''.join('%02x'%i for i in input)
``` |
format ints into string of hex | 5,661,725 | 19 | 2011-04-14T10:15:47Z | 5,661,889 | 23 | 2011-04-14T10:31:50Z | [
"python",
"formatting"
] | I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - "05", 16 - "10"...
e.g.
> input: [0,1,2,3,127,200,255],
>
> output: 000102037fc8ff
I've managed to come up with:
```
#!/usr/bin/env python
def format_me(nums):
result = ""... | ```
>>> str(bytearray([0,1,2,3,127,200,255])).encode('hex')
'000102037fc8ff'
``` |
format ints into string of hex | 5,661,725 | 19 | 2011-04-14T10:15:47Z | 5,662,147 | 7 | 2011-04-14T10:54:18Z | [
"python",
"formatting"
] | I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - "05", 16 - "10"...
e.g.
> input: [0,1,2,3,127,200,255],
>
> output: 000102037fc8ff
I've managed to come up with:
```
#!/usr/bin/env python
def format_me(nums):
result = ""... | Yet another option is `binascii.hexlify`:
```
a = [0,1,2,3,127,200,255]
print binascii.hexlify(bytes(bytearray(a)))
```
prints
```
000102037fc8ff
```
This is also the fastest version for large strings on my machine.
In Python 2.7 or above, you could improve this even more by using
```
binascii.hexlify(memoryview(... |
format ints into string of hex | 5,661,725 | 19 | 2011-04-14T10:15:47Z | 19,996,754 | 30 | 2013-11-15T08:37:13Z | [
"python",
"formatting"
] | I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - "05", 16 - "10"...
e.g.
> input: [0,1,2,3,127,200,255],
>
> output: 000102037fc8ff
I've managed to come up with:
```
#!/usr/bin/env python
def format_me(nums):
result = ""... | Just for completeness, using the modern `.format()` syntax:
```
>>> numbers = [1, 15, 255]
>>> ''.join('{:02X}'.format(a) for a in numbers)
'010FFF'
``` |
Python append performance | 5,663,213 | 4 | 2011-04-14T12:27:01Z | 5,663,252 | 13 | 2011-04-14T12:30:55Z | [
"python",
"performance",
"append"
] | I'm having some performance problems with 'append' in Python.
I'm writing an algorithm that checks if there are two overlapping circles in a (large) set of circles.
I start by putting the extreme points of the circles (x\_i-R\_i & x\_i+R\_i) in a list and then sorting the list.
```
class Circle:
def __init__(self, mid... | Instead of
```
for circle in circles:
... circles.index(circle) ...
```
use
```
for i, circle in enumerate(circles):
... i ...
```
This could decrease your O(n^2) to O(n).
Your whole `makeList` could be written as:
```
sum([[[circle.m[0]-circle.r, 0, i], [circle.m[0]+circle.r, 1, i]] for i, circle in enum... |
Python append performance | 5,663,213 | 4 | 2011-04-14T12:27:01Z | 5,663,258 | 7 | 2011-04-14T12:31:23Z | [
"python",
"performance",
"append"
] | I'm having some performance problems with 'append' in Python.
I'm writing an algorithm that checks if there are two overlapping circles in a (large) set of circles.
I start by putting the extreme points of the circles (x\_i-R\_i & x\_i+R\_i) in a list and then sorting the list.
```
class Circle:
def __init__(self, mid... | Your performance problem is not in the `append()` method, but in your use of `circles.index()`, which makes the whole thing O(n^2).
A further (comparitively minor) improvement is to use a list comprehension instead of `list.append()`:
```
mylist = [[circle.m[0] - circle.r, 0, i]
for i, circle in enumerate(c... |
Upload folders from local system to FTP using python script | 5,663,787 | 7 | 2011-04-14T13:13:01Z | 5,664,673 | 7 | 2011-04-14T14:21:12Z | [
"python",
"ftp"
] | Hi all i have a task where i have to automatically upload folders to an FTP using a python script, i am able to upload single files but not folders with subfolders and files in it i did a lot of search but failed. Could some one help me out here? Thanks in advance.
```
#! /usr/bin/python
import ftplib
s = ftplib.FTP(... | You basically need to use os.walk() to grab those files and transfer them.
Here's a script I wrote for myself to do much of what your asking.
I wrote it a long time ago, so I'd probably do it differently if I wrote it again, but I get a lot of use out of it.
It imports psftplib, which is a wrapper I wrote for the put... |
ImportError: No module named BeautifulSoup | 5,663,980 | 43 | 2011-04-14T13:26:56Z | 10,974,140 | 145 | 2012-06-11T03:05:02Z | [
"python",
"beautifulsoup"
] | I have installed BeautifulSoup using easy\_install and trying to run following script
```
from BeautifulSoup import BeautifulSoup
import re
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This... | Try this `from bs4 import BeautifulSoup`
This might be a problem with Beautiful Soup, version 4, and the beta days. I just read this from the homepage. |
ImportError: No module named BeautifulSoup | 5,663,980 | 43 | 2011-04-14T13:26:56Z | 26,281,671 | 12 | 2014-10-09T14:57:51Z | [
"python",
"beautifulsoup"
] | I have installed BeautifulSoup using easy\_install and trying to run following script
```
from BeautifulSoup import BeautifulSoup
import re
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This... | On Ubuntu 14.04 I installed it from apt-get and it worked fine:
`sudo apt-get install python-beautifulsoup`
Then just do:
`from BeautifulSoup import BeautifulSoup` |
Python unittest against potential infinite loop | 5,664,453 | 5 | 2011-04-14T14:04:19Z | 5,665,044 | 12 | 2011-04-14T14:47:59Z | [
"python",
"multithreading",
"unit-testing"
] | I have a python function which if passed bad data gets caught in an infinite loop. I'd like to write a unit test to confirm that it handles bad parameters gracefully. The problem is of course that if it doesn't detect the bad parameters it won't return.
Is it acceptable to use threads to write a test for this type of ... | You can add a timeout decorator. It's good to separate the logic of your testcase from the timeout mechanism implementation. This will make your code more readable and easier to maintain.
See <http://pypi.python.org/pypi/timeout>
. |
List comprehension (python)and array comprehension (php)? | 5,664,484 | 3 | 2011-04-14T14:06:36Z | 5,664,547 | 7 | 2011-04-14T14:11:05Z | [
"php",
"python",
"arrays",
"arraylist"
] | ```
>>> lst = ['dingo', 'wombat', 'wallaby']
>>> [w.title() for w in lst]
['Dingo', 'Wombat', 'Wallaby']
>>>
```
In python there is simple ways to todo with list comprehension.
What about in php with `array('dingo', 'wombat', 'wallaby');` ?
Are there array comprehension or any build in function ,or normally loop on ... | You can use [`array_map()`](http://www.php.net/manual/en/function.array-map.php) with anonymous functions (closures are PHP 5.3+ only).
```
$arr = array_map(function($el) { return $el[0]; }, array('dingo', 'wombat', 'wallaby'));
print_r($arr);
```
Output
```
Array
(
[0] => d
[1] => w
[2] => w
)
```
Edit... |
Displaying ForeignKey data in Django admin change/add page | 5,665,133 | 4 | 2011-04-14T14:54:39Z | 5,665,280 | 9 | 2011-04-14T15:03:49Z | [
"python",
"django",
"django-models",
"django-admin"
] | I'm trying to get an attribute of a model to show up in the Django admin change/add page of another model. Here are my models:
```
class Download(model.Model):
task = models.ForeignKey('Task')
class Task(model.Model):
added_at = models.DateTimeField(...)
```
Can't switch the foreignkey around, so I can't use... | If you don't need to edit it, you can display it as a readonly field:
```
class DownloadAdmin(admin.ModelAdmin):
readonly_fields = ('task_added_at',)
def task_added_at(self, obj):
return obj.task.added_at
``` |
Pyramid: simpleform or deform? | 5,665,541 | 15 | 2011-04-14T15:22:04Z | 5,672,188 | 10 | 2011-04-15T03:49:33Z | [
"python",
"pyramid"
] | For a new (Python) web application with the Pyramid web framework, I'd like to use a form binding and validation library and so far found [simpleform](http://packages.python.org/pyramid_simpleform/) and [deform](https://github.com/Pylons/pyramid_deform). Does anyone have experience with these, and can tell me why I sho... | I've not had extensive experience with either, but so far this is what I've learned.
They both use colander (which I very much like) for definition and validation of forms. In my opinion what really sets them apart is their rendering mechanisms. In this regard, deform is the most straightforward in the sense that it a... |
Python isinstance() returning error with datetime.date | 5,665,597 | 5 | 2011-04-14T15:26:18Z | 7,801,647 | 12 | 2011-10-18T01:58:04Z | [
"python"
] | I am trying to compile [an old 2008 code](http://djangosnippets.org/snippets/1151/).
```
import datetime
if isinstance(value, datetime.date):
```
But I got an error:
> isinstance() arg 2 must be a class,
> type, or tuple of classes and types
> Python Executable: /usr/bin/python2.6
> Python Version: 2.6.5
What am I... | I suspect you have imported the wrong datetime as in:
```
from datetime import datetime
```
instead use:
```
import datetime
``` |
pylint complains about wxPython 'Too many public methods' | 5,665,797 | 8 | 2011-04-14T15:38:52Z | 5,665,913 | 11 | 2011-04-14T15:47:47Z | [
"python",
"wxpython",
"pylint"
] | For the following simple wxPython snippets:
```
import sys
import wx
class MyApp(wx.App):
def OnInit(self):
self.frame = wx.Frame(None, title="Simple wxPython App")
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def main(argv=sys.argv[:]):
app = MyApp()
app.Ma... | ```
# pylint: disable=R0904
```
Stick that at the top of the offending class.
On older versions of pylint, you have to use
```
# pylint: disable-msg=R0904
```
Unfortunately, if you ever upgrade to a more recent version you'll have to write a sed script to replace all instances of `# pylint: disable-msg` with `# pyl... |
matplotlib - extracting data from contour lines | 5,666,056 | 35 | 2011-04-14T15:59:11Z | 5,666,461 | 34 | 2011-04-14T16:31:40Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"contour"
] | I would like to get data from a single contour of evenly spaced 2D data (an image-like data).
Based on the example found in a similar question: [How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)?](http://stackoverflow.com/q/1560424/429795)
```
>>> import matplotlib.pyplot as plt... | For a given path, you can get the points like this:
```
p = cs.collections[0].get_paths()[0]
v = p.vertices
x = v[:,0]
y = v[:,1]
``` |
matplotlib - extracting data from contour lines | 5,666,056 | 35 | 2011-04-14T15:59:11Z | 14,680,776 | 8 | 2013-02-04T05:17:10Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"contour"
] | I would like to get data from a single contour of evenly spaced 2D data (an image-like data).
Based on the example found in a similar question: [How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)?](http://stackoverflow.com/q/1560424/429795)
```
>>> import matplotlib.pyplot as plt... | from: <http://matplotlib.org/api/path_api.html#module-matplotlib.path>
> Users of Path objects should not access the vertices and codes arrays
> directly. Instead, they should use iter\_segments() to get the
> vertex/code pairs. This is important, since many Path objects, as an
> optimization, do not store a codes at ... |
Show the progress of a Python multiprocessing pool map call? | 5,666,576 | 21 | 2011-04-14T16:40:13Z | 5,666,996 | 11 | 2011-04-14T17:14:02Z | [
"python",
"multiprocessing"
] | I have a script that's successfully doing a multiprocessing Pool set of tasks with a `imap_unordered()` call:
```
p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xrange(num_tasks))
p.close() # No more work
p.join() # Wait for completion
```
However, my `num_tasks` is around 250,000, and so the `join()` lock... | Found an answer myself with some more digging: Taking a look at the `__dict__` of the `imap_unordered` result object, I found it has a `_index` attribute that increments with each task completion. So this works for logging, wrapped in the `while` loop:
```
p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xran... |
Show the progress of a Python multiprocessing pool map call? | 5,666,576 | 21 | 2011-04-14T16:40:13Z | 5,668,200 | 35 | 2011-04-14T18:55:20Z | [
"python",
"multiprocessing"
] | I have a script that's successfully doing a multiprocessing Pool set of tasks with a `imap_unordered()` call:
```
p = multiprocessing.Pool()
rs = p.imap_unordered(do_work, xrange(num_tasks))
p.close() # No more work
p.join() # Wait for completion
```
However, my `num_tasks` is around 250,000, and so the `join()` lock... | There is no need to access private attributes of the result set:
```
from __future__ import division
import sys
for i, _ in enumerate(p.imap_unordered(do_work, xrange(num_tasks)), 1):
sys.stderr.write('\rdone {0:%}'.format(i/num_tasks))
``` |
python listing dirs in a different order based upon platform | 5,667,514 | 9 | 2011-04-14T18:02:39Z | 5,667,552 | 11 | 2011-04-14T18:05:14Z | [
"python",
"os.walk"
] | I am writing and testing code on XPsp3 w/ python 2.7. I am running the code on 2003 server w/ python 2.7. My dir structure will look something like this
```
d:\ssptemp
d:\ssptemp\ssp9-1
d:\ssptemp\ssp9-2
d:\ssptemp\ssp9-3
d:\ssptemp\ssp9-4
d:\ssptemp\ssp10-1
d:\ssptemp\ssp10-2
d:\ssptemp\ssp10-3
d:\ssptemp\ssp10-4... | The order of directories within `os.walk` is not necessarily alphabetical (I think it's actually dependent upon how they're stored within the dirent on the filesystem). It will likely be stable on the same exact directory (*on the same filesystem*) if you don't change the directory contents (ie, repeated calls will ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.