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
Writing a context manager in Python that itself uses a with statement
11,441,042
8
2012-07-11T20:34:32Z
11,441,372
10
2012-07-11T20:58:16Z
[ "python", "contextmanager" ]
I'm trying to write a context manager that uses other context managers, so clients don't need to know the whole recipe, just the interface I'm presenting. I can't do it using `@contextmanager` - the code after `yield` call doesn't get executed if you're interrupted by an exception, so I need to use a class-based manage...
``` @contextmanager def compl(arg, val):    with simple("one",1):         with simple("two",2): print "enter complex", arg try:                 d[arg] = val yield finally:         del d[arg]         print "exit complex", arg ```
How I can make apt-get install to my virtualenv?
11,441,546
10
2012-07-11T21:11:00Z
13,710,008
13
2012-12-04T18:59:22Z
[ "python", "virtualenv", "apt-get" ]
It it's possible, of course. For example - I can download python-dbus like this: $ sudo apt-get download python-dbus But what I should to do next, with this .deb package in my current virtualenv?
If you really need to do it this way, you can just copy the files that get installed globally directly into your virtualenv. For example I couldn't get pycurl working since the required libraries weren't installing, but `apt-get install python-pycurl` did. So I did the following: ``` sudo apt-get install python-pycurl...
How to get SVMs to play nicely with missing data in scikit-learn?
11,441,751
17
2012-07-11T21:26:25Z
11,455,375
19
2012-07-12T15:34:29Z
[ "python", "machine-learning", "scikit-learn" ]
I am using scikit-learn for some data analysis, and my dataset has some missing values (represented by `NA`). I load the data in with `genfromtxt` with `dtype='f8'` and go about training my classifier. The classification is fine on `RandomForestClassifier` and `GradientBoostingClassifier` objects, but using `SVC` from...
You can do data imputation to handle missing values before using SVM. EDIT: In scikit-learn, there's a really easy way to do this, illustrated on [this page](http://scikit-learn.org/stable/modules/preprocessing.html#imputation-of-missing-values). (copied from page and modified) ``` >>> import numpy as np >>> from sk...
Safe to change base class in python?
11,442,100
13
2012-07-11T21:55:57Z
11,442,256
7
2012-07-11T22:09:21Z
[ "python", "class" ]
Questions like this exist, but none exactly like this, and I found no completely satisfactory answers. I'm doing an agent-based biological model. Suppose I have a class of cell type A, and one of type B. They age according to a clock. Suppose when a cell of type A reaches a certain age, it changes to a cell of type B....
While it may be safe for the interpreter, it is definitely unsafe to one trying to understand what's happening. It is hard to find a more natural mapping to object design than a biological cell and you are trying to discard what is naturally there. A cell **has-a** age and various mechanisms turn on and off as a funct...
Parallelizing a Numpy vector operation
11,442,191
30
2012-07-11T22:03:58Z
11,442,933
13
2012-07-11T23:17:22Z
[ "python", "numpy", "multiprocessing" ]
Let's use, for example, `numpy.sin()` The following code will return the value of the sine for each value of the array `a`: ``` import numpy a = numpy.arange( 1000000 ) result = numpy.sin( a ) ``` But my machine has 32 cores, so I'd like to make use of them. (The overhead might not be worthwhile for something like `...
Well this is kind of interesting note if you run the following commands: ``` import numpy from multiprocessing import Pool a = numpy.arange(1000000) pool = Pool(processes = 5) result = pool.map(numpy.sin, a) UnpicklingError: NEWOBJ class argument has NULL tp_new ``` wasn't expecting that, so whats going on, well...
Parallelizing a Numpy vector operation
11,442,191
30
2012-07-11T22:03:58Z
11,460,119
35
2012-07-12T20:28:37Z
[ "python", "numpy", "multiprocessing" ]
Let's use, for example, `numpy.sin()` The following code will return the value of the sine for each value of the array `a`: ``` import numpy a = numpy.arange( 1000000 ) result = numpy.sin( a ) ``` But my machine has 32 cores, so I'd like to make use of them. (The overhead might not be worthwhile for something like `...
There **is** a better way: [numexpr](https://github.com/pydata/numexpr) Slightly reworded from their main page: It's a multi-threaded VM written in C that analyzes expressions, rewrites them more efficiently, and compiles them on the fly into code that gets near optimal parallel performance for both memory and cpu bo...
Combining multiple regex substitutions
11,442,470
7
2012-07-11T22:28:48Z
11,442,587
12
2012-07-11T22:39:55Z
[ "python", "regex" ]
I'm trying to delete some things from a block of text using regex. I have all of my patterns ready, but I can't seem to be able to remove two (or more) that overlap. For example: ``` import re r1 = r'I am' r2 = r'am foo' text = 'I am foo' re.sub(r1, '', text) # Returns ' foo' re.sub(r2, '', text) # Returns 'I ...
You can't do it with consecutive `re.sub` calls as you have shown. You can use `re.finditer` to find them all. Each match will provide you with a match object, which has `.start` and `.end` attributes indicating their positions. You can collect all those together, and then remove characters at the end. Here I use a `b...
Python multiprocessing Queue failure
11,442,892
5
2012-07-11T23:12:20Z
11,443,081
8
2012-07-11T23:33:07Z
[ "python", "queue", "multiprocessing" ]
I create 100 child processes ``` proc_list = [ Process(target = simulator, args=(result_queue,)) for i in xrange(100)] ``` and start them ``` for proc in proc_list: proc.start() ``` Each process puts into the result\_queue (instance of multiprocessing.Queue) 10000 tuples after doing some processing. ``` de...
My solution to multiprocessing issues is almost always to use the Manager objects. While the exposed interface is the same, the underlying implementation is much simpler and has less bugs. ``` from multiprocessing import Manager manager = Manager() result_queue = manager.Queue() ``` Try it out and see if it doesn't f...
How to set up Pylint to only do some inspections
11,442,910
6
2012-07-11T23:14:47Z
11,445,666
7
2012-07-12T05:47:23Z
[ "python", "pylint" ]
I'm trying to set up Pylint to only do certain inspections and no others, e.g. only check for W0601 and W0612. I've tried using an `enable=` line the the `[MESSAGES CONTROL]` section of my pylint.rc but that doesn't seem to do what I want. I'm using Pylint 0.25.1.
Looks like a bug with the way rc files are parsed. Order matters on the command line (undocumented?) so you need to disable first then enable: ``` pylint xyz.py --disable R,C,W,E --enable W0601,W0612 ``` **But this is not reflected correctly with `--generate-rcfile` and does not work with `--rcfile` ...these are pro...
numpy and scipy for preinstalled python 2.6.7 on mac OS Lion
11,442,970
12
2012-07-11T23:21:54Z
11,443,754
34
2012-07-12T01:07:14Z
[ "python", "numpy", "osx-lion", "scipy" ]
Is there anyway to install numpy and scipy on python 2.6.7 that comes with Mac OS Lion? I am aware that Lion has Python 2.7 as well. But I need to stick with Python 2.6 cause I am using a module that does not work on Python 2.7.
Lion comes with an [easy\_install](http://packages.python.org/distribute/easy_install.html) for each of its Python implementations: `/usr/bin/easy_install-2.7` for `/usr/bin/python2.7`, and likewise for 2.6 and 2.5. However, scipy requires a Fortran compiler, and Lion doesn't come with one of those. It also looks like...
numpy and scipy for preinstalled python 2.6.7 on mac OS Lion
11,442,970
12
2012-07-11T23:21:54Z
12,333,015
24
2012-09-08T17:38:39Z
[ "python", "numpy", "osx-lion", "scipy" ]
Is there anyway to install numpy and scipy on python 2.6.7 that comes with Mac OS Lion? I am aware that Lion has Python 2.7 as well. But I need to stick with Python 2.6 cause I am using a module that does not work on Python 2.7.
I was running into similar issues installing SciPy on Mountain Lion. OSX Mountain Lion 10.8 Python 2.7.3 pip 1.1 brew 0.9.2 GNU Fortran (GCC) 4.2.1 Some of the errors I was receiving include: This: ``` pip install scipy ``` Yielded this error: ``` Could not locate executable pgfortran don't know how to compi...
XML parsing in python: expaterror not well-formed
11,443,036
8
2012-07-11T23:28:02Z
11,443,058
7
2012-07-11T23:30:35Z
[ "python", "xml", "parsing" ]
I'm using Python's `xml.etree.ElementTree` to do some XML parsing on a file. However, I get this error mid-way through the document: ``` xml.parsers.expat.ExpatError: not well-formed (invalid token): line X, column Y ``` So I go to line X, column Y in vim and I see an ampersand (&) with red background highlighting. W...
The & is a special character in XML, used for character entities. If your XML has & sitting there by itself, not as part of an entity like `&` or `ѐ` or the like, then the XML is invalid.
Compiling numpy with OpenBLAS integration
11,443,302
30
2012-07-11T23:59:47Z
14,391,693
68
2013-01-18T02:50:38Z
[ "python", "numpy", "blas", "atlas" ]
I am trying to install `numpy` with `OpenBLAS` , however I am at loss as to how the `site.cfg` file needs to be written. When the [installation procedure](http://www.kde.cs.tut.ac.jp/~atsushi/?p=493#) was followed the installation completed without errors, however there is performance degradation on increasing the num...
I just compiled `numpy` inside a `virtualenv` with `OpenBLAS` integration, and it seems to be working OK. This was my process: 1. Compile `OpenBLAS`: ``` ~$ git clone https://github.com/xianyi/OpenBLAS ~$ cd OpenBLAS && make FC=gfortran ~$ sudo make PREFIX=/opt/OpenBLAS install ``` If you don't ha...
Are GAE instances limited to 10 concurrent request?
11,443,423
7
2012-07-12T00:17:09Z
11,443,482
8
2012-07-12T00:26:17Z
[ "java", "python", "google-app-engine", "go" ]
I heard from several sources that Google App Engine Instances have a hard limit of 10 concurrent request. I was wondering if someone could clarify what exactly this means. Does the scheduler block any requests over the 10, or is this enforced through a limit on concurrent threads? Specifically, does this limit affect...
As of July 12, 2012, it's the latter. The 10 concurrent limit is enforced through a limit on concurrent threads on every runtime. Most of such cases, our scheduler will try to spin up a new instance. Please also see the e-mail from jonmac on this thread: <https://groups.google.com/d/msg/google-appengine/y-LnZ2WYJ5Q/j_...
How to make a custom Number class convertible to int & float?
11,443,633
3
2012-07-12T00:46:30Z
11,443,650
7
2012-07-12T00:48:47Z
[ "python", "python-3.x", "numbers" ]
I have implemented a number class in python 3. What do I need to do so that ``` float(mynumber) ``` works correctly?
From the docs, [Emulating Numeric Types](http://docs.python.org/py3k/reference/datamodel.html#emulating-numeric-types): ``` object.__complex__(self) object.__int__(self) object.__long__(self) object.__float__(self) Called to implement the built-in functions complex(), int(), long(), and float(). Should return a ...
How to generate exponentially increasing range in Python
11,443,737
4
2012-07-12T01:04:06Z
11,443,791
8
2012-07-12T01:12:33Z
[ "python" ]
I want to test the performance of some code using an exponentially increasing value. So that as an extra digit is added to the numbers\_size the increment is multiplied by 10. This is how I'm doing it so far but it looks a bit hacky. Suggestions for improvements without introducing non-standard libraries? ``` numbers_...
Why not ``` for exponent in range(2, 10): test(10 ** exponent) ``` if I'm reading your intent right.
Better optimization technique using if/else or dictionary
11,445,226
5
2012-07-12T04:57:55Z
11,445,290
8
2012-07-12T05:07:25Z
[ "python", "algorithm" ]
Which is better optimization? * A series of if/else statement which receives the 'string' returns the appropriate function for it. (Around 40-50 if/else statements). * A dictionary maintaining the key-value pair. key as strings, and values as the function objects, and one main function to search and return the functio...
Choose the dictionary. The dictionary ... * is built-in * is pythonic * requires less boilerplate code * has O(1) complexity, compared to the if-else linear O(n) complexity * isn't guilty of premature pessimization (we have insufficient reason to believe without profiling that it is a less efficient method by a large...
python & smtplib: Is sending mail via gmail using oauth2 possible?
11,445,523
2
2012-07-12T05:32:21Z
11,448,844
14
2012-07-12T09:29:26Z
[ "python", "oauth", "oauth-2.0", "smtplib" ]
So I can login to and send mail through gmail using smtplib (using the script below), but I was just wondering if using oauth2 was an option like with imaplib? I didn't see anything on the smtplib documentation page about oauth and I haven't found anything googling. Thanks. ``` #! /usr/bin/python import smtplib to =...
Interesting, I think it is possible, I found the following links <https://developers.google.com/google-apps/gmail/oauth_overview> **UPDATE** <https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough> This is the new walk through using oauth2, it seems like xoauth has being declared obsolete, I've...
Is it okay to set instance variables in a Django class based view?
11,448,690
14
2012-07-12T09:20:59Z
11,448,882
30
2012-07-12T09:31:14Z
[ "python", "django", "django-class-based-views" ]
I trying out Django's class based views (CBVs). ``` class BlahView(TemplateView): template_name = 'blah/blah.html' def get_context_data(self, **kwargs): #code... def get(self, request, **kwargs): #more code... ``` Now, I know that I can get the request params from self.request. Now say I ...
According to [the source](https://github.com/django/django/blob/1.4/django/views/generic/base.py#L28) of `django.views.generic.base.View.as_view`: * **on django startup**, as\_view() returns a function `view`, which is **not** called * **on request**, `view()` **is called**, it instantiates the class and calls `dispat...
Changing the background color of the axes planes of a matplotlib 3D plot
11,448,972
8
2012-07-12T09:36:20Z
12,623,360
8
2012-09-27T14:09:50Z
[ "python", "3d", "matplotlib", "scatter-plot" ]
On the basis of the [scatterplot example](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/tutorial.html#scatter-plots) of matplotlib, how can I change the gray background color of the 3 axes grid planes? I would like to set it to white, keeping the grid lines with the default gray color. I found [this question](...
Using the same example. You can set the pane color using the `set_pane_color` method as described here <http://matplotlib.org/mpl_toolkits/mplot3d/api.html#axis3d>. You can set the color using the RGBA tuple: ``` # scatter3d_demo.py # ... # Set the background color of the pane YZ ax.w_xaxis.set_pane_color((1.0, 1.0, 1...
Multiple keys per value
11,449,232
32
2012-07-12T09:49:37Z
11,449,344
36
2012-07-12T09:55:28Z
[ "python", "python-3.x", "python-2.7" ]
Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key: ``` dict = {'k1':'v1', 'k2':'v1', 'k3':'v1', 'k4':'v2'} ``` but this is not memory efficient since my data file is > 2 GB. Otherwise you could make a dictionary of dictionary keys: ``` key_d...
What type are the values? ``` dict = {'k1':MyClass(1), 'k2':MyClass(1)} ``` will give duplicate value objects, but ``` v1 = MyClass(1) dict = {'k1':v1, 'k2':v1} ``` results in both keys referring to the same actual object. In the original question, your values are strings: even though you're declaring the same str...
Multiple keys per value
11,449,232
32
2012-07-12T09:49:37Z
16,966,988
7
2013-06-06T16:10:17Z
[ "python", "python-3.x", "python-2.7" ]
Is it possible to assign multiple keys per value in a Python dictionary. One possible solution is to assign value to each key: ``` dict = {'k1':'v1', 'k2':'v1', 'k3':'v1', 'k4':'v2'} ``` but this is not memory efficient since my data file is > 2 GB. Otherwise you could make a dictionary of dictionary keys: ``` key_d...
Check out this - it's an implementation of exactly what you're asking: multi\_key\_dict(ionary) <https://pypi.python.org/pypi/multi_key_dict> (sources at <https://github.com/formiaczek/python_data_structures/tree/master/multi_key_dict>) (on Unix platforms it possibly comes as a package and you can try to install it w...
how do i set proxy for chrome in python webdriver
11,450,158
9
2012-07-12T10:44:59Z
11,821,751
15
2012-08-06T02:00:23Z
[ "python", "google-chrome", "proxy", "webdriver" ]
I'm using this code: ``` profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy.http", "proxy.server.address") profile.set_preference("network.proxy.http_port", "port_number") profile.update_preferences() driver = webdriver.Firefox(firefox_profile=pro...
``` from selenium import webdriver PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--proxy-server=%s' % PROXY) chrome = webdriver.Chrome(chrome_options=chrome_options) chrome.get("http://whatismyipaddress.com") ```
Complex sort with multiple parameters?
11,450,277
5
2012-07-12T10:53:00Z
11,450,312
8
2012-07-12T10:55:00Z
[ "python" ]
I have a list of tuples: ``` li = [('fink', 3), ('flip', 3), ('flock', 4), ('foo', 12), ('foot', 20), ('football', 20), ('futz', 10), ('flip', 3), ('flank', 3), ('flop', 3)] ``` How can I sort the list by descent number first and then alphabetically descending? The results would be: ``` ('foot', 20) ('football', 20)...
This is too complicated for a single `itemgetter`. Use `lambda` instead: ``` sorted_li = sorted(li, key=lambda x: (-x[1], x[0])) ``` It is about the same speed as two consecutive sorts using `itemgetter`, but it is less code and probably more readable.
How do I convert a list of dictionaries to a dictionary of lists in Python?
11,450,575
10
2012-07-12T11:11:26Z
11,450,683
13
2012-07-12T11:17:39Z
[ "python", "dictionary" ]
It may be a classical question in Python, but I haven't found the answer yet. I have a list of dictionaries, these dictionaries have similar keys. It looks like this: ``` [{0: myech.MatchingResponse at 0x10d6f7fd0, 3: myech.MatchingResponse at 0x10d9886d0, 6: myech.MatchingResponse at 0x10d6f7d90, 9: myech...
``` import collections result = collections.defaultdict(list) for d in dictionaries: for k, v in d.items(): result[k].append(v) ```
Skip unittest if some-condition in SetUpClass fails
11,452,981
8
2012-07-12T13:33:33Z
11,453,318
17
2012-07-12T13:50:23Z
[ "python", "unit-testing", "python-3.x", "pyunit" ]
I was playing with `pyUnit` framework for unittest testing of my application. Is there any any way to skip all the tests in class if certain condition in setUpClass fails? Currently, I am setting up environment (creating resources, configuring global settings) in setUpClass. But, if any of these resource creation fail...
Got the answer: For those who gets stuck here- unittest can be skipped from setUpClass in following way- ``` raise unittest.SkipTest(message) ```
Why am I getting “HTTP Error 405: Method Not Allowed” when requesting a URL using urllib2?
11,453,078
5
2012-07-12T13:38:35Z
11,453,146
10
2012-07-12T13:41:58Z
[ "python", "urllib2", "urllib" ]
I am using urllib2 and urllib libraries in python suppose i had the following code ``` import urllib2 import urllib url = 'http://ah.example.com' half_url = u'/servlet/av/jd?ai=782&ji=2624743&sn=I' req = urllib2.Request(url, half_url.encode('utf-8')) response = urllib2.urlopen(req) print response ``` when i run th...
The server you are calling is telling you that the POST method is not allowed for the URL you are trying to call. By passing in the path portion of your URL as the `Request` object data parameter you are making this a POST instead of a GET. I suspect you wanted to send a GET request instead: ``` req = urllib2.Reques...
How to remove all rows in a numpy.ndarray that contain non-numeric values
11,453,141
28
2012-07-12T13:41:52Z
11,453,235
59
2012-07-12T13:46:17Z
[ "python", "numpy" ]
Basically, I'm doing some data analysis. I read in a dataset as a numpy.ndarray and some of the values are missing (either by just not being there, being `NaN`, or by being a string written "`NA`"). I want to clean out all rows containing any entry like this. How do I do that with a numpy ndarray?
``` >>> a = np.array([[1,2,3], [4,5,np.nan], [7,8,9]]) array([[ 1., 2., 3.], [ 4., 5., nan], [ 7., 8., 9.]]) >>> a[~np.isnan(a).any(axis=1)] array([[ 1., 2., 3.], [ 7., 8., 9.]]) ``` and reassign this to `a`. Explanation: `np.isnan(a)` returns a similar array with `True` where ...
Python and PyQt: run function from another class
11,453,256
3
2012-07-12T13:47:18Z
11,484,892
7
2012-07-14T15:19:05Z
[ "python", "class", "function", "pyqt" ]
**Update 3:** Here's the new code, trying to do what you told me to, with no results... I'm starting to think that I have done something very foolish somewhere in my program... Any new ideas? program.py: ``` # -*- coding: utf-8 -*- #imports: import os import platform import sys from PyQt4 import QtCore, QtGui from P...
**Specific error related problem** Remove the classmethod decorator on your update2 method. It makes "self" turn into the class object and there is no tableWidget attribute on your class. Only your widget. There is no use for the decorator here. **General design and fundamental issues** There are some severely major...
How do I get raw text with beautifulsoup?
11,454,633
2
2012-07-12T14:56:58Z
11,454,812
8
2012-07-12T15:05:55Z
[ "python", "xml", "parsing", "hyperlink", "beautifulsoup" ]
I have a xml like this: ``` <link> www.link1.com </link> <link> www.link2.com </link> ``` I have tried this code: ``` from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(results2) #Beautiful Soup linklist = soup.findAll('link') print soup ``` Using this code, the output is ``` [<link>www.li...
Have you tried: ``` linklist = [el.string for el in soup.findAll('link')] ```
Dynamic type casting in python
11,454,784
8
2012-07-12T15:04:01Z
11,454,908
13
2012-07-12T15:10:06Z
[ "python" ]
I have 2 dicts: ``` dicts1 = {'field1':'', 'field2':1, 'field3':1.2} dicts2 = {'field1':123, 'field2':123, 'field3':'123'} ``` I want to convert each value in `dict2` to be the same type as the corresponding value in `dict1`, what's the quickest pythonic way of doing it?
Assuming they're compatible types: ``` for k, v in dicts1.iteritems(): try: dicts2[k] = type(v)(dicts2[k]) except (TypeError, ValueError) as e: pass # types not compatible except KeyError as e: pass # No matching key in dict ```
python, argparse: enable input parameter when another one has been specified
11,455,218
11
2012-07-12T15:26:26Z
11,455,440
9
2012-07-12T15:38:22Z
[ "python", "parameters", "arguments", "argparse" ]
In my python script, I want to be able to use an optional input parameter *only* when another optional parameter has been specified. Example: ``` $ python myScript.py --parameter1 value1 $ python myScript.py --parameter1 value1 --parameter2 value2 ``` But NOT: ``` $ python myScript.py --parameter2 value2 ``` How do...
Use a custom action: ``` import argparse foo_default=None class BarAction(argparse.Action): def __call__(self,parser,namespace,values,option_string=None): didfoo=getattr(namespace,'foo',foo_default) if(didfoo == foo_default): parser.error( "foo before bar!") else: ...
How to capture events on tkinter child widgets?
11,456,631
4
2012-07-12T16:44:53Z
11,459,001
9
2012-07-12T19:14:32Z
[ "python", "events", "tkinter" ]
In the following block, clicking on `a_frame` triggers the event handler `on_frame_click`, but clicking on `a_label` which is a child of `a_frame` does not. Is there a way to force `a_frame` to trap and handle events which originated on it's children (preferably with out having to add handlers to the children directly)...
Yes, you can do what you want, but it requires a bit of work. It's not that it's not supported, it's just that it's actually quite rare to need something like this so it's not the default behavior. **TL;DR - research "tkinter bind tags"** The Tkinter event model includes the notion of "**bind tags**". This is a list ...
removing an instance of an object in python list
11,456,637
9
2012-07-12T16:45:15Z
11,456,817
9
2012-07-12T16:57:13Z
[ "python", "list", "compare" ]
I Think this should work but its giving me an error. I have a list that contains objects of class `node`. I have two different lists 1. open\_list 2. node\_list.( they are not the same lengthwise, ordering wise) When I find a specific node in the `open_list` I need to delete it from the `node_list`. I know that the l...
This is happening because what you understand as identifying features of two instances of your `Node` class, is not how python understands it. The problem lies here. Suppose you asked python `5==5`, python would return `True`. This is because python knows about `int`s. However, `Node` is a custom class that you define...
Python equivalent to R data frames
11,456,844
2
2012-07-12T16:58:53Z
11,457,042
10
2012-07-12T17:11:13Z
[ "python", "arrays" ]
What is the Python equivalent to R's `read.csv()` function, and the `data.frame` it returns? Is there a similar data structure in Python?
Your have two elements in your question, (1) reading/writing CSV and (2) an equivalent data structure to the R `data.frame` that results from reading in a CSV-file. For the first part, there is the [`csv` module](http://docs.python.org/library/csv.html) in the standard library. For the second part, the standard libra...
BeautifulSoup Prettify fails on copyright symbol
11,457,009
8
2012-07-12T17:09:36Z
13,524,760
20
2012-11-23T07:32:39Z
[ "python", "unicode", "beautifulsoup", "prettify" ]
I am getting a Unicode error: `UnicodeEncodeError: 'charmap' codec can't encode character u'\xa9' in position 822: character maps to <undefined>` This appears to be a standard copyright symbol, and in the HTML is &copy. I have not been able to find a way past this. I even tried a custom function to replace copy with a...
I had the same problem. This may work for you: `print soup.prettify().encode('UTF-8')`
How to use a non-keyword arg after a keyword arg in a method call?
11,457,850
2
2012-07-12T18:02:26Z
11,457,872
7
2012-07-12T18:04:00Z
[ "python", "function", "arguments", "keyword" ]
So I have a function defined as such: ``` def getDistnace(self, strings, parentD, nodeName, nodeDistance): ``` And I am calling it with: ``` Node.getDistnace(newNode, strings, parentD, nodeName=None, nodeDistance=None) ``` and ``` Node.getDistnace(node, strings=None, parentD=None, nodeName, nodeDistance) ``` Whic...
All your arguments are positional, you don't need to use keywords at all: ``` Node.getDistnace(newNode, strings, parentD, None, None) Node.getDistnace(node, None, None, nodeName, nodeDistance) ``` I think you are confusing local variables (what you pass into the function) and the argument names of the function. They...
Running an interactive command from within python
11,457,931
13
2012-07-12T18:07:13Z
13,458,449
8
2012-11-19T16:51:57Z
[ "python", "subprocess", "stdout", "stdin", "interactive" ]
I have a script that I want to run from within python (2.6.5) that follows the logic below: * Prompt user for password. Looks like ("Enter password: ") (\*Note: Input does not echo to screen) * Output irrelevant information * Prompt user for response ("Blah Blah filename.txt blah blah (Y/N)?: ") The last prompt line ...
If you are communicating with a program that subprocess spawns, you should check out [Non-blocking read on a subprocess.PIPE in python](http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python). I had a similar problem with my application and found using Queues to be the best way to do...
adding up the elements from all of the nested lists
11,457,942
2
2012-07-12T18:08:02Z
11,457,968
7
2012-07-12T18:10:01Z
[ "python", "nested-lists" ]
I am adding up the elements from all of the nested lists, so far what I have is ``` for i in range(len(b)) : for j in range(len(b[i])): total = total + b[i][j] ``` But this will not work when an integer value exists in the nested list like, ``` b = [[1,2], [3,4], [5,6], 1] ``` In this case i am getting ...
First of all, you are showing a common anti-pattern for Python programmers, don't loop over indices, loop over the objects themselves. E.g: ``` for item in b: do_something(item) ``` Rather than: ``` for i in range(len(b)): do_something(b[i]) ``` It is clearer, simpler and faster. That said, the main proble...
Python: changing value in a tuple
11,458,239
25
2012-07-12T18:27:42Z
11,458,274
40
2012-07-12T18:29:29Z
[ "python", "tuples" ]
I'm new to python so this question might be a little basic. I have a tuple called `values` which contains the following: ``` ('275', '54000', '0.0', '5000.0', '0.0') ``` I want to change the first value (i.e., `275`) in this tuple but I understand that tuples are immutable so `values[0] = 200` will not work. How can ...
First you need to ask, why you want to do this? But it's possible via: ``` t = ('275', '54000', '0.0', '5000.0', '0.0') lst = list(t) lst[0] = '300' t = tuple(lst) ``` But if you're going to need to change things, you probably are better off keeping it as a `list`
Python: changing value in a tuple
11,458,239
25
2012-07-12T18:27:42Z
22,676,204
20
2014-03-27T00:53:59Z
[ "python", "tuples" ]
I'm new to python so this question might be a little basic. I have a tuple called `values` which contains the following: ``` ('275', '54000', '0.0', '5000.0', '0.0') ``` I want to change the first value (i.e., `275`) in this tuple but I understand that tuples are immutable so `values[0] = 200` will not work. How can ...
Depending on your problem slicing can be a really neat solution: ``` >>> b = (1, 2, 3, 4, 5) >>> b[:2] + (8,9) + b[3:] (1, 2, 8, 9, 4, 5) >>> b[:2] + (8,) + b[3:] (1, 2, 8, 4, 5) ``` This allows you to add multiple elements or also to replace a few elements (especially if they are "neighbours". In the above case cast...
Sorting the letters of a one worded string in Python?
11,458,676
10
2012-07-12T18:53:46Z
11,458,688
9
2012-07-12T18:54:24Z
[ "python", "string", "sorting" ]
``` x = 'yellow' print(sorted(x)) ``` returns ``` ['e', 'l', 'l', 'o', 'w', 'y'] ``` What I want it to return ellowy How ran I make it return `'ellowy'` without the letters being in a list?
``` x = 'yellow' print(''.join(sorted(x))) ```
Sorting the letters of a one worded string in Python?
11,458,676
10
2012-07-12T18:53:46Z
11,458,690
11
2012-07-12T18:54:27Z
[ "python", "string", "sorting" ]
``` x = 'yellow' print(sorted(x)) ``` returns ``` ['e', 'l', 'l', 'o', 'w', 'y'] ``` What I want it to return ellowy How ran I make it return `'ellowy'` without the letters being in a list?
The `join()` method of a string joins each element of its argument with copies of the given string object as a delimiter between each item. Many people find this a weird and counterintuitive way to do things, but by joining the elements with an empty string you can convert a list of strings into a single string: ``` x...
Sorting the letters of a one worded string in Python?
11,458,676
10
2012-07-12T18:53:46Z
11,458,695
16
2012-07-12T18:54:40Z
[ "python", "string", "sorting" ]
``` x = 'yellow' print(sorted(x)) ``` returns ``` ['e', 'l', 'l', 'o', 'w', 'y'] ``` What I want it to return ellowy How ran I make it return `'ellowy'` without the letters being in a list?
Actually `sorted()` when used on a string always returns a list of individual characters. so you should use `str.join()` to make a string out of that list. ``` >>> x = 'yellow' >>> ''.join(sorted(x)) 'ellowy' ```
Not able to parse html using lxml Xpath parser
11,458,902
4
2012-07-12T19:08:35Z
11,458,998
7
2012-07-12T19:14:24Z
[ "python", "xpath", "lxml" ]
I am trying to parse review from this page: <http://www.amazon.co.uk/product-reviews/B00143ZBHY> Using following approach: **Code** ``` html # a variable which contains exact html as given at the above page. from lxml import etree tree = etree.HTML(html) r = tree.xpath(".//*[@id='productReviews']/tbody/tr/td[1]/div[...
Try to remove `/tbody` form XPath — there is no `<tbody>` in `#productReviews`. ``` import urllib2 html = urllib2.urlopen("http://www.amazon.co.uk/product-reviews/B00143ZBHY").read() from lxml import etree tree = etree.HTML(html) r = tree.xpath(".//*[@id='productReviews']/tr/td[1]/div[9]/text()[4]") print r[0] ``` ...
How use the mean method on a pandas TimeSeries with Decimal type values?
11,459,106
5
2012-07-12T19:21:46Z
11,461,644
11
2012-07-12T22:26:18Z
[ "python", "decimal", "dataframe", "pandas" ]
I need to store Python decimal type values in a pandas TimeSeries/DataFrame object. Pandas gives me an error when using the "groupby" and "mean" on the TimeSeries/DataFrame. The following code based on floats works well: ``` [0]: by = lambda x: lambda y: getattr(y, x) [1]: rng = date_range('1/1/2000', periods=40, fre...
``` import numpy as np ts.groupby([by('year'), by('month'), by('day')]).apply(np.mean) ```
In matplotlib, what is the difference betweent set_xlim and set_xbound?
11,459,672
15
2012-07-12T19:59:13Z
11,467,349
15
2012-07-13T09:04:32Z
[ "python", "matplotlib" ]
From the help: **set\_xlim:** Set the data limits for the xaxis. **set\_xbound:** Set the lower and upper numerical bounds of the x-axis. That is not very clear, so let’s say that I plot something: ``` import matplotlib.pylab as plt fig, ax = plt.subplots(1, 1) ax.plot(xrange(10), xrange(10)) ``` Now, either I d...
The bound can changes automatically, if you later plot something that is not within the bound. In contrast, limits are fixed and do not change automatically. ``` import pylab as p t = p.arange(0.0, 2.0, 0.01) s = p.sin(2*p.pi*t) ax=p.subplot(111) ax.plot(t, s, color='r',linewidth=1.0) ax.set_ylim(-1,1) ax.plot(t, s+...
Scope of next() in Python
11,461,044
6
2012-07-12T21:33:53Z
11,461,064
10
2012-07-12T21:35:57Z
[ "python", "iterator" ]
I am trying to use the `next` function on an iterator, however, I have a local variable in the same scope that is also named `next`. The obvious solution is to rename the local variable, however, I'm fairly new to Python so I'm curious to learn how to prefix the `next` function so I achieve the desired behavior. The c...
You can use `__builtins__.next` to refer to the `next` built-in function. ``` for prev, curr, next in neighborhood(list): if (prev == desired_value): print(prev+" "+next) desired_value = __builtins__.next(value_iterator) ``` However, as you point out, the obvious solution is to use a different nam...
Pythonanywhere install and import new module
11,461,846
4
2012-07-12T22:47:37Z
11,462,324
8
2012-07-12T23:47:17Z
[ "python", "pip", "import-module", "pythonanywhere" ]
I'm new to Pythonanywhere and want to install the 'soundcloud' Python module. I've opened up a Bash console and given the `pip install --user soundcloud` command. It appears to have installed, as I see it in the list of modules when I used `pip freeze` in the Bash console. However, when I open up a Python 2.7 console ...
You've installed soundcloud for 2.6, but you're trying to use it in 2.7. From [the FAQ](https://www.pythonanywhere.com/faq/): > We've included both easy\_install and pip for Python versions 2.6, 2.7 and 3.2 (the default is 2.6, add -2.7 or -3.2 at the end to specify the others)
Structure of flask applications
11,462,427
17
2012-07-13T00:03:11Z
11,476,607
17
2012-07-13T18:53:26Z
[ "python", "design", "flask", "flask-sqlalchemy" ]
I'm trying to create a simple, but not trivial application with Flask and I keep running into a situation which is not explained well in the docs. I'd like my app to be split between different modules, but it looks like it's hard to access the main `app` object (or `db` from `flask-sqlalchemy`) from any other place th...
The answer to your question is blueprints. In fact, if you look at documentation, it is mentioned that blueprints are there to enable division of application in modules. Sample code: ``` from flask import Blueprint mod = Blueprint(blueprint_name, __name__, template_folder="folder_name" st...
Why does len() not support iterators?
11,463,086
4
2012-07-13T01:51:39Z
11,463,097
9
2012-07-13T01:53:04Z
[ "python", "iterable" ]
Many of Python's built-in functions (`any()`, `all()`, `sum()` to name some) take iterables but why does `len()` not? One could always use `sum(1 for i in iterable)` as an equivalent, but why is it `len()` does not take iterables in the first place?
Many iterables are defined by generator expressions which don't have a well defined len. Take the following which iterates forever: ``` def sequence(i=0): while True: i+=1 yield i ``` Basically, to have a well defined length, you need to know the entire object up front. Contrast that to a function...
Python returning variables from various functions
11,463,171
2
2012-07-13T02:04:57Z
11,463,180
7
2012-07-13T02:07:07Z
[ "python", "function", "variables", "return" ]
``` from __future__ import division import math def main(): the_discriminant = discrim(1,0,-4) print the_discriminant the_rest(discrim,b,a) def discrim(a,b,c): discriminant = math.sqrt(math.pow(b,2)-4*a*c) return discriminant, b,a def the_rest(discrim,b,a): x = ((-b + discriminant) / 2*a) ...
``` the_rest(*the_discriminant) ``` or (and I prefer this method): ``` d, b, a = discrim(1, 0, -4) the_rest(d, b, a) ```
Python Iterate through characters
11,463,237
4
2012-07-13T02:16:33Z
11,463,260
10
2012-07-13T02:19:31Z
[ "python", "string", "list", "character", "loops" ]
I have been trying to pull of median string search for a sequence in the ACGT genome. The problem I have is going to say AAAAAAAA to AAAAAAAC and so forth until I have tried every possible combination. I've been essentially going brute force at it by creating two lists, one containg A,C,G,T and the other the 8 charact...
Using [`itertools`](http://docs.python.org/library/itertools.html) ``` itertools.product("ACGT", repeat=8) ```
Using WordNet to determine semantic similarity between two texts?
11,463,396
3
2012-07-13T02:35:52Z
11,463,726
8
2012-07-13T03:26:25Z
[ "python", "nlp", "nltk", "wordnet", "semantic-analysis" ]
How can you determine the semantic similarity between two texts in python using WordNet? The obvious preproccessing would be removing stop words and stemming, but then what? The only way I can think of would be to calculate the WordNet path distance between each word in the two texts. This is standard for unigrams. B...
One thing that you can do is: 1. Kill the stop words 2. Find as many words as possible that have maximal intersections of synonyms and antonyms with those of other words in the same doc. Let's call these "the important words" 3. Check to see if the set of the important words of each document is the same. The closer th...
Call a function without waiting for it
11,463,456
3
2012-07-13T02:44:39Z
11,463,463
14
2012-07-13T02:46:22Z
[ "java", "python", "function", "methods" ]
Hi I was wondering if there was a way of calling a function/method (preferably in Python or Java) and continue execution without waiting for it. Example: ``` def a(): b() #call a function, b() return "something" def b(): #something that takes a really long time ```
Run it in a new thread. Learn about multithreading in java [here](http://www.tutorialspoint.com/java/java_multithreading.htm) and python multithreading [here](http://www.tutorialspoint.com/python/python_multithreading.htm) Java example: ## The WRONG way ... by subclassing Thread ``` new Thread() { public void ru...
Django model field by variable
11,464,080
6
2012-07-13T04:22:46Z
11,464,112
17
2012-07-13T04:26:15Z
[ "python", "django" ]
Quick question. I'm trying yo access one of the fields of a model using a variable. ``` class ExampleModel(models.Model): the_field = models.CharField() the_field_two = models.CharField() ``` How would access the field dynamically? I tried: ``` model = ExampleModel.objects.get(pk=1) fieldtoget = 'the_fie...
You can use pythons getattr function to do this. Pass the field name in as the attribute. ``` getattr(model, fieldtoget) ``` Since fieldtoget is a variable, this is dynamic. You can use setattr to set it the same way.
Unpack a nested list
11,465,158
3
2012-07-13T06:20:31Z
11,465,171
9
2012-07-13T06:22:08Z
[ "python", "list" ]
My question is simple. There are two lists. The first is a list of integers: ``` a = [1, 2, 3] ``` The other is a list of lists: ``` b = [['a', 'b'], ['c', 'd'], ['e', 'f']] ``` How could I get the result below: ``` result = [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']] ``` Thanks.
``` >>> a = [1, 2, 3] >>> b = [['a', 'b'], ['c', 'd'], ['e', 'f']] >>> [[aa] + bb for aa, bb in zip(a, b)] [[1, 'a', 'b'], [2, 'c', 'd'], [3, 'e', 'f']] ```
Create a field which value is a calculation of other fields' values
11,465,293
16
2012-07-13T06:32:30Z
11,465,349
31
2012-07-13T06:37:20Z
[ "python", "django" ]
``` class PO(models.Model) qty = models.IntegerField(null=True) cost = models.IntegerField(null=True) total = qty * cost ``` How will I solve `total = qty * cost` above. I know it will cause an error, but have no idea of how to deal with this.
You can make `total` a `property` field, see the [docs](https://docs.djangoproject.com/en/dev/topics/db/models/#model-methods) ``` class PO(models.Model) qty = models.IntegerField(null=True) cost = models.IntegerField(null=True) def _get_total(self): "Returns the total" return self.qty * sel...
Create a field which value is a calculation of other fields' values
11,465,293
16
2012-07-13T06:32:30Z
11,466,029
7
2012-07-13T07:31:20Z
[ "python", "django" ]
``` class PO(models.Model) qty = models.IntegerField(null=True) cost = models.IntegerField(null=True) total = qty * cost ``` How will I solve `total = qty * cost` above. I know it will cause an error, but have no idea of how to deal with this.
[Justin Hamades answer](http://stackoverflow.com/questions/808201/annotate-a-sum-of-two-fields-multiplied) ``` class PO(models.Model) qty = models.IntegerField(null=True) cost = models.IntegerField(null=True) @property def total(self): return self.qty * self.cost ```
can we use xpath with BeautifulSoup?
11,465,555
45
2012-07-13T06:55:19Z
11,466,033
80
2012-07-13T07:31:41Z
[ "python", "xpath", "beautifulsoup", "urllib" ]
I am using BeautifulSoup to scrape a url and I had the following code ``` import urllib import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html" req = urllib2.Request(url) response = urllib2.urlopen(req) the_page = response.read() soup = BeautifulS...
Nope, BeautifulSoup, by itself, does not support XPath expressions. An alternative library, [lxml](http://lxml.de/), *does* support XPath 1.0. It has a [BeautifulSoup compatible mode](http://lxml.de/elementsoup.html) where it'll try and parse broken HTML the way Soup does. However, the [default lxml HTML parser](http:...
can we use xpath with BeautifulSoup?
11,465,555
45
2012-07-13T06:55:19Z
11,469,854
42
2012-07-13T11:44:45Z
[ "python", "xpath", "beautifulsoup", "urllib" ]
I am using BeautifulSoup to scrape a url and I had the following code ``` import urllib import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.example.com/servlet/av/ResultTemplate=AVResult.html" req = urllib2.Request(url) response = urllib2.urlopen(req) the_page = response.read() soup = BeautifulS...
I can confirm that there is no XPath support within Beautiful Soup.
Wildcards in column name for MySQL
11,466,764
8
2012-07-13T08:24:56Z
11,466,826
8
2012-07-13T08:29:11Z
[ "python", "mysql", "sql" ]
I am trying to select multiple columns, but not all of the columns, from the database. All of the columns I want to select are going to start with "word". So in pseudocode I'd like to do this: ``` SELECT "word%" from searchterms where onstate = 1; ``` More or less. I am not finding any documentation on how to do thi...
No, SQL doesn't provide you with any syntax to do such a select. What you *can* do is ask MySQL for [a list of column names](https://dev.mysql.com/doc/refman/5.0/en/columns-table.html) first, then generate the SQL query from that information. ``` SELECT column_name FROM information_schema.columns WHERE table_name = '...
Is "continue" the Pythonic way to escape from a try catch block?
11,467,985
3
2012-07-13T09:44:30Z
11,468,682
8
2012-07-13T10:27:59Z
[ "python", "django" ]
I am new to django and thought of doing to simple django application to learn more about it, In one of the places in code I had to pick `locationName` and getting elements that matched same id as `locationName` in a table. When I started wondering is `continue` the most pythonic way to escape a for-loop? Code in quest...
If there's some code you don't want getting executed after the except clause, `continue` is perfectly valid, otherwise some might find `pass` more suitable. ``` for x in range(y): try: do_something() except SomeException: continue # The following line will not get executed for the current x...
Populating dictionary values from a list
11,468,027
3
2012-07-13T09:46:41Z
11,468,057
17
2012-07-13T09:48:24Z
[ "python", "list", "dictionary" ]
I'm trying to construct a dictionary in python. Code looks like this: ``` dicti = {} keys = [1, 2, 3, 4, 5, 6, 7, 8, 9] dicti = dicti.fromkeys(keys) values = [2, 3, 4, 5, 6, 7, 8, 9] ``` How can I populate values of dictionary using a list? Is there some built in function? The result should be like this: ``` dicti...
If you have two lists `keys` and the **corresponding** `values`: ``` keys = [1, 2, 3, 4, 5, 6, 7, 8, 9] values = [2, 3, 4, 5, 6, 7, 8, 9] dicti = dict(zip(keys, values)) ``` `dicti` is now `{1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9}`
How to implement a subscriptable class in Python (subscriptable class, not subscriptable object)?
11,469,025
12
2012-07-13T10:51:07Z
11,469,183
7
2012-07-13T11:01:40Z
[ "python" ]
To implement a subscriptable object is easy, just implement `__getitem__` in this object's class definition. But now I want to implement a subscriptable class. For example, I want to implement this code: ``` class Fruit(object): Apple = 0 Pear = 1 Banana = 2 #________________________________ #/ ...
Seems to work by changing the metaclass. For Python 2: ``` class GetAttr(type): def __getitem__(cls, x): return getattr(cls, x) class Fruit(object): __metaclass__ = GetAttr Apple = 0 Pear = 1 Banana = 2 print Fruit['Apple'], Fruit['Banana'] # output: 0 2 ``` --- On Python 3, you should...
Adjusting 1 space between two strings using python
11,470,996
3
2012-07-13T12:58:35Z
11,471,012
10
2012-07-13T12:59:47Z
[ "python" ]
I have two strings: ``` >>> a = "abcd" >>> b = "xyz" >>> c = a + b >>> c abcdxyz ``` How can I get `abcd xyz` as a result instead when adding `a` and `b`?
Simply just add a space between the two strings: ``` a = "abcd" b = "xyz" c = a + " " + b # note the extra space concatenated with the other two print c ``` this will give you ``` abcd xyz ``` You can use a function such as `.join()`, but for something so short, that would seem almost counter-intuitive (and IMO ...
Adjusting 1 space between two strings using python
11,470,996
3
2012-07-13T12:58:35Z
11,471,016
8
2012-07-13T13:00:04Z
[ "python" ]
I have two strings: ``` >>> a = "abcd" >>> b = "xyz" >>> c = a + b >>> c abcdxyz ``` How can I get `abcd xyz` as a result instead when adding `a` and `b`?
You can use join to concatenate your strings together with your selected delimiter. ``` a = "abcd" b = "xyz" c = " ".join([a, b]) ```
Is it possible to communicate with WCF TCP service with app in java or python?
11,471,767
2
2012-07-13T13:46:43Z
11,472,439
7
2012-07-13T14:23:53Z
[ "java", ".net", "python", "wcf", "tcp" ]
I receive a WCF service to communicate, so, i need to create a client in java or python to get informations provided by this service that is a WCF TCP service. Is it possible?
I'm assuming that when you say the service "is a WCF TCP service", you mean that it employs the netTcpBinding (scheme `net.tcp`). This binding relies on some proprietary Microsoft protocols in addition to public standards such as SOAP. These provide message framing, support for a variety of encoding schemes, and for t...
How to specify version ranges in install_requires (setuptools, distribute)
11,472,810
30
2012-07-13T14:45:09Z
11,495,486
26
2012-07-15T20:44:51Z
[ "python", "setuptools" ]
I want to make a package to depend the particular version range e.g. `>= 0.5.0, < 0.7.0`. Is it possible in `install_requires` option, and if so how should it be?
According to [the documentation](http://peak.telecommunity.com/DevCenter/setuptools#declaring-dependencies), your syntax should work correctly. The documentation states that: > `setuptools` and `pkg_resources` use a common syntax for specifying a project's required dependencies. This syntax consists of a project's PyP...
How to specify version ranges in install_requires (setuptools, distribute)
11,472,810
30
2012-07-13T14:45:09Z
14,405,269
9
2013-01-18T18:27:31Z
[ "python", "setuptools" ]
I want to make a package to depend the particular version range e.g. `>= 0.5.0, < 0.7.0`. Is it possible in `install_requires` option, and if so how should it be?
Be wary of involuntary beta tests. Package maintainers sometimes release incompatible, incomplete, or broken a, b, and c releases to general audiences without warning. The next time you run **setup.py** in a fresh virtualenv, you might pull down one of these poisoned eggs, and suddenly your program will break. To miti...
Set up Python on Windows to not type python in cmd
11,472,843
12
2012-07-13T14:47:08Z
11,473,042
18
2012-07-13T14:59:10Z
[ "python", "windows", "path", "cmd" ]
How do I have to configure so that I don't have to type `python script.py` but simply `script.py` in CMD on Windows? I added my python directory to %PATH% that contains python.exe but still scripts are not run correctly. I tried it with django-admin.py Running `django-admin.py startproject mysite` gives me `Type 'dja...
``` C:\> assoc .py=Python C:\> ftype Python="C:\python27\python.exe %1 %*" ``` Or whatever the relevant path is - you can also set command line args using ftype. --- In order to make a command recognized without having to give the suffix (`.py`), similar to how it works for `.exe` files, add `.py` to the semi-colon ...
Scipy Derivative
11,472,898
5
2012-07-13T14:50:28Z
11,473,001
13
2012-07-13T14:57:02Z
[ "python", "math", "scipy" ]
I have a question about the derivative function of Scipy. I used it last night and got some odd answers. I tried again this morning with some simple functions and got some right answers and some wrong. Here were my tests: ``` In [1]: def poly1(x): ...: return x**2 In [3]: derivative(poly1, 0) Out[3]: 0.0 In [4]:...
As the documentation for `derivative` says: ``` derivative(func, x0, dx=1.0, n=1, args=(), order=3) Find the n-th derivative of a function at point x0. Given a function, use a central difference formula with spacing `dx` to compute the n-th derivative at `x0`. ``` You didn't specify `dx`, so it used the ...
Compiling .py files to .pyo without resorting to a wrapper script
11,472,991
5
2012-07-13T14:56:23Z
11,473,045
11
2012-07-13T14:59:14Z
[ "python" ]
i am looking into compiling quite a big set of python modules and packages to pyo. I know this is possible by either setting the PYTHONOPTIMIZE environment variable or by specifying -O on launch. I'd like to enforce pyo instead of pyc to yield the smallest footprint possible. In order to do that in my deploy module i h...
To *compile* all modules beforehand, run the following command: ``` python -O -m compileall /path/to/your/files ``` The [python `compileall` module](http://docs.python.org/library/compileall.html) takes care of the compilation, the [`-O` switch](http://docs.python.org/using/cmdline.html?highlight=#cmdoption-O) makes ...
Weird timezone issue with pytz
11,473,721
17
2012-07-13T15:37:07Z
11,474,330
28
2012-07-13T16:15:40Z
[ "python", "pytz" ]
``` >>> import pytz >>> pytz.timezone('Asia/Hong_Kong') <DstTzInfo 'Asia/Hong_Kong' LMT+7:37:00 STD> ``` A seven hour and 37 minute offset? This is a little strange, does anyone experience the same issue? In fact I'm getting different behavior between ``` import pytz from datetime import datetime hk = pytz.timezone(...
Time zones and offsets change over the years. The default zone name and offset delivered when pytz creates a timezone object are the earliest ones available for that zone, and sometimes they can seem kind of strange. When you use `localize` to attach the zone to a date, the proper zone name and offset are substituted. ...
Is there go up line character? (Opposite of \n)
11,474,391
23
2012-07-13T16:19:33Z
11,474,400
7
2012-07-13T16:20:09Z
[ "python", "c++", "terminal", "console" ]
I would like to overwrite something on a line above in in a serial console. Is there a character that allows me to move up? Thank you.
No, not really easily, for that you'd have to use something like the [curses library](http://docs.python.org/library/curses.html), especially if you want to have more control over cursor placement and do more things programatically. Here's a link for the Python docs on [Programming with Curses](http://docs.python.org/...
Is there go up line character? (Opposite of \n)
11,474,391
23
2012-07-13T16:19:33Z
11,474,509
29
2012-07-13T16:26:50Z
[ "python", "c++", "terminal", "console" ]
I would like to overwrite something on a line above in in a serial console. Is there a character that allows me to move up? Thank you.
Most terminals understand [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code). The code for going to the beginning of the previous line is `"\033[F"`.
How to change metadata with ffmpeg/avconv without creating a new file?
11,474,532
4
2012-07-13T16:28:19Z
11,479,066
8
2012-07-13T22:15:07Z
[ "python", "command-line", "ffmpeg", "metadata" ]
I am writing a python script for producing audio and video podcasts. There are a bunch of recorded media files (audio and video) and text files containing the meta information. Now I want to program a function which shall add the information from the meta data text files to all media files (the original and the conver...
You can do this with FFmpeg like so: ``` ffmpeg -i input.avi -metadata key=value -codec copy output.avi ``` Example: ``` $ du -h test.mov 27M test.mov $ ffprobe -loglevel quiet -show_format out.mov | grep title # nothing found $ ffmpeg -loglevel quiet -i test.mov -codec copy -metadata title="My title" out.mo...
python .replace() regex
11,475,885
34
2012-07-13T18:03:50Z
11,475,905
58
2012-07-13T18:05:04Z
[ "python", "regex" ]
I am trying to do a grab everything after the "</html>" tag and delete it, but my code doesnt seem to be doing anything. Does .replace() not support regex? python ``` z.write(article.replace('</html>.+', '</html>')) ```
No. Regular expressions in Python are handled by the [`re`](http://docs.python.org/library/re.html) module. ``` article = re.sub(r'(?is)</html>.+', '</html>', article) ```
Getting Site Matching Query Does Not Exist Error after creating django admin
11,476,210
33
2012-07-13T18:27:32Z
11,476,472
70
2012-07-13T18:45:59Z
[ "python", "django", "django-admin", "django-sites" ]
I'm going through the standard Django tutorial to create an admin for an app. After commenting the admin related stuff in settings and running syncdb I'm getting this message: ``` DoesNotExist at /admin/ Site matching query does not exist. ``` Can anyone help me figure this out?
The `Site` object for your Django project is missing. Each Django project has a `Site` object which contains the site's name and domain. It is usually automatically created when creating a Django project (in particular, when the `syncdb` command runs) but in your case it seems that didn't happen. To fix it: Open the ...
Getting Site Matching Query Does Not Exist Error after creating django admin
11,476,210
33
2012-07-13T18:27:32Z
20,000,110
16
2013-11-15T11:30:57Z
[ "python", "django", "django-admin", "django-sites" ]
I'm going through the standard Django tutorial to create an admin for an app. After commenting the admin related stuff in settings and running syncdb I'm getting this message: ``` DoesNotExist at /admin/ Site matching query does not exist. ``` Can anyone help me figure this out?
In addition to Simeon Visser's answer for those of you still experiencing problems, make sure the `SITE_ID` variable in your settings matches the ID of your newly created `Site`-object.
Is it less computationally intensive to use 7.0 or float(7) in Python?
11,476,379
9
2012-07-13T18:39:20Z
11,476,422
9
2012-07-13T18:42:12Z
[ "python", "types" ]
I'm curious which form is more efficient, is correct style, etc. I feel like the ".0" approach is much quicker; I'm not sure why the "float" approach is equally appreciated (if it is).
use the `7.0` approach, the `float(7)` approach is used to transform integer or string types to floats so it's a different use, for example: ``` a = 7 b = "7" print float(a) 7.0 print float(b) 7.0 ```
Is it less computationally intensive to use 7.0 or float(7) in Python?
11,476,379
9
2012-07-13T18:39:20Z
11,476,479
9
2012-07-13T18:46:35Z
[ "python", "types" ]
I'm curious which form is more efficient, is correct style, etc. I feel like the ".0" approach is much quicker; I'm not sure why the "float" approach is equally appreciated (if it is).
Using `float(7)` adds some unnecessary overhead—Python has to find the `float` function in `globals()` and call it. Using `7.0` does all the necessary conversions at compile-time instead of run-time. You can see this using the [Python bytecode disassembler](http://docs.python.org/library/dis.html). ``` >>> import dis ...
Determining how many times a substring occurs in a string in Python
11,476,713
19
2012-07-13T18:59:59Z
11,476,723
35
2012-07-13T19:00:57Z
[ "python", "string", "python-2.7" ]
I am trying to figure out how many times a string occurs in a string. For example: ``` nStr = '000123000123' ``` Say the string I want to find is 123. Obviously it occurs twice in nStr but I am having trouble implementing this logic into Python. What I have got at the moment: ``` pattern = '123' count = a = 0 while ...
Use [`str.count`](http://docs.python.org/library/string.html#string.count): ``` >>> nStr = '000123000123' >>> nStr.count('123') 2 ``` A working version of your code: ``` nStr = '000123000123' pattern = '123' count =0 flag=True start=0 while flag: a = nStr.find(pattern,start) # find() returns -1 if the word is n...
Throttling brute force login attacks in Django
11,477,067
16
2012-07-13T19:26:20Z
11,477,491
15
2012-07-13T19:56:42Z
[ "python", "django", "security", "brute-force" ]
Are there generally accepted tactics for protecting Django applications against this kind of attack?
[django-axes](http://pypi.python.org/pypi/django-axes/) is an existing app for detecting failed login attempts. There is also a more general [django-ratelimit](http://pypi.python.org/pypi/django-ratelimit/).
Multiple linear regression in Python
11,479,064
57
2012-07-13T22:14:40Z
11,479,279
45
2012-07-13T22:41:50Z
[ "python", "numpy", "statistics", "scipy", "linear-regression" ]
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this data: ``` print 'y x1 x2 x3 x4 x5 x6 ...
[`sklearn.linear_model.LinearRegression`](http://scikit-learn.org/stable/modules/linear_model.html#ordinary-least-squares) will do it: ``` from sklearn import linear_model clf = linear_model.LinearRegression() clf.fit([[getattr(t, 'x%d' % i) for i in range(1, 8)] for t in texts], [t.y for t in texts]) ``` The...
Multiple linear regression in Python
11,479,064
57
2012-07-13T22:14:40Z
14,971,531
38
2013-02-20T02:53:40Z
[ "python", "numpy", "statistics", "scipy", "linear-regression" ]
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this data: ``` print 'y x1 x2 x3 x4 x5 x6 ...
Here is a little work around that I created. I checked it with R and it works correct. ``` import numpy as np import statsmodels.api as sm y = [1,2,3,4,3,4,5,4,5,5,4,5,4,5,4,5,6,5,4,5,4,3,4] x = [ [4,2,3,4,5,4,5,6,7,4,8,9,8,8,6,6,5,5,5,5,5,5,5], [4,1,2,3,4,5,6,7,5,8,7,8,7,8,7,8,7,7,7,7,7,6,5], [4,1,2,...
Multiple linear regression in Python
11,479,064
57
2012-07-13T22:14:40Z
26,918,329
10
2014-11-13T21:01:59Z
[ "python", "numpy", "statistics", "scipy", "linear-regression" ]
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this data: ``` print 'y x1 x2 x3 x4 x5 x6 ...
[numpy.linalg.lstsq](http://docs.scipy.org/doc/numpy-1.3.x/reference/generated/numpy.linalg.lstsq.html) is the simplest method, in my opinion. ``` import numpy as np y = [-6,-5,-10,-5,-8,-3,-6,-8,-8] x = [[-4.95,-4.55,-10.96,-1.08,-6.52,-0.81,-7.01,-4.46,-11.54],[-5.87,-4.52,-11.64,-3.36,-7.45,-2.36,-7.33,-7.65,-10.03...
Multiple linear regression in Python
11,479,064
57
2012-07-13T22:14:40Z
27,096,056
7
2014-11-24T00:12:00Z
[ "python", "numpy", "statistics", "scipy", "linear-regression" ]
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this data: ``` print 'y x1 x2 x3 x4 x5 x6 ...
Use `scipy.optimize.curve_fit`. And not only for linear fit. ``` from scipy.optimize import curve_fit import scipy def fn(x, a, b, c): return a + b*x[0] + c*x[1] # y(x0,x1) data: # x0=0 1 2 # ___________ # x1=0 |0 1 2 # x1=1 |1 2 3 # x1=2 |2 3 4 x = scipy.array([[0,1,2,0,1,2,0,1,2,],[0,0,0,1,1,1,2,2,2]]) y =...
Multiple linear regression in Python
11,479,064
57
2012-07-13T22:14:40Z
33,381,686
17
2015-10-28T02:02:22Z
[ "python", "numpy", "statistics", "scipy", "linear-regression" ]
I can't seem to find any python libraries that do multiple regression. The only things I find only do simple regression. I need to regress my dependent variable (y) against several independent variables (x1, x2, x3, etc.). For example, with this data: ``` print 'y x1 x2 x3 x4 x5 x6 ...
Just to clarify, the example you gave is *multiple* linear regression, not *multivariate* linear regression refer. [Difference](https://en.wikipedia.org/wiki/Linear_regression#Simple_and_multiple_regression): > The very simplest case of a single scalar predictor variable x and a single scalar response variable y is kn...
using show() and close() from matplotlib
11,479,065
4
2012-07-13T22:14:43Z
11,485,421
9
2012-07-14T16:24:47Z
[ "python", "matplotlib", "show" ]
I am experiencing some problems with matplotlib.... I can't open 2 windows at once to display a image with show(), it seems that the script stops at the line i use show and doesn't continue unless I close the display manually. Is there a way to close the figure window within the scrip? the following code doesn't run a...
plt.show() is a *blocking* function. Essentially, if you want two windows to open at once, you need to create two figures, and then use plt.show() at the end to display them. In fact, a general rule of thumb is that you set up your plots, and plt.show() is the very last thing you do. So in your case: ``` fig1 = plt....
What does a for loop within a list do in Python?
11,479,392
6
2012-07-13T22:56:46Z
11,479,414
16
2012-07-13T23:00:07Z
[ "python", "loops" ]
Can someone explain the last line of this Python code snippet to me? `Cell` is just another class. I don't understand how the `for` loop is being used to store `Cell` objects into the `Column` object. ``` class Column(object): def __init__(self, region, srcPos, pos): self.region = region self.ce...
The line of code you are asking about is using [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) to create a list and assign the data collected in this list to `self.cells`. It is equivalent to ``` self.cells = [] for i in xrange(region.cellsPerCol): self.cells.append(Ce...
Is there a way to guarantee hierarchical output from NetworkX?
11,479,624
30
2012-07-13T23:32:02Z
11,484,144
42
2012-07-14T13:27:20Z
[ "python", "networkx" ]
I'm trying to produce a flow diagram of a **tree** structure. I've been able to create representative graphs with networkx, but I need a way to show the **tree** structure when I output a plot. I'm using matplotlib.pylab to plot the graph. I need to show the data in a structure similar to what is shown [here](http://w...
If you use a directed graph then the Graphviz dot layout will do something like you want with the tree. Here is some code similar to the above solutions that shows how to do that ``` import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_node("ROOT") for i in xrange(5): G.add_node("Child_%i...
Python 3 turn range to a list
11,480,042
32
2012-07-14T00:45:01Z
11,480,070
38
2012-07-14T00:48:39Z
[ "python", "list", "casting", "python-3.x", "range" ]
I'm trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In python 2 it seems that some\_list = range(1,1000) would have worked, but in python 3 the range is similar to the xrange of python 2? Can anyone provide some insigh...
You can just construct a list from the range object: ``` my_list=list(range(1,1001)) ``` This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of `my_list[i]` more efficiently (`i+1`), and if you just need to iterate over ...
Python 3 turn range to a list
11,480,042
32
2012-07-14T00:45:01Z
28,785,366
10
2015-02-28T18:38:07Z
[ "python", "list", "casting", "python-3.x", "range" ]
I'm trying to make a list with numbers 1-1000 in it. Obviously this would be annoying to write/read, so I'm attempting to make a list with a range in it. In python 2 it seems that some\_list = range(1,1000) would have worked, but in python 3 the range is similar to the xrange of python 2? Can anyone provide some insigh...
in Python 3.x, the `range()` function got its own type. so in this case you must use iterator `list(range(1000))`
correcting the axes using imshow
11,480,568
2
2012-07-14T02:35:11Z
11,481,141
7
2012-07-14T04:45:58Z
[ "python", "numpy", "matplotlib", "scipy" ]
I was trying to make a contour plot using numpy.meshgrid and pylab.imshow(); this worked really well at first using some tips I found on stackoverflow (thanks guy! :D ) ``` f = scipy.linspace(1e5,1e6,100) A = scipy.linspace(1e3,1e5,100) ff,AA = numpy.meshgrid(f,A) SLP = calc_SLP2D(ff,AA) maxAmps = maxA(f) print maxAmp...
Try to add the parameter `aspect='auto'` to `imshow`. Like this: ``` pylab.imshow(SLP,aspect='auto',origin='lower',extent=(ff.min(),ff.max(),AA.min(),AA.max())) ```
Read a large zipped text file line by line in python
11,482,342
12
2012-07-14T08:48:40Z
11,482,347
31
2012-07-14T08:50:15Z
[ "python", "stream", "zip" ]
I am trying to use zipfile module to read a file in an archive. the uncompressed file is ~3GB and the compressed file is 200MB. I don't want them in memory as I process the compressed file line by line. So far I have noticed a memory overuse using the following code: ``` import zipfile f = open(...) z = zipfile.ZipFil...
Python file objects provide iterators, which will read line by line. [`file.readlines()`](http://docs.python.org/library/stdtypes.html#file.readlines) reads them all and returns a list - which means it needs to read everything into memory. The better approach (which should always be preferred over `readlines()`) is to ...
How to force my whole package to use a __future__ directive?
11,483,333
5
2012-07-14T11:21:45Z
11,483,338
8
2012-07-14T11:23:41Z
[ "python", "python-3.x" ]
Can I place: ``` from __future__ import absolute_import ``` inside `__init__.py` on the top level dir on my package and garantee that the absolute\_import will be applied to all code that runs inside that package or sub-packages? Or should I put that directive in each model that does an absolute import? I maintain ...
No, `__future__` imports are only valid for a single file. You will have to put this line at the top of every Python source file. From the [documentation](http://docs.python.org/reference/simple_stmts.html#future): > A future statement is a directive to the compiler that a particular module should be compiled using s...
Python: intersection indices numpy array
11,483,863
21
2012-07-14T12:47:04Z
11,483,958
20
2012-07-14T12:59:00Z
[ "python", "arrays", "numpy" ]
How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with `intersect1d`: ``` import numpy as np a = np.array(xrange(11)) b = np.array([2, 7, 10]) inter = np.intersect1d(a, b) # inter == array([ 2, 7, 10]) ``` But how can I get the indices into `a` of the values in...
You could use the boolean array produced by `in1d` to index an `arange`. Reversing `a` so that the indices are different from the values: ``` >>> a[::-1] array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) >>> a = a[::-1] ``` `intersect1d` still returns the same values... ``` >>> numpy.intersect1d(a, b) array([ 2, ...
What is generator.throw() good for?
11,485,591
32
2012-07-14T16:50:30Z
11,487,070
35
2012-07-14T20:13:07Z
[ "python", "generator", "throw" ]
[PEP 342 (Coroutines via Enhanced Generators)](http://www.python.org/dev/peps/pep-0342/) added a `throw()` method to generator objects, which allows the caller to raise an exception *inside* the generator (as if it was thrown by the `yield` expression). I am wondering what the use cases for this feature are.
Let's say I use a generator to handle adding information to a database; I use this to store network-received information, and by using a generator I can do this efficiently whenever I actually receive data, and do other things otherwise. So, my generator first opens a database connection, and every time you send it so...
Is it possible for the Python compiler to optimize away some integer arithmetic?
11,485,879
3
2012-07-14T17:31:28Z
11,485,944
11
2012-07-14T17:41:39Z
[ "python", "compiler-construction" ]
Inspired by [this](http://stackoverflow.com/questions/11476190/why-0-6-is-6-false) question about Python caching small integers. Is it possible for the Python compiler to replace (0 - 6) with -6 at compile time? The code below suggests that it does not. If it is not possible, why not? I don't think that the meaning of...
First, you shouldn't be using `is` to compare integer values to detect optimizations. That has nothing to do with anything, as explained in the question you linked. If you want to know what optimizations were performed on your function, use the [dis](http://docs.python.org/library/dis.html) module, which produces (in 2...