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
IronPython 3 compatibility
7,751,767
13
2011-10-13T09:06:28Z
7,757,810
18
2011-10-13T17:10:42Z
[ "python", "python-3.x", "ironpython" ]
I love the Python language and mainly use the standard CPython 3.+ version for simple scripting and as an algorithm sandbox. Sometimes I need .NET intergration, so I use IronPython which is now in 2.7 version. I like 3.+ better and am therefore reluctant to use the older 2.7. Is there any info on when will it be relea...
IronPython has one big step towards Py3k support - its strings are already unicode. Many of the native modules are already in place because they were backported to Python 2.7. The re-arranged standard library is free because it's just copied from CPython. The time-consuming part are the parser changes such as function...
Is there a way to identify an inherited method in Python?
7,751,930
3
2011-10-13T09:18:51Z
7,752,095
7
2011-10-13T09:30:43Z
[ "python", "inheritance" ]
I want to tell inherited methods apart from overloaded or newly defined methods. Is that possible with Python? Example: ``` class A(object): def spam(self): print 'A spam' def ham(self): print 'A ham' class B(A): def spam(self): print 'Overloaded spam' def eggs(self): print 'Newly defined egg...
I'm not sure it's a good idea, but you can probably do it by using `hasattr` and `__dict__`. ``` def magicmethod(clazz, method): if method not in clazz.__dict__: # Not defined in clazz : inherited return 'inherited' elif hasattr(super(clazz), method): # Present in parent : overloaded return '...
Python regex findall
7,752,551
20
2011-10-13T10:10:58Z
7,752,661
36
2011-10-13T10:20:25Z
[ "python", "regex" ]
I am trying to extract all occurrences of tagged words from a string using regex in Python 2.7.2. Or simply, I want to extract every piece of text inside the `[p][/p]` tags. Here is my attempt: ``` regex = ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?" line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bi...
``` import re regex = ur"\[P\] (.+?) \[/P\]+?" line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday." person = re.findall(regex, line) print(person) ``` yields ``` ['Barack Obama', 'Bill Gates'] ``` --- The regex `ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?"` is exactly the s...
Python regex findall
7,752,551
20
2011-10-13T10:10:58Z
7,752,669
7
2011-10-13T10:21:12Z
[ "python", "regex" ]
I am trying to extract all occurrences of tagged words from a string using regex in Python 2.7.2. Or simply, I want to extract every piece of text inside the `[p][/p]` tags. Here is my attempt: ``` regex = ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?" line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bi...
Try this : ``` for match in re.finditer(r"\[P[^\]]*\](.*?)\[/P\]", subject): # match start: match.start() # match end (exclusive): match.end() # matched text: match.group() ```
sphinx automodule: how to reference classes in same module?
7,753,805
16
2011-10-13T12:01:47Z
7,754,150
7
2011-10-13T12:31:21Z
[ "python", "django", "documentation", "python-sphinx" ]
I am trying to use the sphinx [autodoc](http://sphinx.pocoo.org/ext/autodoc.html) extension and specifically the automodule directive to automatically generate documentation for django app I am working on. The problem is that I want to create internal references to different classes within the module, without having to...
Don't know if I understand the problem but this works flawlessly to me with autodoc, as per [Cross-referencing Python objects](http://sphinx.pocoo.org/domains.html#python-roles) ``` class FlowDirection(GeneralTable): ''' Heat Flow Direction :cvar int id: database primary key :cvar unicode name: name ...
sphinx automodule: how to reference classes in same module?
7,753,805
16
2011-10-13T12:01:47Z
7,754,189
28
2011-10-13T12:33:55Z
[ "python", "django", "documentation", "python-sphinx" ]
I am trying to use the sphinx [autodoc](http://sphinx.pocoo.org/ext/autodoc.html) extension and specifically the automodule directive to automatically generate documentation for django app I am working on. The problem is that I want to create internal references to different classes within the module, without having to...
You can reference a class like this: ``` class B(object): """docs for B with reference to :class:`.A`""" pass ``` Sphinx will intelligently try and figure out what you're referencing. If there are multiple classes with the name `A`, you might get a warning, but it should pick up the one in the current module.
MSSQL2008 - Pyodbc - Previous SQL was not a query
7,753,830
11
2011-10-13T12:03:47Z
14,979,756
22
2013-02-20T12:21:21Z
[ "python", "windows", "sql-server-2008", "pyodbc" ]
I can't figure out what's wrong with the following code, The syntax IS ok (checked with SQL Management Studio), i have access as i should so that works too.. but for some reason as soon as i try to create a table via PyODBC then it stops working. ``` import pyodbc def SQL(QUERY, target = '...', DB = '...'): cnxn ...
Just in case some lonely net nomad comes across this issue, the solution by Torxed didn't work for me. But the following worked for me. I was calling an SP which inserts some values into a table and then returns some data back. Just add the following to the SP : ``` SET NOCOUNT ON ``` It'll work just fine :) The Py...
Python Regex pattern not being matched
7,754,221
2
2011-10-13T12:36:31Z
7,754,248
7
2011-10-13T12:38:07Z
[ "python", "regex", "file" ]
I'm trying to get some regex to parse some values stored in a set of lua files, each line looks something like one of these two lines 1. `ITEM.ID = 'item_clock';\r\n` 2. `ITEM.Cost = 150;\r\n`. when I run my regex pattern on the first line I get an expected result ``` >>> re.search("ITEM.(?P<key>[a-zA-Z]\w) = (?P<va...
The regex looks for `ITEM.` followed by a letter then followed by **exactly one** word character (the `\w` in the regex). You probably meant something like `ITEM.(?P<key>[a-zA-Z]\w*)`... (note the added asterisk). This will look for `ITEM.` followed by a letter then followed by **zero or more** word characters. Also,...
Post to Tornado server
7,754,936
8
2011-10-13T13:35:28Z
7,756,136
19
2011-10-13T14:58:36Z
[ "python", "post", "web", "tornado" ]
I am trying to post to my Tornado Web Server but keep getting a 405 Error. Not sure what is going wrong. I am fairly new to python but I have been searching up on this for about a month and finally decided to give it a go. Tornado Web Server: ``` import tornado.httpserver import tornado.ioloop import tornado.options ...
You will have to change the LoginHandler to accept a POST request. Like so: ``` class LoginHandler(tornado.web.RequestHandler): def post(self): email_address = self.get_argument('email', '') password = self.get_argument('password', '') if not email_address: login_response = { ...
Embed picture in email
7,755,501
3
2011-10-13T14:15:03Z
7,755,994
7
2011-10-13T14:48:56Z
[ "python", "email", "python-3.x" ]
I currently have a program that will randomly select quotes from a list and email them. I'm now trying to embed an image in the email as well. I've come across a problem where I can attach the email but my quotes no longer work. I have researched online and the solutions are not working for me. Note that I am using Pyt...
You are going through royal pains to construct a valid MIME message in `msg`, then ditching it and sending a simple string `email_message` instead. You should probably begin by understanding what the proper MIME structure looks like. A multipart message by itself has no contents at all, you have to add a text part if ...
Python __repr__ and None
7,756,619
2
2011-10-13T15:32:49Z
7,756,920
8
2011-10-13T15:55:26Z
[ "python", "sqlalchemy", "repr" ]
I'm quite new to Python and currently I need to have a `__repr__` for a SqlAlchemy class. I have an integer column that can accept `Null` value and SqlAlchemy converts it to `None`. For example: ``` class Stats(Base): __tablename__ = "stats" description = Column(String(2000)) mystat = Column(Integer, nullable...
The `__repr__` should return a string that describes the object. If possible, it should be a valid Python expression that evaluates to an equal object. This is true for built-in types like `int` or `str`: ``` >>> x = 'foo' >>> eval(repr(x)) == x True ``` If that's not possible, it should be a `'<...>'` string uniquel...
How do I parse HTML which includes named ISO-8859-1 entities with Python?
7,756,817
2
2011-10-13T15:47:06Z
7,756,853
9
2011-10-13T15:49:57Z
[ "python", "html-parsing", "xhtml" ]
I summarize: minidom appears not to like 8859 named entities; what's an appropriate resolution? Here's code which illustrates my situation: ``` sample = """ <html> <body> <h1>Un ejemplo</h1> <p>Me llamo Juan Fulano y Hern&aacute;ndez.</p> </body> </html> """ sample2 = sample.replace("&aacute;"...
`xml.dom.minidom` is an XML parser, not an HTML parser. Therefore, it doesn't know any HTML entities (only those which are common to both XML and HTML: `&quot;`, `&amp;`, `&lt;`, `&gt;` and `&apos;`). Try [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
PyDev project for Google App Engine not finding webapp2
7,756,981
6
2011-10-13T16:00:40Z
7,757,188
9
2011-10-13T16:19:24Z
[ "python", "eclipse", "google-app-engine", "pydev" ]
I am attempting to try out Google App Engine with python. Being familiar with Eclipse, I decided to use PyDev. After some trouble, I have a hello world program working... almost. It cannot find the webapp2 import, telling me it is unresolved. I have followed all of the instructions I can find, and have the google app e...
In Preferences, look under `PyDev > Interpreter - Python` (or whichever you're using), and make sure that webapp2 is listed under the Libraries tab's System libs. If it's not, add it by clicking New Folder on the right, then click apply and wait for it to re-look up your functions. Note that webapp2 is not part of the...
numpy ndarrays: row-wise and column-wise operations
7,757,313
7
2011-10-13T16:30:47Z
7,757,601
10
2011-10-13T16:53:27Z
[ "python", "arrays", "numpy", "multidimensional-array" ]
If I wanted to apply a function row-wise (or column-wise) to an ndarray, do I look to ufuncs (doesn't seem like it) or some type of array broadcasting (not what I'm looking for either?) ? **Edit** I am looking for something like R's apply function. For instance, ``` apply(X,1,function(x) x*2) ``` would multiply 2 t...
First off, many numpy functions take an `axis` argument. It's probably possible (and better) to do what you want with that sort of approach. However, a generic "apply this function row-wise" approach would look something like this: ``` import numpy as np def rowwise(func): def new_func(array2d, **kwargs): ...
"growing" (appending to) a sequence object
7,757,573
5
2011-10-13T16:51:37Z
7,758,010
7
2011-10-13T17:29:34Z
[ "python", "matlab" ]
In Matlab, this type of algorithm ("growing arrays") is advised against ``` mine = [] for i=1:100, mine = [mine,randn(1)] end ``` whereas it seems that many examples for Python show this kind of algorithm (this is a really bad example though): ``` import numpy.random as rand mine = [] for i in range(100): m...
The difference is that: * In MATLAB, every iteration of your loop re-allocates the matrix to increase the size by one and copies the entire contents into the newly allocated space. * Python lists don't work like that. More space is allocated than is needed at any given point and this allocated space grows in a manner ...
Compare two different files line by line and write the difference in third file - Python
7,757,626
2
2011-10-13T16:56:03Z
7,758,213
7
2011-10-13T17:46:42Z
[ "python", "file" ]
I would like to compare two text files which have three columns each. One file has 999 rows and another has 757 rows. I want the different 242 rows to be stored in a different file. I created the first file (999 rows) using a random network generator (999 rows are edges with third column being weight between first, sec...
The best general-purpose option if you're on a \*nix system is just to use: ``` sort filea fileb | uniq -u ``` But if you need to use Python: Your code reopens the inner file in every iteration of the outer file. Open it outside the loop. Using a nested loop is less efficient than looping over the first storing the...
Python tempfile: broken or am I doing it wrong?
7,757,663
4
2011-10-13T16:58:22Z
7,757,842
8
2011-10-13T17:14:19Z
[ "python", "temporary-files" ]
For a small python script I would like to use a temporary file with the tempfile module. Somehow it does not give the expected behavior and I don't know what I am doing wrong or if this is a bug: ``` Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" ...
I just reproduced this behavior in Python 2.7.1 on Windows XP. This *appears* to be a bug that only occurs when you attempt to read without seeking first. That is: ``` >>> tmp.write('test') >>> tmp.seek(0) >>> tmp.read() 'test' ``` vs. ``` >>> tmp.write('test') >>> tmp.read() 'x\x01\x98\x00pfile.pyR\x05\x00\x00\x0...
Is there any working memory profiler for Python3
7,758,699
19
2011-10-13T18:27:14Z
7,859,439
8
2011-10-22T12:16:12Z
[ "python", "python-3.x", "profiling", "memory-profiling", "memory-leak-detector" ]
In Python 2 there's a couple of tools but everything seems to be old and out-of-dated. I've found PySizer and Heapy but everything seems to be Python2 oriented and would take a lot of effort to port. objgraph is interesting but still not a fully working profiler Which tool are using ?
[Pympler](http://packages.python.org/Pympler/) is a Python memory profiler that is compatible with both Python 2.x and Python3.x.
Can Pygame run with 64bit Python 2.7?
7,760,586
2
2011-10-13T21:22:32Z
13,000,689
8
2012-10-21T18:14:09Z
[ "python", "64bit", "pygame" ]
I know it's advised to uninstall 64bit Python and use the win32 version to run Pygame, but I just wondered if it was possible to run it on 64bit nonetheless.
Basically, the answer is yes. I know because I had the same problem. Once you have installed Python 2.7 on your 64-bit machine, you need to visit this web site, which is linked from the official pygame website: <http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame> On a Windows machine, for example, you download a self...
list printing in formatted string in python
7,760,869
2
2011-10-13T21:51:41Z
7,760,935
7
2011-10-13T21:59:34Z
[ "python" ]
In python to print a formatted string with ints and strings, I'd usually do : ``` print '%d %d - %s' %(x,y, mystr) ``` Is there anything similar for printing out a list? I have: ``` L= [1,0,0] name = 'V' ``` and I want the output to be : ``` v(1,0,0) ``` Is there anything similar to %d for list objects?
If you want complete control how the list gets rendered, you'll have to format it separately. In your case, the code would be something like: ``` items = [1,0,0] name = 'V' formatted = '%s(%s)' % ( name, ','.join(str(it) for it in items) ) ```
how to modify a 2D numpy array at specific locations without a loop?
7,761,393
9
2011-10-13T22:59:10Z
7,761,797
8
2011-10-14T00:00:51Z
[ "python", "numpy" ]
I have a 2D numpy array and I have a arrays of rows and columns which should be set to a particular value. Lets consider the following example ``` a = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) ``` I want to modify entries at rows [0,2] and columns [1,2]. This should result in the following arr...
Adding to what others have said, you can modify these elements using fancy indexing as follows: ``` In [39]: rows = [0,1] In [40]: cols = [2,2] In [41]: a = np.arange(1,10).reshape((3,3)) In [42]: a[rows,cols] = 0 In [43]: a Out[43]: array([[1, 2, 0], [4, 5, 0], [7, 8, 9]]) ``` You might want to re...
matplotlib: adding second axes() with transparent background?
7,761,778
9
2011-10-13T23:57:58Z
7,769,497
32
2011-10-14T14:56:50Z
[ "python", "matplotlib" ]
Define data ``` x = np.linspace(0,2*np.pi,100) y = 2*np.sin(x) ``` Plot ``` fig = plt.figure() ax = plt.axes() fig.add_subplot(ax) ax.plot(x,y) ``` Add second axis ``` newax = plt.axes(axisbg='none') ``` Gives me `ValueError: Unknown element o`, even though it does the same thing as what I am about to describe. I...
You're not actually adding a new axes. Matplotlib is detecting that there's already a plot in that position and returning it instead of a new axes object. (Check it for yourself. `ax` and `newax` will be the same object.) There's probably not a reason why you'd want to, but here's how you'd do it. (Also, don't call...
Override + operator in python for float + obj
7,762,108
8
2011-10-14T01:04:53Z
7,762,131
10
2011-10-14T01:11:28Z
[ "python" ]
I have a class Vec3D (see <http://pastebin.com/9Y7YbCZq>) Currently, I allow Vec3D(1,0,0) + 1.2 but I'm wondering how I should proceed to overload the + operator in such a way that I get the following output: ``` >>> 3.3 + Vec3D(1,0,0) [4.3, 3.3 , 3.3] ``` Code is not required, but just a hint in which direction I s...
You're looking for [`__radd__`](http://docs.python.org/reference/datamodel.html#object.__radd__): ``` class MyClass(object): def __init__(self, value): self.value = value def __radd__(self, other): print other, "radd", self.value return self.value + other my = MyClass(1) print 1 + my...
How can I find out why using PIL functions is resulting in a memory error?
7,762,226
8
2011-10-14T01:31:04Z
7,773,574
8
2011-10-14T21:08:06Z
[ "python", "memory", "python-imaging-library" ]
I am using PIL (python image library) to do some image manipulation, specifically I am stitching images together. My code seems to work fine for some images in small quantities, but sometime I and getting a `MemoryError`. The part that is particularly strange to me is that I am not doing manipulations on bit images, ...
It turns out this is not actually a memory error. As Winston Ewert pointed out I was in fact feeding negative parameters into an images resize method. Even though the python documentation says that memory errors are for problems with memory, this error gets thrown when you give negative params to resize. My suspicion ...
Calculate within categories: Equivalent of R's ddply in Python?
7,762,454
10
2011-10-14T02:26:49Z
7,767,695
16
2011-10-14T12:37:55Z
[ "python" ]
I have some R code I need to port to python. However, R's magic data.frame and ddply are keeping me from finding a good way to do this in python. Sample data (R): ``` x <- data.frame(d=c(1,1,1,2,2,2),c=c(rep(c('a','b','c'),2)),v=1:6) ``` Sample computation: ``` y <- ddply(x, 'd', transform, v2=(v-min(v))/(max(v)-mi...
Indeed [pandas](http://pandas.sourceforge.net) is the right (and only, I believe) tool for this in Python. It's a bit less magical than plyr but here's how to do this using the groupby functionality: ``` df = DataFrame({'d' : [1.,1.,1.,2.,2.,2.], 'c' : np.tile(['a','b','c'], 2), 'v' : n...
how to convert an RGB image to numpy array?
7,762,948
14
2011-10-14T04:13:07Z
7,769,424
12
2011-10-14T14:51:31Z
[ "python", "image", "opencv", "numpy" ]
I have an RGB image. I want to convert it to numpy array. I did the following ``` im = cv.LoadImage("abc.tiff") a = numpy.asarray(im) ``` it creates an array with no shape. I assume it is iplimage object. How to do it? Thanks
PIL (Python Imaging Library) and Numpy work well together. I use the following functions. ``` import Image import numpy as np def load_image( infilename ) : img = Image.open( infilename ) img.load() data = np.asarray( img, dtype="int32" ) return data def save_image( npdata, outfilename ) : img =...
how to convert an RGB image to numpy array?
7,762,948
14
2011-10-14T04:13:07Z
7,776,579
24
2011-10-15T08:02:30Z
[ "python", "image", "opencv", "numpy" ]
I have an RGB image. I want to convert it to numpy array. I did the following ``` im = cv.LoadImage("abc.tiff") a = numpy.asarray(im) ``` it creates an array with no shape. I assume it is iplimage object. How to do it? Thanks
You can use newer OpenCV python interface (if I'm not mistaken it is available since OpenCV 2.2). It natively uses numpy arrays: ``` import cv2 im = cv2.imread("abc.tiff") print type(im) ``` result: ``` <type 'numpy.ndarray'> ```
Django Passing data between views
7,763,115
24
2011-10-14T04:43:34Z
7,763,238
33
2011-10-14T05:01:24Z
[ "python", "django", "django-views" ]
I was wondering what is the 'best' way of passing data between views. Is it better to create invisible fields and pass it using POST or should I encode it in my URLS? Or is there a better/easier way of doing this? Sorry if this question is stupid, I'm pretty new to web programming :) Thanks
There are different ways to pass data between views. Actually this is not much different that the problem of passing data between 2 different scripts & of course some concepts of inter-process communication come in as well. Some things that come to mind are - 1. **GET request** - First request hits view1->send data to...
How to set the sharing rights of a folder in Plone?
7,763,150
3
2011-10-14T04:49:53Z
7,763,989
8
2011-10-14T06:45:51Z
[ "python", "permissions", "plone", "zope" ]
I want to set sharing rights of many folders by using a Python script in a Plone site.
You need to look at the [`AccessControl/rolemanager.py`](https://github.com/zopefoundation/AccessControl/blob/master/src/AccessControl/rolemanager.py) module for details; the sharing tab in Plone is a friendly wrapper around that API. To add roles for a given userid, call [`manage_addLocalRoles`](https://github.com/zo...
Sort words by their usage
7,764,229
3
2011-10-14T07:11:29Z
7,765,539
8
2011-10-14T09:19:12Z
[ "python", "nltk" ]
I have a list of english words (approx 10000) and I'd like to sort them by their usage as they occur in literature, newspaper, blogs etc. Can I sort them in Python or other language? I heard about `NLTK` which is the closest library I know that could help. Or is this task for other tool? thank you
Python and NLTK are the perfect tools to sort your wordlist, as the NLTK comes with some corpora of the english language, from which you can extract frequency information. The following code will print a given `wordlist` in the order of word frequency in the brown corpus: ``` import nltk from nltk.corpus import brown...
in python, how do i iterate a nested dict with a dynamic number of nests?
7,764,892
10
2011-10-14T08:19:36Z
7,764,964
11
2011-10-14T08:27:05Z
[ "python", "nested" ]
OK by dynamic I mean unknown at runtime. here is a dict: ``` aDict[1]=[1,2,3] aDict[2]=[7,8,9,10] aDict[n]=[x,y] ``` I don't know how many n will be but I want to loop as follows: ``` for l1 in aDict[1]: for l2 in aDict[2]: for ln in aDict[n]: # do stuff with l1, l2, ln combination. ``` Any suggestions...
You need [itertools.product](http://docs.python.org/library/itertools.html#itertools.product). ``` from itertools import product for vals in product(*list(aDict.values())): # vals will be (l1, l2, ..., ln) tuple ```
in python, how do i iterate a nested dict with a dynamic number of nests?
7,764,892
10
2011-10-14T08:19:36Z
7,765,972
10
2011-10-14T09:55:54Z
[ "python", "nested" ]
OK by dynamic I mean unknown at runtime. here is a dict: ``` aDict[1]=[1,2,3] aDict[2]=[7,8,9,10] aDict[n]=[x,y] ``` I don't know how many n will be but I want to loop as follows: ``` for l1 in aDict[1]: for l2 in aDict[2]: for ln in aDict[n]: # do stuff with l1, l2, ln combination. ``` Any suggestions...
Same idea as DrTyrsa, but making sure order is right. ``` from itertools import product for vals in product( *[aDict[i] for i in sorted(aDict.keys())]): print vals ```
create boost-python nested namespace
7,765,596
3
2011-10-14T09:24:04Z
8,175,196
9
2011-11-17T22:18:21Z
[ "python", "boost", "boost-python" ]
Using boost python I need create nested namespace. Assume I have following cpp class structure: ``` namespace a { class A{...} namespace b { class B{...} } } ``` Obvious solution not work: ``` BOOST_PYTHON_MODULE( a ) { boost::python::class_<a::A>("A") ... ; BOOST_PYTHON_MO...
What you want is a [boost::python::scope](http://www.boost.org/doc/libs/1_48_0/libs/python/doc/v2/scope.html). Python has no concept of 'namespaces', but you can use a class very much like a namespace: ``` #include <boost/python/module.hpp> #include <boost/python/class.hpp> #include <boost/python/scope.hpp> using nam...
Replay a Scrapy spider on stored data
7,766,414
10
2011-10-14T10:34:45Z
7,830,024
15
2011-10-20T01:05:23Z
[ "python", "web-crawler", "scrapy" ]
I have started using [Scrapy](http://scrapy.org/) to scrape a few websites. If I later add a new field to my model or change my parsing functions, I'd like to be able to "replay" the downloaded raw data offline to scrape it again. It looks like Scrapy had the ability to store raw data in a replay file at one point: <h...
If you run `crawl --record=[cache.file] [scraper]`, you'll be able then use `replay [scraper]`. Alternatively, you can cache all responses with the [`HttpCacheMiddleware`](http://readthedocs.org/docs/scrapy/en/latest/topics/downloader-middleware.html#module-scrapy.contrib.downloadermiddleware.httpcache) by including i...
python webkit webview remember cookies?
7,766,445
4
2011-10-14T10:37:50Z
8,722,590
7
2012-01-04T05:53:12Z
[ "python", "cookies", "webkit" ]
I have written a short python script that opens Google music in web view window. however I can't seem to find anything about getting webkit to use cookies so that I don't have to login every time I start it up. Here's what I have: ``` #!/usr/bin/env python import gtk, webkit import ctypes libgobject = ctypes.CDLL('/...
Worked it out, but it required learning more ctypes than I wanted -\_-. Try this- I required different library paths, etc than you, so I'll just paste what's relevant. ``` #remove all cookiejars generic_cookiejar_type = libgobject.g_type_from_name('SoupCookieJar') libsoup.soup_session_remove_feature_by_type(session, g...
Print two random, different names from a set of names
7,767,185
2
2011-10-14T11:51:00Z
7,767,208
8
2011-10-14T11:53:56Z
[ "python", "random" ]
``` import random mylist = ['anthony', 'kris', 'james', 'vinny', 'joe'] randomList1 = random.randrange(0,len(mylist)) randomList2 = random.randrange(0,len(mylist)) name2 = mylist[randomList1] name3 = mylist[randomList2] print 'The group will consist of', name2, 'and', name3,'. ' ``` Is the code in question...
Use [`random.sample`](http://docs.python.org/library/random.html#random.sample): ``` >>> import random >>> mylist = ['anthony', 'kris', 'james', 'vinny', 'joe'] >>> random.sample(mylist, 2) ['james', 'vinny'] ```
Why isn't 0-padding allowed in Python?
7,767,856
2
2011-10-14T12:51:00Z
7,767,878
8
2011-10-14T12:52:40Z
[ "python" ]
I've just noticed 0-padding is not allowed in Python and I was wondering why this choice was made? For example: ``` a = 09 ``` doesn't work while ``` a = 9 ``` does How's that?! Thank you very much for your answers!
Python, as many other languages, treat numbers starting with 0 as being in [octal](http://en.wikipedia.org/wiki/Octal) notation. 09 is not valid as octal See [chapter 2.4.4](http://docs.python.org/reference/lexical_analysis.html#numeric-literals) in the python language reference.
json[more levels] to dict python
7,768,633
3
2011-10-14T13:51:49Z
7,768,660
9
2011-10-14T13:53:26Z
[ "python", "json", "dictionary" ]
i'm having trouble with a simple question. ``` a = { "apiVersion": "2.1", "data": { "startIndex": 1, "items": [{ "id": "YVA3UoZM0zU", "title": "Trailer - Lisbela eo Prisioneiro" }] ...
Try: ``` js['data']['items'][0]['id'] ``` It would appear that there may be multiple `items` in this structure. If you'd like to extract *all* item ids as a list, the following will do it: ``` [item['id'] for item in js['data']['items']] ```
Python: for loop in index assignment
7,768,859
4
2011-10-14T14:08:52Z
7,768,947
13
2011-10-14T14:14:54Z
[ "python", "dictionary", "indexing", "variable-assignment" ]
While working through the awesome book "Programming Collective Intelligence", by Toby Segaran, I've encountered some techniques in index assignments I'm not entirely familiar with. Take this for example: ``` createkey='_'.join(sorted([str(wi) for wi in wordids])) ``` or: ``` normalizedscores = dict([(u,float(l)/max...
``` [str(wi) for wi in wordids] ``` is a **[list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)**. ``` a = [str(wi) for wi in wordids] ``` is the same as ``` a = [] for wi in wordids: a.append(str(wi)) ``` So ``` createkey='_'.join(sorted([str(wi) for wi in wordids])) ...
Pyramid, Chameleon and template rendering
7,769,062
4
2011-10-14T14:23:46Z
7,769,200
7
2011-10-14T14:33:18Z
[ "python", "pyramid", "chameleon", "template-tal" ]
I started a project with the Python web framwork 'Pyramid', using the template engine 'chameleon'. I'm a beginner of this frameworks, but I have to use it for a customer. I follow the steps in order to install the framework, then I started coding, just for training purpose! My first application was a stupid, simple ...
Using the `${}` syntax escapes the included text by default (to help defend against XSS injection attacks). Instead, use the `structure:` prefix to tell the rendering engine to not escape your text: ``` <div>${structure: body}</div> ```
Python String Slicing Stride Clarification
7,770,689
7
2011-10-14T16:30:53Z
7,770,787
11
2011-10-14T16:39:43Z
[ "python", "stride" ]
So I don't really get the deal with the stride parameter in slicing. For example, `"123456"[::-2]` produces `"642"`, but why does `"123456"[1::-2]` produce `"2"` and `"123456"[2::-2]` produce `"31"`?
The easiest way to explain is probably to address your examples: ``` "123456"[::-2] # This takes the whole string ([::]) # Then it works backward (-) # and it does every other character (2) "123456"[1::-2] # This is also working backward (-) # every other character (2) # but starting at position 1, which is the numbe...
numpy array with dtype Decimal?
7,770,870
17
2011-10-14T16:47:58Z
7,771,210
7
2011-10-14T17:17:01Z
[ "python", "numpy", "decimal" ]
Are Decimal dtypes available in numpy? ``` >>> import decimal, numpy >>> d = decimal.Decimal('1.1') >>> s = [['123.123','23'],['2323.212','123123.21312']] >>> ss = numpy.array(s, dtype=numpy.dtype(decimal.Decimal)) >>> a = numpy.array(s, dtype=float) >>> type(d) <class 'decimal.Decimal'> >>> type(ss[1,1]) <class 'str...
It seems that `Decimal` is available: ``` >>> import decimal, numpy >>> d = decimal.Decimal('1.1') >>> a = numpy.array([d,d,d],dtype=numpy.dtype(decimal.Decimal)) >>> type(a[1]) <class 'decimal.Decimal'> ``` I'm not sure exactly what you are trying to accomplish, your example is more complicated than is necessary for...
numpy array with dtype Decimal?
7,770,870
17
2011-10-14T16:47:58Z
7,772,386
17
2011-10-14T19:06:16Z
[ "python", "numpy", "decimal" ]
Are Decimal dtypes available in numpy? ``` >>> import decimal, numpy >>> d = decimal.Decimal('1.1') >>> s = [['123.123','23'],['2323.212','123123.21312']] >>> ss = numpy.array(s, dtype=numpy.dtype(decimal.Decimal)) >>> a = numpy.array(s, dtype=float) >>> type(d) <class 'decimal.Decimal'> >>> type(ss[1,1]) <class 'str...
Numpy doesn't recognize decimal.Decimal as a specific type. The closest it can get is the most general dtype, object. So when converting the elements to the desired dtype, the conversion is a no-op. ``` >>> ss.dtype dtype('object') ``` Keep in mind that because the elements of the array are Python objects, you won't ...
Simulating integer overflow in Python
7,770,949
5
2011-10-14T16:55:36Z
7,771,363
9
2011-10-14T17:32:23Z
[ "python", "ctypes", "integer-overflow" ]
Python 2 has two integer datatypes `int` and `long`, and automatically converts between them as necessary, especially in order to avoid integer overflow. I am simulating a C function in Python and am wondering if there are standard ways to re-enable integer overflow. For the nonce, I've used ``` overflow_point = maxi...
I think the basic idea is sound, but needs some tweaks: 1. your function doesn't overflow on `sys.maxint+1`, but it should; 2. `sys.maxint` can be exceeded several times over as a result of a single operation; 3. negative values below `-sys.maxint-1` also need to be considered. With this in mind, I came up with the f...
Dedupe and sort a list in Python 2.2
7,770,968
6
2011-10-14T16:56:44Z
7,771,081
7
2011-10-14T17:06:26Z
[ "python", "list", "sorting", "unique", "python-2.2" ]
In Python **2.2** (don't ask), what's the neatest way to sort a list and remove duplicates? I can obviously write a function that would `sort()` then iterate, but am wondering if there's an idiomatic one-liner. **edit:** The list is short, so efficiency is not a concern. Also, the elements are immutable.
For old python versions, and since you're using strings, there's no one-liner I can think of, but a pattern would probably be this, using dictionaries: ``` def sorted_uniq(your_list): table = {} for s in your_list: table[s] = None k = table.keys() k.sort() return k ``` Adapted from an anci...
Parse JSON in Python
7,771,011
57
2011-10-14T17:00:25Z
7,771,071
135
2011-10-14T17:05:26Z
[ "python", "json", "parsing" ]
My project is currently receiving a JSON message in python which I need to get bits of information out of. For the purposes of this, lets set it to some simple JSON in a string: ``` jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}' ``` So far I've been generating JSON requests using a list and then `json.dumps` b...
Very simple: ``` import json j = json.loads('{"one" : "1", "two" : "2", "three" : "3"}') print j['two'] ```
Parse JSON in Python
7,771,011
57
2011-10-14T17:00:25Z
7,771,139
33
2011-10-14T17:09:50Z
[ "python", "json", "parsing" ]
My project is currently receiving a JSON message in python which I need to get bits of information out of. For the purposes of this, lets set it to some simple JSON in a string: ``` jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}' ``` So far I've been generating JSON requests using a list and then `json.dumps` b...
Sometimes your json is not a string. For example if you are getting a json from a url like this: ``` j = urllib2.urlopen('http://site.com/data.json') ``` you will need to use json.load, not json.loads: ``` j_obj = json.load(j) ``` (it is easy to forget: the 's' is for 'string')
Parse JSON in Python
7,771,011
57
2011-10-14T17:00:25Z
17,493,365
7
2013-07-05T16:33:41Z
[ "python", "json", "parsing" ]
My project is currently receiving a JSON message in python which I need to get bits of information out of. For the purposes of this, lets set it to some simple JSON in a string: ``` jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}' ``` So far I've been generating JSON requests using a list and then `json.dumps` b...
**For URL or FIle, use json.load(). For string having .json content, use json.loads().** ``` #! /usr/bin/python import json from pprint import pprint #json_file='a.json' json_file='my_cube.json' cube='1' json_data=open(json_file) data = json.load(json_data) #pprint(data) json_data.close() print "Dimension: ", dat...
The most Pythonic way of checking if a value in a dictionary is defined/has zero length
7,771,318
12
2011-10-14T17:28:24Z
7,771,347
11
2011-10-14T17:30:30Z
[ "coding-style", "dictionary", "python" ]
Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function: ``` mydict = {"key" : "value", "emptykey" : ""} print "True" if len(mydict["key"]) > 0 else "False" # prints true print "True" if len(mydict["emptykey"]) > 0 else "False" # prints fal...
``` print (bool(mydict.get('key'))) ``` or, in an if statement: ``` print ('True' if mydict.get('key') else 'False') ``` If you the value not being present is an error case (i.e. you expect it to be there), you should choose solution #2, i.e. ``` print ('True' if mydict['key'] else 'False') ``` That allows `mydict...
The most Pythonic way of checking if a value in a dictionary is defined/has zero length
7,771,318
12
2011-10-14T17:28:24Z
7,772,135
10
2011-10-14T18:45:24Z
[ "coding-style", "dictionary", "python" ]
Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function: ``` mydict = {"key" : "value", "emptykey" : ""} print "True" if len(mydict["key"]) > 0 else "False" # prints true print "True" if len(mydict["emptykey"]) > 0 else "False" # prints fal...
If you know the key is in the dictionary, use ``` if mydict["key"]: ... ``` It is simple, easy to read, and says, "if the value tied to 'key' evaluates to `True`, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to `True` if their `len` is greater tha...
Which way to append dict to list is more efficient
7,771,609
2
2011-10-14T17:59:04Z
7,771,677
7
2011-10-14T18:04:30Z
[ "python" ]
``` # Method one array_a = [] a = {} for i in range(5): a = {} a[str(i)] = i array_a.append(a) print(array_a) # [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}] # Method two from copy import deepcopy array_b = [] b = {} for i in range(5): b.clear() b[str(i)] = i array_b.append(deepcopy(b)...
The difference is not relevant. Both need to create a new dict each time. Since the first is clearer, it is preferable over the second method. My suggestion would be a list comprehension: ``` array_c = [{str(i): i} for i in range(5)] ```
How to right align level field in Python logging.Formatter
7,771,912
15
2011-10-14T18:25:13Z
7,771,978
20
2011-10-14T18:31:33Z
[ "python", "logging", "formatting" ]
I'm currently trying to right align the logging level field in my Python logger so that output such as: ``` [2011-10-14 13:47:51] [DEBUG] --- starting... (smtphandlers.py:96) [2011-10-14 13:47:51] [INFO] --- first things first... (smtphandlers.py:97) [2011-10-14 13:47:51] [WARNING] --- about to end... (smtphandlers.py...
Like this: ``` logging.Formatter("[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S") ```
How to escape {{ or }} in django template?
7,772,001
34
2011-10-14T18:33:13Z
7,772,192
39
2011-10-14T18:50:42Z
[ "python", "django" ]
Django treats `{{ var }}` as some variable in its template. How can I escape `{{ var }}` or `{{` or `}}` such that django does not treat it as variable. `<p>"{{ some text }}"</p>` Should prints exactly the same.
I believe you are looking for the [`templatetag`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#templatetag) template tag. As the linked-to doc states, > Since the template system has no concept of "escaping", to display one of the bits used in template tags, you must use the `{% templatetag %}` tag. ...
How to escape {{ or }} in django template?
7,772,001
34
2011-10-14T18:33:13Z
7,772,230
9
2011-10-14T18:54:45Z
[ "python", "django" ]
Django treats `{{ var }}` as some variable in its template. How can I escape `{{ var }}` or `{{` or `}}` such that django does not treat it as variable. `<p>"{{ some text }}"</p>` Should prints exactly the same.
You can try escaping with html character escapes like: { = `&#123;` } = `&#125;` ``` <p>"&#123;&#123; some text &#125;&#125;"</p> ``` Try that inside your browser.
How to escape {{ or }} in django template?
7,772,001
34
2011-10-14T18:33:13Z
10,098,241
16
2012-04-11T00:16:40Z
[ "python", "django" ]
Django treats `{{ var }}` as some variable in its template. How can I escape `{{ var }}` or `{{` or `}}` such that django does not treat it as variable. `<p>"{{ some text }}"</p>` Should prints exactly the same.
**Edit:** I don't really recommended this because it's not very clean, but it's still an option. I was searching for one that I could use with JQuery Templates and figured a way to do it without tags or filters. This is as short as I could get it: ``` {{ "{{ any text }" }}} ``` Is printed as: ``` {{ any text }} ```...
How to escape {{ or }} in django template?
7,772,001
34
2011-10-14T18:33:13Z
14,259,259
75
2013-01-10T13:40:14Z
[ "python", "django" ]
Django treats `{{ var }}` as some variable in its template. How can I escape `{{ var }}` or `{{` or `}}` such that django does not treat it as variable. `<p>"{{ some text }}"</p>` Should prints exactly the same.
Django 1.5 introduced [`{% verbatim %}`](https://docs.djangoproject.com/en/dev/ref/templates/builtins/#std%3atemplatetag-verbatim) template tag. It stops template from parsing contents of this tag: ``` {% verbatim %} {{ var }} {% endverbatim %} ``` will be rendered as: ``` {{ var }} ```
main color detection in Python
7,772,510
7
2011-10-14T19:18:25Z
7,773,174
8
2011-10-14T20:23:05Z
[ "python", "colors", "detection" ]
I have about 3000 images and 13 different colors (the background of the majority of these images is white). If the main color of an image is one of those 13 different colors, I'd like them to be associated. I've seen similar questions like [Image color detection using python](http://stackoverflow.com/questions/2270874...
You can use the [getcolors](http://effbot.org/tag/PIL.Image.Image.getcolors) function to get a list of all colors in the image. It returns a list of tuples in the form: ``` (N, COLOR) ``` where `N` is the number of times the color `COLOR` occurs in the image. To get the maximum occurring color, you can pass the list ...
M2Crypto doesn't install in venv, or swig doesn't define __x86_64__ which breaks compiling against OpenSSL
7,772,965
27
2011-10-14T20:04:52Z
7,855,209
26
2011-10-21T20:57:28Z
[ "python", "linux", "openssl", "swig", "virtualenv" ]
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.ta...
M2Crypto supplies a fedora\_setup.sh script to handle the problems with Fedora/RL/CentOs releases, but pip, of course, doesn't know anything about it. After the pip install fails, it leaves the downloaded stuff in the venv/build/M2Crypto directory. do this: ``` cd <path-to-your-venv>/venv/build/M2Crypto chmod u+x fed...
M2Crypto doesn't install in venv, or swig doesn't define __x86_64__ which breaks compiling against OpenSSL
7,772,965
27
2011-10-14T20:04:52Z
19,612,308
8
2013-10-26T21:51:55Z
[ "python", "linux", "openssl", "swig", "virtualenv" ]
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.ta...
You just don't have `swig` installed. **Try:** ``` sudo yum install swig ``` **And then:** ``` sudo easy_install M2crypto ```
M2Crypto doesn't install in venv, or swig doesn't define __x86_64__ which breaks compiling against OpenSSL
7,772,965
27
2011-10-14T20:04:52Z
27,012,264
8
2014-11-19T08:38:59Z
[ "python", "linux", "openssl", "swig", "virtualenv" ]
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.ta...
I did this and it works very well : ``` env SWIG_FEATURES="-cpperraswarn -includeall -I/usr/include/openssl" pip install M2Crypto ``` Of course you have to install swigg with `sudo yum install swig` before
Case insensitive unique model fields in Django?
7,773,341
17
2011-10-14T20:41:12Z
7,773,515
15
2011-10-14T21:01:38Z
[ "python", "django", "postgresql", "model" ]
I have basically a username is unique (case insensitive), but the case matters when displaying as provided by the user. I have the following requirements: * field is CharField compatible * field is unique, but case insensitive * field needs to be searchable ignoring case (avoid using iexact, easily forgotten) * field...
Store the original **mixed-case string in a plain text column**. Use the data type **`text`** or `varchar` without length modifier rather than `varchar(n)`. They are essentially the same, but with varchar(n) you have to set an arbitrary length limit, that can be a pain if you want to change later. Read more about that ...
Case insensitive unique model fields in Django?
7,773,341
17
2011-10-14T20:41:12Z
7,774,039
14
2011-10-14T22:01:38Z
[ "python", "django", "postgresql", "model" ]
I have basically a username is unique (case insensitive), but the case matters when displaying as provided by the user. I have the following requirements: * field is CharField compatible * field is unique, but case insensitive * field needs to be searchable ignoring case (avoid using iexact, easily forgotten) * field...
With overriding the model manager, you have two options. First is to just create a new lookup method: ``` class MyModelManager(models.Manager): def get_by_username(self, username): return self.get(username__iexact=username) class MyModel(models.Model): ... objects = MyModelManager() ``` Then, you use...
cannot urllib.urlencode a URL in python
7,774,003
3
2011-10-14T21:57:33Z
7,774,042
11
2011-10-14T22:02:02Z
[ "python", "urlencode", "urllib" ]
Why am I getting this error when trying to urlencode this string ``` >>> callback = "http://localhost/application/authtwitter?twitterCallback" >>> urllib.urlencode(callback) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/urllib.py", line 1261, in urlencod...
That's not what that function does: ``` urlencode(query, doseq=0) Encode a sequence of two-element tuples or dictionary into a URL query string. ``` Are you looking for `urllib.quote(callback)`?
Load an html5 canvas into a PIL Image with Django
7,774,686
8
2011-10-14T23:42:10Z
7,774,848
18
2011-10-15T00:20:42Z
[ "javascript", "python", "django", "canvas", "python-imaging-library" ]
I'm trying to get the contents of an html5 canvas and pass it to my django server, where it will then be manipulated with PIL and saved as a PNG. Here's what I have so far: From the HTML form, the user clicks the "update" button, the canvas's contents - with canvas.toDataURL() - gets dumped into a text box that is sub...
``` import re datauri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' imgstr = re.search(r'base64,(.*)', datauri).group(1) output = open('output.png', 'wb') output.write(imgstr.decode('base64')) output.close() ``` or if...
Equivalent of "whos" command in Python Numpy
7,774,964
11
2011-10-15T00:42:35Z
7,774,983
18
2011-10-15T00:46:41Z
[ "python", "matlab", "numpy", "octave" ]
I am new to Numpy and trying to search for a function to list out the variables along with their sizes (both the matrix dimensions as well as memory usage) but couldn't find one. I am essentially looking for an equivalent of the "whos" command in MATLAB and Octave. Does there exist any such command in Python Numpy? Th...
If you are using [IPython](http://ipython.org/), there is a `whos` command built-in: ``` In [9]: whos Variable Type Data/Info ------------------------------- a ndarray 4x4x3: 48 elems, type `int64`, 384 bytes b ndarray 100000: 100000 elems, type `int64`, 800000 bytes (781 kb) np ...
"no matching architecture in universal wrapper" when importing pygame
7,775,948
11
2011-10-15T05:22:07Z
14,905,909
14
2013-02-16T01:20:06Z
[ "python", "osx", "osx-snow-leopard", "pygame", "python-2.7" ]
I'm on a MacBook Pro running Snow Leopard 10.6.8 and Python 2.7.2. I went on the pygame website, downloaded and installed all the required frameworks and programs, compiled and installed pygame, but I cant import the module into python. I downloaded an example program off of the pygame website and every time I run it I...
Removing the old pygame install and reinstalling did the trick for me. I'm running Mac OS 10.7 > sudo rm -Rf /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame Then copy and install pygame from: > <http://www.pygame.org/ftp/pygame-1.9.2pre-py2.7-macosx10.7.mpkg.zip>
Read txt file with multi-threaded in python
7,776,293
10
2011-10-15T06:46:15Z
7,776,848
7
2011-10-15T09:01:54Z
[ "python", "multithreading", "text-files" ]
I'm trying to read a file in python (scan it lines and look for terms) and write the results- let say, counters for each term. I need to do that for a big amount of files (more than 3000). Is it possible to do that multi threaded? If yes, how? So, the scenario is like this: * Read each file and scan its lines * Write...
I agree with @aix, `multiprocessing` is definitely the way to go. Regardless you will be i/o bound -- you can only read so fast, no matter how many parallel processes you have running. But there can easily be *some* speedup. Consider the following (input/ is a directory that contains several .txt files from Project Gu...
append two data frame with pandas
7,776,679
22
2011-10-15T08:21:17Z
7,779,260
33
2011-10-15T16:58:28Z
[ "python", "pandas" ]
I try to merge dataframes by rows doing: ``` bigdata=data1.append(data2) ``` and I get the following error: ``` Exception: Index cannot contain duplicate values! ``` The index of the first data frame starts from 0 to 38 and the second one from 0 to 48. I didn't understand that I have to modify the index of one of t...
The `append` function has an optional argument `ignore_index` which you should use here to join the records together, since the index isn't meaningful for your application.
SQL join or R's merge() function in NumPy?
7,776,907
6
2011-10-15T09:13:21Z
7,778,713
9
2011-10-15T15:22:49Z
[ "python", "sql", "numpy" ]
Is there an implementation where I can join two arrays based on their keys? Speaking of which, is the canonical way to store keys in one of the NumPy columns (NumPy doesn't have an 'id' or 'rownames' attribute)?
If you want to use only numpy, you can use **structured arrays** and the `lib.recfunctions.join_by` function (see <http://pyopengl.sourceforge.net/pydoc/numpy.lib.recfunctions.html>). A little example: ``` In [1]: import numpy as np ...: import numpy.lib.recfunctions as rfn ...: a = np.array([(1, 10.), (2, 20.),...
python insert vs append
7,776,938
11
2011-10-15T09:21:18Z
7,776,972
25
2011-10-15T09:28:23Z
[ "python" ]
I have written basic python snippets to first insert values in a list and then reverse them and what i found was there was a huge difference of speed of execution between insert and append methods. Snippet 1: ``` L = [] for i in range(10**5): L.append(i) L.reverse() ``` Time taken to execute this : ``` real 0m0...
Here is the complete [answer](http://bytes.com/topic/python/answers/34036-timing-difference-insert-vs-append-reverse) from *Duncan Booth*: > A list is implemented by an array of pointers to the objects it > contains. > > Every time you call 'insert(0, indx)', all of the pointers already in > the list have to be moved ...
python insert vs append
7,776,938
11
2011-10-15T09:21:18Z
7,777,034
9
2011-10-15T09:40:36Z
[ "python" ]
I have written basic python snippets to first insert values in a list and then reverse them and what i found was there was a huge difference of speed of execution between insert and append methods. Snippet 1: ``` L = [] for i in range(10**5): L.append(i) L.reverse() ``` Time taken to execute this : ``` real 0m0...
Note that your results will depend on the precise Python implementation. cpython (and pypy) automatically resize your list and *overprovision* space for future appends and thereby speed up the `append` furthermore. Internally, lists are just chunks of memory with a constant size (on the *heap*). Sometimes you're lucky...
python try:except:finally
7,777,456
21
2011-10-15T11:12:24Z
7,777,468
41
2011-10-15T11:14:45Z
[ "python", "exception", "file-io", "try-catch" ]
``` # Open new file to write file = None try: file = open(filePath, 'w') except IOError: msg = ("Unable to create file on disk.") file.close() return finally: file.write("Hello World!") file.close() ``` The above code is ripped from a function. One of the user's system is reporting an error in ...
You shouldn't be writing to the file in the `finally` block as any exceptions raised there will not be caught by the `except` block. The `except` bock executes if there is an exception raised by the try block. The `finally` block *always* executes whatever happens. Also, there shouldn't be any need for initialising t...
python try:except:finally
7,777,456
21
2011-10-15T11:12:24Z
7,777,487
19
2011-10-15T11:17:51Z
[ "python", "exception", "file-io", "try-catch" ]
``` # Open new file to write file = None try: file = open(filePath, 'w') except IOError: msg = ("Unable to create file on disk.") file.close() return finally: file.write("Hello World!") file.close() ``` The above code is ripped from a function. One of the user's system is reporting an error in ...
If the file is not opened, the line `file = open(filePath, 'w')` fails, so nothing gets assigned to `file`. Then, the `except` clause runs, but nothing is in file, so `file.close()` fails. The `finally` clause always runs, even if there was an exception. And since `file` is still None you get another exception. You ...
Iterating over submitted form fields in Flask?
7,777,850
4
2011-10-15T12:35:25Z
7,777,905
15
2011-10-15T12:49:34Z
[ "python", "flask" ]
In Flask 0.8, I know I can access individual form fields using `form.fieldname.data`, but is there a simple way of iterating over all the form fields? I'm building an email message body, and I'd like to loop over all the fields and create a fieldname/value entry for each, as opposed to manually building it by naming ea...
I suspect that your are using [WTForms](http://wtforms.readthedocs.org/en/latest/). You can iterate over form data: ``` for fieldname, value in form.data.items(): pass ``` You can iterate over all form fields: ``` for field in form: # these are available to you: field.name field.description fiel...
Python - getattr and concatenation
7,778,867
2
2011-10-15T15:50:52Z
7,778,877
11
2011-10-15T15:52:54Z
[ "python", "getattr" ]
So in playing around with getattr in my code I discovered the following: ``` myVariable = foo.A.bar ``` works...but something like this: ``` B = "A" myVariable = getattr(foo, B + ".bar") ``` returns an error that foo does not contain an attribute A.bar. Where am I going wrong? Thanks!
Because there is no attribute `A.bar` on `foo`. Attribute `bar` is a part of the object pointed to by `A`, which is an attribute of `foo`. You need either ``` getattr(foo.A, "bar") ``` or ``` getattr(getattr(foo, 'A'), 'bar') ``` The generic code for accessing deep attributes is to split on the dot, and go until th...
Elegantly changing the color of a plot frame in matplotlib
7,778,954
14
2011-10-15T16:06:30Z
7,944,576
7
2011-10-30T11:12:33Z
[ "python", "colors", "matplotlib" ]
This is a kind of follow-up question to [this](http://stackoverflow.com/questions/4761623/changing-the-color-of-the-axis-ticks-and-labels-for-a-plot-in-matplotlib) post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this. Changing the color of a c...
Refactoring your code above: ``` import matplotlib.pyplot as plt for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']): plt.setp(ax.spines.values(), color=color) plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color) ```
How can i determine the exact size of a type used by python
7,779,207
6
2011-10-15T16:48:36Z
7,779,281
10
2011-10-15T17:03:03Z
[ "python" ]
``` >>> sys.getsizeof(int) 436 #? does this mean int occupies 436 bytes . >>> sys.getsizeof(1) 12 #12 bytes for int object, is this the memory requirement. ``` I thought int in python is represented by 4 bytes, why is it reporting 12 bytes Please someone explain why is it reporting 12 bytes when int uses just 4 byte...
Yes, an `int` instance takes up 12 bytes on your system. Integers (like any object) have attributes, i.e. pointers to other objects, which take up additional memory space beyond that used by the object's own value. So 4 bytes for the integer's value, 4 bytes for a pointer to `__class__` (otherwise, Python wouldn't know...
Stop running tests if setUp raises an exception in Python unittest
7,779,434
5
2011-10-15T17:31:34Z
7,779,760
8
2011-10-15T18:24:39Z
[ "python", "testing" ]
I have this test class: ``` class mytest(unittest.TestCase): def setUp(self): os.mkdir(...) ... def tearDown(self): shutil.rmtree(...) def test_one(self): ... def test_two(self): ... ``` If something fails after `mkdir` has ran when running `setUp` of `test_o...
Add a failure call in the setUp method. ``` def setUp(self): try: somethingThatMightFail() except: self.fail() ```
Assignment Condition in Python While Loop
7,780,998
14
2011-10-15T22:12:39Z
7,781,008
12
2011-10-15T22:14:18Z
[ "python", "loops", "while-loop", "condition" ]
In C, one can do ``` while( (i=a) != b ) { } ``` but in Python, it appears, one cannot. ``` while (i = sys.stdin.read(1)) != "\n": ``` generates ``` while (i = sys.stdin.read(1)) != "\n": ^ SyntaxError: invalid syntax ``` (the `^` should be on the `=`) Is there a workaround?
Use break: ``` while True: i = sys.stdin.read(1) if i == "\n": break # etc... ```
Assignment Condition in Python While Loop
7,780,998
14
2011-10-15T22:12:39Z
9,217,524
7
2012-02-09T19:37:45Z
[ "python", "loops", "while-loop", "condition" ]
In C, one can do ``` while( (i=a) != b ) { } ``` but in Python, it appears, one cannot. ``` while (i = sys.stdin.read(1)) != "\n": ``` generates ``` while (i = sys.stdin.read(1)) != "\n": ^ SyntaxError: invalid syntax ``` (the `^` should be on the `=`) Is there a workaround?
You can accomplish this using the built-in function [`iter()`](http://docs.python.org/library/functions.html#iter) using the two-argument call method: ``` import functools for i in iter(fuctools.partial(sys.stdin.read, 1), '\n'): ... ``` Documentation for this: > [`iter(o[, sentinel])`](http://docs.python.org/li...
How can I represent an infinite number in Python?
7,781,260
189
2011-10-15T23:06:22Z
7,781,271
21
2011-10-15T23:09:22Z
[ "python", "infinite" ]
In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
I don't know exactly what you are doing, but `float("inf")` gives you a float Infinity, which is greater than any other number.
How can I represent an infinite number in Python?
7,781,260
189
2011-10-15T23:06:22Z
7,781,273
223
2011-10-15T23:09:43Z
[ "python", "infinite" ]
In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
In Python, you can do: ``` test = float("inf") ``` In Python 3.5, you can do: ``` import math test = math.inf ``` And then: ``` test > 1 test > 10000 test > x ``` Will always be true. Unless of course, as pointed out, x is also infinity or "nan" ("not a number"). Additionally (Python 2.x ONLY), in a comparison t...
How can I represent an infinite number in Python?
7,781,260
189
2011-10-15T23:06:22Z
19,330,332
13
2013-10-12T03:53:16Z
[ "python", "infinite" ]
In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
Another, less convenient, way to do it is to use [`Decimal`](http://docs.python.org/2/library/decimal.html) class: ``` from decimal import Decimal pos_inf = Decimal('Infinity') neg_inf = Decimal('-Infinity') ```
How can I represent an infinite number in Python?
7,781,260
189
2011-10-15T23:06:22Z
26,815,934
7
2014-11-08T10:07:23Z
[ "python", "infinite" ]
In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary): ``` None < any integer < any string ``` Thus the check `i < ''` holds `True` for any integer `i`. It has been reasonably deprecated in python3. Now such comparisons end up with ``` TypeError: unorderable types: ...
How can I represent an infinite number in Python?
7,781,260
189
2011-10-15T23:06:22Z
30,157,018
16
2015-05-10T21:49:53Z
[ "python", "infinite" ]
In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this representation of infinity.
Since Python 3.5 you can use `math.inf`: ``` >>> import math >>> math.inf inf ```
how to get all folder only in a given path in python?
7,781,545
12
2011-10-16T00:14:31Z
7,781,555
21
2011-10-16T00:19:34Z
[ "python" ]
i'm using this code to get all files in a given folder. Is there a way to get only the folders ? ``` a = os.listdir('Tools') ```
``` import os.path dirs = [d for d in os.listdir('Tools') if os.path.isdir(os.path.join('Tools', d))] ```
Selenium waitForElement
7,781,792
23
2011-10-16T01:33:11Z
7,784,387
7
2011-10-16T12:55:45Z
[ "python", "selenium-webdriver" ]
How do I write the function for Selenium to wait for a table with just a class identifier in Python? I'm having a devil of a time learning to use Selenium's Python webdriver functions.
I have made good experiences using: * time.sleep(seconds) * webdriver.Firefox.implicitly\_wait(seconds) The first one is pretty obvious - just wait a few seconds for some stuff. For all my Selenium Scripts the sleep() with a few seconds (range from 1 to 3) works when I run them on my laptop, but on my Server the tim...
Selenium waitForElement
7,781,792
23
2011-10-16T01:33:11Z
8,861,512
23
2012-01-14T10:05:29Z
[ "python", "selenium-webdriver" ]
How do I write the function for Selenium to wait for a table with just a class identifier in Python? I'm having a devil of a time learning to use Selenium's Python webdriver functions.
From the [Selenium Documentation PDF](http://seleniumhq.org/docs/book/Selenium_Documentation.pdf) : ``` import contextlib import selenium.webdriver as webdriver import selenium.webdriver.support.ui as ui with contextlib.closing(webdriver.Firefox()) as driver: driver.get('http://www.google.com') wait = ui.WebD...
Selenium waitForElement
7,781,792
23
2011-10-16T01:33:11Z
13,058,101
18
2012-10-24T21:31:48Z
[ "python", "selenium-webdriver" ]
How do I write the function for Selenium to wait for a table with just a class identifier in Python? I'm having a devil of a time learning to use Selenium's Python webdriver functions.
Selenium 2's Python bindings have a new support class called expected\_conditions.py for doing all sorts of things like testing if an element is visible. It's available here : <http://code.google.com/p/selenium/source/browse/trunk/py/selenium/webdriver/support/expected_conditions.py> NOTE: the above file is in trunk ...
How do I use url_for if my method has multiple route annotations?
7,782,046
34
2011-10-16T02:49:54Z
7,794,516
53
2011-10-17T13:32:42Z
[ "python", "google-app-engine", "flask", "werkzeug" ]
So I have a method that is accessible by multiple routes: ``` @app.route("/canonical/path/") @app.route("/alternate/path/") def foo(): return "hi!" ``` Now, how can I call `url_for("foo")` and know that I will get the first route?
Ok. It took some delving into the `werkzeug.routing` and `flask.helpers.url_for` code, but I've figured out. You just change the `endpoint` for the route (in other words, you **name** your route) ``` @app.route("/canonical/path/", endpoint="foo-canonical") @app.route("/alternate/path/") def foo(): return "hi!" @a...
How do I use url_for if my method has multiple route annotations?
7,782,046
34
2011-10-16T02:49:54Z
7,876,088
42
2011-10-24T13:07:50Z
[ "python", "google-app-engine", "flask", "werkzeug" ]
So I have a method that is accessible by multiple routes: ``` @app.route("/canonical/path/") @app.route("/alternate/path/") def foo(): return "hi!" ``` Now, how can I call `url_for("foo")` and know that I will get the first route?
Rules in Flask are unique. If you define the absolute same URL to the same function it will by default clash because you're doing something which we stop you from doing since from our perspective that is wrong. There is one reason why you would want to have more than one URL to the absolute same endpoint and that is b...
How can I get right-click context menus for clicks in QTableView header?
7,782,071
6
2011-10-16T02:57:14Z
7,782,125
10
2011-10-16T03:11:35Z
[ "python", "header", "pyqt", "contextmenu", "qtableview" ]
The sample code below (heavily influenced from [here](http://www.saltycrane.com/blog/2007/12/pyqt-43-qtableview-qabstracttablemodel/)) has a right-click context menu that will appear as the user clicks the cells in the table. Is it possible to have a different right-click context menu for right-clicks in the header of ...
Turned out to be simpler than I thought. In the same manner as I add the popup menu for the QTableView widget itself, I can just get the header from table object and then attach a context menu in the same way as I did with the regular context menu. ``` headers = self.tv.horizontalHeader() headers.setContextMenuPolicy(...
Java raw audio output
7,782,721
5
2011-10-16T06:17:52Z
7,782,749
16
2011-10-16T06:26:38Z
[ "java", "python", "audio", "javasound" ]
Just wondering if there is a library in Java like the module [PyAudiere](http://pyaudiere.org/) in Python, that simply allows you to create tones and play them, like this sample Python code: ``` device = audiere.open_device() tone = device.create_tone(500) #create a 500hz tone tone.play() tone.stop() ``` This simply ...
It is pretty simple to generate a sound in memory. E.G. ![Beeper](http://i.stack.imgur.com/U8dty.png) The important part of generating the tone (and storing it in a `Clip`) is encompassed in this code: ``` /** Generates a tone, and assigns it to the Clip. */ public void generateTone() throws LineUnavailableExce...
How to convert BeautifulSoup.ResultSet to string
7,782,772
5
2011-10-16T06:33:00Z
9,865,533
9
2012-03-26T01:15:41Z
[ "python", "unicode", "beautifulsoup" ]
So I parsed a html page with `.findAll` (BeautifulSoup) to variable named `result`. If I type `result` in Python shell then press Enter, I see normal text as expected, but as I wanted to postprocess this result as string object, I noticed that `str(result)` returns garbage, like this sample: ``` \xd1\x87\xd0\xb8\xd0\x...
Python 2.6.7 BeautifulSoup.**version** 3.2.0 This worked for me: ``` unicode.join(u'\n',map(unicode,result)) ``` I'm pretty sure a `result` is a `BeautifulSoup.ResultSet` object, which seems to be an extension of the standard python list
When to use triple single quotes instead of triple double quotes
7,783,097
22
2011-10-16T08:10:07Z
7,783,116
47
2011-10-16T08:14:00Z
[ "python", "quotes" ]
Learn Python the hard way, exercise 10.2: ``` tabby_cat = "\tI'm tabbed in." persian_cat = "I'm split\non a line." backslash_cat = "I'm \\ a \\ cat." fat_cat = """ I'll do a list: \t* Cat food \t* Fishies \t* Catnip\n\t* Grass """ print tabby_cat print persian_cat print backslash_cat print fat_cat ``` 2: Use `'''` ...
The only reason you might need `"""` instead of `'''` (or vice versa) is if the string itself contains a triple quote. ``` s1 = '''This string contains """ so use triple-single-quotes.''' s2 = """This string contains ''' so use triple-double-quotes.""" ``` If a string contains both triple-single-quotes *and* triple-d...
os.path.dirname(__file__) returns empty
7,783,308
71
2011-10-16T09:03:07Z
7,783,326
124
2011-10-16T09:06:29Z
[ "python" ]
I want to get the path of current directory under which the .py file is executing. A simple file `D:\test.py` with code: ``` import os print os.getcwd() print os.path.basename(__file__) print os.path.abspath(__file__) print os.path.dirname(__file__) ``` It is wired that the output is: ``` D:\ test.py D:\test.py EM...
Because `os.path.abspath = os.path.dirname + os.path.basename` does not hold. we rather have ``` os.path.dirname(filename) + os.path.basename(filename) == filename ``` Both `dirname()` and `basename()` only split the passed filename into components without taking into account the current directory. If you want to als...
Understanding repr( ) function in Python
7,784,148
67
2011-10-16T12:07:55Z
7,784,214
92
2011-10-16T12:22:14Z
[ "python", "repr" ]
`repr()`: evaluatable string representation of an object (can "eval()" it, meaning it is a string representation that evaluates to a Python object) In other words: ``` >>> x = 'foo' >>> repr(x) "'foo'" ``` Questions: 1. Why do I get the double quotes when I do `repr(x)`? (I don't get them when I do `str(x)`) 2. ...
``` >>> x = 'foo' >>> x 'foo' ``` So the name `x` is attached to `'foo'` string. When you call for example `repr(x)` the iterpreter puts `'foo'` instead of `x` and then calls `repr('foo')`. ``` >>> repr(x) "'foo'" >>> x.__repr__() "'foo'" ``` `repr` actually calls a magic method `__repr__` of `x`, which gives the **...
Using Sqlite3 on Heroku Cedar stack
7,784,471
12
2011-10-16T13:07:32Z
7,784,785
22
2011-10-16T14:06:48Z
[ "python", "sqlite3", "heroku" ]
Is there a way to use Sqlite3 with Django on Heroku?
The cedar stack's filesystem is *not* readonly. However, you still mustn't store any data on it because the filesystem is *ephemeral*. Any time your application restarts, whatever you had written to your application's filesystem disappears forever. Any time you add a dyno, the two dynos each have their own ephemeral...
Better Python list Naming Other than "list"
7,785,071
6
2011-10-16T14:57:56Z
7,785,095
12
2011-10-16T15:00:40Z
[ "python", "naming-conventions" ]
Is it better not to name list variables "list"? Since it's conflicted with the python reserved keyword. Then, what's the better naming? "input\_list" sounds kinda awkward. I know it can be problem-specific, but, say I have a quick sort function, then quick\_sort(unsorted\_list) is still kinda lengthy, since list passe...
I like to name it with the plural of whatever's in it. So, for example, if I have a list of names, I call it `names`, and then I can write: ``` for name in names: ``` which I think looks pretty nice. But generally for your own sanity you should name your variables so that you can know what they are just from the name...
Parse paragraphs from HTML using lxml
7,785,463
2
2011-10-16T15:58:49Z
7,785,530
7
2011-10-16T16:09:30Z
[ "python", "lxml" ]
I am new to lxml and want to extract `<p>PARAGRAPHS</p>` and `<li>PARAGRAPHS</li>` from a given url and use them for further steps. I followed an example from a [post](http://stackoverflow.com/questions/5034351/extracting-paragraph-in-python-using-lxml), and tried the following code with no luck: ``` html = lxml.html...
``` import lxml.html htmltree = lxml.html.parse('http://www.google.com/intl/en/about/corporate/index.html') print htmltree.xpath('//p/text()') ```