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
Applying map for partial argument
10,314,859
8
2012-04-25T11:41:52Z
10,314,935
12
2012-04-25T11:46:35Z
[ "python", "functional-programming" ]
Given the following function f with two arguments, what is the standard way to apply map to only x? ``` def f (x,y): print x,y ``` More specifically, I would like to perform the following operation with map in one line. ``` list=[1,2,3] fixed=10 for s in list: f(s,fixed) ``` One way to do so is: ``` import...
First of all, there is no need to use lambda AND partial - they are alternatives: ``` map(lambda x:f(x,fixed),srclist) ``` Secondly, you could just bind the second argument with `partial`, as long as you know the argument's name: ``` map(functools.partial(f,y=fixed),srclist) ``` Alternatively, use a list comprehens...
GAE - Deployment Error: "AttributeError: can't set attribute"
10,315,069
11
2012-04-25T11:55:42Z
10,343,429
13
2012-04-27T01:01:53Z
[ "python", "google-app-engine", "deployment" ]
When I try to deploy my app I get the following error: ``` Starting update of app: flyingbat123, version: 0-1 Getting current resource limits. Password for avigmati: Traceback (most recent call last): File "C:\Program Files (x86)\Google\google_appengine\appcfg.py", line 125, in run_file(__file__, globals()) F...
I had the same problem. I'm using 2 factor authentication for my google account, so I previously had to enter a application specific password to deploy apps to GAE. If I entered my normal google password I got the `AttributeError: can't set attribute` error. However when I created an [application specific password](htt...
Postgresql DROP TABLE doesn't work
10,317,114
13
2012-04-25T13:50:04Z
10,317,371
22
2012-04-25T14:04:33Z
[ "python", "database", "django", "postgresql" ]
I'm trying to drop a few tables with the `"DROP TABLE"` command but for a unknown reason, the program just "sits" and doesn't delete the table that I want it to in the database. I have 3 tables in the database: Product, Bill and Bill\_Products which is used for referencing products in bills. I managed to delete/drop...
What is the output of ``` SELECT * FROM pg_locks l JOIN pg_class t ON l.relation = t.oid AND t.relkind = 'r' WHERE t.relname = 'Bill'; ``` It might be that there're other sessions using your table in parallel and you cannot obtain [Access Exclusive](http://www.postgresql.org/docs/7.4/static/explicit-locking.html...
What is the pythonic way to implement sequential try-excepts?
10,317,790
4
2012-04-25T14:27:24Z
10,317,937
10
2012-04-25T14:36:03Z
[ "python", "nested", "try-catch", "factory-pattern", "sequential" ]
I have to parse some numbers from file names that have no common logic. I want to use the python way of "try and thou shall be forgiven", or try-except structure. Now I have to add more than two cases. What is the correct way of doing this? I am now thinking either nested try's or try-except-pass, try-except-pass,... W...
You can extract the common structure and make a list of possible parameters: ``` tries = [ ('S0001', '.tif'), ('S0001', '.tiff'), ('_0_', '.tif'), ] for sep, subst in tries: num = imBN.split(sep)[-1].replace(subst, '') try: imNo = int(num) break except ValueError: pass ...
How do I call the Python's list while debugging?
10,319,147
22
2012-04-25T15:49:21Z
10,319,201
25
2012-04-25T15:52:38Z
[ "python", "debugging" ]
I have the following python code: ``` values = set([1, 2, 3, 4, 5]) import pdb pdb.set_trace() ``` I run the script and I am in the debugging shell: ``` (pdb) list(values) *** Error in argument: '(values)' (Pdb) ``` How can I call `list(values)` in the debugger without invoking the debugger's own `list` command?
Just `print` it: ``` (Pdb) print list(values) ```
How do I call the Python's list while debugging?
10,319,147
22
2012-04-25T15:49:21Z
12,084,184
11
2012-08-23T03:05:31Z
[ "python", "debugging" ]
I have the following python code: ``` values = set([1, 2, 3, 4, 5]) import pdb pdb.set_trace() ``` I run the script and I am in the debugging shell: ``` (pdb) list(values) *** Error in argument: '(values)' (Pdb) ``` How can I call `list(values)` in the debugger without invoking the debugger's own `list` command?
Use the exclamation mark ! to escape debugger commands: ``` (Pdb) values = set([1, 2, 3, 4, 5]) (Pdb) list(values) *** Error in argument: '(values)' (Pdb) !list(values) [1, 2, 3, 4, 5] ```
Match exactly N repetitions of the same character
10,319,696
8
2012-04-25T16:19:22Z
10,320,338
11
2012-04-25T16:57:59Z
[ "java", ".net", "python", "regex", "perl" ]
How do I write an expression that matches exactly N repetitions of the same character (or, ideally, the same group)? Basically, what `(.)\1{N-1}` does, but with one important limitation: the expression should fail if the subject is repeated *more* than N times. For example, given `N=4` and the string `xxaaaayyybbbbbzzc...
Use negative lookahead *and* negative lookbehind. This would be the regex: `(.)(?<!\1.)\1{N-1}(?!\1)` except that Python's re module is broken (see [this link](http://stackoverflow.com/questions/10279055/impossible-lookbehind-with-a-backreference)). English translation: "Match any character. Make sure that after you ...
Is there a universal way of iterating over a set or values of a dict in Python 2.7?
10,319,850
2
2012-04-25T16:28:19Z
10,319,923
9
2012-04-25T16:32:30Z
[ "python" ]
I expect the collection to be either a set or a dict. Problem is that: ``` for element in collection: print element ``` will give me the elements if collection is a set, but indexes if collection is a dict. What I want is a one-liner that will iterate over dict values. Is that possible?
The most foolproof way to test for a mapping is to use `isinstance` on [`collections.Mapping`](http://docs.python.org/library/collections.html#collections.Mapping): ``` import collections for element in (collection.values() if isinstance(collection, collections.Mapping) else collection): ``` If you ...
'Request' object has no attribute 'get' Python error
10,320,307
3
2012-04-25T16:55:52Z
10,320,602
8
2012-04-25T17:17:36Z
[ "python", "query-string", "flask" ]
I am trying to get a url parameter in Python. I am using this code: ``` from flask import request, url_for, redirect # ... controller = request.get('controller') ``` but I am getting this error: ``` 'Request' object has no attribute 'get' ``` Any ideas? Thanks
You want to use [`request.args`](http://flask.pocoo.org/docs/api/?highlight=args#flask.Request) for your GET parameters in Flask. Here is a quote with an example from the Accessing Request Data section of the [Quickstart](http://flask.pocoo.org/docs/quickstart/#accessing-request-data) document. --- To access paramete...
Numpy Array: Efficiently find matching indices
10,320,751
3
2012-04-25T17:29:28Z
10,322,904
8
2012-04-25T20:02:11Z
[ "python", "numpy", "scipy" ]
I have two lists, one of which is massive (millions of elements), the other several thousand. I want to do the following ``` bigArray=[0,1,0,2,3,2,,.....] smallArray=[0,1,2,3,4] for i in len(smallArray): pts=np.where(bigArray==smallArray[i]) #Do stuff with pts... ``` The above works, but is slow. Is there any w...
In your case you may benefit from presorting your big array. Here is the example demonstrating how you can reduce the time from ~ 45 seconds to 2 seconds (on my laptop)(for one particular set of lengths of the arrays 5e6 vs 1e3). Obviously the solution won't be optimal if the array sizes will be wastly different. E.g. ...
Django with psycopg2 plugin
10,321,568
6
2012-04-25T18:25:41Z
17,577,073
13
2013-07-10T17:26:10Z
[ "python", "django" ]
Ive been reading the Django Book and its great so far, unless something doesn't work properly. I have been trying for two days to install the psycogp2 plugin with no luck. i navigate to the unzipped directory and run setup.py install and it returns "You must have postgresql dev for building a serverside extension or l...
I'm using pip as a part of my deployment process, so using apt-get wasn't a viable option for me. I was able to run ``` sudo apt-get install libpq-dev ``` And remove python-psycopg2 from apt-get. Then ``` pip install psycopg2 ``` worked fine for me.
Integer to bitfield as a list
10,321,978
4
2012-04-25T18:52:15Z
10,322,018
15
2012-04-25T18:54:57Z
[ "python", "list", "bit-fields" ]
I've created a method to convert an `int` to a bitfield (in a list) and it works, but I'm sure there is more elegant solution- I've just been staring at it for to long. I'm curious, how would you convert a `int` to a bitfield represented in a `list`? ``` def get(self): results = [] results.append(1 if (self....
How about this: ``` def bitfield(n): return [int(digit) for digit in bin(n)[2:]] # [2:] to chop off the "0b" part ``` This gives you ``` >>> bitfield(123) [1, 1, 1, 1, 0, 1, 1] >>> bitfield(255) [1, 1, 1, 1, 1, 1, 1, 1] >>> bitfield(1234567) [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1] ``` Th...
Integer to bitfield as a list
10,321,978
4
2012-04-25T18:52:15Z
10,322,122
9
2012-04-25T19:02:52Z
[ "python", "list", "bit-fields" ]
I've created a method to convert an `int` to a bitfield (in a list) and it works, but I'm sure there is more elegant solution- I've just been staring at it for to long. I'm curious, how would you convert a `int` to a bitfield represented in a `list`? ``` def get(self): results = [] results.append(1 if (self....
This doesn't use `bin`: ``` b = [n >> i & 1 for i in range(7,-1,-1)] ``` and this is how to handle any integer this way: ``` b = [n >> i & 1 for i in range(n.bit_length() - 1,-1,-1)] ``` See [`bit_length`](https://docs.python.org/3/library/stdtypes.html#int.bit_length).
How to select Python version in PyCharm?
10,322,424
44
2012-04-25T19:27:22Z
10,322,460
54
2012-04-25T19:29:46Z
[ "python", "configuration", "pycharm" ]
I have PyCharm 1.5.4 and have used the "Open Directory" option to open the contents of a folder in the IDE. I have Python version 3.2 selected (it shows up under the "External Libraries" node). How can I select another version of Python (that I already have installed on my machine) so that PyCharm uses that version i...
File -> Settings Preferences->Project Interpreter->Python Interpreters If it's not listed add it. ![enter image description here](http://i.stack.imgur.com/0lNe3.png)
How to select Python version in PyCharm?
10,322,424
44
2012-04-25T19:27:22Z
23,524,553
7
2014-05-07T17:39:53Z
[ "python", "configuration", "pycharm" ]
I have PyCharm 1.5.4 and have used the "Open Directory" option to open the contents of a folder in the IDE. I have Python version 3.2 selected (it shows up under the "External Libraries" node). How can I select another version of Python (that I already have installed on my machine) so that PyCharm uses that version i...
I think you are saying that you have python2 and python3 installed and have added a reference to each version under Pycharm > Settings > Project Interpreter What I think you are asking is how do you have some projects run with Python 2 and some projects running with Python 3. If so, you can look under Run > Edit Conf...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 17710: ordinal not in range(128)
10,322,432
7
2012-04-25T19:27:56Z
10,322,479
15
2012-04-25T19:31:11Z
[ "python", "unicode", "character-encoding", "web-scraping" ]
I'm trying to print a string from an [archived web crawl](http://commoncrawl.org/), but when I do I get this error: ``` print page['html'] UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 17710: ordinal not in range(128) ``` When I try print `unicode(page['html'])` I get: ``` print unicod...
You need to *encode* the unicode you saved to display it, not *decode* it -- unicode is the unencoded form. You should always specify an encoding, so that your code will be portable. The "usual" pick is `utf-8`: ``` print page['html'].encode('utf-8') ``` If you don't specify an encoding, whether or not it works will ...
Dealing with duplicate primary keys on insert in SQLAlchemy (declarative style)
10,322,514
20
2012-04-25T19:34:02Z
11,620,706
12
2012-07-23T21:22:35Z
[ "python", "mysql", "sqlalchemy", "celery" ]
My application is using a scoped session and the declarative style of SQLALchemy. It's a web-app and a lot of the DB insertions are executed by `Celery`, a task scheduler. Typically, when deciding to insert an object, my code might do something along the following lines: ``` from schema import Session from schema.mod...
If you use `session.merge(bike)` instead of `session.add(bike)`, then you will not generate primary key errors. The `bike` will be retrieved and updated or created as needed.
django-storages with Amazon S3 - prevent overwriting
10,323,241
9
2012-04-25T20:28:39Z
10,323,773
23
2012-04-25T21:04:13Z
[ "python", "django", "file-upload", "amazon-s3" ]
I noticed that django-storages (or perhaps it's Django's storage API itself) overwrites files with the same name. This is a problem for me as my site allows user uploads, so I need to ensure that files are never overwritten. Ideally I'd like to be able to pass a file name to the storage backend from the view level, bu...
If you are using the s3boto backend not the old s3 backend in django-storages then you can change this using the `AWS_S3_FILE_OVERWRITE` setting: <https://bitbucket.org/david/django-storages/src/83fa2f0ba20c/storages/backends/s3boto.py#cl-43>
'cannot filter palette images' error when doing a ImageEnhance.Sharpness()
10,323,692
5
2012-04-25T20:59:10Z
10,324,108
7
2012-04-25T21:31:05Z
[ "python", "image", "image-processing", "python-imaging-library" ]
I have a GIF image file. I opened it using [`PIL.Image`](http://effbot.org/imagingbook/image.htm) and did a couple of size transforms on it. Then I tried to use [`ImageSharpness.Enhance()`](http://effbot.org/imagingbook/imageenhance.htm#tag-ImageEnhance.Sharpness) on it... ``` sharpener = PIL.ImageEnhance.Sharpness(im...
``` sharpener = PIL.ImageEnhance.Sharpness (img.convert('RGB')) ``` It's quite common for algorithms to be unable to work with a palette based image. The `convert` in the above changes it to have a full RGB value at each pixel location.
sphinx-build fail - autodoc can't import/find module
10,324,393
38
2012-04-25T21:54:39Z
10,352,056
40
2012-04-27T13:59:15Z
[ "python", "documentation", "python-sphinx" ]
I'm trying to get started with Sphinx and seem to have relentless problems. Command: `docs/sphinx-quickstart` I answer all the questions and everything works fine. Command: `docs/ls` Everything looks normal. Result: `build Makefile source` Command: `sphinx-build -d build/doctrees source build/html` It seems to wo...
Autodoc can't find your modules, because they are not in `sys.path`. You have to include the path to your modules in in the `sys.path` in your `conf.py`. Look at the top of your `conf.py` (just after the import of `sys`), there is a `sys.path.insert()` statement, which you can adapt. By the way: you can use the `Make...
sphinx-build fail - autodoc can't import/find module
10,324,393
38
2012-04-25T21:54:39Z
12,246,335
18
2012-09-03T10:47:36Z
[ "python", "documentation", "python-sphinx" ]
I'm trying to get started with Sphinx and seem to have relentless problems. Command: `docs/sphinx-quickstart` I answer all the questions and everything works fine. Command: `docs/ls` Everything looks normal. Result: `build Makefile source` Command: `sphinx-build -d build/doctrees source build/html` It seems to wo...
in `conf.py` just add the path to your project folder. ``` sys.path.append('/home/workspace/myproj/myproj') ```
python remove C function body
10,324,922
2
2012-04-25T22:51:08Z
10,325,368
8
2012-04-25T23:44:58Z
[ "python", "c", "regex", "match", "substitution" ]
im looking for way how to remove whole bodies from functions in some C source file. For example I have file with this content: ``` 1. int func1 (int para) { 2. return para; 3. } 4. 5. int func2 (int para) { 6. if (1) { 7. return para; 8. } 9. return para; 10. } ``` I have tried these regex: ``` ...
I think you're trying to re-invent a wheel that has already been implemented many times before. If all you want is to extract the signature of each function in a C file, there are much easier ways to do it. The ctags utility will take care of this for you: ``` ~/test$ ctags -x --c-types=f ./test.c func1 fu...
Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?
10,325,494
10
2012-04-26T00:02:11Z
10,325,535
7
2012-04-26T00:07:23Z
[ "python", "iterator" ]
I'd like to cycle through a list repeatedly (N times) via an iterator, so as not to actually store N copies of the list in memory. Is there a built-in or elegant way to do this without writing my own generator? Ideally, itertools.cycle(my\_list) would have a second argument to limit how many times it cycles... alas, n...
``` itertools.chain.from_iterable(iter(L) for x in range(N)) ```
Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?
10,325,494
10
2012-04-26T00:02:11Z
10,325,545
14
2012-04-26T00:08:35Z
[ "python", "iterator" ]
I'd like to cycle through a list repeatedly (N times) via an iterator, so as not to actually store N copies of the list in memory. Is there a built-in or elegant way to do this without writing my own generator? Ideally, itertools.cycle(my\_list) would have a second argument to limit how many times it cycles... alas, n...
``` import itertools itertools.chain.from_iterable(itertools.repeat([1, 2, 3], 5)) ``` Itertools is a wonderful library. :)
How can you parse a document stored in the MARC21 format with Python
10,325,895
5
2012-04-26T01:00:36Z
10,392,577
10
2012-05-01T01:41:23Z
[ "python", "parsing", "marc" ]
Yesterday [harvard released](http://openmetadata.lib.harvard.edu/) open access to all its library metadata (some 12 million records) I was looking to parse the data and play with it as the goal of the release was to "support innovation" Download the 12GB tarball, unpacked it to find 13 .mrc files about 800MB each [M...
[pymarc](http://github.com/edsu/pymarc) is the best option to parse MARC21 records using Python (full disclosure: I'm one of its maintainers). If you're unfamiliar with working with MARC21, it's worth reading through some of the specification you linked to on the Library of Congress website. I'd also read through the [...
Singular matrix issue with Numpy
10,326,015
2
2012-04-26T01:17:40Z
10,326,041
15
2012-04-26T01:21:40Z
[ "python", "matrix", "numpy" ]
I am trying to multiply a vector(3 by 1) by its transpose(1 by 3). I get a (3 by 3) array but I cannot get its inverse. Any idea why? ``` import numpy as np c=array([1, 8, 50]) np.transpose(c[np.newaxis]) * c array([[ 1, 8, 50], [ 8, 64, 400], [ 50, 400, 2500]]) np.linalg.inv(np.transpose(c[np.new...
By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix. Each row is a linear combination of the first row. Notice that the second row is just 8x the first row. Likewise, the third row is 50x the first row. There's only one independent row in your matrix.
Singular matrix issue with Numpy
10,326,015
2
2012-04-26T01:17:40Z
10,326,044
15
2012-04-26T01:22:05Z
[ "python", "matrix", "numpy" ]
I am trying to multiply a vector(3 by 1) by its transpose(1 by 3). I get a (3 by 3) array but I cannot get its inverse. Any idea why? ``` import numpy as np c=array([1, 8, 50]) np.transpose(c[np.newaxis]) * c array([[ 1, 8, 50], [ 8, 64, 400], [ 50, 400, 2500]]) np.linalg.inv(np.transpose(c[np.new...
The matrix you pasted ``` [[ 1, 8, 50], [ 8, 64, 400], [ 50, 400, 2500]] ``` Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist) <http://en.wikipedia.org/wiki/Invertible_matrix>
Encoding a numeric string into a shortened alphanumeric string, and back again
10,326,118
6
2012-04-26T01:32:49Z
10,326,158
9
2012-04-26T01:38:55Z
[ "python", "string", "encode", "numeric" ]
Quick question. I'm trying to find or write an encoder in Python to shorten a string of numbers by using upper and lower case letters. The numeric strings look something like this: ``` 20120425161608678259146181504021022591461815040210220120425161608667 ``` The length is always the same. My initial thought was to wr...
This is a pretty good compression: ``` import base64 def num_to_alpha(num): num = hex(num)[2:].rstrip("L") if len(num) % 2: num = "0" + num return base64.b64encode(num.decode('hex')) ``` It first turns the integer into a bytestring and then base64 encodes it. Here's the decoder: ``` def alpha_...
Setting aspect ratio of 3D plot
10,326,371
18
2012-04-26T02:18:31Z
10,328,142
10
2012-04-26T06:15:51Z
[ "python", "matplotlib", "mplot3d" ]
I am trying to plot a 3D image of the seafloor from the data of a sonar run over a 500m by 40m portion of the seafloor. I am using matplotlib/mplot3d with Axes3D and I want to be able to change the aspect ratio of the axes so that the x & y axis are to scale. An example script with generated data rather than the real d...
Add following code before savefig: ``` ax.auto_scale_xyz([0, 500], [0, 500], [0, 0.15]) ``` ![enter image description here](http://i.stack.imgur.com/eR26l.png) If you want no square axis: edit the `get_proj` function inside site-packages\mpl\_toolkits\mplot3d\axes3d.py: ``` xmin, xmax = self.get_xlim3d() / self.pb...
has no attribute '_meta' error when creating a ModelAdmin object
10,326,535
3
2012-04-26T02:46:13Z
10,326,642
10
2012-04-26T03:01:47Z
[ "python", "django" ]
I am new to Django and I was trying to customize the Admin interface for my model but I get an error when trying to add a ModelAdmin object. My code and error is included below. If i take out the BlogAdmin object from the register statement, I don't get any errors and the site loads fine. Thanks for your help! ``` cl...
When you write: ``` admin.site.register([Blog, BlogAdmin]) ``` you register in admin two models: `Blog` and `BlogAdmin`, you must register `Model` and `ModelAdmin` for it, like this: ``` admin.site.register(Blog, BlogAdmin) ```
Sort cProfile output by percall when profiling a Python script
10,326,936
27
2012-04-26T03:45:33Z
13,924,641
33
2012-12-18T00:40:00Z
[ "python", "profiling", "cprofile" ]
I'm using `python -m cProfile -s calls myscript.py` `python -m cProfile -s percall myscript.py` does not work. The Python documentation says "Look in the Stats documentation for valid sort values.": <http://docs.python.org/library/profile.html#module-cProfile>, which I cannot find.
-s only uses [the keys found under sort\_stats.](http://docs.python.org/2/library/profile.html#pstats.Stats.sort_stats) ``` 'calls' (call count) 'cumulative' (cumulative time) 'cumtime' (cumulative time) 'file' (file name) 'filename' (file name) 'module' (file name) 'ncalls' (call count) 'pcalls' (primitive call count...
Replace string values in lists
10,328,289
2
2012-04-26T06:29:58Z
10,328,344
7
2012-04-26T06:34:32Z
[ "python", "string", "list" ]
I have a list : ``` s = ["sam1", "s'am2", "29"] ``` I want to replace `'` from the whole list. I need output as ``` s = ["sam1", "sam2", "30"] ``` currently I am iterating through the list. Is there any better way to achieve it?
You could try this: ``` s = [i.replace("'", "") for i in s] ``` but as pointed out this is still iterating through the list. I can't think of any solution that wouldn't include some sort of iteration (explicit or *implicit*) of the list at some point. If you have a lot of data you want to do this to and are concer...
Python 3.x: Using string.maketrans() in order to create a unicode-character transformation
10,329,290
7
2012-04-26T07:52:36Z
10,331,248
10
2012-04-26T10:02:39Z
[ "python", "string", "unicode", "python-3.x" ]
I would like to write the following code: ``` import string frm = b'acdefhnoprstuw' to = 'אקדיפהנופרסתאו' trans_table = string.maketrans(frm, to) hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) ``` The above code doesn't work because the `to` parameter to `string.maketrans(frm, to...
You need to use str.maketrans(), which takes two str as arguments. ``` >>> frm = 'acdefhnoprstuw' >>> to = 'אקדיפהנופרסתאו' >>> trans_table = str.maketrans(frm, to) >>> hebrew_phrase = 'fear cuts deeper than swords'.translate(trans_table) >>> hebrew_phrase 'פיאר קאתס דייפיר תהאנ סוו×...
How to backtrace a function in python 2.7?
10,330,119
3
2012-04-26T08:51:59Z
10,330,184
8
2012-04-26T08:55:53Z
[ "python", "debugging", "python-2.7" ]
I have a big python script, with multiple files, and I need to know where a method was called. Is there a backtrace function in python like debug\_backtrace in php?
See the [traceback](http://docs.python.org/library/traceback.html#module-traceback) module. ``` import traceback def foo(): bar() def bar(): baz() def baz(): traceback.print_stack() # or trace = traceback.extract_stack() foo() ```
Python Logging setlevel
10,332,748
12
2012-04-26T11:45:57Z
15,368,084
27
2013-03-12T17:31:04Z
[ "python", "logging" ]
Does anyone know if there is a way to use a variable in the setlevel() function of Python's Logging module? At the moment I am using this: ``` Log = logging.getLogger('myLogger') Log.setLevel(logging.DEBUG) ``` But I'd like to have this: ``` Log = logging.getLogger('myLogger') levels = {'CRITICAL' : logging.critica...
You should also be able to do this: ``` Log = logging.getLogger('myLogger') level = logging.getLevelName('INFO') Log.setLevel(level) ``` The `logging.getLevelName(lvl)` function works both ways. I use it, it works (you should check your python implementation though). This saves you the trouble to maintain your own d...
tell pip to install the dependencies of packages listed in a requirement file
10,333,814
18
2012-04-26T12:52:45Z
10,335,237
11
2012-04-26T14:11:41Z
[ "python", "pip", "requirements" ]
Developing a Django web app, I have a list of packages I need to install in a virtualenv. Say: ``` Django==1.3.1 --extra-index-url=http://dist.pinaxproject.com/dev/ Pinax==0.9b1.dev10 git+git://github.com/pinax/pinax-theme-bootstrap.git@cff4f5bbe9f87f0c67ee9ada9aa8ae82978f9890 # and other packages ``` Initially I ins...
Given your comment to the question (where you say that executing the install for a single package works as expected), I would suggest looping over your requirement file. In bash: ``` #!/bin/sh while read p; do pip install $p done < requirements.pip ``` HTH!
tell pip to install the dependencies of packages listed in a requirement file
10,333,814
18
2012-04-26T12:52:45Z
14,182,161
29
2013-01-06T12:35:37Z
[ "python", "pip", "requirements" ]
Developing a Django web app, I have a list of packages I need to install in a virtualenv. Say: ``` Django==1.3.1 --extra-index-url=http://dist.pinaxproject.com/dev/ Pinax==0.9b1.dev10 git+git://github.com/pinax/pinax-theme-bootstrap.git@cff4f5bbe9f87f0c67ee9ada9aa8ae82978f9890 # and other packages ``` Initially I ins...
simplifily, use: ``` pip install -r requirement.txt ``` it can install all listed in requirement file.
Can not pip install PIL in a virtualenv in Windows because of Warning and ValueError
10,334,355
4
2012-04-26T13:23:13Z
12,802,133
7
2012-10-09T14:19:38Z
[ "python", "windows", "python-imaging-library", "virtualenv", "pip" ]
I am trying to install `PIL` in a virtualenv but have failed. I created a brand new virtualenv and did `pip install PIL` and got the following ``` C:\Users\s3z\Desktop\My Dropbox\pythons\ham>Scripts\activate (ham) C:\Users\s3z\Desktop\My Dropbox\pythons\ham>pip install PIL Downloading/unpacking PIL Downloading PIL-1...
Installing PIL on windows with PIP gives me issues, but using easy\_install works fine. "c:\VirtualENV \ easy\_install PIL"
Update DynamoDB Atomic Counter with Python / Boto
10,334,533
9
2012-04-26T13:32:28Z
10,349,746
12
2012-04-27T11:25:41Z
[ "python", "counter", "atomic", "boto", "amazon-dynamodb" ]
I am trying to update an atomic count counter with Python Boto 2.3.0, but can find no documentation for the operation. It seems there is no direct interface, so I tried to go to "raw" updates using the layer1 interface, but I was unable to complete even a simple update. I tried the following variations but all with n...
Sorry, I misunderstood what you were looking for. You can accomplish this via layer2 although there is a small bug that needs to be addressed. Here's some Layer2 code: ``` >>> import boto >>> c = boto.connect_dynamodb() >>> t = c.get_table('counter') >>> item = t.get_item('counter') >>> item {u'id': 'counter', u'n': 1...
numpy replace negative values in array
10,335,090
36
2012-04-26T14:03:09Z
10,335,137
46
2012-04-26T14:05:31Z
[ "python", "numpy" ]
Can anyone advise a simple way of replacing all negative values in an array with 0? I'm having a complete block on how to do it using a numpy array e.g. ``` a = array([1, 2, 3, -4, 5]) ``` i need to return ``` [1, 2, 3, 0, 5] ``` `a < 0` gives: ``` [False, False, False, True, False] ``` This is where I'm stuck ...
Try `numpy.clip`: ``` >>> import numpy >>> a = numpy.arange(-10, 10) >>> a array([-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> a.clip(0, 10) array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` You can clip only the bottom half with...
numpy replace negative values in array
10,335,090
36
2012-04-26T14:03:09Z
10,335,159
64
2012-04-26T14:06:45Z
[ "python", "numpy" ]
Can anyone advise a simple way of replacing all negative values in an array with 0? I'm having a complete block on how to do it using a numpy array e.g. ``` a = array([1, 2, 3, -4, 5]) ``` i need to return ``` [1, 2, 3, 0, 5] ``` `a < 0` gives: ``` [False, False, False, True, False] ``` This is where I'm stuck ...
You are halfway there. Try: ``` In [4]: a[a < 0] = 0 In [5]: a Out[5]: array([1, 2, 3, 0, 5]) ```
Split a list of lists
10,335,537
2
2012-04-26T14:29:33Z
10,335,596
7
2012-04-26T14:33:15Z
[ "python" ]
How can I split a list of lists per lines? ``` list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] ``` into: ``` a b c d e f g h i ```
``` In [11]: lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] In [12]: print('\n'.join(' '.join(l) for l in lst)) a b c d e f g h i ```
scatter plot in matplotlib
10,336,614
11
2012-04-26T15:30:18Z
10,336,800
48
2012-04-26T15:42:22Z
[ "python", "matplotlib", "scatter-plot" ]
This is my first matplotlib program, so sorry for my ignorance. I've two arrays of string. say, `A = ['test1','test2']` and `B = ['test3','test4']`. If any correlation exists between `A` and `B` element, their corr value will be set to `1`. ``` test1 | test2 test3 | 1 | 0 test4 | 0 | 1 ``` Now, ...
Maybe something like this: ``` import matplotlib.pyplot import pylab x = [1,2,3,4] y = [3,4,8,6] matplotlib.pyplot.scatter(x,y) matplotlib.pyplot.show() ``` EDIT: Let me see if I understand you correctly now: You have: ``` test1 | test2 | test3 test3 | 1 | 0 | 1 test4 | 0 | 1 | 0 test5 ...
Matplotlib - grids and plotting color coded y values/data ranges
10,336,774
5
2012-04-26T15:40:52Z
10,343,664
8
2012-04-27T01:34:39Z
[ "python", "matplotlib" ]
New matplotlib user here. I'm trying to plot a color coded line of data, or better, a color coded range of data. Color coding intervals along the y-axis. A crude demonstration script follows: ``` import matplotlib.pyplot as plt # dummy test data datapoints = 25 maxtemps = [ 25, 24, 24, 25, 26, 27, 22, 21, 22, 19, 17,...
To answer your second question: you can set all the `fill_between` zorder to 0.1, 0.2, 0.3 ... grid lines belong to xaxis and yaxis, and the zorder of xaxis and yaxis is 2.5. So any zorder less than 2.5 will be shown under the grid lines. I write some code similar with yours, but use for loop and `numpy.interp`, `nu...
A fast way to find the largest N elements in an numpy array
10,337,533
25
2012-04-26T16:29:59Z
10,337,643
25
2012-04-26T16:35:58Z
[ "python", "sorting", "numpy" ]
I know I can do it like the following: ``` import numpy as np N=10 a=np.arange(1,100,1) np.argsort()[-N:] ``` However, it is very slow since it did a full sort. I wonder whether numpy provide some methods the do it fast.
The [`bottleneck`](http://pypi.python.org/pypi/Bottleneck) module has a fast partial sort method that works directly with Numpy arrays: [`bottleneck.partsort()`](http://berkeleyanalytics.com/bottleneck/reference.html#bottleneck.partsort). Note that `bottleneck.partsort()` returns the actual values sorted, if you want ...
A fast way to find the largest N elements in an numpy array
10,337,533
25
2012-04-26T16:29:59Z
10,463,055
8
2012-05-05T15:02:18Z
[ "python", "sorting", "numpy" ]
I know I can do it like the following: ``` import numpy as np N=10 a=np.arange(1,100,1) np.argsort()[-N:] ``` However, it is very slow since it did a full sort. I wonder whether numpy provide some methods the do it fast.
Each negative sign in the proposed bottleneck solution ``` -bottleneck.partsort(-a, 10)[:10] ``` makes a copy of the data. We can remove the copies by doing ``` bottleneck.partsort(a, a.size-10)[-10:] ``` Also the proposed numpy solution ``` a.argsort()[-10:] ``` returns indices not values. The fix is to use the ...
A fast way to find the largest N elements in an numpy array
10,337,533
25
2012-04-26T16:29:59Z
20,177,786
29
2013-11-24T17:50:20Z
[ "python", "sorting", "numpy" ]
I know I can do it like the following: ``` import numpy as np N=10 a=np.arange(1,100,1) np.argsort()[-N:] ``` However, it is very slow since it did a full sort. I wonder whether numpy provide some methods the do it fast.
`numpy 1.8` implements `partition` and `argpartition` that perform partial sort ( in O(n) time as opposed to full sort that is O(n) \* log(n)). ``` import numpy as np test = np.array([9,1,3,4,8,7,2,5,6,0]) temp = np.argpartition(-test, 4) result_args = temp[:4] temp = np.partition(-test, 4) result = -temp[:4] ``` ...
Computing total_seconds in Python for datetime module with true division enabled
10,339,593
7
2012-04-26T18:51:40Z
10,339,647
9
2012-04-26T18:56:26Z
[ "python", "datetime" ]
I'm trying to do some computations on date, I have a `timedelta` object, and I want to get the number of seconds. It seems like `dt.total_seconds()` does exactly what I need but unfortunately it was introduced in Python 2.7 and I'm stuck with an older version. If I read [the official documentation](http://docs.python....
With true division, `1 / 2` would result in `0.5`. The default behavior in Python 2.x is to use integer division, where `1 / 2` would result in `0`. Here is the explanation from the [docs](http://docs.python.org/reference/expressions.html#binary-arithmetic-operations): > Plain or long integer division yields an intege...
getdefaultlocale returning None when running sync.db on Django project in PyCharm
10,339,963
5
2012-04-26T19:20:36Z
10,341,282
7
2012-04-26T20:53:30Z
[ "python", "django", "pycharm" ]
OSX 10.7.3, PyCharm version 2.5 build PY 117.200 I'll run through how I get the error: 1. I start a new project 2. Create a new VirtualEnv and select Python 2.7 as my base interpreter (leave inherit global packages un-ticked) 3. Click Install and choose Django v1.4 4. Select `Django` project type 5. Tick `Enable Admi...
Go onto Terminal: ``` $ nano .bash_profile ``` add: ``` export LC_ALL=en_GB.UTF-8 export LANG=en_GB.UTF-8 ``` (or use the locale -a command to see which ones are available to you) save and try again.
getdefaultlocale returning None when running sync.db on Django project in PyCharm
10,339,963
5
2012-04-26T19:20:36Z
10,341,356
13
2012-04-26T21:00:26Z
[ "python", "django", "pycharm" ]
OSX 10.7.3, PyCharm version 2.5 build PY 117.200 I'll run through how I get the error: 1. I start a new project 2. Create a new VirtualEnv and select Python 2.7 as my base interpreter (leave inherit global packages un-ticked) 3. Click Install and choose Django v1.4 4. Select `Django` project type 5. Tick `Enable Admi...
Basically the reason this occurs is that PyCharm doesn't, by default, have access to environmental variables. I've found 3 solutions to this problem: 1. Set a global environmental variable, using the link CrazyCoder suggests in the comments to this question. 2. Run PyCharm from a terminal window by changing to the Py...
How to order these lines for a highscore table in Python
10,340,225
4
2012-04-26T19:38:33Z
10,340,252
7
2012-04-26T19:40:31Z
[ "python" ]
I have the following in a text file: ``` ('bob', '10') ('Ben', '10') ('Ben', '9') ('Ben', '8') ('Ben', '2') ('Ben', '6') ('Ben', '5') ('Ben', '5') ('Ben', '3') ('Ben', '2') ``` I would like to reorder it so that it is ordered by numbers going down, so that I can print them off in a high score table, however I cannot ...
You can use [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval) to parse the tuples and then pass them to `sorted`: ``` import ast from operator import itemgetter def parse_item(s): name, score = ast.literal_eval(s) return name, int(score) with open("infile", "r") as infile: items = ...
print the appengine model entity id in the html template
10,340,439
5
2012-04-26T19:51:25Z
10,341,212
10
2012-04-26T20:48:02Z
[ "python", "google-app-engine", "jinja2", "webapp2" ]
Following is the simple database model i have: ``` class Notes(db.Model): text = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) ``` Now in the url handler, i send all the notes to the template as follows: ``` class MainPage(webapp2.RequestHandler): def get(self): notes = No...
Well replace the `href` line with the following: ``` (<a href ="edit/{{note.key().id()}}">edit </a>) ``` This shall be enough.
Whats more random, hashlib or urandom?
10,341,112
11
2012-04-26T20:39:48Z
10,341,149
29
2012-04-26T20:43:03Z
[ "python", "random", "hash" ]
I'm working on a project with a friend where we need to generate a random hash. Before we had time to discuss, we both came up with different approaches and because they are using different modules, I wanted to ask you all what would be better--if there is such a thing. ``` hashlib.sha1(str(random.random())).hexdigest...
This solution: ``` os.urandom(16).encode('hex') ``` is the best since it [uses the OS](http://docs.python.org/library/os.html#os.urandom) to generate randomness which *should* be usable for cryptographic purposes (depends on the OS implementation). `random.random()` generates [pseudo-random values](http://docs.pytho...
Is there a reason why when importing python files, you still need to name the file.function_name?
10,341,487
4
2012-04-26T21:11:04Z
10,341,539
7
2012-04-26T21:15:14Z
[ "python", "import" ]
I am currently doing a python tutorial, but they use IDLE, and I opted to use the interpreter on terminal. So I had to find out how to import a module I created. At first I tried ``` import my_file ``` then I tried calling the function inside the module by itself, and it failed. I looked around and doing ``` my_file...
If you wanted to use `my_file.function` by just calling `function`, try using the `from` keyword. Instead of `import my_file` try `from my_file import *`. You can also do this to only import parts of a module like so : `from my_file import function1, function2, class1` To avoid clashes in names, you can import thing...
How to migrate a python site to another machine?
10,341,707
5
2012-04-26T21:30:05Z
10,341,733
10
2012-04-26T21:32:46Z
[ "python", "django", "virtualenv" ]
I would like to know how to setup a complex python website, that is currently running in production environment, into a local machine for development? Currently the site uses python combined with Django apps (registration + cms modules) in a virtual environment.
In case you are using `pip` for package management, you can easily recreate the virtualenv on another system: On system1, run `pip freeze --local > requirements.txt` and copy that file to system2. Over there, create and activate the virtualenv and use `pip install -r requirements.txt` to install all packages that were...
lxml and <wbr> tags
10,341,954
5
2012-04-26T21:52:32Z
10,780,635
10
2012-05-28T07:04:59Z
[ "python", "html", "lxml", "wbr" ]
By default lxml doesn't understsand the wbr tag, used to add word-breaks in long words. It formats it as `<wbr></wbr>` when it should be formatted simply as `<wbr>`, similar to the br tag. How do I add this behavior to lxml?
Actually it is not difficult to patch libxml2 (this walkthrough was done on Ubuntu 11.04 with Python 2.7.3) First define a test program `wbr_test.py`: ``` from lxml import etree from cStringIO import StringIO wbr_html = """\ <html> <head> <title>wbr test</title> </head> <body> Test for a breakable<wbr>word...
Power set and Cartesian Product of a set python
10,342,939
3
2012-04-26T23:43:52Z
10,342,948
9
2012-04-26T23:45:11Z
[ "python", "python-3.x" ]
I am trying to find the cartesian product of two different sets. I can not find anything on the web about cartesian products of sets it's either of list or dictionaries. Also power set is very confusing. Neither one of these are in my book I have been using. Could one of yall point me to the right direction.
For the Cartesian product, check out [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product). For the powerset, [the `itertools` docs](http://docs.python.org/library/itertools.html#recipes) also give us a recipe: ``` def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (...
Efficiently determine if two of three items in a list are the same
10,343,413
2
2012-04-27T00:59:59Z
10,343,450
9
2012-04-27T01:04:22Z
[ "python", "algorithm", "list" ]
What is the most efficient way to determine if exactly two elements in a list are the same? For example: ``` >>> has1dup(["one", "one", "two"]) True >>> has1dup(["one", "two", "three"]) False >>> has1dup(["one", "one", "one"]) False ``` I have successfully done this using if/else statements. However, if the list were...
You can see how many unique values are there with a `set`. If there is one less item in the set than in the list, one was a duplicate: ``` def has1dup(lst): return len(lst)-1 == len(set(lst)) ```
How does Django's Meta class work?
10,344,197
70
2012-04-27T02:59:00Z
10,344,218
15
2012-04-27T03:02:43Z
[ "python", "django", "metaclass" ]
I am using Django which allows people to add extra parameters to a class by using `class Meta`. ``` class FooModel(models.Model): ... class Meta: ... ``` The only thing I found in Python's documentation was: ``` class FooMetaClass(type): ... class FooClass: __metaclass__ = FooMetaClass ``` ...
Django's `Model` class specifically handles having an attribute named `Meta` which is a class. It's not a general Python thing. Python metaclasses are completely different.
How does Django's Meta class work?
10,344,197
70
2012-04-27T02:59:00Z
10,344,231
99
2012-04-27T03:04:44Z
[ "python", "django", "metaclass" ]
I am using Django which allows people to add extra parameters to a class by using `class Meta`. ``` class FooModel(models.Model): ... class Meta: ... ``` The only thing I found in Python's documentation was: ``` class FooMetaClass(type): ... class FooClass: __metaclass__ = FooMetaClass ``` ...
You are asking a question about two different things: 1. **`Meta` inner class in Django models**: This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and pl...
How does Django's Meta class work?
10,344,197
70
2012-04-27T02:59:00Z
18,117,867
23
2013-08-08T04:23:23Z
[ "python", "django", "metaclass" ]
I am using Django which allows people to add extra parameters to a class by using `class Meta`. ``` class FooModel(models.Model): ... class Meta: ... ``` The only thing I found in Python's documentation was: ``` class FooMetaClass(type): ... class FooClass: __metaclass__ = FooMetaClass ``` ...
Extending on Tadeck's Django answer above, the use of 'class Meta:' in Django is just normal Python too. The internal class is a convenient namespace for shared data among the class instances (hence the name Meta for 'metadata' but you can call it anything you like). While in Django it's generally read only configurat...
SQLAlchemy: how to filter on PgArray column types?
10,344,468
4
2012-04-27T03:48:20Z
10,344,851
10
2012-04-27T04:45:56Z
[ "python", "sql", "postgresql", "sqlalchemy" ]
In pure postgres we can write: ``` SELECT * FROM my_table WHERE 10000 = ANY (array_field); ``` or ``` SELECT * FROM my_table WHERE 10000 = ALL (array_field); ``` How to do the same with the help of sqlalchemy without raw sql?
`a = ANY(b_array)` is equivalent to `a`**`IN`**`(elements_of_b_array)`1. Therefore you can use the [`in_()` method](http://docs.sqlalchemy.org/en/latest/core/expression_api.html#sqlalchemy.sql.operators.ColumnOperators.in_). I can't remember ever having used `a = ALL(b_array)` in all my years with PostgreSQL. Have yo...
Is the max thread limit actually a non-relevant issue for Python / Linux?
10,344,529
13
2012-04-27T03:58:24Z
10,344,591
10
2012-04-27T04:08:22Z
[ "python", "multithreading", "thread-safety", "threadpool", "python-multithreading" ]
The current Python application that I'm working on has a need to utilize 1000+ threads (Pythons threading module). Not that any single thread is working at max cpu cycles, this is just a web server load test app I'm creating. I.E. emulate 200 firefox clients all longing into web server and downloading small web compone...
1. "One thread is running at a time because of the GIL." Well, sort of. The GIL means that only one thread can be executing *Python* code at a time. However, any number of threads could be doing IO, various other syscalls, or other code that doesn't hold the GIL. It sounds like your threads will be doing mostly net...
Understanding lambda in python and using it to pass multiple arguments
10,345,278
22
2012-04-27T05:35:52Z
10,345,294
8
2012-04-27T05:38:03Z
[ "python", "python-3.x", "tkinter" ]
After reading everything I can find on lambda I still don't understand how to make it do what I want. Everyone uses the example ``` lambda x, y : x + y ``` Why do you need to state both 'x' and 'y' before the ':'? Also how do you make it return multiple arguments? for example: ``` self.buttonAdd_1 = Button(self, t...
I believe bind always tries to send an event parameter. Try: ``` self.entry_1.bind("<Return>", lambda event: self.calculate(self.buttonOut_1.grid_info(), 1)) ``` You accept the parameter and never use it.
Understanding lambda in python and using it to pass multiple arguments
10,345,278
22
2012-04-27T05:35:52Z
10,345,354
48
2012-04-27T05:43:40Z
[ "python", "python-3.x", "tkinter" ]
After reading everything I can find on lambda I still don't understand how to make it do what I want. Everyone uses the example ``` lambda x, y : x + y ``` Why do you need to state both 'x' and 'y' before the ':'? Also how do you make it return multiple arguments? for example: ``` self.buttonAdd_1 = Button(self, t...
> Why do you need to state both 'x' and 'y' before the ':'? Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to ``` def f(x, y) : return x + y ``` just without binding it to a name like `f`. > Also how do you make it return multiple arguments? The same way ...
SQLAlchemy: create an intentionally empty query?
10,345,327
16
2012-04-27T05:41:19Z
12,837,029
17
2012-10-11T10:02:45Z
[ "python", "sqlalchemy" ]
What's the best way to create an intentionally empty query in SQLAlchemy? For example, I've got a few functions which build up the query (adding `WHERE` clauses, for example), and at some points I know that the the result will be empty. What's the best way to create a query that won't return any rows? Something like ...
If you need the proper return type, just return `session.query(MyObject).filter(sqlalchemy.sql.false())`. When evaluated, this will still hit the DB, but it should be fast.
How do I split models.py into different files for different models in Pyramid?
10,345,698
9
2012-04-27T06:20:00Z
10,353,065
19
2012-04-27T15:03:36Z
[ "python", "model-view-controller", "pyramid" ]
I am new to pyramid and have been struggling to make some changes to my project. I am trying to split my models/Classes into individual files instead of a single models.py file. In order to do so I have removed the old models.py and created a models folder with `__init__.py` file along with one file for each class. In ...
``` myapp __init__.py scripts __init__.py initialize_db.py models __init__.py meta.py foo.py moo.py ``` now `meta.py` can contain a shared `Base` as well as the `DBSession`: ``` Base = declarative_base() DBSession = scoped_session(sessionmaker(extension=Zope...
List of lists into numpy array
10,346,336
38
2012-04-27T07:15:07Z
10,346,365
45
2012-04-27T07:17:45Z
[ "python", "list", "numpy" ]
How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
Um... ``` >>> numpy.array([[1, 2], [3, 4]]) array([[1, 2], [3, 4]]) ```
List of lists into numpy array
10,346,336
38
2012-04-27T07:15:07Z
10,346,405
8
2012-04-27T07:21:00Z
[ "python", "list", "numpy" ]
How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
It's as simple as: ``` >>> lists = [[1, 2], [3, 4]] >>> np.array(lists) array([[1, 2], [3, 4]]) ```
List of lists into numpy array
10,346,336
38
2012-04-27T07:15:07Z
26,224,619
32
2014-10-06T20:47:27Z
[ "python", "list", "numpy" ]
How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.
If your list of lists has lists with varying number of elements than the answer of Ignacio Vazquez-Abrams will not work. Instead there are 3 options: 1) Make an array of arrays: ``` x=[[1,2],[1,2,3],[1]] y=numpy.array([numpy.array(xi) for xi in x]) type(y) >>><type 'numpy.ndarray'> type(y[0]) >>><type 'numpy.ndarray'...
Django Foreign Key: get related model?
10,347,210
12
2012-04-27T08:20:49Z
10,347,326
16
2012-04-27T08:29:39Z
[ "python", "django", "django-models", "foreign-keys" ]
Is it possible to get the related model of a foreign key through the foreign key field itself? For example, if I have 3 models: ``` class ModelA(models.Model) field1 = models.CharField(max_length=10) class ModelB(models.Model) field1 = models.CharField(max_length=10) class ModelC(models.Model) field1 = ...
If ModelA has an FK field named "foo", then this is how you can get the related model: ``` ModelA._meta.get_field('foo').rel.to ``` With your code, it would look like: ``` for field in ModelC._meta.fields: if field.get_internal_type() == "ForeignKey": print field.rel.to ``` If found it out by using tab ...
MongoEngine query list for objects having properties starting with prefixes specified in a list
10,348,874
6
2012-04-27T10:19:46Z
10,349,291
8
2012-04-27T10:51:44Z
[ "python", "mongodb", "nosql", "mongoengine" ]
I need to query Mongo database for elements that have a certain property beginning with any prefix in the list. Now I have a piece of code like this: ``` query = mymodel(terms__term__in=query_terms) ``` and this matches objects that have an item on a list "terms" that has StringField "term" explicitly occurring on a ...
If your querying a term for it's value, you can filter the values that begin with a perfix like so: ``` MyModel.objects.filter(terms__term__startswith='foo') ``` If you need to filter for multiple prefixes you'll have to create Q objects for that: ``` MyModel.objects.filter(Q(terms__term__startswith='foo') | Q(terms...
How to escape “\” characters in python
10,349,439
3
2012-04-27T11:02:02Z
10,349,541
12
2012-04-27T11:09:49Z
[ "python", "regex" ]
i am very new to regular expression and trying get "\" character using python normally i can escape "\" like this ``` print ("\\"); print ("i am \\nit"); ``` output ``` \ i am \nit ``` but when i use the same in regX it didn't work as i thought ``` print (re.findall(r'\\',"i am \\nit")); ``` and return me output...
**EDIT**: The problem is *actually* how `print` works with lists & strings. It prints the representation of the string, not the string itself, the representation of a string containing just a backslash is `'\\'`. So `findall` is actually finding the single backslash correctly, but `print` isn't printing it as you'd exp...
How to open (read-write) or create a file with truncation possible?
10,349,781
25
2012-04-27T11:27:13Z
10,350,773
10
2012-04-27T12:39:41Z
[ "python", "ruby", "truncate" ]
I want to: * open a file in read-write mode if it exists; * create it if it doesn't exist; * be able to truncate it anytime-anywhere. **EDIT**: with truncate I mean write until a position and discard the remaining part of the file, if present All this atomically (with a single `open()` call or simulating a single `o...
Well, there are only these modes, and all of them have the "defects" you listed. Your only option is to wrap `open()`. Why not something like this? (Python) ``` def touchopen(filename, *args, **kwargs): open(filename, "a").close() # "touch" file return open(filename, *args, **kwargs) ``` it behaves just like...
How to open (read-write) or create a file with truncation possible?
10,349,781
25
2012-04-27T11:27:13Z
10,352,231
26
2012-04-27T14:10:44Z
[ "python", "ruby", "truncate" ]
I want to: * open a file in read-write mode if it exists; * create it if it doesn't exist; * be able to truncate it anytime-anywhere. **EDIT**: with truncate I mean write until a position and discard the remaining part of the file, if present All this atomically (with a single `open()` call or simulating a single `o...
According to [OpenGroup](http://pubs.opengroup.org/onlinepubs/7908799/xsh/open.html): > O\_TRUNC > > If the file exists and is a regular file, and the file is successfully > opened O\_RDWR or O\_WRONLY, its length is truncated to 0 and the mode > and owner are unchanged. It will have no effect on FIFO special files > ...
Optimise filtering lists in Python 2.7
10,349,787
5
2012-04-27T11:27:58Z
10,349,937
22
2012-04-27T11:37:40Z
[ "python", "generator", "python-2.7" ]
I need to filter a large lists several times, but I'm concerned with both simplicity of code and execution efficiency. To give an example: ``` all_things # huge collection of all things # inefficient but clean code def get_clothes(): return filter(lambda t: t.garment, allThings) def get_hats(): return filter...
First of all using `filter`/`lambda` combination is going to be deprecated. Current functional programming style is described in [Python Functional Programming HOWTO](http://docs.python.org/howto/functional.html). Secondly, if you concerned with efficiency, rather than construct lists, you should return [generators](h...
Unable to understand this python code
10,351,312
3
2012-04-27T13:15:00Z
10,351,334
13
2012-04-27T13:16:15Z
[ "python" ]
I was reading about python functions and saw this code: ``` def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear " + person + ".") print("Happy Birthday to you!") happyBirthday('Emily') happyBirthday('Andre') ``` I couldn't understand ...
> Is it really necessary to use those brackets? In Python 2.x, `print` is a statement, and the brackets are optional. In Python 3.x, `print()` is a function, and the brackets are mandatory. It is considered good practice to use brackets even in Python 2.x, to ease eventual transition to Python 3.x. > I am unable to...
converting list of string to list of integer
10,351,772
5
2012-04-27T13:44:46Z
10,351,826
20
2012-04-27T13:47:27Z
[ "python", "list", "input", "integer" ]
How do I convert a space separated integer input into a list of integers? Example input: ``` list1 = list(input("Enter the unfriendly numbers: ")) ``` Example conversion: ``` ['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5] ```
`map()` is your friend, it applies the function given as first argument to all items in the list. ``` map(int, yourlist) ``` since it maps every iterable, you can even do: ``` map(int, input("Enter the unfriendly numbers: ")) ``` which (in python3.x) returns a map object, which can be converted to a list. I assume ...
converting list of string to list of integer
10,351,772
5
2012-04-27T13:44:46Z
10,351,840
11
2012-04-27T13:48:12Z
[ "python", "list", "input", "integer" ]
How do I convert a space separated integer input into a list of integers? Example input: ``` list1 = list(input("Enter the unfriendly numbers: ")) ``` Example conversion: ``` ['1', '2', '3', '4', '5'] to [1, 2, 3, 4, 5] ```
One way is to use list comprehensions: ``` intlist = [int(x) for x in stringlist] ```
How to use __del__ in a reliable way?
10,352,480
4
2012-04-27T14:26:04Z
10,352,514
8
2012-04-27T14:27:52Z
[ "python", "destructor", "python-2.4" ]
I have learned that python [does](http://docs.python.org/reference/datamodel.html#object.__del__) [not](http://stackoverflow.com/questions/1481488/how-to-call-the-del-method) [guarantee](http://stackoverflow.com/questions/4199653/in-python-2-x-should-i-call-object-del) that `__del__` is called whenever an object is del...
In short: No, there is no way to ensure it gets called. The answer is to implement context managers yourself. A `with` statement roughly translates to: ``` x.__enter__() try: ... finally: x.__exit__() ``` So just do it manually. It is a little more complex than that, so I recommend reading [PEP 343](http://w...
how do i loop through fields of an object?
10,353,804
5
2012-04-27T15:50:42Z
10,360,423
18
2012-04-28T03:53:52Z
[ "python", "django", "model" ]
I have a model like this, how can I loop through it and not have to type out company.id, company.name, etc? ``` class Company(models.Model): name = models.CharField(max_length=1000) website = models.CharField(max_length=1000) email = models.CharField(max_length=200) phone_number = models.CharField(max_...
You can loop over all field names like so ``` for name in Company._meta.get_all_field_names(): print name ``` this also works if you have a category instance: ``` c = Company(name="foo",website="bar",email="baz@qux.com",....,) c.save() for field in c._meta.get_all_field_names(): print getattr(c, field, None)...
Assigning a function to a variable
10,354,163
13
2012-04-27T16:12:13Z
10,354,184
35
2012-04-27T16:13:16Z
[ "python" ]
Let's say I have a function ``` def x(): print(20) ``` Now I want to assign the function to a variable called `y`, so that if I use the `y` it calls the function `x` again. if i simply do the assignment `y = x()`, it returns `None`.
You simply don't call the function. ``` >>>def x(): >>> print(20) >>>y = x >>>y() 20 ``` The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns `y` the value *returned* by `x` (which in this case is `None`).
Python Matplotlib Y-Axis ticks on Right Side of Plot
10,354,397
56
2012-04-27T16:24:42Z
10,354,993
83
2012-04-27T17:11:42Z
[ "python", "matplotlib" ]
I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?
Use `ax.yaxis.tick_right()` for example: ``` from matplotlib import pyplot as plt f = plt.figure() ax = f.add_subplot(111) ax.yaxis.tick_right() plt.plot([2,3,4,5]) plt.show() ``` ![enter image description here](http://i.stack.imgur.com/DXSiM.png)
Python Matplotlib Y-Axis ticks on Right Side of Plot
10,354,397
56
2012-04-27T16:24:42Z
13,723,460
49
2012-12-05T12:40:11Z
[ "python", "matplotlib" ]
I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?
For right labels use `ax.yaxis.set_label_position("right")`, i.e.: ``` f = plt.figure() ax = f.add_subplot(111) ax.yaxis.tick_right() ax.yaxis.set_label_position("right") plt.plot([2,3,4,5]) ax.set_xlabel("$x$ /mm") ax.set_ylabel("$y$ /mm") plt.show() ```
Python Matplotlib Y-Axis ticks on Right Side of Plot
10,354,397
56
2012-04-27T16:24:42Z
20,481,365
23
2013-12-09T21:39:24Z
[ "python", "matplotlib" ]
I have a simple line plot and need to move the y-axis ticks from the (default) left side of the plot to the right side. Any thoughts on how to do this?
joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up `tick_right()` with a call to `set_ticks_position('both')`. A revised example: ``` from matplotlib import pyplot as plt f = plt.figure() ax = f.add_subplot(111) ax.yaxis.tick_right() ax.yaxis.set_t...
What is producing "405 Method Not Allowed" in this python code (google app engine)?
10,354,425
3
2012-04-27T16:27:01Z
13,426,655
8
2012-11-17T01:10:53Z
[ "python", "html", "google-app-engine" ]
I'm a python newbie and I'm trying to build an app copying step by step what was taught earlier in my class, but I'm getting the "405 Method Not Allowed" error. Here what the professor did: ![enter image description here](http://i.stack.imgur.com/iOBwO.png) Here what I did: ![enter image description here](http://i.s...
I am just trying Python following Udacity's online course and met similar issue that the AppEngine unable to find the post method. And finally it turns out that the root cause is the **INDENTION**. I used Notepad++ as the editor for the small project and it just can't work, keep throwing the 405 error. then I copy an...
Pygame: Draw single pixel
10,354,638
9
2012-04-27T16:41:52Z
10,354,667
15
2012-04-27T16:43:29Z
[ "python", "pygame" ]
I'm looking for method that allow me to draw single pixel on display screen. For example when I click mouse, I want the position of clicked pixel to change color. I know how to read mouse pos, but I could not find simple pixel draw ( there is screen.fill method but it's not working as I want).
You can do this with [`surface.set_at()`](http://www.pygame.org/docs/ref/surface.html#Surface.set_at): ``` surface.set_at((x, y), color) ``` You can also use [`pygame.gfxdraw.pixel()`](http://www.pygame.org/docs/ref/gfxdraw.html#pygame.gfxdraw.pixel): ``` from pygame import gfxdraw gfxdraw.pixel(surface, x, y, color...
tornado maps GET and POST arguments to lists. How can I disable this "feature"?
10,355,939
9
2012-04-27T18:29:02Z
10,358,286
22
2012-04-27T21:47:24Z
[ "python", "json", "tornado", "cyclone" ]
The HTTPRequest class in the tornado\* web framework helpfully [maps GET and POST arguments to lists](https://github.com/facebook/tornado/blob/master/tornado/httpserver.py). I understand why -- in case a given argument name is used multiple times. But for some RequestHandlers, this is a pain. For instance, if I want to...
Instead of accessing self.arguments directly you should use the accessor functions: ``` self.get_argument("ID", default=None, strip=False) ``` This returns a single item. If you want to turn the arguments into a JSON object you can quite easily do so: ``` json.dumps({ k: self.get_argument(k) for k in self.request.a...
How can I copy files bigger than 5 GB in Amazon S3?
10,355,941
20
2012-04-27T18:29:21Z
10,365,161
20
2012-04-28T15:57:26Z
[ "python", "amazon-s3", "boto" ]
Amazon S3 REST API documentation says there's a size limit of 5gb for upload in a PUT operation. Files bigger than that have to be uploaded using multipart. Fine. However, what I need in essence is to rename files that might be bigger than that. As far as I know there's no rename or move operation, therefore I have to...
> As far as I know there's no rename or move operation, therefore I have > to copy the file to the new location and delete the old one. That's correct, it's pretty easy to do for objects/files smaller than 5 GB by means of a [PUT Object - Copy](http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectCOPY.html)...
How can I copy files bigger than 5 GB in Amazon S3?
10,355,941
20
2012-04-27T18:29:21Z
15,327,662
8
2013-03-10T21:10:33Z
[ "python", "amazon-s3", "boto" ]
Amazon S3 REST API documentation says there's a size limit of 5gb for upload in a PUT operation. Files bigger than that have to be uploaded using multipart. Fine. However, what I need in essence is to rename files that might be bigger than that. As far as I know there's no rename or move operation, therefore I have to...
The above was very close to working, unfortunately should have ended with `mp.complete_upload()` instead of the typo `upload_complete()`! I've added a working boto s3 multipart copy script here, based of the AWS Java example and tested with files over 5 GiB: <https://gist.github.com/joshuadfranklin/5130355>
Python: Very simple strptime() call throws error
10,356,727
2
2012-04-27T19:30:05Z
10,356,802
13
2012-04-27T19:36:01Z
[ "python", "osx", "datetime", "python-2.7" ]
Some very simple code leads to a mystifying error, and Google gives me nothing... Code: ``` import sys import datetime for line in sys.stdin: date = datetime.datetime.strptime(line, '%Y%m%dT%H%M%S') print date ``` First few input lines on stdin: ``` 20101119T141500 20101119T164500 20110310T081500 20110310T...
You called your script "time.py", shadowing the `time` module. Don't do that.
Python faster than compiled Haskell?
10,357,663
39
2012-04-27T20:51:20Z
10,358,131
28
2012-04-27T21:30:15Z
[ "python", "haskell", "quicksort" ]
Please feel free to mark this as irrelevant if you think it doesn't belong here. I have a simple script written in both Python and Haskell. It reads a file with 1,000,000 newline separated integers, parses that file into a list of integers, quick sorts it and then writes it to a different file sorted. This file has th...
More a Pythonista than a Haskellite, but I'll take a stab: 1. There's a fair bit of overhead in your measured runtime just reading and writing the files, which is probably pretty similar between the two programs. Also, be careful that you've warmed up the cache for both programs. 2. Most of your time is spent making c...
Python faster than compiled Haskell?
10,357,663
39
2012-04-27T20:51:20Z
10,358,198
37
2012-04-27T21:37:37Z
[ "python", "haskell", "quicksort" ]
Please feel free to mark this as irrelevant if you think it doesn't belong here. I have a simple script written in both Python and Haskell. It reads a file with 1,000,000 newline separated integers, parses that file into a list of integers, quick sorts it and then writes it to a different file sorted. This file has th...
In short, don't use `read`. Replace `read` with a function like this: ``` import Numeric fastRead :: String -> Int fastRead s = case readDec s of [(n, "")] -> n ``` I get a pretty fair speedup: ``` ~/programming% time ./test.slow ./test.slow 9.82s user 0.06s system 99% cpu 9.901 total ~/programming% time ./test.fa...
Python faster than compiled Haskell?
10,357,663
39
2012-04-27T20:51:20Z
10,360,424
47
2012-04-28T03:54:20Z
[ "python", "haskell", "quicksort" ]
Please feel free to mark this as irrelevant if you think it doesn't belong here. I have a simple script written in both Python and Haskell. It reads a file with 1,000,000 newline separated integers, parses that file into a list of integers, quick sorts it and then writes it to a different file sorted. This file has th...
**The Original Haskell Code** There are two issues with the Haskell version: * You're using string IO, which builds linked lists of characters * You're using a non-quicksort that looks like quicksort. This program takes 18.7 seconds to run on my Intel Core2 2.5 GHz laptop. (GHC 7.4 using -O2) **Daniel's ByteString ...
Python faster than compiled Haskell?
10,357,663
39
2012-04-27T20:51:20Z
10,436,356
9
2012-05-03T17:22:52Z
[ "python", "haskell", "quicksort" ]
Please feel free to mark this as irrelevant if you think it doesn't belong here. I have a simple script written in both Python and Haskell. It reads a file with 1,000,000 newline separated integers, parses that file into a list of integers, quick sorts it and then writes it to a different file sorted. This file has th...
This is after the fact, but I think most of the trouble is in the Haskell writing. The following module is pretty primitive -- one should use builders probably and certainly avoid the ridiculous roundtrip via String for showing -- but it is simple and did distinctly better than pypy with kindall's improved python and b...
How to generate audio from a numpy array?
10,357,992
19
2012-04-27T21:17:23Z
10,359,645
30
2012-04-28T01:00:51Z
[ "python", "audio", "numpy", "matplotlib" ]
I want to create "heart rate monitor" effect from a 2D array in numpy and want the tone to reflect the values in the array.
You can use the [`write` function](http://docs.scipy.org/doc/scipy-0.9.0/reference/generated/scipy.io.wavfile.write.html) from `scipy.io.wavfile` to create a wav file which you can then play however you wish. Note that the array must be integers, so if you have floats, you might want to scale them appropriately: ``` i...
How to generate audio from a numpy array?
10,357,992
19
2012-04-27T21:17:23Z
10,383,478
10
2012-04-30T12:10:26Z
[ "python", "audio", "numpy", "matplotlib" ]
I want to create "heart rate monitor" effect from a 2D array in numpy and want the tone to reflect the values in the array.
In addition, you could try [scikits.audiolab](http://cournape.github.com/audiolab/). It features file IO and the ability to 'play' arrays. Arrays don't have to be integers. To mimick dbaupp's example: ``` import numpy as np import scikits.audiolab data = np.random.uniform(-1,1,44100) # write array to file: scikits.au...
How to generate audio from a numpy array?
10,357,992
19
2012-04-27T21:17:23Z
37,423,879
9
2016-05-24T21:05:17Z
[ "python", "audio", "numpy", "matplotlib" ]
I want to create "heart rate monitor" effect from a 2D array in numpy and want the tone to reflect the values in the array.
For the people coming here in 2016 scikits.audiolab doesn't really seem to work anymore. I was able to get a solution using sounddevice. ``` import numpy as np import sounddevice as sd fs = 44100 data = np.random.uniform(-1, 1, fs) sd.play(data, fs) ```
wxPython WebView example
10,358,998
8
2012-04-27T23:04:59Z
10,866,495
15
2012-06-02T22:44:05Z
[ "python", "webview", "wxpython" ]
I am writing a small reporting app using wxPython (wxAUI). I want to render my data as HTML, to be displayed in a WebView 'widget'. I am looking for a sample 'hello world' snippet that will show how to display/render an HTML string in a WebView widget - but have been unable to find a single example - and the WebView wi...
This is a simple example that works for me. Make sure you are running the **latest** version of wxpython. (wxpython 2.9) ``` import wx import wx.html2 class MyBrowser(wx.Dialog): def __init__(self, *args, **kwds): wx.Dialog.__init__(self, *args, **kwds) sizer = wx.BoxSizer(wx.VERTICAL) self.brows...
Is it possible to read multiple result sets using a ResultProxy object in sqlalchemy?
10,359,438
4
2012-04-28T00:21:44Z
10,360,707
8
2012-04-28T04:55:29Z
[ "python", "sqlalchemy", "pyodbc" ]
I'm trying to call a stored procedure that returns multiple result sets using SQLAlchemy. If it matters, underneath I'm using PyODBC and FreeTDS. I call the execute() method using a raw query with "exec" calling my stored procedure on a session object and get a ResultProxy object back. With a raw pyodbc cursor, I can ...
support for nextset() is [ticket 1635](http://www.sqlalchemy.org/trac/ticket/1635). It's two years old. It contains a partial patch which needs updating, in particular to work along with an execution option that passes along a hint that the statement will be returning multiple result sets, so that the resultproxy's exi...