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
How to handle the pylint message: ID:W0612 Unused Variable
10,107,350
10
2012-04-11T13:52:16Z
10,107,410
16
2012-04-11T13:55:58Z
[ "python", "coding-style", "pylint" ]
I'm updating some code to PEP 8 standard using pylint. Part of the code is throwing the W0612 unused variable error but it's because it's using a module that returns (x,y) for example when only x is needed in this particular case, this is what's done. ``` (var_1, var_2) = func() def func(): a="a" b="b" re...
I believe that `a, dummy = func()` does the trick. Pylint allows (if I recall correctly) unused variables names that start with `_` or `dummy`, e.g. `dummy_index`. You can configure this by passing `--dummy-variables-rgx` option to Pylint. This specifies the regex that catches dummy variable names. **Note**: Using `_...
python RuntimeError: dictionary changed size during iteration
10,107,676
8
2012-04-11T14:11:34Z
10,107,763
20
2012-04-11T14:15:36Z
[ "python" ]
I have obj like this ``` {hello: 'world', "foo.0.bar": v1, "foo.0.name": v2, "foo.1.bar": v3} ``` It should be expand to ``` { hello: 'world', foo: [{'bar': v1, 'name': v2}, {bar: v3}]} ``` I wrote code below, splite by `'.'`, remove old key, append new key if contains `'.'`, but it said `RuntimeError: dictionary c...
Like the message says: you changed the number of entries in obj inside of expandField() while in the middle of looping over this entries in expand. You might try instead creating a new dictionary of the form you wish, or somehow recording the changes you want to make, and then making them AFTER the loop is done.
Why does this implementation of izip() not work?
10,108,423
8
2012-04-11T14:50:23Z
10,108,496
12
2012-04-11T14:54:10Z
[ "python" ]
To better understand Python's generator I'm trying to implement facilities in the `itertools` module, and get into trouble with `izip`: ``` def izip(*iterables): its = tuple(iter(it) for it in iterables) while True: yield tuple(next(it) for it in its) # ERROR # yield tuple(map(next, its)) # O...
The reason your implementation does not work is because the `StopIteration` exception caused by one of the iterables being exhausted is thrown *inside a generator expression*. It will only terminate the generator expression, not the enclosing generator function.
Efficiently generate all composite numbers less than N (with their factorizations)
10,109,510
12
2012-04-11T15:52:57Z
10,110,008
10
2012-04-11T16:26:17Z
[ "python", "algorithm", "iterator", "generator" ]
I'd like to build an efficient Python iterator/generator that yields: * All composite numbers less than N * Along with their prime factorization I'll call it "composites\_with\_factors()" *Assume we already have* a list of primes less than N, or a primes generator that can do the same. Note that I: * DO NOT need t...
Assuming `primesiter(n)` creates an iterator over all primes up to `n` (1 should NOT be included in `primesiter`, or following code well enter inf. loop) ``` def composite_value(n, min_p = 0): for p in primesiter(n): # avoid double solutions such as (6, [2,3]), and (6, [3,2]) if p < min_p: continue...
Python Adds An Extra CR At The End Of The Received Lines
10,110,702
7
2012-04-11T17:10:31Z
10,111,341
7
2012-04-11T17:55:32Z
[ "java", "python", "sockets", "client-server", "carriage-return" ]
A Java application sends an XML to a Python application. They are both on the same machine. When I open the received file I can see extra lines (because of extra CRs). What could be the reason for this? This is the receiver: ``` f = open('c:/python/python.xml', 'w') while 1: print("xxx") data = socket...
Change filemode from `'w'` to `'wb'`, otherwise Python converts any newlines (`'\n'`) into the platform specific representation (`'\r\n'` for Windows). Binary mode suppresses this conversion.
Python multiline string - $ for variables
10,112,614
23
2012-04-11T19:28:04Z
10,112,660
16
2012-04-11T19:32:09Z
[ "python", "string", "variables", "multiline" ]
I'm looking for a clean way to use variables within a Python multiline string. Say I wanted to do the following ``` string1 = go string2 = now string3 = great """ I'm will $string1 there I will go $string2 $string3 """ ``` In a way I'm looking to see if there is a Perl like $ to indicate a variable in the Python syn...
You probably could have answered this one with a little bit of Googling, but here's the code you were looking for. Note that I corrected your syntax on strings. ``` string1 = "go" string2 = "now" string3 = "great" s = """ I'm will %s there I will go %s %s """ % (string1, string2, string3) print s ``` Some reading t...
Python multiline string - $ for variables
10,112,614
23
2012-04-11T19:28:04Z
10,112,665
42
2012-04-11T19:32:23Z
[ "python", "string", "variables", "multiline" ]
I'm looking for a clean way to use variables within a Python multiline string. Say I wanted to do the following ``` string1 = go string2 = now string3 = great """ I'm will $string1 there I will go $string2 $string3 """ ``` In a way I'm looking to see if there is a Perl like $ to indicate a variable in the Python syn...
The common way is the `format()` function: ``` >>> s = "This is an {example} with {vars}".format(vars="variables", example="example") >>> s 'This is an example with variables' ``` You can also pass a dictionary with variables: ``` >>> d = { 'vars': "variables", 'example': "example" } >>> s = "This is an {example} wi...
Python: is the iteration of the multidimensional array super slow?
10,112,745
2
2012-04-11T19:37:37Z
10,112,850
12
2012-04-11T19:45:07Z
[ "python", "performance", "numpy" ]
I have to iterate all items in two-dimensional array of integers and change the value (according to some rule, not important). I'm surprised how significant difference in performance is there between python runtime and C# or java runtime. Did I wrote totally wrong python code (v2.7.2)? ``` import numpy a = numpy.ndar...
Yep! Iterating through numpy arrays in python is slow. (Slower than iterating through a python list, as well.) Typically, you avoid iterating through them directly. If you can give us an example of the rule you're changing things based on, there's a good chance that it's easy to vectorize. As a toy example: ``` imp...
Python: is the iteration of the multidimensional array super slow?
10,112,745
2
2012-04-11T19:37:37Z
10,112,915
10
2012-04-11T19:50:31Z
[ "python", "performance", "numpy" ]
I have to iterate all items in two-dimensional array of integers and change the value (according to some rule, not important). I'm surprised how significant difference in performance is there between python runtime and C# or java runtime. Did I wrote totally wrong python code (v2.7.2)? ``` import numpy a = numpy.ndar...
The example you gave was presumably meant to set all items of a two-dimensional NumPy array to 123. This can be done efficiently like this: ``` a.fill(123) ``` or ``` a[:] = 123 ```
Best way to parse a URL query string
10,113,090
24
2012-04-11T20:04:07Z
10,113,201
34
2012-04-11T20:11:43Z
[ "python", "string", "http", "webserver" ]
What is the best way to parse data out of a URL query string (for instance, data appended to the URL by a form) in python? My goal is to accept form data and display it on the same page. I've researched several methods that aren't quite what I'm looking for. I'm creating a simple web server with the goal of learning a...
The urllib.parse module is your friend: <https://docs.python.org/3/library/urllib.parse.html> Check out [urllib.parse.parse\_qs](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs) (parsing a query-string, i.e. form data sent to server by GET or form data posted by POST, at least for non-multipa...
How to decide when to wrap/port/write-from-scratch
10,113,218
2
2012-04-11T20:12:36Z
10,113,985
10
2012-04-11T21:05:00Z
[ "python", "wrapper", "porting", "smalltalk", "pharo" ]
There is a project I'm about to build in Smalltalk (Pharo). And there is a python library which I intend to use for the same. Now, there are 3 options: * Smalltalk wrapper for those python libraries * Porting the python library to Smalltalk * Write the library from scratch (in Smalltalk) for use in my project The fol...
## Wrapper Write functions in the native language whose sole purpose is to call the functions in the external library. The goal is to do as little as possible in the native language. For example, translating data types from the native language to the external library language, etc. Wrappers make sense when the extern...
Handle circular dependencies in Python modules?
10,113,383
4
2012-04-11T20:24:16Z
10,113,552
12
2012-04-11T20:36:27Z
[ "python", "import", "include" ]
this is a case again where I'm running around in circles and I'm about to go wild. I wish Python would analyze all files at first, so that it would know all identifiers from the beginning (I think like Java does). I have a "main.py" and a "gui.py". Every file contains a class, that makes use of the class in the other...
I thought I'd expand this into an answer instead of a comment. It's worth noting that [circular imports are generally a sign of bad design](http://stackoverflow.com/questions/1356304/are-circular-class-dependencies-bad-from-a-coding-style-point-of-view): instead of demanding the language suit your design, why not chan...
Why does my program work with a .py extension but not with a .pyw extension?
10,114,018
5
2012-04-11T21:07:39Z
10,114,171
8
2012-04-11T21:20:15Z
[ "python", "user-interface", "tkinter", "pythonw" ]
I have a script that converts Google Earth `.kml` / `.kmz` files to shapefiles with a simple GUI interface written in Tkinter. My problem is that it works fine with a `.py` extension, but when saved out with a `.pyw` extension it stalls while reading my `.kml` files. There are no error messages and it doesn't crash. ...
`.pyw` files are run differently than .py files -- they are associated with a different interpreter, `pythonw.exe` instead of `python.exe`, which doesn't have a console associated with it. According to some sources, including [this old mailing list thread](http://mail.python.org/pipermail/python-list/2001-September/10...
How to properly send HTTP response with Python using socket library only?
10,114,224
4
2012-04-11T21:25:06Z
10,114,266
7
2012-04-11T21:28:32Z
[ "python", "http", "sockets", "webserver" ]
I have a very simple web sever written in Python. It listens on port 13000, how can I make it deliver a simple "Hello World" webpage if `http://localhost:13000` is opened in browser? Right there is my code: ``` # set up socket and connection while True: sock, addr = servSock.accept() # WHAT GOES HERE? soc...
**Updated according to question change** Possibly, it keeps spinning because in combination of absense of `Content-Length` and `Connection` headers, browser may assume it's `Connection: keep-alive`, so it continues to receive data from your server forever. Try to send `Connection: close`, and pass actual `Content-Leng...
Setting points with no data to white with Matplotlib imshow
10,114,576
4
2012-04-11T21:59:20Z
10,114,676
8
2012-04-11T22:08:41Z
[ "python", "graph", "matplotlib" ]
I am graphing data from a numpy array using matplotlib imshow. However, some points have no data in them. I initialized the array using np.zeroes, so these points are dragging down the whole map. I know that none of the data will ever have a value of 0.0. Is there some way for me to tell the imshow routine to ignore th...
Have you tried instantiating your array with NaNs instead of zeros to see if matplotlib's default will ignore the NaNs in a way that works for you? You could also try just using logical indexing to make the locations of 0 equal to NaN right before plotting: ``` my_data[my_data == 0.0] = numpy.nan ``` Alternatively, y...
How to keep a C++ class name unmodified with Cython?
10,114,710
13
2012-04-11T22:12:43Z
10,121,232
14
2012-04-12T09:50:12Z
[ "c++", "python", "cython" ]
I have a C++ class called Foo. If I follow the [Cython C++ tutorial](http://docs.cython.org/src/userguide/wrapping_CPlusPlus.html) I will need to call the Python class differently, PyFoo for example. However I really need to call the Python class Foo as well. How to do that efficiently? Edit: I'm trying to interface a...
There are two ways to handle this. 1. Declare C++ class with an alternate name; original name has to be specified in double quotes: ``` cdef extern from "defs.h" namespace "myns": cdef cppclass CMyClass "myns::MyClass": ... ``` Then you can use `MyClass` for your python class and refer ...
Python-Requests close http connection
10,115,126
14
2012-04-11T22:54:13Z
10,115,553
13
2012-04-11T23:47:07Z
[ "python", "http", "urllib2", "httplib", "python-requests" ]
I was wondering, how do you close a connection with Requests (python-requests.org)? With `httplib` it's `HTTPConnection.close()`, but how do I do the same with Requests? Code is below: ``` r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd')) ...
As discussed [here](http://stackoverflow.com/questions/3272653/in-what-conditions-are-closing-a-http-connection-necessary/3272700#3272700), there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about ...
Python-Requests close http connection
10,115,126
14
2012-04-11T22:54:13Z
15,511,852
26
2013-03-19T22:37:27Z
[ "python", "http", "urllib2", "httplib", "python-requests" ]
I was wondering, how do you close a connection with Requests (python-requests.org)? With `httplib` it's `HTTPConnection.close()`, but how do I do the same with Requests? Code is below: ``` r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd')) ...
I think a more reliable way of closing a connection is to tell the sever explicitly to close it in a way compliant with HTTP specification. This is what works for me: ``` r = requests.post(url=url, data=body, headers={'Connection':'close'}) ``` HTTP header 'Connection' should do the trick on the server's side.
How to test if an attribute exists in some XML
10,115,396
4
2012-04-11T23:29:29Z
10,115,420
9
2012-04-11T23:31:43Z
[ "python", "xml", "lxml" ]
I have some XML that I am parsing in python via lxml. I am encountering situations where some elements have attributes and some don't. I need to extract them if they exist, but skip them if they don't - I'm currently landing with errors (as my approach is wrong...) I have deployed a testfornull, but that doesn't wor...
I'm surprised that a test for null values on an attribute which often won't exist works *ever* -- what you should be doing is checking whether it exists, not whether it's empty: ``` if 'Reference' in current_element.attrib: ...do something with it... ```
PyBrain: When creating network from ground up how and where do you create a bias?
10,115,600
6
2012-04-11T23:52:48Z
10,115,875
10
2012-04-12T00:31:45Z
[ "python", "neural-network", "pybrain" ]
Following the [PyBrain](http://pybrain.org/) documentation, [Building Networks with Modules and Connections](http://pybrain.org/docs/tutorial/netmodcon.html), I'm building a neural network piecewise (in contrast to using the buildNetwork shortcut). I'm constructing a simple 3-layer (input, hidden, output) neural networ...
Realized PyBrain is open source and I have the source code sitting in my Python directory. I opened the C:\Python27\Lib\site-packages\pybrain\tools\shortcuts.py file. Inside this file I located the buildNetwork function and saw how it adds BiasUnit's. The relevant code is here: ``` ... n = Network() # linear input lay...
I'm getting Key error in python
10,116,518
49
2012-04-12T02:11:27Z
10,116,540
84
2012-04-12T02:15:05Z
[ "python", "dictionary" ]
In my python program I am getting this error: ``` KeyError: 'variablename' ``` From this code: ``` path = meta_entry['path'].strip('/'), ``` Can anyone please explain why this is happening?
A [`KeyError`](http://docs.python.org/library/exceptions.html#exceptions.KeyError) generally means the key doesn't exist. So, are you sure the `path` key exists? From the official python docs: **exception KeyError** > Raised when a mapping (dictionary) key is not found in the set of > existing keys. For example: `...
I'm getting Key error in python
10,116,518
49
2012-04-12T02:11:27Z
10,116,571
45
2012-04-12T02:20:09Z
[ "python", "dictionary" ]
In my python program I am getting this error: ``` KeyError: 'variablename' ``` From this code: ``` path = meta_entry['path'].strip('/'), ``` Can anyone please explain why this is happening?
I fully agree with the Key error comments. You could also use the [dictionary's get()](http://docs.python.org/library/stdtypes.html#dict) method as well to avoid the exceptions. This could also be used to give a default path rather than `None` as shown below. ``` >>> d = {"a":1, "b":2} >>> x = d.get("A",None) >>> prin...
how to use initializer to set up my multiprocess pool?
10,117,073
22
2012-04-12T03:40:18Z
10,118,250
53
2012-04-12T06:10:29Z
[ "python", "multiprocessing" ]
I'm trying to use the multiprocess Pool object. I'd like each process to open a database connection when it starts, then use that connection to process the data that is passed in. (Rather than opening and closing the connection for each bit of data.) This seems like what the initializer is for, but I can't wrap my head...
The initialize function is called thus: ``` def worker(...): ... if initializer is not None: initializer(*args) ``` so there is no return value saved anywhere. You might think this dooms you, but no! Each worker is in a separate process. Thus, you can use an ordinary `global` variable. This is not ex...
Pickleable Image Object
10,118,068
9
2012-04-12T05:49:11Z
10,118,087
16
2012-04-12T05:51:57Z
[ "python", "python-imaging-library", "pickle" ]
How do I create a pickleable file from a PIL Image object such that you could save those images as a single pickle file then maybe upload to another computer such as a server running PIL and unpickle it there?
You can convert the Image object into data then you can pickle it: ``` image = { 'pixels': im.tostring(), 'size': im.size, 'mode': im.mode, } ``` And back to an Image: ``` im = Image.fromstring(image['mode'], image['size'], image['pixels']) ``` **NOTE:** As `astex` mentioned, if you're using Pillow (whi...
Pickleable Image Object
10,118,068
9
2012-04-12T05:49:11Z
10,118,440
9
2012-04-12T06:25:27Z
[ "python", "python-imaging-library", "pickle" ]
How do I create a pickleable file from a PIL Image object such that you could save those images as a single pickle file then maybe upload to another computer such as a server running PIL and unpickle it there?
Slight variation of Gerald's answer using keyword args create pickleable object ``` image = {'data': im.tostring(), 'size':im.size, 'mode':im.mode} ``` or ``` image = dict(data=im.tostring(), size=im.size, mode=im.mode) ``` unpickle back to image ``` im = Image.fromstring(**image) ```
Remove one value from a NumPy array
10,120,008
2
2012-04-12T08:28:28Z
10,120,263
7
2012-04-12T08:48:15Z
[ "python", "arrays", "numpy" ]
I am trying to all rows that only contain zeros from a NumPy array. For example, I want to remove `[0,0]` from ``` n = np.array([[1,2], [0,0], [5,6]]) ``` and be left with: ``` np.array([[1,2], [5,6]]) ```
To remove the second row from a numpy table: ``` import numpy n = numpy.array([[1,2],[0,0],[5,6]]) new_n = numpy.delete(n, 1, axis=0) ``` To remove rows containing only 0: ``` import numpy n = numpy.array([[1,2],[0,0],[5,6]]) idxs = numpy.any(n != 0, axis=1) # index of rows with at least one non zero value n_non_zer...
Valid characters in a python class name
10,120,295
18
2012-04-12T08:50:16Z
10,120,327
25
2012-04-12T08:52:14Z
[ "python", "metaprogramming" ]
I'm dynamically creating python classes, and I know not all characters are valid in this context. Is there a method somewhere in the class library that I can use to sanitize a random text string, so that I can use it as a class name? Either that or a list of the allowed characters would be a good help. --- **Additio...
[Python Language Reference, §2.3, "Identifiers and keywords"](http://docs.python.org/reference/lexical_analysis.html#identifiers) > Identifiers (also referred to as *names*) are described by the following lexical definitions: > > ``` > identifier ::= (letter|"_") (letter | digit | "_")* > letter ::= lowercase |...
Create a simple password for unittest user using PASSWORD_HASHERS
10,120,518
8
2012-04-12T09:04:12Z
10,120,651
11
2012-04-12T09:12:27Z
[ "python", "django", "django-testing" ]
Until django 1.2.5 i could use the following code to create a user for testing and then log it in: ``` class TestSomeLoginRequiredView(TestCase): urls = 'sonloop.tests.test_urls' def setUp(self): self.user = User.objects.create(username='testuser',password='some_password') def test_the_view(self...
``` self.user = User.objects.create(username='testuser',password='!') self.user.set_password('some_password') self.user.save() # <--- You need this ;) ``` OR: [from here](https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.UserManager.create_user) ``` self.user = User.objects.create_user(use...
Create a simple password for unittest user using PASSWORD_HASHERS
10,120,518
8
2012-04-12T09:04:12Z
10,120,790
13
2012-04-12T09:20:56Z
[ "python", "django", "django-testing" ]
Until django 1.2.5 i could use the following code to create a user for testing and then log it in: ``` class TestSomeLoginRequiredView(TestCase): urls = 'sonloop.tests.test_urls' def setUp(self): self.user = User.objects.create(username='testuser',password='some_password') def test_the_view(self...
While searching for a solution i found one more thing that would work, allthough i will most probably use Thomas User.objects.create\_user solution, as that is really simple. But for whatever it's worth, that's what i came up with: ``` from django.contrib.auth.hashers import make_password pwd = make_password('some_p...
Where is the default parameter in Python function
10,120,974
5
2012-04-12T09:32:24Z
10,121,437
10
2012-04-12T10:03:50Z
[ "python" ]
I think many people have seen the python's function which receives default parameters. For example: ``` def foo(a=[]): a.append(3) return a ``` If we call this function using foo(), the output will append integer '3' each time after the call. When this function is defined, a function object named 'foo' is de...
As others already said, the default values are stored in the function object. For example, in CPython you can do this: ``` >>> def f(a=[]): ... pass ... >>> f.func_defaults ([],) >>> f.func_code.co_varnames ('a',) >>> ``` However, `co_varnames` may contain more than names of args so it needs further processing a...
Requirements file for apt-get, similar to pip
10,121,210
11
2012-04-12T09:49:08Z
10,123,093
20
2012-04-12T11:57:05Z
[ "python", "pip", "apt", "apt-get" ]
I like how you can manage dependencies with pip requirements. Is there something similar in case of apt-get? <http://www.pip-installer.org/en/latest/requirements.html#requirements-file-format>
Your question is that you want to have a list of system dependences in one file, for being able to install it with one command. I don't recomend you to include the version of a package in the system dependencies. In the soft system dependences like "*build-essential*" or "*uuid-dev*" you normally want the latest versi...
Initialise numpy array of unknown length
10,121,926
8
2012-04-12T10:39:14Z
10,122,185
7
2012-04-12T10:57:33Z
[ "python", "arrays", "numpy" ]
I want to be able to 'build' a numpy array on the fly, I do not know the size of this array in advance. For example I want to do something like this: ``` a= np.array() for x in y: a.append(x) ``` Which would result in a containing all the elements of x, obviously this is a trivial answer. I am just curious whet...
You can do this: ``` a = np.array([]) for x in y: a = np.append(a, x) ```
Initialise numpy array of unknown length
10,121,926
8
2012-04-12T10:39:14Z
10,122,262
25
2012-04-12T11:04:00Z
[ "python", "arrays", "numpy" ]
I want to be able to 'build' a numpy array on the fly, I do not know the size of this array in advance. For example I want to do something like this: ``` a= np.array() for x in y: a.append(x) ``` Which would result in a containing all the elements of x, obviously this is a trivial answer. I am just curious whet...
Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(*n*) for the conversion to array, for a total of O(*n*). ``` a = [] for x in y: a.append(x) a = np.array(a) ```
how do you make a For loop when you don't need index in python?
10,122,109
4
2012-04-12T10:51:37Z
10,122,118
8
2012-04-12T10:52:24Z
[ "python", "coding-style", "pylint", "dummy-data" ]
if i need a for loop in python ``` for i in range(1,42): print "spam" ``` but don't use the "i" for anything pylint complains about the unused variable. How should i handle this? I know you can do this: ``` for dummy_index in range(1,42): print "spam" ``` but doing this seems quite strange to me, is there a...
``` for _ in range(1,42): print "spam" ```
unknown command: crawl error
10,123,104
10
2012-04-12T11:58:08Z
10,123,615
29
2012-04-12T12:30:58Z
[ "python", "scrapy", "web-crawler" ]
I am a newbie to python. I am running python 2.7.3 version 32 bit on 64 bit OS. (I tried 64 bit but it didn't workout). I followed the tutorial and installed scrapy on my machine. I have created one project, demoz. But when I enter `scrapy crawl demoz` it shows an error. I came across this thing when i hit scrapy comm...
You should run `scrapy crawl spider_name` command being in a scrapy project folder, where `scrapy.cfg` file resides. From the [docs](http://doc.scrapy.org/en/latest/intro/tutorial.html#crawling): > Crawling > > To put our spider to work, go to the project’s top level directory and run: > > `scrapy crawl dmoz`
How do I make a dictionary with multiple keys to one value?
10,123,853
16
2012-04-12T12:45:37Z
10,124,826
11
2012-04-12T13:42:42Z
[ "python", "dictionary" ]
I have a question about a dictionary I want to make. My goal is to have multiple keys to a single value,like below: ``` dictionary={('a','b'):1,('c','d'):2} ``` Any ideas?
I guess you mean this: ``` class Value: def __init__(self, v=None): self.v = v v1 = Value(1) v2 = Value(2) d = {"a":v1, "b":v1, "c":v2, "d":v2} d["a"].v += 1 d["b"].v == 2 ``` * Pythons strings and numbers are language values, * So, if you want d["a"] and d["b"] both point to "**a single same value**", make ...
Python requests fetch a file from a local url
10,123,929
18
2012-04-12T12:51:08Z
10,124,165
9
2012-04-12T13:05:08Z
[ "python", "http", "local", "python-requests" ]
I am using Python's [requests](http://docs.python-requests.org/en/latest/index.html) library in one method of my application. The body of the method looks like this: ``` def handle_remote_file(url, **kwargs): response = requests.get(url, ...) buff = StringIO.StringIO() buff.write(response.content) ... ...
[packages/urllib3/poolmanager.py](https://github.com/kennethreitz/requests/blob/775b6f6f0098ffa9edd3874b1af4b98378377211/requests/packages/urllib3/poolmanager.py#L18) pretty much explains it. Requests doesn't support local url. ``` pool_classes_by_scheme = { ...
Python requests fetch a file from a local url
10,123,929
18
2012-04-12T12:51:08Z
22,989,322
16
2014-04-10T13:21:49Z
[ "python", "http", "local", "python-requests" ]
I am using Python's [requests](http://docs.python-requests.org/en/latest/index.html) library in one method of my application. The body of the method looks like this: ``` def handle_remote_file(url, **kwargs): response = requests.get(url, ...) buff = StringIO.StringIO() buff.write(response.content) ... ...
As @WooParadog explained requests library doesn't know how to handle local files. Although, current version allows to define [transport adapters](http://docs.python-requests.org/en/latest/user/advanced/?highlight=mount#transport-adapters). Therefore you can simply define you own adapter which will be able to handle lo...
Python requests fetch a file from a local url
10,123,929
18
2012-04-12T12:51:08Z
27,786,580
8
2015-01-05T19:36:36Z
[ "python", "http", "local", "python-requests" ]
I am using Python's [requests](http://docs.python-requests.org/en/latest/index.html) library in one method of my application. The body of the method looks like this: ``` def handle_remote_file(url, **kwargs): response = requests.get(url, ...) buff = StringIO.StringIO() buff.write(response.content) ... ...
Here's a transport adapter I wrote which is more featureful than b1r3k's and has no additional dependencies beyond Requests itself. I haven't tested it exhaustively yet, but what I have tried seems to be bug-free. ``` import requests import os from urllib import url2pathname class LocalFileAdapter(requests.adapters.B...
Python Boto Dynamodb very slow performance for small record set retrieval on range keys
10,124,062
10
2012-04-12T12:59:11Z
10,141,470
12
2012-04-13T13:10:07Z
[ "python", "performance", "boto", "amazon-dynamodb" ]
I am testing dynamodb via boto and have found it to be surprisingly slow in retrieving data sets based on hashkey, rangekey condition queries. I have seen some discussion about the oddity that causes ssl (is\_secure) to perform about 6x faster then non-ssl and I can confirm that finding. But even using ssl I am seeing ...
This isn't a complete answer but I thought it was worth posting it at this time. I've heard reports like this from a couple of people over the last few weeks. I was able to reproduce the anomaly of HTTPS being considerably faster than HTTP but wasn't able to track it down. It seemed like that problem was unique to Pyt...
convert a flat list to list of list in python
10,124,751
10
2012-04-12T13:38:17Z
10,124,783
21
2012-04-12T13:40:16Z
[ "python", "list" ]
Normally, you want to go the other way around, [like here](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). I was wondering how you can convert a flat list to a list of list, quasy reshaping array in python In numpy you could do something like: ``` >>> a=numpy.aranage(9) >...
``` >>> l = ['a', 'b', 'c', 'd', 'e', 'f'] >>> zip(*[iter(l)]*2) [('a', 'b'), ('c', 'd'), ('e', 'f')] ``` As it has been pointed out by @Lattyware, this only works if there are enough items in each argument to the `zip` function each time it returns a tuple. If one of the parameters has less items than the others, ite...
convert a flat list to list of list in python
10,124,751
10
2012-04-12T13:38:17Z
10,124,806
9
2012-04-12T13:41:32Z
[ "python", "list" ]
Normally, you want to go the other way around, [like here](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python). I was wondering how you can convert a flat list to a list of list, quasy reshaping array in python In numpy you could do something like: ``` >>> a=numpy.aranage(9) >...
This is usually done using the grouper recipe from the [`itertools` documentation](http://docs.python.org/library/itertools.html#recipes): ``` def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args) `...
Flask - headers are not converted to unicode?
10,124,786
6
2012-04-12T13:40:29Z
10,130,966
10
2012-04-12T20:05:30Z
[ "python", "unicode", "flask", "werkzeug", "storm-orm" ]
I'm developping a small web service in python using: * Flask (v. 0.8) * storm ORM (v. 0.19) * Apache with mod\_wsgi I have a custom HTTP header, `Unison-UUID` which I'm using at some point to retrieve information in my database. here's the (slightly rewritten for simplicity) snippet that I'm having trouble with: ``...
At <http://flask.pocoo.org/docs/api/#flask.request> we read > The request object is an instance of a `Request` subclass and provides > all of the attributes Werkzeug defines. The word `Request` links to <http://werkzeug.pocoo.org/docs/wrappers/#werkzeug.wrappers.Request> where we read > The `Request` and `Response` ...
how to randomly choose multiple keys and its value in a dictionary python
10,125,568
4
2012-04-12T14:23:50Z
10,125,602
12
2012-04-12T14:25:13Z
[ "python" ]
I have a dictionary like this: ``` user_dict = { user1: [(video1, 10),(video2,20),(video3,1)] user2: [(video1, 4),(video2,8),(video6,45)] ... user100: [(video1, 46),(video2,34),(video6,4)] } (video1,10) means (videoid, number of request) ``...
That's what [`random.sample()`](http://docs.python.org//library/random.html?highlight=random.choice#random.sample) is for: > Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement. This can be used to choose the keys. The values can subsequently be ...
SWIG and C++ shared library
10,126,531
9
2012-04-12T15:15:39Z
10,126,794
22
2012-04-12T15:28:52Z
[ "c++", "python", "linker", "g++", "swig" ]
I have a C++ library (let's call it `mylib`) which compiles to `libmylib.so` file in `/usr/local/lib` and I have a bunch of header files in a directory called `my lib` in `/usr/local/include`. Now the thing I wanted to do (for starters) is just use one of the header files (it contains information about a class my libr...
I've put together a complete example for you: ## Header file: (mylib.h) ``` class Foo { }; void bar(const Foo&); ``` ## Implementation: ``` #include "mylib.h" #include <iostream> void bar(const Foo& f) { std::cout << &f << std::endl; } ``` ## Compile the library: ``` g++ -fPIC -Wall -Wextra -shared mylib.cc ...
Can I override a C++ virtual function within Python with Cython?
10,126,668
9
2012-04-12T15:22:23Z
11,595,962
9
2012-07-21T21:22:43Z
[ "c++", "python", "cython" ]
I have a C++ class with a virtual method: ``` //C++ class A { public: A() {}; virtual int override_me(int a) {return 2*a;}; int calculate(int a) { return this->override_me(a) ;} }; ``` What I would like to do is to expose this class to Python with Cython, inherit from this class in Pytho...
The solution is somewhat complicated, but it is possible. There is a fully working example here: <https://bitbucket.org/chadrik/cy-cxxfwk/overview> Here is an overview of the technique: Create a specialized subclass of `class A` whose purpose will be to interact with a cython extension: ``` // created by cython when...
Can I override a C++ virtual function within Python with Cython?
10,126,668
9
2012-04-12T15:22:23Z
12,700,121
8
2012-10-02T23:57:49Z
[ "c++", "python", "cython" ]
I have a C++ class with a virtual method: ``` //C++ class A { public: A() {}; virtual int override_me(int a) {return 2*a;}; int calculate(int a) { return this->override_me(a) ;} }; ``` What I would like to do is to expose this class to Python with Cython, inherit from this class in Pytho...
Excellent ! Not complete but sufficient. I've been able to do the trick for my own purpose. Combining this post with the sources linked above. It's not been easy, since I'm a beginner at Cython, but I confirm that it is the only way I could find over the www. Thanks a lot to you guys. I am sorry that I don't have so...
how to set and check a boolean flag in python
10,126,679
3
2012-04-12T15:23:08Z
10,126,716
12
2012-04-12T15:24:56Z
[ "python", "boolean" ]
I'm very very new to python. I'm trying to do something like this with a boolean: ``` /* ... other stuff */ loggedDocument = false for line in inFile: if (line.find( /*something*/ ) != -1): println("FOUND DOCUMENT: %s" % line) loggedDocument = true if (loggedDocument == false): /* do something else */ ...
You're looking for `True` and `False` (note the capitals). Also the more pythonic way to write the last line is `if not loggedDocument` instead of `if loggedDocument == False`. Edit: And BTW, the `println` is not Python a builtin Python function; are you looking for `print()`?
Ubuntu Chrome: How to read a cookie from a python script
10,126,734
6
2012-04-12T15:26:01Z
10,128,830
7
2012-04-12T17:38:56Z
[ "python", "google-chrome", "cookies", "ubuntu" ]
I am creating a little application that has two parts: One of them is displayed inside a Chrome browser and the other is a local application programmed in Python. In Chrome, the user has a `<select>` to choose his/her preferred language. That information is stored by Chrome in a cookie. I would like to know if it's p...
Yep, as I mentioned in the comments to my question, sqlite3 sounded promising... The day I learn to read, I'll conquer the world!! Anyway, just in case is helpful for someone else: ``` #!/usr/bin/env python import os import sqlite3 import pwd _cookieName = "preferredLanguage" def getPreferredLanguageFromCookieDB():...
Overlay imshow plots in matplotlib
10,127,284
11
2012-04-12T15:56:41Z
10,127,675
20
2012-04-12T16:23:50Z
[ "python", "numpy", "matplotlib" ]
I would like to compare two different sets of data on the same imshow plot to make it easy to see the differences. My first instinct is to make the colors in the colormap transparent (the lower values especially) but I haven't been able to get this to work: ``` from matplotlib.colors import colorConverter import matpl...
You can set the `alpha` argument in your `imshow` command. In your example, `img3 = plt.imshow(zvals2, interpolation='nearest', cmap=cmap2, origin='lower', alpha=0.6)` # EDIT: Thanks for the clarification. Here is a description of what you can do: * First, choose a [matplotlib colormap](http://www.scipy.org/Cookboo...
Find indexes on two lists based on items condition
10,128,360
7
2012-04-12T17:06:18Z
10,128,399
11
2012-04-12T17:08:39Z
[ "python", "list", "data-structures", "indexing" ]
Lets say I have two lists. They are lists of ratings of books on a scale from -5, to 5. I want to know when list1's element is `>= 1` and list2's element `== 0`, so for example. ``` list1 = [3, 3, 1, 0, 3, 0, 3, 0, 0, -3, 0, 5, 3, 0, 1, 0, 0, 5, 3, 0, 0, 0, 0, 1, 0, 3, 0, 1, 0, 0, 3, 5, 3, 3, 0, 0, 0, 5, 0, 5, 0, 3, ...
``` >>> [i for i, v in enumerate(list1) if v>=1 and list2[i]==0] [1, 2, 4, 14, 18, 27, 39, 48, 52] ```
Find indexes on two lists based on items condition
10,128,360
7
2012-04-12T17:06:18Z
10,128,450
7
2012-04-12T17:12:05Z
[ "python", "list", "data-structures", "indexing" ]
Lets say I have two lists. They are lists of ratings of books on a scale from -5, to 5. I want to know when list1's element is `>= 1` and list2's element `== 0`, so for example. ``` list1 = [3, 3, 1, 0, 3, 0, 3, 0, 0, -3, 0, 5, 3, 0, 1, 0, 0, 5, 3, 0, 0, 0, 0, 1, 0, 3, 0, 1, 0, 0, 3, 5, 3, 3, 0, 0, 0, 5, 0, 5, 0, 3, ...
Another variant: ``` >>> [i for i, (l1, l2) in enumerate(zip(list1, list2)) if l1 >= 1 and l2 == 0] [1, 2, 4, 14, 18, 27, 39, 48, 52] ```
Combining numpy with sympy
10,129,213
6
2012-04-12T18:04:55Z
10,138,307
10
2012-04-13T09:25:08Z
[ "python", "numpy", "sympy" ]
I have a the following code: ``` p = classp(); for i in range(1,10): x = numpy.array([[2],[4],[5]]) print p.update(x) class classp: def __init__(self): self.mymodel = array([2*x[1]], [3*x[0]], [x[2]]); def update(self, x): return self.mymodel #replace x(0)...x(1) with the given parameter ```...
I can propose you two solutions. Firstly, there is `DeferedVector` that was created for use with `lambdify`: ``` In [1]: from sympy.matrices import DeferredVector In [2]: v = DeferredVector('v') In [3]: func = lambdify(v, Matrix([v[1], 2*v[2]])) In [4]: func(np.array([10,20,30])) Out[4]: [[20] [60...
Python: sort an array of dictionaries with custom comparator?
10,129,598
9
2012-04-12T18:30:17Z
10,129,652
22
2012-04-12T18:34:07Z
[ "python" ]
I have the following Python array of dictionaries: ``` myarr = [ { 'name': 'Richard', 'rank': 1 }, { 'name': 'Reuben', 'rank': 4 }, { 'name': 'Reece', 'rank': 0 }, { 'name': 'Rohan', 'rank': 3 }, { 'name': 'Ralph', 'rank': 2 }, { 'name': 'Raphael', 'rank': 0 }, { 'name': 'Robin', 'rank': 0 } ] ``` I'd like to sort it...
Option 1: ``` key=lambda d:(d['rank']==0, d['rank']) ``` Option 2: ``` key=lambda d:d['rank'] if d['rank']!=0 else float('inf') ``` Demo: > "I'd like to sort it by the rank values, ordering as follows: 1-2-3-4-0-0-0." --original poster ``` >>> sorted([0,0,0,1,2,3,4], key=lambda x:(x==0, x)) [1, 2, 3, 4, 0, 0] >>...
efficient way of accessing values in a tuple (python)
10,131,180
2
2012-04-12T20:20:51Z
10,131,215
9
2012-04-12T20:22:47Z
[ "python", "class", "tuples" ]
i have a function that returns a tuple of ``` x = (1, 2, 3, 4, 5, 6, 7, 8, 9) ``` i also have a class that requires 10 total args (including self) i want the tuple to be able to populate the args in the class, but if i just put ``` y = Class(x) ``` it returns the error ``` > TypeError: __init__() takes exactly 10...
Use the asterisk to [unpack argument lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) ``` Class(*x) ```
Install libpq-dev on Mac OS X
10,132,274
8
2012-04-12T21:40:17Z
10,145,243
12
2012-04-13T17:10:03Z
[ "python", "django", "postgresql", "psycopg2" ]
I'm trying to run Django with a Postgresql backend on my local Mac OS X. I've installed Django using pip: ``` sudo pip install Django ``` I've installed Postgresql with one of the binary installers [here](http://www.postgresql.org/download/macosx/). But when I try to install psycopg2 I get an error (pasted below) th...
So I ended up following the advice here: <http://blog.jonypawks.net/2008/06/20/installing-psycopg2-on-os-x/> Turns out I did have `pg-config` installed, but I had to dig around to find it a bit. Once I included that in the path, everything worked swimmingly. Here's the snippet from that link: ``` PATH=$PATH:/Library...
Install libpq-dev on Mac OS X
10,132,274
8
2012-04-12T21:40:17Z
22,868,821
9
2014-04-04T17:03:42Z
[ "python", "django", "postgresql", "psycopg2" ]
I'm trying to run Django with a Postgresql backend on my local Mac OS X. I've installed Django using pip: ``` sudo pip install Django ``` I've installed Postgresql with one of the binary installers [here](http://www.postgresql.org/download/macosx/). But when I try to install psycopg2 I get an error (pasted below) th...
For OSX 10.9.2 Mavericks, this is what worked for me. Try installing postgres with brew first: ``` brew install postgresql ``` Then install pg ``` gem install pg ```
Timeit, NameError: global name is not defined. But I didn't use a global variable
10,132,646
6
2012-04-12T22:12:56Z
10,132,742
11
2012-04-12T22:22:45Z
[ "python", "global-variables", "nameerror", "timeit" ]
I'd like to measure the execution speed of the following code: ``` def pe1(): l = [] for i in range(1000): if i%3 == 0 or i%5 == 0: l.append(i) print sum(l) ``` I stored this code under pe1m.py . Now I'd like to test the speed of file with the python interpreter. I did: ``` import tim...
Try this: ``` t = timeit.Timer(stmt='pe1()', setup='from pe1m import pe1') ``` `timeit.Timer` object doesn't know about the namespace you're calling it in so it can't access the `pe1m` module that you imported. The `setup` argument is a statement executed in the context of the timed statement, they share the same na...
How do I dynamically add mixins as base classes without getting MRO errors?
10,132,679
9
2012-04-12T22:16:34Z
10,132,775
9
2012-04-12T22:26:13Z
[ "python", "class", "architecture", "method-resolution-order" ]
Say I have a class `A`, `B` and `C`. Class `A` and `B` are both mixin classes for Class `C`. ``` class A( object ): pass class B( object ): pass class C( object, A, B ): pass ``` This will not work when instantiating class C. I would have to remove `object` from class C to make it work. (Else you'll get ...
Think of it this way -- you want the mixins to override some of the behaviors of `object`, so they need to be before `object` in the method resolution order. So you need to change the order of the bases: ``` class C(A, B, object): pass ``` Due to [this bug](http://bugs.python.org/issue672115), you need `C` not t...
PyBrain: Loading data with numpy.loadtxt?
10,133,386
5
2012-04-12T23:43:39Z
10,134,487
8
2012-04-13T02:23:32Z
[ "python", "numpy", "pybrain" ]
I have some working code which correctly loads data from a csv file into a PyBrain Dataset: ``` def old_get_dataset(): reader = csv.reader(open('test.csv', 'rb')) header = reader.next() fields = dict(zip(header, range(len(header)))) print header # assume last field in csv is single target variab...
After a lot of experimenting and re-reading the [dataset documentation](http://pybrain.org/docs/tutorial/datasets.html), the following runs without error: ``` def get_dataset(): array = numpy.loadtxt('test.csv', delimiter=',', skiprows=1) # assume last field in csv is single target variable # and all oth...
How to programmatically select pan/zoom in pyqt/matplotlib navigation
10,133,478
4
2012-04-12T23:55:27Z
10,144,999
8
2012-04-13T16:50:29Z
[ "python", "matplotlib", "pyqt4" ]
I have a pyqt4 matplotlib application and I would like the figure to start out (default) to the pan zoom mode when the application opens. I can't find any example or clue from the documentation on how to do this programmatically. Also along this same line how would I enable the shortcut keys in my application (http://...
I had a similar issue and in my case I solved it by using `toolbar.zoom()`: ``` import pylab plt.Figure() thismanager = get_current_fig_manager() thismanager.toolbar.zoom() ``` In that case the figure will appear with the zoom tool already selected
Python optimisations in this code?
10,134,038
4
2012-04-13T01:12:02Z
10,134,465
7
2012-04-13T02:19:19Z
[ "python", "optimization" ]
I have two fairly simple code snippets and I'm running both of them a very large amount of times; I'm trying to determine if there's any optimisation I can do to speed up the execution time. If there's anything that stands out as something that could be done a lot quicker... In the first one, we've got a list, fields....
When you are trying to optimise, the thing you ***have*** to do is profile and measure! Python provides the `timeit` module which makes measuring things easy! This will assume that you've converted fields to a list of floats beforehand (outside any of these functions), since the string → float conversion is very slow....
my rotation matrix for numpy (python) isn't working
10,134,290
4
2012-04-13T01:50:05Z
10,134,315
9
2012-04-13T01:53:59Z
[ "python", "numpy" ]
i was making a program to display matrices under various transforms, and all of them work except for my rotation matrix. ive tried fiddling with it, but nothing seems to work ``` y = input("how many degrees do you want to rotate the shape around the origin?: ") j = array([(cos(int(y)), -sin(int(y))), (sin(int(y)), ...
As the python documentation for [`cos`](http://docs.python.org/library/math.html#math.cos) and [`sin`](http://docs.python.org/library/math.html#math.sin) point out, the arguments should be in *radians*, not *degrees*. You can use the [`math.radians`](http://docs.python.org/library/math.html#math.radians) function to c...
String manipulation weirdness when incrementing trailing digit
10,134,622
2
2012-04-13T02:46:01Z
10,134,730
8
2012-04-13T03:08:28Z
[ "python", "regex", "string" ]
I got this code: ``` myString = 'blabla123_01_version6688_01_01Long_stringWithNumbers' versionSplit = re.findall(r'-?\d+|[a-zA-Z!@#$%^&*()_+.,<>{}]+|\W+?', myString) for i in reversed(versionSplit): id = versionSplit.index(i) if i.isdigit(): digit = '%0'+str(len(i))+'d' i = int(i) + 1 ...
Is there a reason why you aren't doing something like this instead: ``` prefix, version = re.match(r"(.*[^\d]+)([\d]+)$", myString).groups() newstring = prefix + str(int(version)+1).rjust(len(version), '0') ``` Notes: * This will actually "carry over" the version numbers properly: ("09" -> "10") and ("99" -> "100") ...
Using Requests python library to connect Django app failed on authentication
10,134,690
3
2012-04-13T02:59:26Z
16,022,262
8
2013-04-15T18:29:21Z
[ "python", "django", "authentication", "python-requests" ]
Maybe a stupid question here: Is Requests(A python HTTP lib) support Django 1.4 ? I use **Requests** follow the Official Quick Start like below: ``` requests.get('http://127.0.0.1:8000/getAllTracks', auth=('myUser', 'myPass')) ``` but i never get authentication right.(Of course i've checked the url, username, passwo...
In Django authentication works in following way: * There is a SessionMiddleware and AuthenticationMiddleware. The process\_request() of both these classes is called before any view is called. * SessionMiddleware uses cookies at a lower level. It checks for a cookie named `sessionid` and try to associate this cookie wi...
Executing Javascript from Python
10,136,319
19
2012-04-13T06:39:40Z
10,136,615
21
2012-04-13T07:07:56Z
[ "javascript", "python", "screen-scraping" ]
I have HTML webpages that I am crawling using xpath. The `etree.tostring` of a certain node gives me this string: ``` <script> <!-- function escramble_758(){ var a,b,c a='+1 ' b='84-' a+='425-' b+='7450' c='9' document.write(a+c+b) } escramble_758() //--> </script> ``` I just need the output of `escramb...
Using [PyV8](https://code.google.com/p/pyv8/), I can do this. However, I have to replace `document.write` with `return` because there's no DOM and therefore no `document`. ``` import PyV8 ctx = PyV8.JSContext() ctx.enter() js = """ function escramble_758(){ var a,b,c a='+1 ' b='84-' a+='425-' b+='7450' c='9' document...
Executing Javascript from Python
10,136,319
19
2012-04-13T06:39:40Z
30,537,286
7
2015-05-29T19:08:35Z
[ "javascript", "python", "screen-scraping" ]
I have HTML webpages that I am crawling using xpath. The `etree.tostring` of a certain node gives me this string: ``` <script> <!-- function escramble_758(){ var a,b,c a='+1 ' b='84-' a+='425-' b+='7450' c='9' document.write(a+c+b) } escramble_758() //--> </script> ``` I just need the output of `escramb...
You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features. ``` import js2py js = """ function escramble_758(){ var a,b,c a='+1 ' b='84-' a+='425-' b+='7450' c='...
python pylab plot normal distribution
10,138,085
32
2012-04-13T09:06:41Z
10,138,308
63
2012-04-13T09:25:09Z
[ "python", "matplotlib" ]
Given a mean and a variance is there a simple pylab function call which will plot a normal distribution? Or do I need to make one myself?
``` import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab import math mu = 0 variance = 1 sigma = math.sqrt(variance) x = np.linspace(-3, 3, 100) plt.plot(x,mlab.normpdf(x, mu, sigma)) plt.show() ``` ![gass distro, mean is 0 variance 1](http://i.stack.imgur.com/IvOTE.png)
python pylab plot normal distribution
10,138,085
32
2012-04-13T09:06:41Z
10,138,381
17
2012-04-13T09:29:36Z
[ "python", "matplotlib" ]
Given a mean and a variance is there a simple pylab function call which will plot a normal distribution? Or do I need to make one myself?
I don't think there is a function that does all that in a single call. However you can find the Gaussian probability density function in `scipy.stats`. So the simplest way I could come up with is: ``` import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm # Plot between -10 and 10 with .001 ...
Can Pylint error checking be customized?
10,138,917
22
2012-04-13T10:08:14Z
10,138,997
28
2012-04-13T10:14:21Z
[ "python", "pydev", "pylint" ]
I am using pydev where I have set up pylint. The problem is that even inside the comments, pylint reports warnings. I was looking to disable any sort of checking inside any line or a block comment. Also, I wish to follow camelCase naming convention instead of underscores for variables and arguments in my code. Is there...
You can globally disable warnings of a certain class using ``` pylint --disable=W1234 ``` or by using a special PyLint configuration file ``` pylint --rcfile=/path/to/config.file ``` A sample config file is given below: ``` [MESSAGES CONTROL] # C0111 Missing docstring # I0011 Warning locally suppressed using disa...
Can Pylint error checking be customized?
10,138,917
22
2012-04-13T10:08:14Z
10,140,373
15
2012-04-13T11:58:06Z
[ "python", "pydev", "pylint" ]
I am using pydev where I have set up pylint. The problem is that even inside the comments, pylint reports warnings. I was looking to disable any sort of checking inside any line or a block comment. Also, I wish to follow camelCase naming convention instead of underscores for variables and arguments in my code. Is there...
As said by cfedermann, you can specify messages to be disabled in a ~/.pylintrc file (notice you can generate a stub file using "pylint --generate-rcfile" if you don't want to use inline comments. You'll also see in the generated file, in the [BASIC] section, options like "method-rgx", "function-rgx", etc. which you c...
Handling an undefined template variable in Tornado
10,139,341
14
2012-04-13T10:43:26Z
10,139,436
14
2012-04-13T10:50:11Z
[ "python", "tornado" ]
This is a tornado template (say, in the file logout.html) I render on an error in the logout process: ``` {% if logout_error %} Oops! The logout failed. Please close all open documents and try again {% end %} ``` This can be called using ``` self.render("logout.html", logout_error=True) ``` If the logout is...
You can use ``` {% if locals().get('logout_error', False) %} ``` Substitute `False` with the value you want if the property is not set.
Handling an undefined template variable in Tornado
10,139,341
14
2012-04-13T10:43:26Z
10,141,734
15
2012-04-13T13:27:27Z
[ "python", "tornado" ]
This is a tornado template (say, in the file logout.html) I render on an error in the logout process: ``` {% if logout_error %} Oops! The logout failed. Please close all open documents and try again {% end %} ``` This can be called using ``` self.render("logout.html", logout_error=True) ``` If the logout is...
Hacking around using `locals().get()` is one way to do it. Another, bit more orthodox is using `try`. Tornado template supports it, so you can: ``` {% try %} {% if logout_error %} Oops! The logout failed. Please close all open documents and try again {% end %} {% except %} {% end %} ```
Calling variable defined inside one function from another function
10,139,866
7
2012-04-13T11:21:23Z
10,139,935
14
2012-04-13T11:26:35Z
[ "python", "function", "variables" ]
if I have this: ``` def oneFunction(lists): category=random.choice(list(lists.keys())) word=random.choice(lists[category]) def anotherFunction(): for letter in word: #problem is here print("_",end=" ") ``` I have previously defined `lists`, so `oneFunction(lists)` works perfectly. M...
Yes, you should think of defining both your function in a Class, and making word a member. This is cleaner ``` class Spam: def oneFunction(self,lists): category=random.choice(list(lists.keys())) self.word=random.choice(lists[category]) def anotherFunction(self): for letter in self.word...
Finding out the two nearest numbers to any float out of a list
10,140,243
2
2012-04-13T11:49:17Z
10,140,372
7
2012-04-13T11:58:00Z
[ "python", "list", "dictionary", "floating-point" ]
I have a dict with floats as keys and objects as values. I receive a float, and I'd like to know between what two keys this float is. How do I find this? Example of what I mean in code: ``` a = {} a[1.2] = some_unimportant_instance a[2.3] = some_other_unimportant_instance a[2.6] = some_third_unimportant_instance etc....
First observation: dict-s are bad for this. They are implemented using hashes and are efficient for retrieving values only for exact matches. For your purpose, you would have to first transform the dict into a list of keys. Then you could use modules such as bisect. Example: ``` import bisect keys = sorted(a.keys()) ...
How to find out whether a file is at its `eof`?
10,140,281
25
2012-04-13T11:52:08Z
10,140,327
16
2012-04-13T11:54:37Z
[ "python", "file", "eof" ]
``` fp = open("a.txt") #do many things with fp c = fp.read() if c is None: print 'fp is at the eof' ``` Besides the above method, any other way to find out whether is fp is already at the eof?
I'd argue that reading from the file is the most reliable way to establish whether it contains more data. It could be a pipe, or another process might be appending data to the file etc. If you *know* that's not an issue, you could use something like: ``` f.tell() == os.fstat(f.fileno()).st_size ```
How to find out whether a file is at its `eof`?
10,140,281
25
2012-04-13T11:52:08Z
10,140,333
28
2012-04-13T11:55:04Z
[ "python", "file", "eof" ]
``` fp = open("a.txt") #do many things with fp c = fp.read() if c is None: print 'fp is at the eof' ``` Besides the above method, any other way to find out whether is fp is already at the eof?
`fp.read()` reads up to the end of the file, so after it's successfully finished you know the file is at EOF; there's no need to check. If it cannot reach EOF it will raise an exception. When reading a file in chunks rather than with `read()`, you know you've hit EOF when `read` returns less than the number of bytes y...
How to find out whether a file is at its `eof`?
10,140,281
25
2012-04-13T11:52:08Z
24,738,688
13
2014-07-14T14:18:44Z
[ "python", "file", "eof" ]
``` fp = open("a.txt") #do many things with fp c = fp.read() if c is None: print 'fp is at the eof' ``` Besides the above method, any other way to find out whether is fp is already at the eof?
The "for-else" design is often overlooked. See: [Python Docs "Control Flow in Loop"](https://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops): **Example** ``` with open('foobar.file', 'rb') as f: for line in f: foo() else: # No more lines to...
No web processes running Error - Deploying Django on Heroku
10,142,284
14
2012-04-13T14:01:57Z
10,201,310
17
2012-04-18T00:54:07Z
[ "python", "django", "heroku" ]
I am using the tutorial to deploy Django. [http://devcenter.heroku.com/articles/django] After I do a git push heroku master, there are no web processes. ``` Process State Command ------- ----- ------- ``` On the log it looks like the following. ``` 2012-04-13T03:48:45+00:00 heroku[slugc]: Slug compilation star...
This is most likely the result of scaling your web processes down to zero through the client. ``` $ heroku ps:scale web=0 ``` Use the `heroku ps` command to determine the state of your web processes., and you should take a look at the [Error Codes](https://devcenter.heroku.com/articles/error-codes) to understand the ...
No web processes running Error - Deploying Django on Heroku
10,142,284
14
2012-04-13T14:01:57Z
10,368,964
7
2012-04-29T01:24:27Z
[ "python", "django", "heroku" ]
I am using the tutorial to deploy Django. [http://devcenter.heroku.com/articles/django] After I do a git push heroku master, there are no web processes. ``` Process State Command ------- ----- ------- ``` On the log it looks like the following. ``` 2012-04-13T03:48:45+00:00 heroku[slugc]: Slug compilation star...
I had the exact same problem. At first, when I ran `heroku scale web=1`, I got the same 'Record not found' error as you. But I waited a few minutes and ran it again, and it worked. If your build fails on the first push for some reason, then heroku doesn't automatically give you a web process, and the 'Record not found...
boost::python: compilation fails because copy constructor is private
10,142,417
8
2012-04-13T14:09:42Z
10,172,037
23
2012-04-16T09:58:26Z
[ "c++", "python" ]
i use boost::python to wrap a C++ class. This class does not allow copy constructors, but the python module always wants to create one. The C++ class looks like this (simplified) ``` class Foo { public: Foo(const char *name); // constructor private: ByteArray m_bytearray; }; ``` The ByteArray class is i...
I found it. i have to specify boost::noncopyable: ``` BOOST_PYTHON_MODULE(Foo) { class_<Foo, boost::noncopyable>("Foo", init<const char *>()) ; } ```
NameError: name 'reload' is not defined
10,142,764
11
2012-04-13T14:30:55Z
10,142,772
30
2012-04-13T14:31:17Z
[ "python", "python-3.x" ]
I'm using python 3.2.2. When I write a simple program, I meet the problem. ``` >>> reload(recommendations) Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> reload(recommendations) NameError: name 'reload' is not defined ``` How should I do it?
You probably wanted [`imp.reload()`](http://docs.python.org/py3k/library/imp.html#imp.reload). ``` from imp import reload ``` In Python 2.x, this was a [builtin](http://docs.python.org/library/functions.html#reload), but in 3.x, it's in the `imp` module. Note that using `reload()` outside of the interpreter is gener...
6th degree curve fitting with numpy/scipy
10,143,174
8
2012-04-13T14:54:40Z
10,143,572
16
2012-04-13T15:16:52Z
[ "python", "numpy", "scipy", "curve-fitting", "linear-regression" ]
I have a very specific requirement for interpolating nonlinear data using a 6th degree polynomial. I've seen numpy/scipy routines (scipy.interpolate.InterpolatedUnivariateSpline) that allow interpolation only up to degree 5. Even if there's no direct function to do this, is there a way to replicate Excel's LINEST line...
You can use [`scipy.optimize.curve_fit`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html) to fit whatever function you want (within reason) to your data. The signature of this function is ``` curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw) ``` and it uses non-linear least squar...
6th degree curve fitting with numpy/scipy
10,143,174
8
2012-04-13T14:54:40Z
10,143,702
7
2012-04-13T15:24:32Z
[ "python", "numpy", "scipy", "curve-fitting", "linear-regression" ]
I have a very specific requirement for interpolating nonlinear data using a 6th degree polynomial. I've seen numpy/scipy routines (scipy.interpolate.InterpolatedUnivariateSpline) that allow interpolation only up to degree 5. Even if there's no direct function to do this, is there a way to replicate Excel's LINEST line...
Use numpys polyfit routine. <http://docs.scipy.org/doc/numpy-1.3.x/reference/generated/numpy.polyfit.html>
Python: two-curve gaussian fitting with non-linear least-squares
10,143,905
10
2012-04-13T15:36:50Z
10,149,641
14
2012-04-13T23:36:22Z
[ "python", "scipy", "gaussian", "least-squares" ]
My knowledge of maths is limited which is why I am probably stuck. I have a spectra to which I am trying to fit two Gaussian peaks. I can fit to the largest peak, but I cannot fit to the smallest peak. I understand that I need to sum the Gaussian function for the two peaks but I do not know where I have gone wrong. An ...
This code worked for me providing that you are only fitting a function that is a combination of two Gaussian distributions. I just made a residuals function that adds two Gaussian functions and then subtracts them from the real data. The parameters (p) that I passed to Numpy's least squares function include: the mean...
Python: two-curve gaussian fitting with non-linear least-squares
10,143,905
10
2012-04-13T15:36:50Z
19,182,915
8
2013-10-04T13:48:09Z
[ "python", "scipy", "gaussian", "least-squares" ]
My knowledge of maths is limited which is why I am probably stuck. I have a spectra to which I am trying to fit two Gaussian peaks. I can fit to the largest peak, but I cannot fit to the smallest peak. I understand that I need to sum the Gaussian function for the two peaks but I do not know where I have gone wrong. An ...
You can use Gaussian mixture models from [scikit-learn](http://scikit-learn.org/stable/modules/mixture.html): ``` from sklearn import mixture import matplotlib.pyplot import matplotlib.mlab import numpy as np clf = mixture.GMM(n_components=2, covariance_type='full') clf.fit(yourdata) m1, m2 = clf.means_ w1, w2 = clf.w...
Centering line-broken axis label in matplotlib
10,144,962
8
2012-04-13T16:47:48Z
10,145,077
13
2012-04-13T16:56:45Z
[ "python", "latex", "matplotlib" ]
Any idea why the ylabel isn't center justified and how I might go about centering it? ![ylabel not centered in plot](http://i.stack.imgur.com/z5b2s.png) Rendering text with LaTeX (`text.usetex: True`) `ylabel('Soil Moisture Sensitivity,\n(0.01 K m$^3$ m$^{-3}$)')` Tried adding \centering, didn't work.
did you try `ylabel('Soil Moisture Sensitivity,\n(0.01 K m$^3$ m$^{-3}$)', multialignment='center')`? As seen here: <http://matplotlib.sourceforge.net/examples/pylab_examples/multiline.html>
Pandas: trouble understanding how merge works
10,145,224
9
2012-04-13T17:08:02Z
10,147,050
11
2012-04-13T19:22:11Z
[ "python", "pandas" ]
I'm doing something wrong with merge and I can't understand what it is. I've done the following to estimate a histogram of a series of integer values: ``` import pandas as pnd import numpy as np series = pnd.Series(np.random.poisson(5, size = 100)) tmp = {"series" : series, "count" : np.ones(len(series))} hist = pn...
From [docs](http://pandas.sourceforge.net/merging.html#database-style-dataframe-joining-merging): > on: Columns (names) to join on. Must be found in both the left and > right DataFrame objects. If not passed and left\_index and right\_index > are False, the intersection of the columns in the DataFrames will be > infer...
Convert string to integer using map()
10,145,347
4
2012-04-13T17:19:08Z
10,145,364
16
2012-04-13T17:20:05Z
[ "python" ]
In the following i am trying to convert the first list to a integer list using the map function how can i achieve this ``` T1 = ['13', '17', '18', '21', '32'] print T1 T3=[map(int, x) for x in T1] print T3 [[1, 3], [1, 7], [1, 8], [2, 1], [3, 2]] Expected is: T3=[13,17,18,21,32] ```
``` >>> T1 = ['13', '17', '18', '21', '32'] >>> T3 = map(int,T1) >>> T3 [13, 17, 18, 21, 32] ``` This does the same thing as: ``` >>> T3 = [int(x) for x in T1] >>> T3 [13, 17, 18, 21, 32] ``` so what you are doing is ``` >>> T3 = [[int(letter) for letter in x] for x in T1] >>> T3 [[1, 3], [1, 7], [1, 8], [2, 1], [3...
Django 1.4 and NoReverseMatch at /admin/ error
10,145,583
5
2012-04-13T17:36:34Z
10,146,055
11
2012-04-13T18:09:07Z
[ "python", "django", "django-admin" ]
I am getting this error when trying to access my admin panel after updating to Django 1.4 - the error is: ``` NoReverseMatch at /admin/ Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found. ``` My best guess is that I'm defining a logout urlpattern which is somehow conflicting with the one th...
``` (r'^admin/(.*)', include(admin.site.urls)), ``` Should be ``` (r'^admin/', include(admin.site.urls)), ``` (.\*) would eat up all anything following admin as the view argument. Also, do you know what is calling `reverse('logout')`? In my local 1.4 install, the admin is namespaced and I have to call `reverse('adm...
Finding the maximum of a function
10,146,924
8
2012-04-13T19:13:10Z
10,146,978
10
2012-04-13T19:17:45Z
[ "python", "numpy" ]
How do I find the maximum of a function in Python? I could try to hack together a derivative function and find the zero of that, but is there a method in `numpy` (or other library) that can do it for me?
You can use [`scipy.optimize.fmin`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin.html) on the negative of your function. ``` def f(x): return -2 * x**2 + 4 * x max_x = scipy.optimize.fmin(lambda x: -f(x), 0) # array([ 1.]) ```
Disable all scons warnings
10,147,079
2
2012-04-13T19:24:22Z
10,147,124
7
2012-04-13T19:27:54Z
[ "python", "build", "scons" ]
This should be ridiculously simple. I found the man page here: <http://www.scons.org/doc/HTML/scons-man.html> Directly from it it says: ``` --warn=all, --warn=no-all // Enables or disables all warnings. ``` So I type: ``` scons --warn=no-all ``` And I still get a million warnings when building. I must be scre...
The warnings you are getting are coming from your compiler, not from Scons itself. Scons itself doesn't have very many warnings. The `--warn=` switch only applies to Scons. What you need to do is pass the appropriate compiler flag to your compiler to turn off the warning you don't want. You can do this using the `CCFL...
How to send an email with Gmail as provider using Python?
10,147,455
142
2012-04-13T19:54:18Z
10,147,497
121
2012-04-13T19:57:54Z
[ "python", "email", "smtp", "gmail" ]
I am trying to send email (Gmail) using python, but I am getting following error. ``` Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by s...
You need to say `EHLO` before just running straight into `STARTTLS`: ``` server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() ``` --- Also you should really create `From:`, `To:` and `Subject:` message headers, separated from the message body by a blank line and use `CRLF` as EOL markers. E.g...
How to send an email with Gmail as provider using Python?
10,147,455
142
2012-04-13T19:54:18Z
10,147,883
9
2012-04-13T20:28:42Z
[ "python", "email", "smtp", "gmail" ]
I am trying to send email (Gmail) using python, but I am getting following error. ``` Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by s...
You can find it here: <http://jayrambhia.com/blog/send-emails-using-python> ``` smtp_host = 'smtp.gmail.com' smtp_port = 587 server = smtplib.SMTP() server.connect(smtp_host,smtp_port) server.ehlo() server.starttls() server.login(user,passw) fromaddr = raw_input('Send mail by the name of: ') tolist = raw_inpu...
How to send an email with Gmail as provider using Python?
10,147,455
142
2012-04-13T19:54:18Z
12,424,439
164
2012-09-14T12:19:26Z
[ "python", "email", "smtp", "gmail" ]
I am trying to send email (Gmail) using python, but I am getting following error. ``` Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by s...
``` def send_email(user, pwd, recipient, subject, body): import smtplib gmail_user = user gmail_pwd = pwd FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: %s\n\n%s ...
How to send an email with Gmail as provider using Python?
10,147,455
142
2012-04-13T19:54:18Z
27,515,833
68
2014-12-16T23:27:25Z
[ "python", "email", "smtp", "gmail" ]
I am trying to send email (Gmail) using python, but I am getting following error. ``` Traceback (most recent call last): File "emailSend.py", line 14, in <module> server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by s...
I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this: <https://support.google.com/accounts/answer/6010255> In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort ...
Numpy how to iterate over columns of array?
10,148,818
26
2012-04-13T21:55:04Z
10,148,855
59
2012-04-13T21:59:04Z
[ "python", "loops", "numpy" ]
Suppose I have and m x n array. I want to pass each column of this array to a function to perform some operation on the entire column. How do I iterate over the columns of the array? For example, I have a 4 x 3 array like ``` 1 99 2 2 14 5 3 12 7 4 43 1 for column in array: some_function(column) ``` where col...
Just iterate over the transposed of your array: ``` for column in array.T: some_function(column) ```
Numpy how to iterate over columns of array?
10,148,818
26
2012-04-13T21:55:04Z
10,148,862
7
2012-04-13T21:59:45Z
[ "python", "loops", "numpy" ]
Suppose I have and m x n array. I want to pass each column of this array to a function to perform some operation on the entire column. How do I iterate over the columns of the array? For example, I have a 4 x 3 array like ``` 1 99 2 2 14 5 3 12 7 4 43 1 for column in array: some_function(column) ``` where col...
This should give you a start ``` >>> for col in range(arr.shape[1]): some_function(arr[:,col]) [1 2 3 4] [99 14 12 43] [2 5 7 1] ```
Python itertools.product with variable number of arguements
10,148,834
3
2012-04-13T21:56:11Z
10,148,844
12
2012-04-13T21:57:41Z
[ "python", "list", "itertools" ]
I am trying to write a module to combine a variable number of lists using itertools.product. The closest I can get is: ``` import itertools lists = [["item1","item2"],["A","b","C"], ["etc..."]] searchterms = list(itertools.product(lists)) print searchterms ``` This doesn't work, because lists is a single list, so it...
You need to use `*` to separate the single list into its constituent lists: ``` searchterms = list(itertools.product(*lists)) ``` See the Python Tutorial section on [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
Extract a part of the filepath (a directory) in Python
10,149,263
33
2012-04-13T22:48:00Z
10,149,358
51
2012-04-13T23:01:11Z
[ "python", "directory", "filepath" ]
I need to extract the name of the parent directory of a certain path. This is what it looks like: `c:\ stuff \ directory_i_need \ subdir \ file`. I am modifying the content of the "file" with something that uses the `directory_i_need` name in it (not the path). I have created a function that will give me a list of all ...
``` import os ## first file in current dir (with full path) file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]) file os.path.dirname(file) ## directory of file os.path.dirname(os.path.dirname(file)) ## directory of directory of file ... ``` And you can continue doing this as many times as necessary... **Edit...