title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
is += in python thread safe?
10,359,985
6
2012-04-28T02:05:44Z
10,360,018
9
2012-04-28T02:13:15Z
[ "python" ]
``` globalnum = 0 n = 1 class T( threading.Thread ): def run( self ): global globalnum globalnum += n for _ in xrange( 0, 999 ): t = T() t.start() print globalnum ``` the result is 999 In my test i seems += thread safe My question is: is += really thread safe?
`+=` is not threadsafe ([source](http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm)).
is += in python thread safe?
10,359,985
6
2012-04-28T02:05:44Z
10,360,021
15
2012-04-28T02:13:41Z
[ "python" ]
``` globalnum = 0 n = 1 class T( threading.Thread ): def run( self ): global globalnum globalnum += n for _ in xrange( 0, 999 ): t = T() t.start() print globalnum ``` the result is 999 In my test i seems += thread safe My question is: is += really thread safe?
No, it isn't thread-safe as the operation `x += 1` takes 4 opcodes as shown below: ``` 4 0 LOAD_GLOBAL 0 (x) 3 LOAD_CONST 1 (1) 6 INPLACE_ADD 7 STORE_GLOBAL 0 (x) ``` selected out of: ``` >>> import dis >>> def test...
Access value, column index, and row_ptr data from scipy CSR sparse matrix
10,360,210
8
2012-04-28T03:02:12Z
10,364,941
10
2012-04-28T15:30:23Z
[ "python", "scipy", "sparse-matrix", "csr" ]
I have a large matrix that I would like to convert to sparse CSR format. When I do: ``` import scipy as sp Ks = sp.sparse.csr_matrix(A) print Ks ``` Where A is dense, I get ``` (0, 0) -2116689024.0 (0, 1) 394620032.0 (0, 2) -588142656.0 (0, 12) 1567432448.0 (0, 14) -36273164.0 (0, 24) 233332608.0 (...
``` value = Ks.data column_index = Ks.indices row_pointers = Ks.indptr ``` I believe these attributes are undocumented which may make them subject to change, but I've used them on several versions of scipy.
Python: Why is global needed only on assignment and not on reads?
10,360,229
24
2012-04-28T03:07:08Z
10,360,255
15
2012-04-28T03:12:20Z
[ "python", "global" ]
If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it can do so without using a global declaration: ``` X = 10 def foo(): global X X = 20 # Needs global declaration def bar(): print( X ) # D...
Look at this code: ``` from module import function def foo(x): return function(x) ``` The name `function` here is a global. It would get awfully tedious if I had to say `global function` to get this code to work. Before you say that your `X` and my `function` are different (because one is a variable and the oth...
Python: Why is global needed only on assignment and not on reads?
10,360,229
24
2012-04-28T03:07:08Z
10,360,319
22
2012-04-28T03:31:22Z
[ "python", "global" ]
If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it can do so without using a global declaration: ``` X = 10 def foo(): global X X = 20 # Needs global declaration def bar(): print( X ) # D...
With nested scopes, the variable lookups are easy. They occur in a chain starting with locals, through enclosing defs, to module globals, and then builtins. The rule is the first match found wins. Accordingly, you don't need a "global" declaration for lookups. In contrast, with writes you need to specify which scope t...
Python: Why is global needed only on assignment and not on reads?
10,360,229
24
2012-04-28T03:07:08Z
10,360,383
15
2012-04-28T03:42:44Z
[ "python", "global" ]
If a function needs to modify a variable declared in global scope, it need to use the global declaration. However, if the function just needs to read a global variable it can do so without using a global declaration: ``` X = 10 def foo(): global X X = 20 # Needs global declaration def bar(): print( X ) # D...
Because explicit is better than implicit. There's no ambiguity when you read a variable. You always get the first one found when searching scopes up from local until global. When you assign, there's only two scopes the interpreter may unequivocally assume you are assigning to: local and global. Since assigning to loc...
Limiting scope of Python import
10,360,460
5
2012-04-28T04:00:24Z
10,360,477
7
2012-04-28T04:03:26Z
[ "python", "namespaces" ]
I have some code that looks like this: ``` from pyparsing import Word, alphas, Optional, ... # Do stuff ... # And at the end, save a result to the outside world. parser = ... # Now use parser but don't use anything else from pyparsing again. ``` I like having the convenience of calling `from <package> import <etc>`,...
One easy way is to use function scope to control import visibility within a file: ``` def prepare_parser(): from pyparsing import Word, alphas, Optional, ... # do stuff, and get the final thing to return return ... parser = prepare_parser() ```
Limiting scope of Python import
10,360,460
5
2012-04-28T04:00:24Z
10,360,481
10
2012-04-28T04:05:04Z
[ "python", "namespaces" ]
I have some code that looks like this: ``` from pyparsing import Word, alphas, Optional, ... # Do stuff ... # And at the end, save a result to the outside world. parser = ... # Now use parser but don't use anything else from pyparsing again. ``` I like having the convenience of calling `from <package> import <etc>`,...
The usual ways to control namespace pollution are 1. Delete the variables after use 2. Use the \_\_all\_\_ variable 3. Use import-as to underscored variable names These techniques are all used by the core developers in the standard library. For example, the *decimal* module: * starts out with [private name imports](...
In Python, when should I use a meta class?
10,361,181
5
2012-04-28T06:24:53Z
10,361,426
7
2012-04-28T07:10:05Z
[ "python", "oop" ]
I have gone through this: [What is a metaclass in Python?](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) But can any one explain more specifically when should I use the meta class concept and when it's very handy? Suppose I have a class like below: ``` class Book(object): CATEGORIES =...
You use metaclasses when you want to mutate the *class* as it is being created. Metaclasses are hardly ever needed, they're hard to debug, and they're difficult to understand -- but occasionally they can make frameworks easier to use. In our 600Kloc code base we've used metaclasses 7 times: ABCMeta once, 4x models.Subf...
How to run an IPython magic from a script (or timing a Python script)
10,361,206
27
2012-04-28T06:29:04Z
15,898,875
23
2013-04-09T09:56:59Z
[ "python", "ipython" ]
The IPython %timeit magic command does its job well for measuring time required to run some Python code. Now, I want to use something analogous in the Python script. I know about the timeit module, however, it has several disadvantages, for example, how to select the number of runs adaptively? i.e., the default code `...
It depends a bit on which version of IPython you have. If you have 1.x: ``` from IPython import get_ipython ipython = get_ipython() ``` If you have an older version: ``` import IPython.core.ipapi ipython = IPython.core.ipapi.get() ``` or ``` import IPython.ipapi ipython = IPython.ipapi.get() ``` **Once that's...
Image transformation in OpenCV
10,364,201
16
2012-04-28T14:01:24Z
10,374,811
20
2012-04-29T18:34:39Z
[ "python", "opencv", "wolfram-mathematica", "computer-vision" ]
This question is related to this question: [`How to remove convexity defects in sudoku square`](http://stackoverflow.com/questions/10196198/how-to-remove-convexity-defects-in-sudoku-square) I was trying to implement [`nikie's answer`](http://stackoverflow.com/a/10226971/1134940) in `Mathematica to OpenCV-Python`. But ...
Apart from etarion's suggestion, you could also use the [remap](http://opencv.itseez.com/modules/imgproc/doc/geometric_transformations.html?highlight=cv2.remap#cv2.remap) function. I wrote a quick script to show how you can do this. As you see coding this is really easy in Python. This is the test image: ![distorted i...
How dict objects are pickled?
10,364,818
5
2012-04-28T15:17:33Z
10,364,942
7
2012-04-28T15:30:26Z
[ "python", "pickle" ]
After reading pickle documentation, I got an impression that a class needs to implement either `__reduce__` or `__getstate__` to get pickled correctly. But how pickling of dictionaries work then? They don't have any of those attributes: ``` > dict(a=1).__reduce__() ----------------------------------------------------...
[The pickle module handles a number of types "natively"](http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled). The types it *doesn't* handle natively will need to implement the ["pickle protocol"](http://docs.python.org/library/pickle.html#the-pickle-protocol). Dicts, and simple subclasses, are...
Flask debug=True does not work when going through uWSGI
10,364,854
24
2012-04-28T15:21:09Z
10,364,965
17
2012-04-28T15:33:30Z
[ "python", "wsgi", "flask" ]
I call `app.run(debug=True)` in my flask file. and I have it deployed with uWSGI and nginx (I followed [these instructions](http://readncode.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/)) ``` uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666 ``` But when I get an...
The problem is `uwsgi` does not call `app.run()`. It calls `app()`. So instead you can do this: ``` from flask import Flask app = Flask(__name__) app.debug = True ```
Flask debug=True does not work when going through uWSGI
10,364,854
24
2012-04-28T15:21:09Z
10,460,399
20
2012-05-05T09:12:09Z
[ "python", "wsgi", "flask" ]
I call `app.run(debug=True)` in my flask file. and I have it deployed with uWSGI and nginx (I followed [these instructions](http://readncode.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/)) ``` uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666 ``` But when I get an...
According to [the Flask mailing list](http://flask.pocoo.org/mailinglist/archive/2011/10/19/debug-when-deploy-in-uwsgi/#7be089baf631971dfb73a5a7b79e2248) you cannot use Flask's debug option with `uWSGI`, because it's not to be used in a forking environment. > You see 502 because flask/werkzeug do not send any data to ...
Flask debug=True does not work when going through uWSGI
10,364,854
24
2012-04-28T15:21:09Z
17,839,750
19
2013-07-24T16:29:01Z
[ "python", "wsgi", "flask" ]
I call `app.run(debug=True)` in my flask file. and I have it deployed with uWSGI and nginx (I followed [these instructions](http://readncode.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/)) ``` uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666 ``` But when I get an...
This question is old, but I'll post this for future reference... If you want to get the werkzeug error page to work with uwsgi, try using werkzeug's `DebuggedApplication` middleware: ``` from werkzeug.debug import DebuggedApplication app.wsgi_app = DebuggedApplication(app.wsgi_app, True) ``` That should do the trick...
is this code truly private? (python)
10,365,193
2
2012-04-28T16:00:57Z
10,365,207
10
2012-04-28T16:02:22Z
[ "python", "private" ]
I am trying to make python allow private variable, so I made this decorator that you put at the begging of a class so that every function will get an additional private parameter that they can modify to be what they want. as far as I can tell, it is impossible to get the variables from outside the class, but I'm not a ...
In short: Don't do this. [There is no need to make things truly private in Python](http://docs.python.org/tutorial/classes.html#tut-private). The people using your software can see if something is marked as private (variable name begins with `_`), so they know. If they still want to access it, why stop them? I'm sure...
is this code truly private? (python)
10,365,193
2
2012-04-28T16:00:57Z
10,365,338
9
2012-04-28T16:20:35Z
[ "python", "private" ]
I am trying to make python allow private variable, so I made this decorator that you put at the begging of a class so that every function will get an additional private parameter that they can modify to be what they want. as far as I can tell, it is impossible to get the variables from outside the class, but I'm not a ...
That's an interesting idea, but the wrapper functions you're using for the decorator will have a reference to the "private" object in their `func_closure` attribute. So your "private" variable is accessible as `a.getValue.func_closure[0].cell_contents.test`. (You can use any wrapped function to get to your "private" ob...
"sys.getsizeof(int)" returns an unreasonably large value?
10,365,624
12
2012-04-28T16:59:15Z
10,365,639
26
2012-04-28T17:00:54Z
[ "python" ]
I want to check the size of int data type in python: ``` import sys sys.getsizeof(int) ``` It comes out to be "436", which doesn't make sense to me. Anyway, I want to know how many bytes (2,4,..?) int will take on my machine.
You're getting the size of the *class*, not of an instance of the class. Call `int` to get the size of an instance: ``` >>> sys.getsizeof(int()) 24 ``` If that size still seems a little bit large, remember that a Python `int` is very different from an `int` in (for example) c. In Python, an `int` is a fully-fledged o...
Parent initializer not called in multi-level inheritence?
10,365,636
2
2012-04-28T17:00:35Z
10,365,663
10
2012-04-28T17:02:54Z
[ "python", "inheritance", "initialization" ]
I have a class scheme with 2-levels of inheritance. My expectation is that each class constructor would run through- and yet the mid-level class constructor never seems to get hit. What's missing here? ``` class Base(object): def __init__(self): print "BASE" class Next(Base): def __init__(self): ...
You should be calling `super()` with the *current* class, not the parent. ``` class Base(object): def __init__(self): super(Base, self).__init__() print "BASE" class Next(Base): def __init__(self): super(Next, self).__init__() print "NEXT" class Final(Next): def __init__(s...
Pyramid: Default values in route pattern
10,366,245
3
2012-04-28T18:13:27Z
10,367,862
12
2012-04-28T21:52:07Z
[ "python", "url", "pyramid", "routes" ]
I was wondering: Is it possible, to provide default values within the pattern of a route configuration? For example: I have a view that shows a (potentially large) list of files bound to a data set. I want to split up the view in pages, which each page showing 100 files. When the page part in the url pattern is omi...
You're probably content with [this answer](http://stackoverflow.com/a/10366325/), but another option is to use multiple routes that dispatch to the same view. ``` config.add_route('show_files', '/show_files/{datasetid}') config.add_route('show_files:page', '/show_files/{datasetid}/{page}') @view_config(route_name='sh...
What is the 'pythonic' equivalent to the 'fold' function from functional programming?
10,366,374
73
2012-04-28T18:30:48Z
10,366,417
78
2012-04-28T18:35:51Z
[ "python", "list", "functional-programming", "reduce", "fold" ]
What is the most idiomatic way to achieve something like the following, in Haskell: ``` foldl (+) 0 [1,2,3,4,5] --> 15 ``` Or its equivalent in Ruby: ``` [1,2,3,4,5].inject(0) {|m,x| m + x} #> 15 ``` Obviously, Python provides the `reduce` function, which is an implementation of fold, exactly as above, however, I w...
The Pythonic way of summing an array is `sum`. For other purposes, you can sometimes use some combination of `reduce` and the `operator` module, e.g. ``` def product(xs): return reduce(operator.mul, xs, 1) ``` Be aware that `reduce` is actually a `foldl`, in Haskell terms. There is no special syntax to perform fo...
How to read contents of an Table in MS-Word file Using Python?
10,366,596
2
2012-04-28T19:01:51Z
10,375,434
11
2012-04-29T19:54:08Z
[ "python", "table", "ms-word" ]
How can I read and process contents of every cell of a table in a DOCX file? I am using Python 3.2 on Windows 7 and PyWin32 to access the MS-Word Document. I am a beginner so I don't know proper way to reach to table cells. So far I have just done this: ``` import win32com.client as win32 word = win32.gencache.Ensur...
Here is what works for me in Python 2.7: ``` import win32com.client as win32 word = win32.Dispatch("Word.Application") word.Visible = 0 word.Documents.Open("MyDocument") doc = word.ActiveDocument ``` To see how many tables your document has: ``` doc.Tables.Count ``` Then, you can select the table you want by its in...
Get sums of pairs of elements in a numpy array
10,366,665
6
2012-04-28T19:08:51Z
10,366,764
15
2012-04-28T19:19:59Z
[ "python", "numpy", "scipy" ]
I have an array: ``` t = [4, 5, 0, 7, 1, 6, 8, 3, 2, 9] ``` which is just a random shuffle of the range [0, 9]. I need to calculate this: ``` t2 = [9, 5, 7, 8, 7, 14, 11, 5, 11, 13] ``` which is just: ``` t2 = [t[0]+t[1], t[1]+t[2], t[2]+t[3], t[3]+t[4], ..., t[9]+t[0]] ``` Is there a way I can do this with numpy...
You could take advantage of a NumPy array's ability to sum element-wise: ``` In [5]: import numpy as np In [6]: t = np.array([4, 5, 0, 7, 1, 6, 8, 3, 2, 9]) In [7]: t + np.r_[t[1:],t[0]] Out[7]: array([ 9, 5, 7, 8, 7, 14, 11, 5, 11, 13]) ``` [np.r\_](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r_...
Python ImportError cannot import urandom Since Ubuntu 12.04 upgrade
10,366,821
54
2012-04-28T19:28:25Z
10,366,919
45
2012-04-28T19:42:16Z
[ "python", "ubuntu", "random" ]
Upgraded Ubuntu to Precise Pangolin (12.04), and Python's Random is now broken... I suspect other things might be broken too. How do I fix Python? ``` File "/usr/lib/python2.7/random.py", line 47, in <module> from os import urandom as _urandom ImportError: cannot import name urandom ``` *Alas, poor Python! I ...
Is this your problem? <https://bugs.launchpad.net/ubuntu/+source/python-defaults/+bug/989856> Seems to be caused by running it in a virtual environment, and there is a work around. BTW this was the top result in google.
Python ImportError cannot import urandom Since Ubuntu 12.04 upgrade
10,366,821
54
2012-04-28T19:28:25Z
10,378,480
7
2012-04-30T04:24:03Z
[ "python", "ubuntu", "random" ]
Upgraded Ubuntu to Precise Pangolin (12.04), and Python's Random is now broken... I suspect other things might be broken too. How do I fix Python? ``` File "/usr/lib/python2.7/random.py", line 47, in <module> from os import urandom as _urandom ImportError: cannot import name urandom ``` *Alas, poor Python! I ...
I was getting this same error and fixed it by just re-running virtualenv (e.g., `virtualenv --no-site-packages ~/venv/myvirtualenv/`).
Python ImportError cannot import urandom Since Ubuntu 12.04 upgrade
10,366,821
54
2012-04-28T19:28:25Z
10,415,270
36
2012-05-02T13:57:59Z
[ "python", "ubuntu", "random" ]
Upgraded Ubuntu to Precise Pangolin (12.04), and Python's Random is now broken... I suspect other things might be broken too. How do I fix Python? ``` File "/usr/lib/python2.7/random.py", line 47, in <module> from os import urandom as _urandom ImportError: cannot import name urandom ``` *Alas, poor Python! I ...
I had the same problem. To solve it just ran virtualenv over the same installation and it worked: ``` $ virtualenv ~/lib/virtualenv/netunong Overwriting /home/adam/lib/virtualenv/netunong/lib/python2.7/site.py with new content New python executable in /home/adam/lib/virtualenv/netunong/bin/python Installing distribute...
compare two lists in python and return indices of matched values
10,367,020
6
2012-04-28T19:53:11Z
10,367,036
13
2012-04-28T19:55:19Z
[ "python", "list", "match", "indices" ]
For two lists a and b, how can I get the indices of values that appear in both? For example, ``` a = [1, 2, 3, 4, 5] b = [9, 7, 6, 5, 1, 0] return_indices_of_a(a, b) ``` would return `[0,4]`, with `(a[0],a[4]) = (1,5)`.
The best way to do this would be to make `b` a `set` since you are only checking for membership inside it. ``` >>> a = [1, 2, 3, 4, 5] >>> b = set([9, 7, 6, 5, 1, 0]) >>> [i for i, item in enumerate(a) if item in b] [0, 4] ```
What is producing "TypeError character mapping must return integer..." in this python code?
10,367,302
13
2012-04-28T20:32:42Z
10,367,327
24
2012-04-28T20:37:49Z
[ "python", "google-app-engine", "typeerror" ]
please, can someone help me with the code bellow? When I run it the logs said: ``` return method(*args, **kwargs) File "C:\Users\CG\Documents\udacity\rot13serendipo\main.py", line 51, in post text = rot13(text) File "C:\Users\CG\Documents\udacity\rot13serendipo\main.py", line 43, in rot13 return st.transla...
It's probably because the text is being entered as unicode: ``` >>> def rot13(st): ... import string ... tab1 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ... tab2 = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM' ... tab = string.maketrans(tab1, tab2) ... return st.translate(tab...
Delete Function
10,367,414
5
2012-04-28T20:49:21Z
10,367,461
11
2012-04-28T20:57:34Z
[ "python" ]
I'm trying to create a function to delete another function. ``` def delete_function(func): del func ``` is what I have so far, but for some reason it doesn't work. ``` def foo(): print("foo") delete_function(foo) ``` doesn't seem to do the trick. I know one can do it easily, just ``` del(foo) ``` but I'm...
Deleting a function isn't really something you do to the function itself; it's something you do to the namespace it lives in. (Just as removing the number 3 from a list isn't something you do to the number 3, it's something you do to the list.) Suppose you say ``` def foo(x): return 1 bar = foo ``` Then (more or les...
Running python script in terminal, nothing prints or shows up - why?
10,367,751
2
2012-04-28T21:37:56Z
10,367,791
7
2012-04-28T21:42:37Z
[ "python", "terminal" ]
Going through Learn Python the Hard Way, lesson 25. I try to execute the script, and the result is like so: ``` myComp:lphw becca$ python l25 myComp:lphw becca$ ``` Nothing prints or displays in terminal. Here's the code. ``` def breaks_words(stuff): """This function will break up words for us.""" words...
All your code is function definitions, but you never **call** any of the functions, so the code doesn't do anything. Defining a function with the `def` keyword just, well, *defines a function*. It doesn't run it. For example, say you just have this function in your program: ``` def f(x): print x ``` You're tell...
Create a list of sets of atoms
10,367,929
7
2012-04-28T22:01:32Z
10,367,955
15
2012-04-28T22:06:20Z
[ "python", "set" ]
Say I have an array of atoms like this: ``` ['a', 'b', 'c'] ``` (the length may be any) And I want to create a list of sets that can be made with them: ``` [ ['a'], ['b'], ['c'], ['a', 'b'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c'] ] ``` Is it possible to do it easily in python? Maybe it's very...
That sounds to me like [`powerset`](http://docs.python.org/library/itertools.html#recipes): ``` def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) ```
How to use POST method in Tornado?
10,367,981
14
2012-04-28T22:10:18Z
10,369,073
26
2012-04-29T01:51:31Z
[ "python", "post", "tornado" ]
I'm trying to use Tornado to start a server and post a string to it. I've found lots of examples of how to write the post method in the handler class, but no examples of how to write the post request. My current code does cause the post method to execute, but get\_argument isn't getting the data--it just prints the def...
> it seems people create their own parameters Not quite. From the docs: > fetch(request, \*\*kwargs) > > Executes a request, returning an > HTTPResponse. > > The request may be either a string URL or an HTTPRequest object. If it > is a string, we construct an HTTPRequest using any additional kwargs: > HTTPRequest(req...
matplotlib animated plot wont update labels on axis using blit
10,368,371
9
2012-04-28T23:10:50Z
10,704,274
7
2012-05-22T14:37:57Z
[ "python", "animation", "matplotlib", "axes" ]
I am plotting data in a plot using wxPython where the data limits on the y- axis are changing with the data. I would like to change the axis dynamically without redrawing the whole canvas like `canvas.draw()` rather I'd like to use `blitting` for this as I do for the plot itself. What I got to work is the changing y-a...
It looks like the labels are drawn but the blit command doesn't copy them over to the canvas because the bounding box only includes the inner part of the axes. For me changing `update_line.background = canvas.copy_from_bbox(ax.bbox)` to `update_line.background = canvas.copy_from_bbox(ax.get_figure().bbox)` and `canvas...
python multiprocessing pool Assertion Error in interpreter
10,368,810
3
2012-04-29T00:49:18Z
10,368,833
10
2012-04-29T00:54:55Z
[ "python", "multiprocessing" ]
I am writing a sample program to test the usage of multiprocessing pool of workers in python 2.7.2+ This is the code i have written in the python ubuntu interpreter ``` >>> from multiprocessing import Pool >>> def name_append(first_name,last_name): ... return first_name+" "+last_name ... >>> from functools impor...
You typed: ``` >>> pool.close() ``` [from the docs:](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close) > close() > > Prevents any more tasks from being submitted to the pool. Once all the tasks > have been completed the worker processes will exit. Of course you can...
how to make qmenu item checkable pyqt4 python
10,368,947
9
2012-04-29T01:20:09Z
10,369,171
16
2012-04-29T02:15:40Z
[ "python", "pyqt4", "qmenu" ]
How can i make my qmenu checkable? ``` from PyQt4 import QtGui app = QtGui.QApplication([]) menu = QtGui.QMenu() menu.addAction('50%') menu.addAction('100%') menu.addAction('200%') menu.addAction('400%') menu.show() app.exec_() ```
like this: ``` from PyQt4 import QtGui app = QtGui.QApplication([]) w = QtGui.QMainWindow() menu = QtGui.QMenu("menu", w) menu.addAction(QtGui.QAction('50%', menu, checkable=True)) menu.addAction(QtGui.QAction('100%', menu, checkable=True)) menu.addAction(QtGui.QAction('200%', menu, checkable=True)) menu.addAction(...
Python permutation
10,369,300
3
2012-04-29T02:47:50Z
10,369,335
11
2012-04-29T02:54:57Z
[ "python" ]
How would I accomplish the following in python: ``` first = ['John', 'David', 'Sarah'] last = ['Smith', 'Jones'] combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones'] ``` Is there a method to combine all permutations?
[`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) ``` import itertools combined = [f + ' ' + l for f, l in itertools.product(first, last)] ```
Python permutation
10,369,300
3
2012-04-29T02:47:50Z
10,369,338
7
2012-04-29T02:56:28Z
[ "python" ]
How would I accomplish the following in python: ``` first = ['John', 'David', 'Sarah'] last = ['Smith', 'Jones'] combined = ['John Smith', 'John Jones', 'David Smith', 'David Jones', 'Sarah Smith', 'Sarah Jones'] ``` Is there a method to combine all permutations?
Not sure if there is a more elegant solution, but this should work: `[x + " " + y for x in first for y in last]`
Need a python module for stemming of text documents
10,369,393
7
2012-04-29T03:11:21Z
10,369,407
19
2012-04-29T03:15:23Z
[ "python", "module", "preprocessor", "nlp", "stemming" ]
I need a good python module for stemming text documents in the pre-processing stage. I found this one <http://pypi.python.org/pypi/PyStemmer/1.0.1> but i cannot find the documentation int the link provided. I anyone knows where to find the documentation or any other good stemming algorithm please help.
You may want to try [NLTK](http://www.nltk.org/) ``` >>> from nltk import PorterStemmer >>> PorterStemmer().stem_word('complications') ```
Using Dictionaries in Python in place of Case/Switch statement
10,369,537
8
2012-04-29T03:50:20Z
10,369,567
14
2012-04-29T03:58:13Z
[ "python", "random", "dictionary", "rubiks-cube" ]
I want to randomize a rubik's cube that is initialized as complete (all colors on the correct sides). I have move functions that rotate the cube. I want to randomly pick 50 functions in a row to properly randomize it. I am doing this project to learn a little bit more about Python, since I mostly do C++ and I see ther...
When you define the dict, it's actually calling the functions, and storing the return value in the dictionary. To just have the dictionary store a reference to the functions, you need to drop the trailing parentheses. So something like: ``` scramble = { 0: self.up_turn, 1: self.down_turn, ...
Django Ajax Jquery Call
10,369,667
6
2012-04-29T04:25:12Z
10,370,956
11
2012-04-29T09:03:05Z
[ "jquery", "python", "ajax", "django" ]
This may be basic, but I've spent two days, read countless tutorials and I still can not get this to work. For simplicitly I tried to accomplish a basic task just to see it work. I want to send make an ajax call to my donate view. I see that it successfully passes through but I was expecting that my template would also...
I think the problem is at where you pass the data. Do you use `Firebug`? An excellent tool for checking if you pass anything in `POST`, it is an excellent tool for web development in general. Here's a working example for sending Ajax call from a form ``` $("#form").submit(function(event) { var $form = $(this)...
How to plot bar graphs with same X coordinates side by side
10,369,681
9
2012-04-29T04:28:36Z
10,369,955
12
2012-04-29T05:32:21Z
[ "python", "matplotlib" ]
``` import matplotlib.pyplot as plt gridnumber = range(1,4) b1 = plt.bar(gridnumber, [0.2, 0.3, 0.1], width=0.4, label="Bar 1", align="center") b2 = plt.bar(gridnumber, [0.3, 0.2, 0.2], color="red", width=0.4, label="Bar 2", align="center") plt.ylim([0,0.5]) plt.xlim([0,4]) plt.xtic...
There is an [example](http://matplotlib.sourceforge.net/examples/api/barchart_demo.html) in the matplotlib site. Basically, you just shift the `x` values by `width`. Here is the relevant bit: ``` import numpy as np import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind =...
How to avoid object creation in python?
10,370,951
3
2012-04-29T09:01:52Z
10,370,957
7
2012-04-29T09:03:30Z
[ "python", "python-3.x" ]
I am new to python programming,I have one class,for this class i created one object( obj1).i don't want to create other than this object,if any body wants to create one more object for this class that should refer to first object only(instead of creating one more object).how to do this? please refer the below code? > ...
So you want something singleton-ish? Then do not use objects for this at all. Simply put the functions in a separate module (.py file) and put your variables in the module scope (e.g. global variables) - that's the pythonic way to do what you want if you do not need thread safety. Remember: It's not java and using clas...
python : how to disable auto sort when creating dictionary
10,371,085
5
2012-04-29T09:29:01Z
10,371,103
17
2012-04-29T09:32:42Z
[ "python", "sorting", "dictionary" ]
i need help for this case : ``` m={} m[1]=1 m[333]=333 m[2]=2 # Result: {1: 1, 2: 2, 333: 333} ``` so even when i didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fi...
It is not sorting. `dict` is not ordered at all, so you cannot influence the key order in any way. There is [`collections.OrderedDict`](http://docs.python.org/library/collections.html#collections.OrderedDict) in 2.7 and 3.1+, there is also [standalone module](http://pypi.python.org/pypi/ordereddict) for 2.4-2.6.
Storing dictionary path in Python
10,371,732
4
2012-04-29T11:26:48Z
10,371,754
7
2012-04-29T11:29:49Z
[ "python", "dictionary" ]
Brand new to python, Let's say I have a dict: ``` kidshair = {'allkids':{'child1':{'hair':'blonde'}, 'child2':{'hair':'black'}, 'child3':{'hair':'red'}, 'child4':{'hair':'brown'}}} ``` If child3 changes their hair colour regularly, I might want to writ...
Depending on what you need, the easiest option may be to use tuples as dictionary keys instead of nested dictionaries: ``` kidshair['allkids', 'child3', 'hair'] mypath = ('allkids', 'child3', 'hair') kidshair[mypath] ``` The only issue with this is that you can't get a portion of the dictionary, so, for example, you ...
python, detecting elements have been removed/added/changed positions in a list
10,371,889
4
2012-04-29T11:50:29Z
10,371,999
9
2012-04-29T12:06:36Z
[ "python", "list" ]
I have a list of items.. An orginal list and a modified list - what i want to know is which elements have been removed/added from the modified list and what position w.r.t to the original list. The lists do not have duplicates and are not sorted because the ordering of the items in the list matters. Take an example ``...
You can use [difflib](http://docs.python.org/library/difflib.html) to do this kind of thing: ``` >>> import difflib >>> Org = ['AMEND', 'ASTRT', 'ETIME', 'OBJ', 'ast', 'bias', 'chip', 'cold'] >>> mod = ['AMEND', 'ASTRT', 'OBJ', 'ast', 'bias', 'chip', 'cold', 'flat', 'deb'] >>> list(difflib.ndiff(Org, mod)) [' AMEND',...
How to create a user in Django?
10,372,877
19
2012-04-29T14:27:13Z
10,374,174
16
2012-04-29T17:18:54Z
[ "python", "django" ]
I'm trying to create a new User in a Django project by the following code, but the highlighted line fires an exception. ``` def createUser(request): userName = request.REQUEST.get('username', None) userPass = request.REQUEST.get('password', None) userMail = request.REQUEST.get('email', None) # TODO: c...
Have you confirmed that you are passing actual values and not `None`? ``` from django.shortcuts import render def createUser(request): userName = request.REQUEST.get('username', None) userPass = request.REQUEST.get('password', None) userMail = request.REQUEST.get('email', None) # TODO: check if alrea...
How to create a user in Django?
10,372,877
19
2012-04-29T14:27:13Z
23,482,284
43
2014-05-05T21:32:53Z
[ "python", "django" ]
I'm trying to create a new User in a Django project by the following code, but the highlighted line fires an exception. ``` def createUser(request): userName = request.REQUEST.get('username', None) userPass = request.REQUEST.get('password', None) userMail = request.REQUEST.get('email', None) # TODO: c...
The correct way to create a user in Django is to use the create\_user function. This will handle the hashing of the password, etc.. ``` from django.contrib.auth.models import User user = User.objects.create_user(username='john', email='jlennon@beatles.com', ...
Simple flask application that reads its content from a .html file. External style sheet being blocked?
10,372,883
4
2012-04-29T14:27:56Z
10,374,125
12
2012-04-29T17:13:09Z
[ "python", "css", "flask" ]
I made a very simple flask application that reads its content from a .html file. The application works except for the style. Strangely my inline css code works but not the external style sheet. I've checked the syntax, it should work. Does flask somehow prevent the .css file from being read? The files in the folder ca...
Your code is not serving files using Flask, it is simply reading a file and sending it to the browser - which is why URLs are not working. You need to render the file from within the method. First make a `templates` folder in the same directory as your `.py` file and move your html file into this folder. Create anoth...
Why this code gets this 'str' object has no attribute 'get_match_routes' error?
10,373,309
5
2012-04-29T15:20:42Z
10,373,337
7
2012-04-29T15:25:25Z
[ "python", "html", "google-app-engine" ]
I'm trying to build one (newbie) app with Google App Engine, but when I run it I find this (logs) error which I didn't understand: ``` File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1479, in __init__ self.router = self.router_class(routes) File "C:\Program Files (x86)\Google\...
Fix your routes definition with: ``` app = webapp2.WSGIApplication([(r'/', MainHandler), (r'/welcome', WelcomeHandler)], debug=True) ``` Check also [webapp2 routing extended](http://webapp-improved.appspot.com/guide/routing.html) for something more advance...
display two png images simultaneously using pylab
10,373,500
13
2012-04-29T15:47:31Z
10,373,691
19
2012-04-29T16:15:30Z
[ "python", "png", "matplotlib", "grayscale" ]
I want to open two png image files and display them side by side for visual comparison. I have this code for opening one png file (which I got from unutbu on stackoverflow.com): ``` import numpy as np import pylab import matplotlib.cm as cm import Image fname='file.png' image=Image.open(fname).convert("L") arr=np.asa...
The following works for me (you can comment/uncomment the lines in the code to change the layout of the "composite" image): ``` #!/usr/bin/env python #-*- coding:utf-8 -*- import numpy as np import pylab import matplotlib.cm as cm import Image f = pylab.figure() for n, fname in enumerate(('1.png', '2.png')): ima...
Converting a Pandas GroupBy object to DataFrame
10,373,660
96
2012-04-29T16:10:35Z
10,374,456
138
2012-04-29T17:50:33Z
[ "python", "pandas" ]
I'm starting with input data like this ``` df1 = pandas.DataFrame( { "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } ) ``` Which when printed appears as this: ``` City Name 0 Seattle Alice 1 S...
`g1` here *is* a DataFrame. It has a hierarchical index, though: ``` In [19]: type(g1) Out[19]: pandas.core.frame.DataFrame In [20]: g1.index Out[20]: MultiIndex([('Alice', 'Seattle'), ('Bob', 'Seattle'), ('Mallory', 'Portland'), ('Mallory', 'Seattle')], dtype=object) ``` Perhaps you want something like this...
Converting a Pandas GroupBy object to DataFrame
10,373,660
96
2012-04-29T16:10:35Z
32,307,259
23
2015-08-31T08:48:05Z
[ "python", "pandas" ]
I'm starting with input data like this ``` df1 = pandas.DataFrame( { "Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] , "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"] } ) ``` Which when printed appears as this: ``` City Name 0 Seattle Alice 1 S...
I want to little bit change answer by Wes, because version 0.16.2 need set `as_index=False`. If you don't set it, you get empty dataframe. [Source](http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation): > Aggregation functions will not return the groups that you are aggregating over if they are named ...
Birthday Paradox List is nonetype
10,374,256
3
2012-04-29T17:28:23Z
10,374,287
7
2012-04-29T17:30:50Z
[ "python", "birthday-paradox" ]
I'm trying to solve the Birthday Paradox with Python. I'm close but the last piece has me at a loss. I'm using random to generate a list of numbers given a range and number of items to create. That works. I then check to see if a list (generated above) has duplicates. That works. I then try to generate a given (n) of...
In line 5 you print `t` but do not return it, so that `make_bd` returns `None`. Change the line to ``` return t ```
Dynamically assigning function implementation in Python
10,374,527
4
2012-04-29T17:58:49Z
10,374,569
16
2012-04-29T18:03:24Z
[ "python", "anonymous-function", "anonymous-methods", "callable" ]
I want to assign a function implementation dynamically. Let's start with the following: ``` class Doer(object): def __init__(self): self.name = "Bob" def doSomething(self): print "%s got it done" % self.name def doItBetter(self): print "Done better" ``` In other languages we would make...
Your first approach was OK, you just have to assign the function to the class: ``` class Doer(object): def __init__(self): self.name = "Bob" def doSomething(self): print "%s got it done" % self.name def doItBetter(self): print "%s got it done better" % self.name Doer.doSomething = doItBe...
Dynamically assigning function implementation in Python
10,374,527
4
2012-04-29T17:58:49Z
10,374,643
11
2012-04-29T18:11:51Z
[ "python", "anonymous-function", "anonymous-methods", "callable" ]
I want to assign a function implementation dynamically. Let's start with the following: ``` class Doer(object): def __init__(self): self.name = "Bob" def doSomething(self): print "%s got it done" % self.name def doItBetter(self): print "Done better" ``` In other languages we would make...
yak's answer works great if you want to change something for every instance of a class. If you want to change the method only for a particular *instance* of the object, and not for the entire class, you'd need to use the `MethodType` type constructor to create a bound method: ``` from types import MethodType doer.do...
Why is "(1/6)*(66.900009-62.852596)" evaluating to zero?
10,374,645
3
2012-04-29T18:11:55Z
10,374,661
11
2012-04-29T18:13:54Z
[ "python", "xcode" ]
Tried in both Objective-C (Xcode) and Python (terminal) and `(1/6)*(66.900009-62.852596)` evaluates to zero both times. Anyone know why this is? Shouldn't it be 0.26246?
You are doing integer arithmetic on `1/6`, and the floor of `1/6` is `0`. Try `1.0/6` instead.
Matplotlib: Annotating a 3D scatter plot
10,374,930
15
2012-04-29T18:48:18Z
10,394,128
20
2012-05-01T05:58:27Z
[ "python", "matplotlib", "plot" ]
I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: [Matplotlib: How to put individual tags for a scatter plot](http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot). I've tried to use this function ...
Calculate the 2D position of the point, and use it create the annotation. If you need interactive with the figure, you can recalculate the location when mouse released. ``` import pylab from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import proj3d fig = pylab.figure() ax = fig.add_subplot(111, projec...
Matplotlib: Annotating a 3D scatter plot
10,374,930
15
2012-04-29T18:48:18Z
34,139,293
12
2015-12-07T17:12:39Z
[ "python", "matplotlib", "plot" ]
I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: [Matplotlib: How to put individual tags for a scatter plot](http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot). I've tried to use this function ...
Maybe easier via ax.text(...): ``` from matplotlib import * from mpl_toolkits.mplot3d import Axes3D m=rand(3,3) # m is an array of (x,y,z) coordinate triplets fig = pylab.figure() ax = Axes3D(fig) for i in range(len(m)): #plot each point + it's index as text above ax.scatter(m[i,0],m[i,1],m[i,2],color='b') ax.t...
Number of installations statistics for PyPI packages?
10,376,429
12
2012-04-29T22:07:30Z
10,377,100
7
2012-04-30T00:01:32Z
[ "python", "pypi" ]
I've got a couple of packages on the Python Package Index (PyPI) now. Is there any way to get hold of statistics as to how many times they have been downloaded (either manually or via `easy_install` or `pip`? Or, alternatively, how many views the main package page has received?
**UPDATE 2: it's back! There's now a "Downloads (All Versions)" just after the list of downloads (below the user-supplied docs).** announcement at <http://mail.python.org/pipermail/distutils-sig/2013-June/021344.html> - it's currently daily counts; weeks and months will be added as they become available. but, curiousl...
Number of installations statistics for PyPI packages?
10,376,429
12
2012-04-29T22:07:30Z
15,672,232
17
2013-03-28T00:37:58Z
[ "python", "pypi" ]
I've got a couple of packages on the Python Package Index (PyPI) now. Is there any way to get hold of statistics as to how many times they have been downloaded (either manually or via `easy_install` or `pip`? Or, alternatively, how many views the main package page has received?
There are at least two packages that help with this: [`pypstats`](https://pypi.python.org/pypi/pypstats/) and [`vanity`](https://pypi.python.org/pypi/vanity). Vanity is very easy to use from the command line: ``` vanity numpy ``` and you'll get a printout to your console.
accepting return values for arguments to a function
10,376,506
2
2012-04-29T22:17:55Z
10,376,519
11
2012-04-29T22:20:03Z
[ "python", "python-2.7" ]
So i am trying to use a function that returns values, but i want these values to be returned into a different function. An example of something that i need is below. ``` def returner(): x=1 y=2 z=3 return x,y,z def tester(arg1,arg2,arg3): print arg1,arg2,arg3 tester(returner()) ``` What i would l...
You want to use `*` - the splat (or star) operator: ``` tester(*returner()) ``` This is argument unpacking - it unpacks the tuple of returned values into the arguments for the function. ``` >>> def test(): ... return 1,2,3 ... >>> def test2(arg1, arg2, arg3): ... print(arg1, arg2, arg3) ... >>> test2(*test()...
Overriding special methods on an instance
10,376,604
11
2012-04-29T22:36:17Z
10,376,655
11
2012-04-29T22:42:30Z
[ "python", "metaprogramming" ]
I hope someone can answer this that has a good deep understanding of Python :) Consider the following code: ``` >>> class A(object): ... pass ... >>> def __repr__(self): ... return "A" ... >>> from types import MethodType >>> a = A() >>> a <__main__.A object at 0x00AC6990> >>> repr(a) '<__main__.A object at 0...
Python doesn't call the special methods, those with name surrounded by `__` on the instance, but only on the class, apparently to improve performance. So there's no way to override `__repr__()` directly on an instance and make it work. Instead, you need to do something like so: ``` class A(object): def __repr__(se...
Installed Python Modules - Python can't find them
10,376,647
11
2012-04-29T22:41:28Z
10,377,863
13
2012-04-30T02:30:34Z
[ "python", "numpy", "pandas" ]
This is a beginner `python` installation question. This the first time I have tried to install and call a package. I've got `pip` installed, and I tried to install two modules - `numpy` and `pandas`. In terminal, I ran the following commands: ``` sudo pip install numpy sudo pip install pandas ``` Both commands retu...
argh. you've got two pythons in your path that are the same version? don't do that. pip, easy-install, etc are associated with a particular python install and will use that python by default. so if you have a system-provided python and a system-provided easy\_install (or installed easy\_install yourself using the syst...
Multiple conditions using 'or' in numpy array
10,377,096
18
2012-04-30T00:01:03Z
10,377,148
21
2012-04-30T00:11:00Z
[ "python", "numpy" ]
So I have these conditions: > A = 0 to 10 **OR** 40 to 60 > > B = 20 to 50 and I have this code: ``` area1 = N.where((A>0) & (A<10)),1,0) area2 = N.where((B>20) & (B<50)),1,0) ``` My question is: how do I do '**OR**' condition in numpy?
If numpy overloads `&` for boolean `and` you can safely assume that `|` is boolean `or`. ``` area1 = N.where(((A>0) & (A<10)) | ((A>40) & (A<60))),1,0) ```
Multiple conditions using 'or' in numpy array
10,377,096
18
2012-04-30T00:01:03Z
10,377,160
20
2012-04-30T00:13:22Z
[ "python", "numpy" ]
So I have these conditions: > A = 0 to 10 **OR** 40 to 60 > > B = 20 to 50 and I have this code: ``` area1 = N.where((A>0) & (A<10)),1,0) area2 = N.where((B>20) & (B<50)),1,0) ``` My question is: how do I do '**OR**' condition in numpy?
There's `numpy.logical_or` <http://docs.scipy.org/doc/numpy/reference/generated/numpy.logical_or.html> numpy `logical_and` and `logical_or` are the ufuncs that you want (I think) Note that `&` is not `logical and`, it is **bitwise** `and`. This still works for you because (a>10) returns a logical array (e.g. 1's and...
How to use can_add_related in Django Admin
10,377,642
6
2012-04-30T01:47:50Z
17,348,422
8
2013-06-27T16:26:10Z
[ "python", "django", "django-admin" ]
I've read about the can\_add\_related feature here: <https://code.djangoproject.com/ticket/9071> I tried using it this way: ``` def get_form(self, request, obj=None, **kwargs): self.fields['person'].can_add_related = False return super(OperationAdmin, self).get_form(request, obj, **kwargs) ``` But this throw...
This is probably coming in late. But for other viewers reference, ``` def get_form(self, request, obj=None, **kwargs): form = super(ProductAdmin, self).get_form(request, obj, **kwargs) form.base_fields['category'].widget.can_add_related = False return form ```
How can I iterate over files in a given directory?
10,377,998
81
2012-04-30T02:58:01Z
10,378,012
119
2012-04-30T03:01:13Z
[ "python", "iterator", "directory" ]
I need to iterate through all `.asm` files of a given directory and do some actions on them. How can this be done in a efficient way?
``` for filename in os.listdir(directory): if filename.endswith(".asm") or filename.endswith(".py"): # print(os.path.join(directory, filename)) continue else: continue ```
How can I iterate over files in a given directory?
10,377,998
81
2012-04-30T02:58:01Z
10,378,046
44
2012-04-30T03:06:20Z
[ "python", "iterator", "directory" ]
I need to iterate through all `.asm` files of a given directory and do some actions on them. How can this be done in a efficient way?
You can try using `glob` module ``` import glob for filename in glob.iglob('/foobar/*.asm'): print('/foobar/%s' % filename) ```
How can I iterate over files in a given directory?
10,377,998
81
2012-04-30T02:58:01Z
30,255,302
19
2015-05-15T08:51:39Z
[ "python", "iterator", "directory" ]
I need to iterate through all `.asm` files of a given directory and do some actions on them. How can this be done in a efficient way?
This will iterate over all descendant files, not just the immediate children of the directory: ``` import os for subdir, dirs, files in os.walk(rootdir): for file in files: #print os.path.join(subdir, file) filepath = subdir + os.sep + file if filepath.endswith(".asm"): print ...
String immutability in CPython violated
10,378,083
15
2012-04-30T03:15:55Z
10,378,319
13
2012-04-30T03:58:02Z
[ "python", "string", "fuzzy" ]
This is more of an 'interesting' phenomena I encountered in a Python module that I'm trying to understand, rather than a request for help (though a solution would also be useful). ``` >>> import fuzzy >>> s = fuzzy.Soundex(4) >>> a = "apple" >>> b = a >>> sdx_a = s(a) >>> sdx_a 'A140' >>> a 'APPLE' >>> b 'APPLE' ``` ...
This bug was resolved [back in February](https://bitbucket.org/yougov/fuzzy/issue/1/soundex-modifies-input-argument); update your version. To answer your question, yes, there are several ways to modify immutable types at the C level. The security implications are unknown, and possibly even unknowable, at this point.
Deleting an Object from Collection in SQLAlchemy
10,378,468
2
2012-04-30T04:22:05Z
10,489,557
7
2012-05-07T21:41:28Z
[ "python", "mysql", "sqlalchemy" ]
I am storing a bunch of patent data in a MySQL database and interacting with it via SQLAlchemy. I have a collection inside the Patent class that represents the list of assignees (the companies that were assigned the patent): ``` assignees = relationship('Company', secondary=patent_company_table, backref='patents') ```...
a working sample script means, we can run it fully. Here's a script generated from the snippets you've given. The one thing that helps is to evaluate "assignees" as a list, since you are removing from it, it's likely you're not iterating correctly. ``` from sqlalchemy import * from sqlalchemy.orm import * from sqlalch...
Plotting directed graphs in Python in a way that show all edges separately
10,379,448
11
2012-04-30T06:33:52Z
10,419,646
14
2012-05-02T18:33:58Z
[ "python", "graph-visualization" ]
I'm using Python to simulate a process that takes place on directed graphs. I would like to produce an animation of this process. The problem that I've run into is that most Python graph visualization libraries combine pairs of directed edges into a single edge. For example, [NetworkX](http://networkx.lanl.gov) draws ...
The [Graphviz](http://www.graphviz.org/) tools appear to display distinct edges. For example, giving this: ``` digraph G { A -> B; A -> B; A -> B; B -> C; B -> A; C -> B; } ``` to `dot` produces: ![example graph](http://i.imgur.com/A7dnv.gif) Graphviz's input language is pretty simple so you can gener...
Split a string of words by uppercase words
10,380,065
3
2012-04-30T07:36:06Z
10,380,165
8
2012-04-30T07:44:00Z
[ "python", "regex", "string" ]
I have a set of names where the surname is in capital and first and middle names are normal, e.g. ``` OBAMA Barack DEL MONTE Alfredo ``` I want to split these in ``` "OBAMA", "Barack" "DEL MONTE", "Alfredo" ``` What is the pythonic way to achieve this?
``` >>> import itertools >>> [ ... ' '.join(items) ... for _, items in itertools.groupby('DEL MONTE Alfredo'.split(), str.isupper) ... ] ['DEL MONTE', 'Alfredo'] ```
get python dictionary from string containing key value pairs
10,380,992
5
2012-04-30T09:03:29Z
10,381,057
27
2012-04-30T09:07:56Z
[ "python", "string", "dictionary" ]
i have a python string in the format: ``` str = "name: srek age :24 description: blah blah" ``` is there any way to convert it to dictionary that looks like ``` {'name': 'srek', 'age': '24', 'description': 'blah blah'} ``` where each entries are (key,value) pairs taken from string. I tried splitting the string to l...
``` >>> r = "name: srek age :24 description: blah blah" >>> import re >>> regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") >>> d = dict(regex.findall(r)) >>> d {'age': '24', 'name': 'srek', 'description': 'blah blah'} ``` **Explanation:** ``` \b # Start at a word boundary (\w+) # Match an...
How to set ForeignKey in CreateView?
10,382,838
26
2012-04-30T11:21:16Z
10,565,744
10
2012-05-12T17:03:27Z
[ "python", "django", "django-class-based-views" ]
I have a model: ``` class Article(models.Model): text = models.CharField() author = models.ForeignKey(User) ``` How do I write class-based view that creates a new model instance and sets `author` foreign key to `request.user`?
I solved this by overriding `form_valid` method. Here is verbose style to clarify things: ``` class CreateArticle(CreateView): model = Article def form_valid(self, form): article = form.save(commit=False) article.author = self.request.user #article.save() # This is redundant, see comm...
Restricting attribute type with metaclass
10,382,995
4
2012-04-30T11:33:14Z
10,383,793
8
2012-04-30T12:34:19Z
[ "python", "metaclass" ]
I'm trying to get into metaclass programming in Python and I'd like to know how to restrict attribute type with metaclass. It's quite easy with the descriptors, but what about metaclasses? Here is short example: ``` >>> class Image(Object): ... height = 0 ... width = 0 ... path = '/tmp' .....
Just override `__setattr__` in the metaclass and check default type for every attribute during initialization: ``` >>> class Meta(type): def __new__(meta, name, bases, dict): def _check(self, attr, value): if attr in self.defaults: if not isinstance(value, self.defaults[attr]): ...
Fuzzy String Comparison
10,383,044
23
2012-04-30T11:37:20Z
10,383,524
46
2012-04-30T12:13:28Z
[ "python", "nlp", "fuzzy-comparison" ]
What I am striving to complete is a program which reads in a file and will compare each sentence according to the original sentence. The sentence which is a perfect match to the original will receive a score of 1 and a sentence which is the total opposite will receive a 0. All other fuzzy sentences will receive a grade...
There is a module in the standard library (called [`difflib`](http://docs.python.org/library/difflib.html)) that can compare strings and return a score based on their similarity. The [`SequenceMatcher`](http://docs.python.org/library/difflib.html#sequencematcher-objects) class should do what you are after. **EDIT:** S...
Fuzzy String Comparison
10,383,044
23
2012-04-30T11:37:20Z
28,467,760
49
2015-02-12T01:29:16Z
[ "python", "nlp", "fuzzy-comparison" ]
What I am striving to complete is a program which reads in a file and will compare each sentence according to the original sentence. The sentence which is a perfect match to the original will receive a score of 1 and a sentence which is the total opposite will receive a 0. All other fuzzy sentences will receive a grade...
There is a package called [`fuzzywuzzy`](https://github.com/seatgeek/fuzzywuzzy). Install via pip: ``` pip install fuzzywuzzy ``` Simple usage: ``` >>> from fuzzywuzzy import fuzz >>> fuzz.ratio("this is a test", "this is a test!") 96 ``` The package is built on top of `difflib`. Why not just use that, you ask?...
get all the links of HTML using lxml
10,383,383
3
2012-04-30T12:02:52Z
10,383,452
8
2012-04-30T12:08:44Z
[ "python", "lxml" ]
I want to find out all the urls and its name from a html page using lxml. I can parse the url and can find out this thing but is there any easy way from which I can find all the url links using lxml?
``` from lxml.html import parse dom = parse('http://www.google.com/').getroot() links = dom.cssselect('a') ```
Map different URLs to same view
10,383,763
9
2012-04-30T12:32:07Z
10,383,836
18
2012-04-30T12:37:47Z
[ "python", "pyramid" ]
It seems trivial enough but I can't find a valid answer to this problem. Suppose I have two different links '/' and '/home' and I want them to point to the same view. (This means whether user opens xyz.com or xyz.com/home, same page will be displayed). In pyramid I tried ``` config.add_route('home','/') config.add_r...
You need to add them under different route names (they must be unique per application): ``` config.add_route('home','/') config.add_route('home1','home/') ``` and then configure the same view for both: ``` config.add_view(yourview, route_name='home') config.add_view(yourview, route_name='home1') ``` or, in case of ...
Getting inverse (1/x) elements of a numpy array
10,384,757
6
2012-04-30T13:46:19Z
10,384,785
7
2012-04-30T13:48:22Z
[ "python", "numpy", "division" ]
My question is very simple, suppose that I have an array like ``` array = np.array([1, 2, 3, 4]) ``` and I'd like to get an array like ``` [1, 0.5, 0.3333333, 0.25] ``` However, if you write something like ``` 1/array ``` or ``` np.divide(1.0, array) ``` it won't work. The only way I've found so far is to writ...
`1 / array` makes an integer division and returns `array([1, 0, 0, 0])`. `1. / array` will cast the array to float and do the trick: ``` >>> array = np.array([1, 2, 3, 4]) >>> 1. / array array([ 1. , 0.5 , 0.33333333, 0.25 ]) ```
Python TypeError: expected a character buffer object, personal misunderstanding
10,385,419
3
2012-04-30T14:31:25Z
10,385,520
11
2012-04-30T14:39:45Z
[ "python", "unicode" ]
i was stuck at this error during a long time : ``` TypeError: expected a character buffer object ``` i just understand what i has misunderstood, it is something about a difference between an unicode string and a 'simple' string, i have tried to use the above code with a "normal" string, while i had to pass a unicode...
The issue is that the `translate` method of a bytestring is different from the `translate` method of a unicode string. Here's the docstring of the non-unicode version: > S.translate(table [,deletechars]) -> string > > Return a copy of the string S, where all characters occurring > in the optional argument deletechars ...
list match in python: get indices of a sub-list in a larger list
10,385,647
5
2012-04-30T14:49:24Z
10,385,670
7
2012-04-30T14:50:49Z
[ "python", "list", "set", "match", "indices" ]
For two lists, ``` a = [1, 2, 9, 3, 8, ...] (no duplicate values in a, but a is very big) b = [1, 9, 1,...] (set(b) is a subset of set(a), 1<<len(b)<<len(a)) indices = get_indices_of_a(a, b) ``` how to let `get_indices_of_a` return `indices = [0, 2, 0,...]` with `array(a)[indices] = b`? Is there a faster...
Presuming we are working with smaller lists, this is as easy as: ``` >>> a = [1, 2, 9, 3, 8] >>> b = [1, 9, 1] >>> [a.index(item) for item in b] [0, 2, 0] ``` On larger lists, this will become quite expensive. (If there are duplicates, the first occurrence will always be the one referenced in the resulting list, i...
list match in python: get indices of a sub-list in a larger list
10,385,647
5
2012-04-30T14:49:24Z
10,385,786
10
2012-04-30T14:56:34Z
[ "python", "list", "set", "match", "indices" ]
For two lists, ``` a = [1, 2, 9, 3, 8, ...] (no duplicate values in a, but a is very big) b = [1, 9, 1,...] (set(b) is a subset of set(a), 1<<len(b)<<len(a)) indices = get_indices_of_a(a, b) ``` how to let `get_indices_of_a` return `indices = [0, 2, 0,...]` with `array(a)[indices] = b`? Is there a faster...
A fast method (when `a` is a large list) would be using a dict to map values in `a` to indices: ``` >>> index_dict = dict((value, idx) for idx,value in enumerate(a)) >>> [index_dict[x] for x in b] [0, 2, 0] ``` This will take linear time in the average case, compared to using `a.index` which would take quadratic time...
Python: self.__class__ vs. type(self)
10,386,166
34
2012-04-30T15:22:50Z
10,386,227
21
2012-04-30T15:26:26Z
[ "python" ]
I'm wondering if there is a difference between ``` class Test(object): def __init__(self): print self.__class__.__name__ ``` and ``` class Test(object): def __init__(self): print type(self).__name__ ``` ? Is there a reason to prefer one or the other? (In my use case I want to use it to det...
``` >>> class Test(object): pass >>> t = Test() >>> type(t) is t.__class__ True >>> type(t) __main__.Test ``` So those two are the same. I would use `self.__class__` since it's more obvious what it is. However, `type(t)` won't work for old-style classes since the type of an instance of an old-style class is `instance...
Can't get Flask running using Passenger WSGI on Dreamhost shared hosting
10,386,520
7
2012-04-30T15:46:22Z
10,389,257
16
2012-04-30T19:14:15Z
[ "python", "passenger", "flask", "shared", "dreamhost" ]
I'm trying to get a Flask "hello world" application working on a Dreamhost shared server, following the [instructions on their wiki](http://wiki.dreamhost.com/Flask), but I'm not having any luck. My Flask application is the "hello world" one from the [Flask quickstart guide](http://flask.pocoo.org/docs/quickstart/): ...
Does answering my own question mean I'm talking to myself? Anyway - I seem to have fixed it. Rather than find a nice helpful error message, I went through all the steps again one at a time, and it turns out it was an import error in the `passenger_wsgi.py` file. As the app is in the `mysite` subdirectory, the line: `...
Why can you add an attribute to an instance of a subclass of object, but not to an instance of object?
10,387,190
4
2012-04-30T16:34:18Z
10,387,270
9
2012-04-30T16:38:48Z
[ "python", "object", "attributes" ]
Why does this raise an error: ``` o = object() o.i = 1 ``` But this does not: ``` class A(object): pass a = A() a.i = 1 ``` ?
Because built-in types don't have dictionaries associated with them to hold added attributes: ``` >>> o = object() >>> dir(o) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '...
Follow up: Execute .sql files from python
10,387,892
4
2012-04-30T17:28:06Z
10,520,364
11
2012-05-09T16:36:45Z
[ "python", "sql", "sql-server", "pyodbc", "python-db-api" ]
Over a year ago someone asked this question: [Execute .sql files that are used to run in SQL Management Studio in python](http://stackoverflow.com/questions/5174269/execute-sql-files-that-are-used-to-run-in-sql-management-studio-in-python). I am writing a script in python that connects to a SQL server and creates and ...
I found it's actually faster to read the file in python and execute in batches using pyodbc than it is to use the SQLCMD utility externally (and I don't have to install SQLCMD on every computer I run the scripts on!). Here is the code I used (because pyodbc doesn't seem to have an `executescript()` method): ``` with ...
CSRF verification failed. Request aborted
10,388,033
9
2012-04-30T17:38:50Z
10,388,110
11
2012-04-30T17:44:52Z
[ "python", "django", "csrf", "requestcontext" ]
I try to build a very simple website where one can add data into sqlite3 database. I have a POST form with two text input. index.html: ``` {% if top_list %} <ul> <b><pre>Name Total steps</pre></b> {% for t in top_list %} <pre>{{t.name}} {{t.total_steps}}</pre> {% endfor %} </ul> {% ...
Use the [`render` shortcut](http://django.me/render) which adds `RequestContext` automatically. ``` from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from steps_count.models import Top_List from steps_count.forms import Top_List_Form def index(request): if request.metho...
Solving Puzzle in Python
10,388,060
18
2012-04-30T17:40:51Z
10,389,135
8
2012-04-30T19:06:06Z
[ "python", "permutation", "combinations", "puzzle", "itertools" ]
I got one puzzle and I want to solve it using Python. > Puzzle: > > A merchant has a 40 kg weight which he used in his shop. Once, it fell > from his hands and was broken into 4 pieces. But surprisingly, now he > can weigh any weight between 1 kg to 40 kg with the combination of > these 4 pieces. > > So question is, w...
Here is a brute-force itertools solution: ``` import itertools as it def merchant_puzzle(weight, pieces): full = range(1, weight+1) all_nums = set(full) comb = [x for x in it.combinations(full, pieces) if sum(x)==weight] funcs = (lambda x: 0, lambda x: x, lambda x: -x) for c in comb: sums ...
Solving Puzzle in Python
10,388,060
18
2012-04-30T17:40:51Z
10,389,181
22
2012-04-30T19:08:24Z
[ "python", "permutation", "combinations", "puzzle", "itertools" ]
I got one puzzle and I want to solve it using Python. > Puzzle: > > A merchant has a 40 kg weight which he used in his shop. Once, it fell > from his hands and was broken into 4 pieces. But surprisingly, now he > can weigh any weight between 1 kg to 40 kg with the combination of > these 4 pieces. > > So question is, w...
**Earlier walk-through anwswer:** We know `a*A + b*B + c*C + d*D = x` for all `x` between 0 and 40, and `a, b, c, d` are confined to `-1, 0, 1`. Clearly `A + B + C + D = 40`. The next case is `x = 39`, so clearly the smallest move is to remove an element (it is the only possible move that could result in successfully ...
Static classes in Python
10,388,127
15
2012-04-30T17:46:30Z
10,388,155
22
2012-04-30T17:48:36Z
[ "python", "class", "static", "instance", "class-method" ]
I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class. I'm writing a program in Python. Is it a bad style, if I use `@classmethod` for every method of a class?
Generally, usage like this is better done by just using functions in a module, without a class at all.
Static classes in Python
10,388,127
15
2012-04-30T17:46:30Z
10,388,168
12
2012-04-30T17:49:28Z
[ "python", "class", "static", "instance", "class-method" ]
I once read (I think on a page from Microsoft) that it's a good way to use static classes, when you don't NEED two or more instances of a class. I'm writing a program in Python. Is it a bad style, if I use `@classmethod` for every method of a class?
It's terrible style, unless you actually need to access the class. > A static method [...] does not translate to a Python classmethod. Oh sure, it results in more or less the same effect, but the goal of a classmethod is actually to do something that's usually not even possible [...] (like inheriting a non-default con...
Matplotlib different size subplots
10,388,462
66
2012-04-30T18:09:02Z
10,397,528
14
2012-05-01T12:17:00Z
[ "python", "plot", "matplotlib", "figure" ]
I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using `GridSpec` and the `colspan` argument but I would like to do this using `figure` so I can save to PDF. I can adjust the first figure using the `figsize` argument in the constr...
I used `pyplot`'s `axes` object to manually adjust the sizes without using `GridSpec`: ``` import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 10, 0.2) y = np.sin(x) # definitions for the axes left, width = 0.07, 0.65 bottom, height = 0.1, .8 bottom_h = left_h = left+width+0.02 rect_cones = [left, bo...
Matplotlib different size subplots
10,388,462
66
2012-04-30T18:09:02Z
10,411,424
96
2012-05-02T09:53:35Z
[ "python", "plot", "matplotlib", "figure" ]
I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using `GridSpec` and the `colspan` argument but I would like to do this using `figure` so I can save to PDF. I can adjust the first figure using the `figsize` argument in the constr...
You can use [`gridspec`](http://matplotlib.org/users/gridspec.html) and `figure`: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec # generate some data x = np.arange(0, 10, 0.2) y = np.sin(x) # plot it fig = plt.figure(figsize=(8, 6)) gs = gridspec.GridSpec(1, 2, width_ratios=...
Matplotlib different size subplots
10,388,462
66
2012-04-30T18:09:02Z
15,884,335
15
2013-04-08T16:31:59Z
[ "python", "plot", "matplotlib", "figure" ]
I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using `GridSpec` and the `colspan` argument but I would like to do this using `figure` so I can save to PDF. I can adjust the first figure using the `figsize` argument in the constr...
Probably the simplest way is using `subplot2grid`, described in [Customizing Location of Subplot Using GridSpec](http://matplotlib.org/users/gridspec.html). ``` ax = plt.subplot2grid((2, 2), (0, 0)) ``` is equal to ``` import matplotlib.gridspec as gridspec gs = gridspec.GridSpec(2, 2) ax = plt.subplot(gs[0, 0]) ```...
Matplotlib different size subplots
10,388,462
66
2012-04-30T18:09:02Z
35,881,382
27
2016-03-09T01:37:23Z
[ "python", "plot", "matplotlib", "figure" ]
I need to add two subplots to a figure. One subplot needs to be about three times as wide as the second (same height). I accomplished this using `GridSpec` and the `colspan` argument but I would like to do this using `figure` so I can save to PDF. I can adjust the first figure using the `figsize` argument in the constr...
Another way is to use the `subplots` function and pass the width ratio with `gridspec_kw`: ``` import numpy as np import matplotlib.pyplot as plt # generate some data x = np.arange(0, 10, 0.2) y = np.sin(x) # plot it f, (a0, a1) = plt.subplots(1,2, gridspec_kw = {'width_ratios':[3, 1]}) a0.plot(x,y) a1.plot(y,x) f...
python SyntaxError with dict(1=...), but {1:...} works
10,390,606
9
2012-04-30T21:09:13Z
10,390,625
15
2012-04-30T21:10:44Z
[ "python", "dictionary", "notation" ]
Python seems to have an inconsistency in what kind of keys it will accept for dicts. Or, put another way, it allows certain kinds of keys in one way of defining dicts, but not in others: ``` >>> d = {1:"one",2:2} >>> d[1] 'one' >>> e = dict(1="one",2=2) File "<stdin>", line 1 SyntaxError: keyword can't be an expre...
This is not a `dict` issue, but an artifact of Python syntax: keyword arguments must be valid identifiers, and `1` and `2` are not. When you want to use anything that is not a string following Python identifier rules as a key, use the `{}` syntax. The constructor keyword argument syntax is just there for convenience i...
python SyntaxError with dict(1=...), but {1:...} works
10,390,606
9
2012-04-30T21:09:13Z
10,390,632
9
2012-04-30T21:11:05Z
[ "python", "dictionary", "notation" ]
Python seems to have an inconsistency in what kind of keys it will accept for dicts. Or, put another way, it allows certain kinds of keys in one way of defining dicts, but not in others: ``` >>> d = {1:"one",2:2} >>> d[1] 'one' >>> e = dict(1="one",2=2) File "<stdin>", line 1 SyntaxError: keyword can't be an expre...
`dict` is a function call, and function keywords must be identifiers.
How to add extra key-value pairs to a dict() constructed with a generator argument?
10,390,899
8
2012-04-30T21:35:05Z
10,390,954
16
2012-04-30T21:39:55Z
[ "python", "syntax" ]
One can create dictionaries using generators ([PEP-289](http://www.python.org/dev/peps/pep-0289/)): ``` dict((h,h*2) for h in range(5)) #{0: 0, 1: 2, 2: 4, 3: 6, 4: 8} ``` Is it syntactically possible to add some extra key-value pairs in the same dict() call? The following syntax is incorrect but better explains my q...
Constructor: ``` dict(iterableOfKeyValuePairs, **dictOfKeyValuePairs) ``` Example: ``` >>> dict(((h,h*2) for h in range(5)), foo='foo', **{'bar':'bar'}) {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 'foo': 'foo', 'bar': 'bar'} ``` (Note that you will need to parenthesize generator expressions if not the sole argument.)