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 |
|---|---|---|---|---|---|---|---|---|---|
Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes? | 6,479,317 | 6 | 2011-06-25T17:16:06Z | 6,479,349 | 11 | 2011-06-25T17:22:48Z | [
"python"
] | Is it normal for python's `io.BytesIO.getvalue()` to return str instead of bytes?
```
Python 2.7.1 (r271:86832, Jun 13 2011, 14:28:51)
>>> import io
>>> a = io.BytesIO()
>>> a
<_io.BytesIO object at 0x10f9453b0>
>>> a.getvalue()
''
>>> print type(a.getvalue())
<type 'str'>
>>>
```
Should I file a bug? | Nope, you shouldn't file a bug. This is normal behaviour. See this answer: [the bytes type in python 2.7 and PEP-358](http://stackoverflow.com/questions/5901706/the-bytes-type-in-python-2-7-and-pep-358)
It basicly comes down that the 2.7 `bytes` is just an alias for `str` to smoothen the transition to 3.x. |
Does "\d" in regex mean a digit? | 6,479,423 | 82 | 2011-06-25T17:33:51Z | 6,479,605 | 319 | 2011-06-25T18:06:14Z | [
"python",
"regex",
"encoding",
"gedit"
] | I found that in `123`, `\d` matches `1` and `3` but not `2`. I was wondering if `\d` matches a digit satisfying what kind of requirement? I am talking about Python style regex.
Regular expression plugin in Gedit is using Python style regex. I created a text file with its content being
```
123
```
Only `1` and `3` ar... | `[0-9]` **isn't equivalent** to `\d`. `[0-9]` matches only `0123456789` characters, while `\d` matches `[0-9]` and other digit characters, for example Eastern Arabic numerals `٠١٢٣٤٥٦٧٨٩` |
Bug in Python's str.rstrip() function, or my own stupidity? | 6,479,676 | 7 | 2011-06-25T18:17:47Z | 6,479,686 | 19 | 2011-06-25T18:19:42Z | [
"python",
"string",
"strip"
] | Either this is a bug, or I'm about to learn something new about how Python behaves. :)
I have a dictionary filled with key/value pairs. Each key has a unique prefix, **`ias_XX_XX_`**. I'm attempting to get a list of every unique prefix in the dictionary.
1. First I get a list of all keys which end in `'_x1'`.
2. Next... | The parameter to `rstrip()` is a set of characters to be stripped, not an exact string:
```
>>> "abcbcbaba".rstrip("ab")
"abcbc"
```
General hint: If you suspect a bug in some function, read its [documentation](http://docs.python.org/library/stdtypes.html#str.rstrip). |
ctypes pointer into the middle of a numpy array | 6,480,310 | 7 | 2011-06-25T20:25:43Z | 6,480,380 | 11 | 2011-06-25T20:37:23Z | [
"python",
"pointers",
"numpy",
"ctypes"
] | I know how to get a ctypes pointer to the beginning of a numpy array:
```
a = np.arange(10000, dtype=np.double)
p = a.ctypes.data_as(POINTER(c_double))
p.contents
c_double(0.0)
```
however, I need to pass the pointer to, let's say, element 100, *without copying the array*.
There must be an easy way to do it but canno... | Slicing a numpy array creates a view, not a copy:
```
>>> a = numpy.arange(10000, dtype=numpy.double)
>>> p = a[100:].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
>>> p.contents
c_double(100.0)
>>> a[100] = 55
>>> p.contents
c_double(55.0)
``` |
2D array of objects in Python | 6,480,441 | 6 | 2011-06-25T20:51:14Z | 6,480,465 | 9 | 2011-06-25T20:55:39Z | [
"python",
"object",
"multidimensional-array"
] | I'm converting some java code to python code and I ended up getting stumped on how to convert a 2D array of objects in Java to python.
Java code:
```
private Node nodes[][] = new Node[rows][columns];
```
How would I do this in python? | I think that's what you want
```
nodes = [[Node() for j in range(cols)] for i in range(rows)]
```
But it is not always a good practice to initialize lists. For matrices it may make sense.
If you're wondering: Documentation about [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehen... |
urllib.urlencode doesn't like unicode values: how about this workaround? | 6,480,723 | 40 | 2011-06-25T21:43:33Z | 6,481,120 | 51 | 2011-06-25T23:22:10Z | [
"python",
"unicode",
"urlencode"
] | If I have an object like:
```
d = {'a':1, 'en': 'hello'}
```
...then I can pass it to `urllib.urlencode`, no problem:
```
percent_escaped = urlencode(d)
print percent_escaped
```
But if I try to pass an object with a value of type `unicode`, game over:
```
d2 = {'a':1, 'en': 'hello', 'pt': u'olá'}
percent_escaped... | You should indeed be nervous. The whole idea that you might have a mixture of bytes and text in some data structure is horrifying. It violates the fundamental principle of working with string data: decode at input time, work exclusively in unicode, encode at output time.
Update in response to comment:
You are about t... |
Django SUM Query? | 6,481,279 | 28 | 2011-06-26T00:01:44Z | 6,481,297 | 61 | 2011-06-26T00:05:26Z | [
"python",
"django",
"django-queryset",
"django-1.2"
] | I have a query akin to the following:
```
SELECT SUM(ISNULL(table.name)) FROM table
```
How does that `SUM` translate into a QuerySet in Django? (i.e. What operation `xyz` does it translate to, in something like `MyModel.objects.xyz()`?) | Update: The following incorporates the ISNULL aspect of the original query:
```
from django.db.models import Sum
ModelName.objects.filter(field_name__isnull=True).aggregate(Sum('field_name'))
```
You're looking for the Sum aggregation function, which works as follows:
```
ModelName.objects.aggregate(Sum('field_name... |
Property decorator | 6,481,733 | 2 | 2011-06-26T02:08:28Z | 6,481,795 | 10 | 2011-06-26T02:32:20Z | [
"python",
"python-3.x",
"decorator",
"pydev",
"pylint"
] | I have a property decorator so:
```
def Property(f):
"""
Allow readable properties without voodoo.
"""
fget, fset, fdel = f()
fdoc = f.__doc__
return property(fget, fset, fdel, fdoc)
```
Used (for example) so:
```
@Property
def method():
""""""
def fget(self):
... | You could use [@staticmethod](http://docs.python.org/library/functions.html#staticmethod) to create a method which does not receive an implicit first argument. Doesn't Python's [@property](http://docs.python.org/library/functions.html#property) decorator already do what you want?
```
class Foo(object):
@property
... |
Intersection between text files | 6,481,953 | 4 | 2011-06-26T03:26:34Z | 6,482,031 | 7 | 2011-06-26T03:50:31Z | [
"python",
"bash",
"text",
"emacs",
"grep"
] | How can I compute the intersection between two text files in terms of raw text? It doesn't matter whether the solution uses a shell command or is expressed in Python, Elisp, or other common scripting languages.
I know `comm` and `grep -Fxv -f file1 file2`. Both assume that I am interested in the intersection of *lines... | You're looking for Python's `difflib` module (in the standard library), and in particular `difflib.SequenceMatcher`. |
Python+MySQL - Bulk Insert | 6,482,004 | 13 | 2011-06-26T03:41:34Z | 6,482,087 | 12 | 2011-06-26T04:10:14Z | [
"python",
"mysql"
] | I'm working with the MySQLdb module in Python to interact with a database. I have a situation where there is a very large list (tens of thousands of elements) which I need to insert as rows into a table.
My solution right now is to generate a large `INSERT` statement as a string and execute it.
Is there a smarter way... | There is a smarter way.
The problem with bulk insertions is that by default [autocommit is enabled](http://dev.mysql.com/doc/refman/5.0/en/commit.html) thus causing each `insert` statement to be saved to stable store before the next insert can initiate.
As the manual page notes:
> By default, MySQL runs with autocom... |
Python+MySQL - Bulk Insert | 6,482,004 | 13 | 2011-06-26T03:41:34Z | 6,482,610 | 10 | 2011-06-26T07:02:39Z | [
"python",
"mysql"
] | I'm working with the MySQLdb module in Python to interact with a database. I have a situation where there is a very large list (tens of thousands of elements) which I need to insert as rows into a table.
My solution right now is to generate a large `INSERT` statement as a string and execute it.
Is there a smarter way... | If you have to insert very large amount of data why are you trying to insert all of them in one single `insert`? (This will unecessary put load on your memory in making this large `insert` string and also while executing it. Also this isn't a very good solution if your data to be inserted is very very large.)
Why don'... |
What is meant by classes themselves are objects? | 6,482,207 | 12 | 2011-06-26T04:50:34Z | 6,482,227 | 8 | 2011-06-26T04:56:14Z | [
"c#",
"java",
"python",
"ruby",
"smalltalk"
] | I was Just reading about the python classes documentation,it says ,in python "classes themselves are object".How is that different from C# or Java classes?
What advantageous and disadvantages this type of classes have compared with C# or Java? | In Python, classes are objects in the sense that you can assign them to variables, pass them to functions, etc. just like any other objects. For example
```
>>> t = type(10)
>>> t
<type 'int'>
>>> len(t.__dict__)
55
>>> t() # construct an int
0
>>> t(10)
10
```
Java has `Class` objects which provide some information ... |
Opening an EXE of my Pygame program gives me import errors | 6,482,235 | 4 | 2011-06-26T04:58:35Z | 6,574,032 | 8 | 2011-07-04T16:37:10Z | [
"python",
"pygame",
"py2exe"
] | I made an MP3 player with pygame code:
```
from Tkinter import *
import pygame
import glob
import tkFont
songs=[]
for x in glob.glob('C:\WhaleTunes\Downloaded/*mp3'):
songs.append(x)
Admin=Tk()
num=0
plpa=-1
songas=Label(Admin,text='',bg='red')
songas.place(relx=0.0,rely=0.7)
def play(number):
pygame.mixer.m... | The solution is to add `import pygame._view` to the top of your main source file. Any of the packagers should work after that. I encountered this problem using cx\_Freeze, py2exe, and pyInstaller. This is a serious bug affecting many of the exe packagers when attempting to package pygame programs. |
Get random sample from list while maintaining ordering of items? | 6,482,889 | 34 | 2011-06-26T08:12:50Z | 6,482,922 | 52 | 2011-06-26T08:24:00Z | [
"python",
"list",
"random",
"sortedlist"
] | I have a sorted list, let say: (its not really just numbers, its a list of objects that are sorted with a complicated time consuming algorithm)
```
mylist = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9 , 10 ]
```
Is there some python function that will give me N of the items, but will keep the order?
Example:
```
randomList... | Following code will generate a random sample of size 4.
```
rand_smpl = [ mylist[i] for i in sorted(random.sample(xrange(len(mylist)), 4)) ]
```
Explanation:
```
random.sample(xrange(len(mylist)), sample_size)
```
generates a random sample of the *indices* of the original list.
This sample then gets sorted to pres... |
Get random sample from list while maintaining ordering of items? | 6,482,889 | 34 | 2011-06-26T08:12:50Z | 6,482,925 | 53 | 2011-06-26T08:24:18Z | [
"python",
"list",
"random",
"sortedlist"
] | I have a sorted list, let say: (its not really just numbers, its a list of objects that are sorted with a complicated time consuming algorithm)
```
mylist = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9 , 10 ]
```
Is there some python function that will give me N of the items, but will keep the order?
Example:
```
randomList... | ## Simple-to-code O(N + K\*log(K)) way
Take a random sample without replacement of the indices, sort the indices, and take them from the original.
```
indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]
```
Or more concisely:
```
[x[1] for x in sorted(random.sample(enumerate(myList),... |
Grouping Elements of Lists Within a List by Index | 6,483,114 | 3 | 2011-06-26T09:20:11Z | 6,483,122 | 8 | 2011-06-26T09:22:05Z | [
"python",
"list"
] | I am trying to take a list of lists, and return a list of lists which contain each element at an index of the original list of lists. I know that that's badly worded. Here's an example.
Say I have the following list of lists:
```
[[1,2,3], [4,5,6], [7,8,9]]
```
I want to get another list of lists, in which each list... | ```
>>> [list(t) for t in zip(*[[1,2,3], [4,5,6], [7,8,9]])]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
``` |
Python MySQLdb unique records, ignore errors | 6,483,333 | 2 | 2011-06-26T10:12:34Z | 6,484,272 | 7 | 2011-06-26T13:34:26Z | [
"python",
"mysql",
"mysql-python"
] | I'm trying to insert records to my db from an array :
```
for string in self.FinalMailsArray:
c.execute("""INSERT INTO table (email) VALUES(%s) """,(string))
```
The problem is, that I want the field email to be unique, so I enabled that in the DB. When I start inserting, I get errors for duplicate entry... | [INSERT IGNORE](http://dev.mysql.com/doc/refman/5.1/en/insert.html) will ignore inserts that would otherwise conflict with a unique key:
```
for string in self.FinalMailsArray:
c.execute("""INSERT IGNORE INTO table (email) VALUES(%s) """,(string))
``` |
python Decimal precision | 6,483,440 | 6 | 2011-06-26T10:42:58Z | 6,483,469 | 10 | 2011-06-26T10:51:03Z | [
"python"
] | For some reason Decimal object looses precision when multiplied. There is no reason to happen so. Please check the testcase and enlighten me.
```
from decimal import *
getcontext().prec = 11
a = Decimal('5085.28725881485')
b = 1
print getcontext()
print 'a = '+str(a)
print 'b = '+str(b)
print 'a * b = '+str(... | The precision you specify in the context (11 places) is only applied when performing *calculations*, not when creating decimal.Decimal objects -- and the result, `5085.2872588` does indeed obey that limit. Using `1` as the multiplier does not change the rules with regards to precision; the result of arithmetic operatio... |
Change the color of all pixels with another color | 6,483,489 | 2 | 2011-06-26T10:56:12Z | 6,501,902 | 7 | 2011-06-28T05:20:16Z | [
"python",
"image-processing",
"colors",
"imagemagick",
"python-imaging-library"
] | I would like to change a single color with Python.
If a fast solution with PIL exists, I would prefer this solution.
At the moment, I use
```
convert -background black -opaque '#939393' MyImage.png MyImage.png
``` | If `numpy` is available on your machine, try doing something like:
```
import numpy as np
import Image
im = Image.open('fig1.png')
data = np.array(im)
r1, g1, b1 = 0, 0, 0 # Original value
r2, g2, b2 = 255, 255, 255 # Value that we want to replace it with
red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mas... |
Python TypeError: Required argument 'source' (pos 1) not found | 6,483,611 | 6 | 2011-06-26T11:29:15Z | 6,483,639 | 8 | 2011-06-26T11:34:46Z | [
"python",
"typeerror"
] | I get an error: `TypeError: Required argument 'source' (pos 1) not found`
but I haven't got a clue what it means :/. Can anyone put me on the right track?
My code is:
```
def openFile(self,fileName):
email_pattern = re.compile(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b', re.IGNORECASE)
with open(fileNa... | `email_pattern.findall()` requires an argument to be passed. So your code should be this -
```
with open(fileName) as lijstEmails:
self.FinalMailsArray.append([email_pattern.findall(line) for line in lijstEmails])
```
Note that `email_pattern.findall()` returns a list, so what you will be making will be list of ... |
How to test django application placed in subfolder? | 6,483,636 | 11 | 2011-06-26T11:33:51Z | 6,964,563 | 16 | 2011-08-06T03:31:26Z | [
"python",
"django",
"unit-testing",
"testing"
] | I have problem with testing django apps grouped in subfolder.
Well, let me explain situation.
Standart django project structure looks like this:
```
django_project/
--appname1
--appname2
--appname3
--lib
--tests
--docs
settings.py
etc...
```
When project structure is standart you can run tests for appname1 just by... | You need both these files under your app folder:
```
__init__.py
models.py
```
They can be empty. |
Is there an elegant way to count tag elements in a xml file using lxml in python? | 6,483,851 | 12 | 2011-06-26T12:19:04Z | 6,483,876 | 7 | 2011-06-26T12:23:38Z | [
"python",
"xml",
"tags",
"count",
"lxml"
] | I could read the content of the xml file to a string and use string operations to achieve this, but I guess there is a more elegant way to do this. Since I did not find a clue in the docus, I am sking here:
**Given an xml (see below) file, how do you count xml tags, like *count of author-tags* in the example bewlow th... | Use an [XPath](http://infohost.nmt.edu/tcc/help/pubs/pylxml/xpath.html) with [`count`](http://msdn.microsoft.com/en-us/library/ms256103.aspx). |
Is there an elegant way to count tag elements in a xml file using lxml in python? | 6,483,851 | 12 | 2011-06-26T12:19:04Z | 6,483,900 | 16 | 2011-06-26T12:27:35Z | [
"python",
"xml",
"tags",
"count",
"lxml"
] | I could read the content of the xml file to a string and use string operations to achieve this, but I guess there is a more elegant way to do this. Since I did not find a clue in the docus, I am sking here:
**Given an xml (see below) file, how do you count xml tags, like *count of author-tags* in the example bewlow th... | If you want to count all author tags:
```
import lxml.etree
doc = lxml.etree.parse(xml)
count = doc.xpath('count(//author)')
``` |
Django ./manage.py | 6,484,646 | 2 | 2011-06-26T14:46:26Z | 6,484,664 | 14 | 2011-06-26T14:49:00Z | [
"python",
"django"
] | I was wondering how to set up a configuration file on my computer so that when I want to run manage.py for my django project I would be able to run "./manage.py" as opposed to "python manage.py".
Thanks. | If you're on Windows, you can already provided the file extension registration is correct (invoking `python.exe` rather than `pythonw.exe`, I mean, or you won't see the console output and it won't wait for it to finish).
On other operating systems, make `manage.py` executable with `chmod +x manage.py` and then you can... |
python matplotlib colorbar setting tick formator/locator changes tick labels | 6,485,000 | 5 | 2011-06-26T15:54:41Z | 6,490,838 | 13 | 2011-06-27T09:21:34Z | [
"python",
"matplotlib",
"customization",
"colorbar"
] | users,
I want to customize the ticks on a colorbar. However, I found the following strange behavior. I try to change the tick formator to the default formator (I thought this should change nothing at all) but I end up with different labels. Does anybody know what I am doing wrong? Or is this a bug?
I use matplotlib fr... | I just found the solution. One has to call
```
bar.update_ticks()
```
after the formators/locators are changed, see
<http://matplotlib.sourceforge.net/api/colorbar_api.html>
Then everything works well.
Update:
Here is also the code which changes the Formator/Locator. It is based on the internal structure of the c... |
Django - use generic views or not? | 6,485,005 | 6 | 2011-06-26T15:55:49Z | 6,485,415 | 9 | 2011-06-26T17:11:35Z | [
"python",
"django",
"django-generic-views"
] | I was going through quick poll tutorial on the Django site, and the last topic is introduction of generic views. A convenient way to bypass the need of creation of custom views for every URL pattern.
This is the main idea as far as I understand:
1) Request -> URL patterns -> View -> Template
or
2) Request -> URL pa... | The intention of Generic Views is to reduce boilerplate code when you repeatedly use similar code in several views. You should really use it just for that. Basically, just because *django allows something you are doing generically* you shouldn't do it, particularly not when *your code* becomes *not to your like*.
If y... |
What is the easiest way to clear a database from the CLI with manage.py in Django? | 6,485,106 | 38 | 2011-06-26T16:15:56Z | 6,485,171 | 60 | 2011-06-26T16:28:54Z | [
"python",
"mysql",
"django",
"django-1.3"
] | I am using Django to build a website with MySQL. Now as I am learning so I need to change the Model very often so I want that all tables get cleared and new table get created.
But `syncdb` doesn't touch existing tables. Is there any better way to handle this problem? | If you don't care about data:
Best way would be to drop the database and run `syncdb` again. Or you can run:
For Django >= 1.5
```
python manage.py flush
```
For Django < 1.5
```
python manage.py reset appname
```
(you can add `--no-input` to the end of the command for it to skip the interactive prompt.)
If you ... |
Python variable assignment question | 6,485,195 | 4 | 2011-06-26T16:32:18Z | 6,485,210 | 11 | 2011-06-26T16:35:16Z | [
"python",
"variable-assignment",
"fibonacci"
] | ```
a,b = 0,1
while b < 50:
print(b)
a = b
b = a+b
```
outputs:
```
1
2
4
8
16
32
```
wheras:
```
a,b = 0,1
while b < 50:
print(b)
a,b = b, a+b
```
outputs (correct fibonacci sequence):
```
1
1
2
3
5
8
13
21
34
```
Aren't they the same? I mean `a,b = b, a+b` is essentially the same as `a = ... | No, they are not the same.
When you write `a,b = b, a+b` , the assignments are done "simultaneously". `a,b = b, a+b` is same as `(a, b) = (b, a+b)`. So, after
```
a, b = 5, 8
```
a=5 and b=8. When Python sees this
```
(a, b) = (b, a+b)
```
it **first calculates the right side** `(b, a+b)` which is `(8,13)` **and t... |
How to I use PIL Image.point(table) method to apply a threshold to a 256 gray image? | 6,485,254 | 10 | 2011-06-26T16:42:47Z | 6,490,819 | 8 | 2011-06-27T09:19:43Z | [
"python",
"python-imaging-library",
"threshold"
] | I have 8-bit greyscale TIFF images that I want to convert to Monochrome using a 75% white (decimal 190) threshold. In the Image.convert(mode) method section, the PIL manual says:
> "When translating a greyscale image into a bitlevel image (mode "1"), all non-zero values are set to 255 (white). To use other thresholds,... | I found the complete solution in this answer "[Write TIFF file in python from String](http://stackoverflow.com/questions/5262871/write-tiff-file-in-python-from-string)". The function must include "and 255"
```
threshold = 191
im = im.point(lambda p: p > threshold and 255)
``` |
Gtk.StatusIcon PopupMenu in python | 6,485,264 | 10 | 2011-06-26T16:45:36Z | 6,498,063 | 15 | 2011-06-27T19:43:27Z | [
"python",
"pygtk",
"pygobject"
] | im trying to port some small examples from PyGTK to the new PyGobject bindings, but ive hit a roadblock with a popupmenu, despite getting no errors, no menu is being shown on rightclick, here is the code,
```
from gi.repository import Gtk
class aStatusIcon:
def __init__(self):
self.statusicon = Gtk.StatusI... | ah finally, if anyone else has this problem, it got solved thanks to some awesome help from one of the guys on gimpnet#python youve got to keep your menu in scope or it gets garbage collected hence no errors but no menu either this is the working code
```
from gi.repository import Gtk
class aStatusIcon:
def __ini... |
Numpy Array to base64 and back to Numpy Array - Python | 6,485,790 | 7 | 2011-06-26T18:12:06Z | 6,485,943 | 8 | 2011-06-26T18:36:21Z | [
"python",
"django",
"arrays",
"numpy",
"base64"
] | I am now trying to figure out how I can recover a numpy array from base64 data. This question and answer suggest it is possible: [Reading numpy arrays outside of Python](http://stackoverflow.com/questions/2725602/reading-numpy-arrays-outside-of-python) but an example is not given.
Using the code below as an example, h... | ```
import base64
import numpy as np
t = np.arange(25, dtype=np.float64)
s = base64.b64encode(t)
r = base64.decodestring(s)
q = np.frombuffer(r, dtype=np.float64)
print(np.allclose(q, t))
# True
``` |
Regular Expression [^.] in Python | 6,485,816 | 2 | 2011-06-26T18:15:59Z | 6,485,831 | 15 | 2011-06-26T18:18:49Z | [
"python",
"regex",
"pattern-matching"
] | ```
import re
str="Everyone loves Stack Overflow"
print(re.findall("[ESO][^.]",str))
```
I don't understand why `[^.]` does anything. I thought it only matches characters that are not characters - in other words: nothing! But the output is the following:
```
['Ev', 'St', 'Ov']
```
Can someone shed some light on this... | Most of the regular expression special characters lose their special meaning within a character class (square brackets), so while `.` matches any character, `[.]` matches a literal `.` and `[^.]` matches any character other than `.`. You will sometimes see people wrap a character like `.` in square brackets just to mak... |
Implement list-like index access in Python | 6,486,387 | 13 | 2011-06-26T20:03:29Z | 6,486,401 | 24 | 2011-06-26T20:06:07Z | [
"python",
"arrays",
"list",
"indexing"
] | I'd like to be able to access some values of a python object using array-like syntax, ie:
```
obj = MyClass()
zeroth = obj[0]
first = obj[1]
```
Is this possible? If so, how do you implement this in the python class in question? | You need to write or override [`__getitem__`](http://docs.python.org/reference/datamodel.html#object.__getitem__), [`__setitem__`](http://docs.python.org/reference/datamodel.html#object.__setitem__), and [`__delitem__`](http://docs.python.org/reference/datamodel.html#object.__delitem__).
So for example:
```
class Met... |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 6,486,453 | 8 | 2011-06-26T20:15:00Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | You would want to use a `set` instead of a `list`. |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 6,486,467 | 178 | 2011-06-26T20:16:51Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | ```
>>> set([1,2,3,4]) - set([2,5])
set([1, 3, 4])
>>> set([2,5]) - set([1,2,3,4])
set([5])
``` |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 6,486,483 | 45 | 2011-06-26T20:19:21Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | You can do a
```
list(set(A)-set(B))
```
and
```
list(set(B)-set(A))
``` |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 6,486,513 | 84 | 2011-06-26T20:23:00Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | Use `set` if you don't care about items order or repetition. Use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) if you do:
```
>>> def diff(first, second):
second = set(second)
return [item for item in first if item not in second]
>>> diff(A, B)
[1, 3, 4... |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 6,489,180 | 14 | 2011-06-27T06:07:22Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | One liner:
```
diff = lambda l1,l2: [x for x in l1 if x not in l2]
diff(A,B)
diff(B,A)
```
Or:
```
diff = lambda l1,l2: filter(lambda x: x not in l2, l1)
diff(A,B)
diff(B,A)
``` |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 15,646,006 | 8 | 2013-03-26T19:42:36Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | The above examples trivialized the problem of calculating differences. Assuming sorting or de-duplication definitely make it easier to compute the difference, but if your comparison cannot afford those assumptions then you'll need a non-trivial implementation of a diff algorithm. See difflib in the python standard libr... |
Python, compute list difference | 6,486,450 | 85 | 2011-06-26T20:14:17Z | 23,062,482 | 7 | 2014-04-14T14:16:35Z | [
"python",
"list"
] | In Python, what is the best way to compute the difference between two lists?
example
```
A = [1,2,3,4]
B = [2,5]
A - B = [1,3,4]
B - A = [5]
``` | Python 2.7.3 (default, Feb 27 2014, 19:58:35) - IPython 1.1.0 - timeit: [(github gist)](https://gist.github.com/morenopc/10651856)
```
def diff(a, b):
b = set(b)
return [aa for aa in a if aa not in b]
def set_diff(a, b):
return list(set(a) - set(b))
diff_lamb_hension = lambda l1,l2: [x for x in l1 if x not in ... |
Python code for the coin toss issues | 6,486,877 | 5 | 2011-06-26T21:31:38Z | 6,486,895 | 13 | 2011-06-26T21:35:50Z | [
"python",
"random",
"statistics",
"coin-flipping"
] | I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.
Here's my code:
```
import random
tries = 0
while tries < 100:
tries += 1
coin = random.randint(1, 2)
if coin == 1:
... | ```
import random
samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)
for s in samples:
msg = 'Heads' if s==1 else 'Tails'
print msg
print "Heads count=%d, Tails count=%d" % (heads, tails)
``` |
replace all "\" with "\\" python | 6,486,918 | 7 | 2011-06-26T21:40:52Z | 6,486,921 | 14 | 2011-06-26T21:41:44Z | [
"python",
"regex"
] | Does anyone know how replace all `\` with `\\` in python?
Ive tried:
```
re.sub('\','\\',string)
```
But it screws it up because of the escape sequence.
does anyone know the awnser to my question? | You just need to escape the backslashes in your strings: *(also there's no need for regex stuff)*
```
>>> s = "cats \\ dogs"
>>> print s
cats \ dogs
>>> print s.replace("\\", "\\\\")
cats \\ dogs
``` |
replace all "\" with "\\" python | 6,486,918 | 7 | 2011-06-26T21:40:52Z | 6,486,930 | 7 | 2011-06-26T21:43:02Z | [
"python",
"regex"
] | Does anyone know how replace all `\` with `\\` in python?
Ive tried:
```
re.sub('\','\\',string)
```
But it screws it up because of the escape sequence.
does anyone know the awnser to my question? | you should do:
```
re.sub(r'\\', r'\\\\', string)
```
As `r'\'` is not a valid string
BTW, you should always use raw (`r''`) strings with regex as many things are done with backslashes. |
Synthesize musical notes (with piano sounds) in Python | 6,487,180 | 8 | 2011-06-26T22:37:02Z | 6,487,217 | 8 | 2011-06-26T22:45:36Z | [
"python",
"audio",
"music",
"midi"
] | I would like to have a python implementation of a musical instrument library (for instance, a piano object) that I can use to convert a list of notes and a duration into sound. For instance, something like:
```
import Piano
pn = Piano()
pn.play([note, note, ..., note], duration)
```
Does something like this exist fo... | A subset of @Marcelos answer: <http://code.google.com/p/mingus/>
> mingus is a package for Python used by programmers, musicians, composers and researchers to make and investigate music. **At the core of mingus is music theory, which includes topics like intervals, chords, scales and progressions**.
>
> The MIDI packa... |
Synthesize musical notes (with piano sounds) in Python | 6,487,180 | 8 | 2011-06-26T22:37:02Z | 15,811,112 | 8 | 2013-04-04T12:27:00Z | [
"python",
"audio",
"music",
"midi"
] | I would like to have a python implementation of a musical instrument library (for instance, a piano object) that I can use to convert a list of notes and a duration into sound. For instance, something like:
```
import Piano
pn = Piano()
pn.play([note, note, ..., note], duration)
```
Does something like this exist fo... | A student of mine has just started using mingus to do just this so here's quick guide on how to get going on linux (ubuntu):
Install fluidsynth and mingus if you don't have them already:
`$` sudo apt-get install fluidsynth
`$` sudo easy\_install mingus
Now you should be able to open python and type:
```
>>> from m... |
Django - authentication, registration with email confirmation | 6,488,384 | 13 | 2011-06-27T03:40:16Z | 6,488,398 | 19 | 2011-06-27T03:43:32Z | [
"python",
"django",
"authentication",
"django-registration"
] | I'm looking at the API for authentication
<https://docs.djangoproject.com/en/1.3/topics/auth/>
I can't seem to find information on simple user registration form that would send confirmation email as it is the usual way on web sites.
I guess I could do this:
1) Display a form
2) User enters info and submits
3) Save ... | It's not built into Django. There is a reusable app called [django-allauth](https://github.com/pennersr/django-allauth), which will fit your needs.
An app called [django-registration](https://bitbucket.org/ubernostrum/django-registration) used to be recommended, but that is now unmaintained and out of date.
*Editor n... |
Don't parse options after the last positional argument | 6,488,752 | 9 | 2011-06-27T05:00:11Z | 6,671,440 | 12 | 2011-07-12T21:33:43Z | [
"python",
"argparse"
] | I'm writing a wrapper around the `ssh` command line client. After the first positional argument that's part of `command`, all further options should also be treated as positional arguments.
Under `optparse`, I believe this would be done with [`disable_interspersed_args`](http://docs.python.org/py3k/library/optparse.ht... | I had the same problem. I found the solution on the argparse bug tracker: <http://code.google.com/p/argparse/issues/detail?id=52>
The solution is simple: replace `nargs='+'` (or `'*'`) with `nargs=argparse.REMAINDER`. This special value is not documented, but it does what you want. |
Where are the ampersand and vertical bar characters used in Python? | 6,488,928 | 14 | 2011-06-27T05:29:26Z | 6,488,945 | 7 | 2011-06-27T05:32:07Z | [
"python",
"short-circuiting"
] | In the [Wikipedia page describing short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation), `&` and `|` are listed as eager operators in Python. What does this mean and when are they used in the language? | It means the left operand and the right operand are always evaluated. `&` is the bitwise AND operator and `|` is the bitwise OR operator. |
Where are the ampersand and vertical bar characters used in Python? | 6,488,928 | 14 | 2011-06-27T05:29:26Z | 6,490,106 | 24 | 2011-06-27T08:04:54Z | [
"python",
"short-circuiting"
] | In the [Wikipedia page describing short-circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation), `&` and `|` are listed as eager operators in Python. What does this mean and when are they used in the language? | The wikipedia page is wrong, I've corrected it. `|` and `&` are not boolean operators, even though they *are* eager operators, which just means that they are not short circuit operators. As you probably know, here's how the python `and` and `or` operators work:
```
>>> def talk(x):
... print "Evaluating: ", bool(x... |
Do I need extra code for Image Field in Django | 6,489,173 | 4 | 2011-06-27T06:06:23Z | 6,489,194 | 17 | 2011-06-27T06:10:05Z | [
"python",
"django",
"imagefield"
] | I have this in Model
```
image_name = models.ImageField(upload_to='accounts/')
```
In my view I have
```
def account_form(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validatio... | You need to pass `request.FILES` to your account form as well.
```
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
```
Reference: <https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method>
> Other than the `save()` and `save_m2m()` methods, a `ModelForm` works ex... |
Do I need extra code for Image Field in Django | 6,489,173 | 4 | 2011-06-27T06:06:23Z | 6,489,246 | 17 | 2011-06-27T06:16:15Z | [
"python",
"django",
"imagefield"
] | I have this in Model
```
image_name = models.ImageField(upload_to='accounts/')
```
In my view I have
```
def account_form(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validatio... | Also make sure your form `enctype` is set in the HTML to submit file data:
```
<form action="..." method="POST" enctype="multipart/form-data">
``` |
List of R / Python equivalents | 6,489,466 | 22 | 2011-06-27T06:49:13Z | 6,489,527 | 17 | 2011-06-27T06:54:56Z | [
"python"
] | I've noticed several posts from Python programmers who are asking "how do I do this in R?". So before posting new questions of that same type, I'd rather ask if any of you know of a list of common tasks along with their Python and R implementations, side-by-side. It would be very nice, but I haven't found one; only par... | The [Rosetta Code Project](http://rosettacode.org/wiki/Category%3aR) has a lot of amazing code pieces written in hundreds of languages. I'm not sure that Python and R are directly comparable enough for problems to really *translate* well (I'd use them for different things), but they've given it a shot. |
List of R / Python equivalents | 6,489,466 | 22 | 2011-06-27T06:49:13Z | 6,493,539 | 19 | 2011-06-27T13:25:27Z | [
"python"
] | I've noticed several posts from Python programmers who are asking "how do I do this in R?". So before posting new questions of that same type, I'd rather ask if any of you know of a list of common tasks along with their Python and R implementations, side-by-side. It would be very nice, but I haven't found one; only par... | Try this: Thesaurus of Mathematical Languages: R, Matlab, Python <http://mathesaurus.sourceforge.net/> |
Vim failing to compile with python on OS X | 6,490,513 | 7 | 2011-06-27T08:52:49Z | 8,276,426 | 7 | 2011-11-26T05:07:56Z | [
"python",
"osx",
"vim",
"compilation"
] | I've been trying to compile **vim 7.3** with **python 2.7** support on **mac OS X 10.6**. Vim itself compiles fine, but the embedded python not so much.
The steps I've taken:
```
hg clone https:/vim.googlecode.com/hg/ vim
cd vim/src
./configure --without-x --disable-gui --disable-darwin \
--enable-pythoni... | Turns out the bug is actually in the Python Makefile, believe it or not.
Open the file
```
/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config
```
or whatever the appropriate path is for you, and search for `PyMac_Error`. It should be on the line defining `LINKFORSHARED`, and... |
How do I move the last item in a list to the front in python? | 6,490,560 | 9 | 2011-06-27T08:57:15Z | 6,490,586 | 8 | 2011-06-27T08:59:37Z | [
"python",
"list"
] | I searched thoroughly but can't find anything relating to this exact specific. I have a list:
```
a = [two, three, one]
```
I want to move `one` to the front, so it becomes:
```
a = [one, two, three]
```
The thing is, it could be ANY amount of numbers in the list. Assume there is no way of knowing whether there wil... | The `-1` index relates to the last item.
```
a = a[-1:] + a[:-1]
```
This will work for any number of elements in list. |
How do I move the last item in a list to the front in python? | 6,490,560 | 9 | 2011-06-27T08:57:15Z | 6,490,608 | 19 | 2011-06-27T09:01:14Z | [
"python",
"list"
] | I searched thoroughly but can't find anything relating to this exact specific. I have a list:
```
a = [two, three, one]
```
I want to move `one` to the front, so it becomes:
```
a = [one, two, three]
```
The thing is, it could be ANY amount of numbers in the list. Assume there is no way of knowing whether there wil... | Basically:
```
a.insert(0, a.pop())
```
Consider using [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) if you're doing that often, though. |
python: force two zeroes after dot when converting float to string | 6,491,743 | 5 | 2011-06-27T10:51:51Z | 6,491,763 | 7 | 2011-06-27T10:53:07Z | [
"python",
"string",
"floating-point"
] | I am currently trying to force python to keep two zeroes after converting a float to a string, i.e.:
150.00 instead of 150.0
I am not very experienced with python and thus can only think of a brute force method to achieve this. Is there a built in functionality to do this?
Thanks | ```
>>> "{0:.2f}".format(150)
'150.00'
```
or
```
>>> format(150, ".2f")
'150.00'
```
For an introduction to string formatting, see [the Python tutorial](http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting) and the links given there. |
python: force two zeroes after dot when converting float to string | 6,491,743 | 5 | 2011-06-27T10:51:51Z | 6,491,775 | 8 | 2011-06-27T10:54:17Z | [
"python",
"string",
"floating-point"
] | I am currently trying to force python to keep two zeroes after converting a float to a string, i.e.:
150.00 instead of 150.0
I am not very experienced with python and thus can only think of a brute force method to achieve this. Is there a built in functionality to do this?
Thanks | ```
>>> "%.02f" % 150
'150.00'
```
Edit: Just tested, does work in 3.2 actually. It also works in older versions of Python, whilst the format methods do not - however, upgrading and using the format methods is preferred where possible. If you can't upgrade, use this. |
Cannot access Queue.Empty: "AttributeError: 'function' object has no attribute 'Empty'" | 6,491,942 | 8 | 2011-06-27T11:11:00Z | 6,492,093 | 19 | 2011-06-27T11:23:35Z | [
"python",
"multiprocessing"
] | For some reason I can't access the `Queue.Empty` exception - what am I doing wrong here?
```
from multiprocessing import Process, Queue
# ...
try:
action = action_queue.get(False)
print "Action: " + action
except Queue.Empty:
pass
```
The stack trace:
```
Traceback (most recent call last):
File "C:\P... | The Queue.Empty exception is in the Queue module, not in the multiprocessing.queues.Queue class. The multiprocessing module actually uses the Queue (module) Empty exception class:
```
from multiprocessing import Queue
from Queue import Empty
q = Queue()
try:
q.get( False )
except Empty:
print "Queue was empty"... |
Automatically process numbers in e (scientific) notation in python | 6,492,096 | 8 | 2011-06-27T11:23:51Z | 6,492,108 | 18 | 2011-06-27T11:25:16Z | [
"python",
"numbers"
] | I am reading in data files from a mass spectrometer and many of the numbers are in e form e.g.
```
4096.26 5.785e1
4096.29 5.784e1
4096.31 5.784e1
4096.33 5.784e1
4096.36 5.783e1
```
I am planning on using the split function to get the two numbers out, but I wanted to know is there a function to convert the second co... | The `float()` constructor will accept strings in `e` notation:
```
>>> float("5.785e1")
57.85
```
So you can simply use `map(float, line.split())` to convert a text line to a list of floats. |
Editing the Form in Django creates new instance | 6,492,325 | 6 | 2011-06-27T11:44:04Z | 6,492,428 | 10 | 2011-06-27T11:53:52Z | [
"python",
"django",
"forms"
] | I am editing the form , it loads data correctly buy when i hit save it creates new entry in database.
Here is the view functions
```
def create_account(request):
if request.method == 'POST': # If the form has been submitted...
form = AccountForm(request.POST, request.FILES) # A form bound to the POST da... | You are missing the `instance` argument at the `POST` section.
Instead of this:
```
form = AccountForm(request.POST, request.FILES) # A form bound to the POST data
```
You should use this:
```
form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
```
Once you add that to the a... |
What is the pythonic way to print values right aligned? | 6,493,024 | 2 | 2011-06-27T12:44:34Z | 6,493,040 | 8 | 2011-06-27T12:46:19Z | [
"format",
"python"
] | I've a list of strings which I want to group by their suffix and then print the values right-aligned, padding the left side with spaces.
What is the pythonic way to do that?
My current code is:
```
def find_pos(needle, haystack):
for i, v in enumerate(haystack):
if str(needle).endswith(v):
re... | Very close.
```
fmt = "{:>{size}s}"
for item in errors_list:
print fmt.format(item, size=size)
``` |
Running Scrapy from a script - Hangs | 6,494,067 | 7 | 2011-06-27T14:01:40Z | 6,502,863 | 7 | 2011-06-28T07:09:57Z | [
"python",
"scrapy"
] | I'm trying to run scrapy from a script as discussed [here](https://groups.google.com/forum/#!topic/scrapy-users/8zL8W3SdQBo). It suggested using [this](http://snippets.scrapy.org/snippets/13/) snippet, but when I do it hangs indefinitely. This was written back in version .10; is it still compatible with the current sta... | ```
from scrapy import signals, log
from scrapy.xlib.pydispatch import dispatcher
from scrapy.crawler import CrawlerProcess
from scrapy.conf import settings
from scrapy.http import Request
def handleSpiderIdle(spider):
'''Handle spider idle event.''' # http://doc.scrapy.org/topics/signals.html#spider-idle
prin... |
How to save and load an array of complex numbers using numpy.savetxt? | 6,494,102 | 12 | 2011-06-27T14:04:11Z | 6,522,396 | 7 | 2011-06-29T14:31:24Z | [
"python",
"numpy",
"complex-numbers"
] | I want to use [`numpy.savetxt()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html) to save an array of complex numbers to a text file. Problems:
* If you save the complex array with the default format string, the imaginary part is discarded.
* If you use `fmt='%s'`, then `numpy.loadtxt()` can't ... | It's easier and saves a few temporary arrays to just reinterpret the array as a real array.
Saving:
```
numpy.savetxt('outfile.txt', array.view(float))
```
Loading:
```
array = numpy.loadtxt('outfile.txt').view(complex)
```
If you prefer to have real and imaginary part on the same line in the file, you can use
``... |
Parsing HTML with Python 2.7 - HTMLParser, SGMLParser, or Beautiful Soup? | 6,494,199 | 14 | 2011-06-27T14:11:55Z | 6,494,811 | 13 | 2011-06-27T14:56:07Z | [
"python",
"html",
"parsing",
"beautifulsoup",
"html-parsing"
] | I want to do some screen-scraping with Python 2.7, and I have no context for the differences between `HTMLParser`, `SGMLParser`, or Beautiful Soup.
Are these all trying to solve the same problem, or do they exist for different reasons? Which is simplest, which is most robust, and which (if any) is the default choice?
... | I am using and would recommend **lxml** and **pyquery** for parsing HTML. I had to write a web scraping bot a few month ago and of all the popular alternatives I tried, including **HTMLParser** and **BeautifulSoup**, I went with **lxml** and the syntax sugar of **pyquery**. I haven't tried **SGMLParser** though.
For w... |
How do you pick "x" number of unique numbers from a list in python? | 6,494,508 | 8 | 2011-06-27T14:32:54Z | 6,494,519 | 21 | 2011-06-27T14:33:55Z | [
"python",
"list",
"random"
] | I need to pick out "x" number of non-repeating, random numbers out of a list. for example :
all\_data = [1,2,2,3,4,5,6,7,8,8,9,10,11,11,12,13,14,15,15]
how do I pick out a list like [2,11,15] and not [3,8,8]? | That's exactly what [`random.sample()`](http://docs.python.org/library/random.html#random.sample) does.
```
>>> random.sample(range(1, 16), 3)
[11, 10, 2]
```
**Edit**: I'm almost certain this is not what you asked, but I was pushed to include this comment: If the population you want to take samples from contains dup... |
How to display "x days ago" type time using Humanize in Django template? | 6,494,921 | 11 | 2011-06-27T15:04:55Z | 6,495,277 | 19 | 2011-06-27T15:32:23Z | [
"python",
"django",
"humanize"
] | When I do this:
```
{% load humanize %}
{{ video.pub_date|naturaltime|capfirst }}
```
I get `2 days, 19 hours ago`
How can I get just 2 days without the hours. Basically if the video was published in less than a day ago then it should say X hours ago, then it should count in days like X days ago, then in weeks. I j... | Django has [a built-in template filter](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#timesince) `timesince` that offers the same output you mentioned above. The following filter just strips the second part after the comma:
```
from datetime import datetime, timedelta
from django import template
from d... |
Rich JavaScript Applications With django | 6,497,354 | 4 | 2011-06-27T18:38:05Z | 6,498,666 | 9 | 2011-06-27T20:37:55Z | [
"jquery",
"python",
"django"
] | I am working to build a django application and will relay on a lot of JavaScripting using JQuery. When using heavy javascripting I will require to pass some variables on run time and am trying to keep my code neat without inline js.
My first question: Is there a best practices for how to manage the js libraries that a... | ## Rich applications: heavy client side, somewhat light server side
I think, you should take a look at JavaScript frameworks that implement some sort of model-view-controller pattern on the client side (if you haven't done it already).
Here is a quote from a [discussion](http://news.ycombinator.com/item?id=1788381) a... |
Iterating through THREE lists at once in Python? | 6,497,824 | 3 | 2011-06-27T19:22:00Z | 6,498,180 | 18 | 2011-06-27T19:54:13Z | [
"python",
"maya"
] | This might be a rather complex question since it's possible a lot of you don't know the software that I'm writing it for: Autodesk Maya 2011. I am trying to speed up a tedious slow process (rigging: giving 3d characters the ability to move) by writing a script that does it automatically.
I'll try my best to explain th... | I do not quite understand the question, are you looking for
```
import itertools
for a, b, c in itertools.izip(lst1, lst2, lst3):
...
```
?
What `izip` does is it takes a variable number of arguments and returns an iterator that always yields the respective items of the arguments (a tuple of the first arguments ... |
Is there python way to generate pairs? | 6,499,327 | 11 | 2011-06-27T21:48:40Z | 6,499,338 | 20 | 2011-06-27T21:49:49Z | [
"python",
"generator",
"pair"
] | I want something like code below, but "pythonic" style or using standard library:
```
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
``` | These are not really "combinations" in the sense of combinatorics, these are rather elements from the cartesian product of `a` and `b`. The function in the standard library to generate these pairs is [`itertools.product()`](http://docs.python.org/library/itertools.html#itertools.product):
```
for i, j in itertools.pro... |
Is there python way to generate pairs? | 6,499,327 | 11 | 2011-06-27T21:48:40Z | 6,499,407 | 7 | 2011-06-27T21:56:45Z | [
"python",
"generator",
"pair"
] | I want something like code below, but "pythonic" style or using standard library:
```
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
``` | A nested generator expression will work too:
```
product = ((i, j) for i in a for j in b)
for i, j in product:
# ...
``` |
Python Scrapy: Convert relative paths to absolute paths | 6,499,603 | 13 | 2011-06-27T22:19:35Z | 6,502,422 | 18 | 2011-06-28T06:25:59Z | [
"python",
"scrapy",
"imagesource"
] | I have amended the code based on solutions offered below by the great folks here; I get the error shown below the code here.
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from dmoz2.items im... | What i do is:
```
import urlparse
...
def parse(self, response):
...
urlparse.urljoin(response.url, extractedLink.strip())
...
```
Notice `strip()`, because i meet sometimes strange links like:
```
<a href="
/MID_BRAND_NEW!%c2%a0MID_70006_Google_Android_2.2_7%22%c2%a0Tablet_PC_Silver/a9043... |
Why can't I unpack a float with other types and get the expected result? | 6,500,604 | 4 | 2011-06-28T01:11:38Z | 6,500,637 | 8 | 2011-06-28T01:19:39Z | [
"python",
"struct"
] | I'm trying to parse out some data packed into this binary file and Python's struct module is causing me all sorts of problems. It won't seem to give me the correct float variable when it's trying to do more than one type at a time:
```
import struct
# a fragment of the binary file
a = '\x39\x00\xFF\x00\x00\x0A\x00\x1... | > By default, C types are represented in the machineâs native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).
The unpacking expects the float to be aligned on an 8-byte boundary and skips over 1 padding byte to get there. You can confirm... |
Removing from a list while iterating over it | 6,500,888 | 6 | 2011-06-28T02:19:09Z | 6,501,064 | 10 | 2011-06-28T02:55:37Z | [
"python",
"iterator"
] | The following code:
```
a = list(range(10))
remove = False
for b in a:
if remove:
a.remove(b)
remove = not remove
print(a)
```
Outputs `[0, 2, 3, 5, 6, 8, 9]`, instead of `[0, 2, 4, 6, 8]` when using Python 3.2.
1. Why does it output these particular values?
2. Why is no error given to indicate that ... | I debated answering this for a while, because similar questions have been asked many times here. But it's just unique enough to be given the benefit of the doubt. (Still, I won't object if others vote to close.) Here's a visual explanation of what is happening.
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <- b = 0; remov... |
Difference between exit() and sys.exit() in Python | 6,501,121 | 214 | 2011-06-28T03:05:31Z | 6,501,134 | 290 | 2011-06-28T03:08:54Z | [
"python",
"exit"
] | In Python, there are two similarly-named functions, `exit()` and `sys.exit()`. What's the difference and when should I use one over the other? | [`exit`](http://docs.python.org/library/constants.html#exit) is a helper for the interactive shell - [`sys.exit`](http://docs.python.org/library/sys.html#sys.exit) is intended for use in programs.
> The site module (which is imported automatically during startup, except if the -S command-line option is given) adds sev... |
SQLAlchemy + SQL Injection | 6,501,583 | 25 | 2011-06-28T04:33:47Z | 6,501,664 | 31 | 2011-06-28T04:46:58Z | [
"python",
"security",
"sqlalchemy"
] | What are the best practices for mitigating SQL injection attacks when using SQLAlchemy? | > If you have any "special" characters (such as semicolons or
> apostrophes) in your data, they will
> be automatically quoted for you by the
> SQLEngine object, so you don't have to
> worry about quoting. This also means
> that unless you deliberately bypass
> SQLAlchemy's quoting mechanisms,
> SQL-injection attacks a... |
SQLAlchemy + SQL Injection | 6,501,583 | 25 | 2011-06-28T04:33:47Z | 16,001,395 | 38 | 2013-04-14T16:30:25Z | [
"python",
"security",
"sqlalchemy"
] | What are the best practices for mitigating SQL injection attacks when using SQLAlchemy? | tldr: Avoid raw SQL as much as possible.
The accepted answer is lazy and incorrect. The filter method accepts raw SQL, and if used in that way, is fully susceptible to SQL injection attacks. For instance, if you were to accept a value from a url and combine it with raw sql in the filter, you are open to attack:
`sess... |
Is the better way to match two different repetitions of the same character class in a regex? | 6,502,592 | 6 | 2011-06-28T06:44:09Z | 6,502,640 | 7 | 2011-06-28T06:47:50Z | [
"python",
"regex"
] | I had been using `[0-9]{9,12}` all along to signify that the numeric string has a length of 9 or 12 characters. However I now realized that it will match input strings of length 10 or 11 as well. So I came out with the naive:
```
( [0-9]{9} | [0-9]{12} )
```
Is there a more succinct regex to represent this ? | You could save one character by using
```
[0-9]{9}([0-9]{3})?
```
but in my opinion your way is better because it conveys your intention more clearly. Regexes are hard enough to read already.
Of course you could use `\d` instead of `[0-9]`.
(Edit: I first thought you could drop the parens around `[0-9]{3}` but you ... |
Understanding nested yield / return in python | 6,503,079 | 17 | 2011-06-28T07:32:03Z | 6,503,192 | 11 | 2011-06-28T07:42:32Z | [
"python",
"nested",
"generator",
"yield"
] | I have a function in python whose output is a generator :
```
def main_function(x):
r = get_range()
for i in range(r):
yield x+i
```
I want to refactor the code (I've simplified the use case but actual computation might be complex & longer. Please see EDIT below). Based on my understanding, this is wh... | You're right; the initial example and a) do the same thing since both return a generator.
b) is different: It returns a generator which yields a single element (which is another generator). To use that, you need two loops (one over the outer and one over the inner generator).
There are no advantages per se but someti... |
Prevent memory error in itertools.permutation | 6,503,388 | 4 | 2011-06-28T08:01:55Z | 6,503,429 | 13 | 2011-06-28T08:06:35Z | [
"python",
"itertools"
] | Firstly I would like to mention that i have a 3 gb ram.
I am working on an algorithm that is exponential in time on the nodes so for it I have in the code
```
perm = list( itertools.permutations(list(graph.Nodes))) # graph.Nodes is a tuple of 1 , 2 , ... n integers
```
which generates all the combinations of vertice... | Try to use the iterator generated by the permutations instead of recreating a list with it :
```
perm_iterator = itertools.permutations(list(graph.Nodes))
for item in perm_iterator:
do_the_stuff(item)
```
by doing this, python will keep in memory only the currently used permutation, not all the permutations (in t... |
Is it possible to escape a reserved word in Python? | 6,503,920 | 3 | 2011-06-28T08:50:34Z | 6,504,209 | 7 | 2011-06-28T09:15:52Z | [
"python",
"syntax"
] | It may not be a good idea to name a variable after a reserved word, but I am curious:
Is there any escape syntax in Python to allow you to use a reserved word as the name of a variable?
For example, in C# this can be done by prefixing the reserved word with `@` | It is not possible, however it is some kind of a tradition in Python to append a `_` to get a new identifier:
```
def drive(from_, to):
pass
``` |
How to decode unicode raw literals to readable string? | 6,504,200 | 24 | 2011-06-28T09:14:58Z | 6,504,515 | 28 | 2011-06-28T09:41:47Z | [
"python",
"string",
"unicode",
"encoding",
"unicode-literals"
] | If I assign unicode raw literals to a variable, I can read its value:
```
>>> s = u'\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e'
>>> s
u'\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d... | Use the [unicode\_escape codec](http://docs.python.org/library/codecs.html):
```
s.decode('unicode_escape')
``` |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 6,504,860 | 787 | 2011-06-28T10:11:58Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | Since you're on Ubuntu, don't bother with those source packages. Just install those development packages using apt-get.
```
apt-get install libxml2-dev libxslt1-dev python-dev
```
If you're happy with a possibly older version of lxml altogether though, you could try
```
apt-get install python-lxml
```
and be done w... |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 15,686,204 | 93 | 2013-03-28T15:44:21Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | I also had to install lib32z1-dev before lxml would compile (Ubuntu 13.04 x64).
```
sudo apt-get install lib32z1-dev
```
Or all the required packages together:
```
sudo apt-get install libxml2-dev libxslt-dev python-dev lib32z1-dev
``` |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 15,823,382 | 7 | 2013-04-04T23:19:20Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | After installing the packages mentioned by AKX I still had the same problem. Solved it with
```
apt-get install python-dev
``` |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 19,289,133 | 36 | 2013-10-10T07:02:47Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | As @Pepijn commented on @Druska 's answer, on ubuntu 13.04 x64, there is no need to use lib32z1-dev, zlib1g-dev is enough:
```
sudo apt-get install libxml2-dev libxslt-dev python-dev zlib1g-dev
``` |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 25,372,234 | 12 | 2014-08-18T21:21:35Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | I installed lxml with pip in Vagrant, using Ubuntu 14.04 and had the same problem. Even though all requirements where installed, i got the same error again and again. Turned out, my VM had to little memory by default. With 1024 MB everything works fine.
Add this to your VagrantFile and lxml should properly compile / i... |
How to install lxml on Ubuntu | 6,504,810 | 352 | 2011-06-28T10:08:21Z | 31,157,631 | 7 | 2015-07-01T09:32:47Z | [
"python",
"ubuntu",
"lxml",
"libxml2",
"easy-install"
] | I'm having difficulty installing lxml with easy\_install on Ubuntu 11.
When I type `$ easy_install lxml` I get:
```
Searching for lxml
Reading http://pypi.python.org/simple/lxml/
Reading http://codespeak.net/lxml
Best match: lxml 2.3
Downloading http://lxml.de/files/lxml-2.3.tgz
Processing lxml-2.3.tgz
Running lxml-2... | For Ubuntu 14.04
`sudo apt-get install python-lxml`
worked for me. |
Dictionary keys match on list; get key/value pair | 6,505,008 | 11 | 2011-06-28T10:25:43Z | 6,505,031 | 8 | 2011-06-28T10:28:02Z | [
"python",
"list",
"dictionary",
"match",
"key"
] | In python... I have a list of elements 'my\_list', and a dictionary 'my\_dict' where some keys match in 'my\_list'.
I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my\_list' elements.
I tried this...
```
if any(x in my_dict for x in my_list):
print set(my_l... | ```
new_dict = dict((k, v) for k, v in dict.iteritems() if k in list)
```
Turning list into a set `set(list)` *may* yield a noticeable speed increase |
Dictionary keys match on list; get key/value pair | 6,505,008 | 11 | 2011-06-28T10:25:43Z | 6,505,032 | 11 | 2011-06-28T10:28:12Z | [
"python",
"list",
"dictionary",
"match",
"key"
] | In python... I have a list of elements 'my\_list', and a dictionary 'my\_dict' where some keys match in 'my\_list'.
I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my\_list' elements.
I tried this...
```
if any(x in my_dict for x in my_list):
print set(my_l... | Don't use `dict` and `list` as variable names. They shadow the built-in functions. Assuming list `l` and dictionary `d`:
```
kv = [(k, d[k]) for k in l if k in d]
``` |
Dictionary keys match on list; get key/value pair | 6,505,008 | 11 | 2011-06-28T10:25:43Z | 6,505,035 | 22 | 2011-06-28T10:28:24Z | [
"python",
"list",
"dictionary",
"match",
"key"
] | In python... I have a list of elements 'my\_list', and a dictionary 'my\_dict' where some keys match in 'my\_list'.
I would like to search the dictionary and retrieve key/value pairs for the keys matching the 'my\_list' elements.
I tried this...
```
if any(x in my_dict for x in my_list):
print set(my_l... | (I renamed `list` to `my_list` and `dict` to `my_dict` to avoid the conflict with the type names.)
For better performance, you should iterate over the list and check for membership in the dictionary:
```
for k in my_list:
if k in my_dict:
print k, my_dict[k]
```
If you want to create a new dictionary fro... |
Join float list into space-separated string in Python | 6,507,431 | 17 | 2011-06-28T13:45:49Z | 6,507,456 | 40 | 2011-06-28T13:47:26Z | [
"python",
"list"
] | I have a list of floats in python:
```
a = [1.2, 2.9, 7.4]
```
I want to join them to produce a space-separated string - ie.:
```
1.2 2.9 7.4
```
However, when I try:
```
print " ".join(a)
```
I get an error because they're floats, and when I try:
```
print " ".join(str(a))
```
I get
```
[ 1 . 2 , 1 . 8 , ... | You need to convert each entry of the list to a string, not the whole list at once:
```
print " ".join(map(str, a))
```
If you want more control over the conversion to string (e.g. control how many digits to print), you can use
```
print "".join(format(x, "10.3f") for x in a)
```
See [the documentation of the synta... |
Python: How to load a module twice? | 6,507,896 | 5 | 2011-06-28T14:15:33Z | 6,507,970 | 14 | 2011-06-28T14:20:51Z | [
"python",
"module",
"load"
] | Is there a way to load a module twice in the same python session?
To fill this question with an example: Here is a module:
Mod.py
```
x = 0
```
Now I would like to import that module twice, like creating two instances of a class to have actually two copies of `x`.
To already answer the questions in the comments, ... | Yes, you can load a module twice:
```
import mod
import sys
del sys.modules["mod"]
import mod as mod2
```
Now, `mod` and `mod2` are two instances of the same module.
That said, I doubt this is ever useful. Use classes instead -- eventually it will be less work.
**Edit**: In Python 2.x, you can also use the followin... |
Regular expression to find any number in a string | 6,508,043 | 3 | 2011-06-28T14:25:40Z | 6,508,110 | 12 | 2011-06-28T14:30:47Z | [
"python",
"regex"
] | What's the notation for any number in re?
Like if I'm searching a string for any number, positive or negative.
I've been using \d+ but that can't find 0 or -1 | Searching for positive, negative, and/or decimals, you could use `[+-]?\d+(?:\.\d+)?`
```
>>> nums = re.compile(r"[+-]?\d+(?:\.\d+)?")
>>> nums.search("0.123").group(0)
'0.123'
>>> nums.search("+0.123").group(0)
'+0.123'
>>> nums.search("123").group(0)
'123'
>>> nums.search("-123").group(0)
'-123'
>>> nums.search("1")... |
remove one comma using a python script | 6,508,254 | 4 | 2011-06-28T14:40:26Z | 6,508,491 | 10 | 2011-06-28T14:56:50Z | [
"python",
"vim",
"csv",
"comma"
] | I have csv file with a line that looks something like this:
```
,,,,,,,,,,
```
That's 10 commas. I wish to remove only the last (i.e. the 10th) comma, so that the line changes to:
```
,,,,,,,,,
```
Has anyone had any experience dealing with a case like this? I use the vim text editor also. So, any help using python... | Removing last comma in current line in vim:
`:s/,$//`
The same for lines n through m:
`:n,ms/,$//`
The same for whole file:
`:%s/,$//` |
What is the difference between sys and os.sys | 6,508,576 | 15 | 2011-06-28T15:02:28Z | 6,508,604 | 23 | 2011-06-28T15:04:40Z | [
"python"
] | What is the difference between `sys` and `os.sys` in python? I have seen many projects using `sys` when they have imported `os`. When I tried `dir(sys)` and `dir(os.sys)` they had same functions and their output was same.
I often see code using `sys.exit` like this, rather than using `os.sys.exit`, but both do the sam... | `os.sys` is `os`'s "private" name for `sys`; Python does not hide imports performed in another module. You should not depend on its existence, and should instead import `sys` directly yourself. |
Python - Find non mutual items in two dicts | 6,508,986 | 3 | 2011-06-28T15:29:20Z | 6,509,121 | 11 | 2011-06-28T15:39:11Z | [
"python"
] | Lets say I have two dictionaries:
```
a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}
```
What's the most pythonic way to find the non mutual items between the two of them such that for `a` and `b` I would get:
```
{'a': 1, 'd': 4, 'e': 5}
```
I had thought:
```
{key: b[key] for key in b if not a... | ```
>>> dict(set(a.iteritems()) ^ set(b.iteritems()))
{'a': 1, 'e': 5, 'd': 4}
``` |
How to use concurrent.futures with timeouts? | 6,509,261 | 5 | 2011-06-28T15:47:51Z | 6,514,268 | 9 | 2011-06-28T23:33:02Z | [
"python",
"concurrency",
"timeout",
"python-3.x"
] | I am trying to get timeouts to work in python3.2 using the concurrent.futures module. However when it does timeout, it doesn't really stop the execution. I tried with both threads and process pool executors neither of them stop the task, and only until its finished does a timeout become raised. So does anyone know if i... | As far as I can tell, TimeoutError is actually raised when you would expect it, and not after the task is finished.
However, your program itself will keep on running until all running tasks have been completed. This is because currently executing tasks (in your case, probably all your submitted tasks, as your pool siz... |
Get URL when handling urllib2.URLError | 6,509,337 | 6 | 2011-06-28T15:53:18Z | 6,509,402 | 7 | 2011-06-28T15:58:38Z | [
"python",
"exception-handling",
"urllib2"
] | This pertains to urllib2 specifically, but custom exception handling more generally. How do I pass additional information to a calling function in another module via a raised exception? I'm assuming I would re-raise using a custom exception class, but I'm not sure of the technical details.
Rather than pollute the samp... | You can add information to and then re-raise the exception.
```
#mymod.py
import urllib2
def openurl():
req = urllib2.Request("http://duznotexist.com/")
try:
response = urllib2.urlopen(req)
except urllib2.URLError as e:
# add URL and reason to the exception object
e.url = "http://d... |
Efficient Alternative to "in" | 6,509,647 | 4 | 2011-06-28T16:14:44Z | 6,509,683 | 14 | 2011-06-28T16:17:18Z | [
"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... | Perhaps you could use a [**`set`**](https://docs.python.org/2/library/stdtypes.html#set) instead of a [**`list`**](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists) for the urls that you have seen so far. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.