title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to repeat last command in python interpreter shell?
4,289,937
60
2010-11-27T03:09:39Z
17,552,700
13
2013-07-09T15:51:04Z
[ "python", "shell", "virtualenv", "interpreter", "python-idle" ]
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters. ``` (ve)[kakarukeys@localhost ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more i...
You didn't specific which interpreter. Assuming you are using IDLE. From IDLE documentation: Command history: ``` Alt-p retrieves previous command matching what you have typed. Alt-n retrieves next. (These are Control-p, Control-n on the Mac) Return while cursor is on a previous command retrieves that command. ...
How to repeat last command in python interpreter shell?
4,289,937
60
2010-11-27T03:09:39Z
17,800,063
25
2013-07-23T01:24:13Z
[ "python", "shell", "virtualenv", "interpreter", "python-idle" ]
How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don't work. They produce nonsensical characters. ``` (ve)[kakarukeys@localhost ve]$ python Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) [GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2 Type "help", "copyright", "credits" or "license" for more i...
Alt + p for previous command from histroy, Alt + n for next command from history. This is default configure, and you can change these key shortcut at your preference from Options -> Configure IDLE.
Fitting data to distributions?
4,290,081
24
2010-11-27T04:10:10Z
4,290,214
33
2010-11-27T05:05:32Z
[ "python", "statistics", "scipy" ]
I am not a statistician (more of a researchy web developer) but I've been hearing a lot about [scipy](http://www.scipy.org/) and [R](http://www.r-project.org/) these days. So out of curiosity I wanted to ask this question (though it might sound silly to the experts around here) because I am not sure of the advances in ...
This is a complicated question, and there are no perfect answers. I'll try to give you an overview of the major concepts, and point you in the direction of some useful reading on the topic. Assume that you a one dimensional set of data, and you have a finite set of probability distribution functions that you think the...
Fitting data to distributions?
4,290,081
24
2010-11-27T04:10:10Z
4,292,243
10
2010-11-27T15:04:35Z
[ "python", "statistics", "scipy" ]
I am not a statistician (more of a researchy web developer) but I've been hearing a lot about [scipy](http://www.scipy.org/) and [R](http://www.r-project.org/) these days. So out of curiosity I wanted to ask this question (though it might sound silly to the experts around here) because I am not sure of the advances in ...
Take a look at `fitdistrplus` (<http://cran.r-project.org/web/packages/fitdistrplus/index.html>). A couple of quick things to note: * Try the function `descdist`, which provides a plot of skew vs. kurtosis of the data and also shows some common distributions. * `fitdist` allows you to fit any distributions you can de...
Why can't I change another modules variable in python?
4,290,178
4
2010-11-27T04:47:40Z
4,290,197
7
2010-11-27T04:59:37Z
[ "python", "variables", "import", "circular-dependency" ]
I'm trying to allow a second module to modify the variables of the first in a circular import, but it doesn't seem to work. I have 2 questions: 1) Why doesn't this work / what is the reasoning for this from a language development perspective and 2) are there any easy solutions that allow me to do the same thing perhap...
What's happening is that when `b.py` tries to `import a`, there isn't an entry for it in `sys.modules` because the entry is under `__main__`. This causes the import mechanisms to re-import the module and place it under the name `a`. So now there is an `a` module and an entirely unrelated `__main__` module. Changing `b....
How to write bytes to a file in Python 3 without knowing the encoding?
4,290,716
17
2010-11-27T08:17:45Z
4,290,730
24
2010-11-27T08:22:12Z
[ "python", "io", "python-3.x" ]
In Python 2.x with 'file-like' object: ``` sys.stdout.write(bytes_) tempfile.TemporaryFile().write(bytes_) open('filename', 'wb').write(bytes_) StringIO().write(bytes_) ``` How to do the same in Python 3? How to write equivalent of this Python 2.x code: ``` def write(file_, bytes_): file_.write(bytes_) ``` Not...
It's a matter of using APIs that operate on bytes, rather than strings. ``` sys.stdout.buffer.write(bytes_) ``` As the [docs](http://docs.python.org/py3k/library/sys.html#sys.stdin) explain, you can also `detach` the streams, so they're binary by default. This accesses the underlying byte buffer. ``` tempfile.Tempo...
Edit the values in a list of dictionaries?
4,291,236
8
2010-11-27T10:48:02Z
4,291,255
14
2010-11-27T10:53:58Z
[ "python", "list", "dictionary" ]
``` my_dicts = [ { 'key1' : 'value1', 'key2' : 'value2' }, { 'key1' : 'value1', 'key2' : 'value2' }, { 'key1' : 'value1', 'key2' : 'value2' }] ``` What would be the most efficient way to replace all instances of 'value2' with 'value3' ?
I did not do any timings, but you probably can't get much better than ``` for d in my_dicts: d.update((k, "value3") for k, v in d.iteritems() if v == "value2") ```
Dynamic forms in django-admin
4,291,516
8
2010-11-27T11:57:12Z
4,292,564
8
2010-11-27T16:15:06Z
[ "python", "django", "django-admin", "django-forms" ]
I want to make admin add-form dynamic. I want to add few formfields depending on setting in related object. I have something like this: ``` class ClassifiedsAdminForm(forms.ModelForm): def __init__(self,*args, **kwargs): super(ClassifiedsAdminForm, self).__init__(*args, **kwargs) self.fields['testujemy'...
I've managed to do it using type(). ``` class ClassifiedAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): adminform = ClassifiedsAdminForm() fields = adminform.getNewFields() form = type('ClassifiedsAdminForm', (forms.ModelForm,), fields) return form ``` Hope it will help ...
How can you remove the new line characters in python?
4,292,113
3
2010-11-27T14:28:52Z
4,292,123
11
2010-11-27T14:30:43Z
[ "python", "newline" ]
I am writing a vcf parser and I have the file open but now I need to parse their first name. The file shows "FN:John Smith;;;\n\r" I want to take out the \n and \r. Can anybody help me?
Use the [`rstrip`](http://docs.python.org/library/stdtypes.html#str.rstrip) function: ``` s = s.rstrip() ``` This will remove all whitespace from the end of your string.
python: how binding works
4,292,304
8
2010-11-27T15:14:39Z
4,292,348
7
2010-11-27T15:25:11Z
[ "python" ]
I am trying to understand, how exactly variable binding in python works. Let's look at this: ``` def foo(x): def bar(): print y return bar y = 5 bar = foo(2) bar() ``` This prints 5 which seems reasonable to me. ``` def foo(x): def bar(): print x return bar x = 5 bar = foo(2) bar() `...
The issue that you are alluding to is one of lexical vs dynamic scoping of variables in python. To be explicit, python defines the following four scopes. 1. The innermost scope, which is searched first, contains the local names 2. The scopes of any enclosing functions, which are searched starting with the nearest encl...
In emacs python-mode customize multi-line statement indentation
4,293,074
16
2010-11-27T18:00:12Z
4,339,241
11
2010-12-02T19:56:59Z
[ "python", "emacs" ]
I am using the python-mode shipped with emacs 23. I want to customize the auto-indentation of mult-line statements. For example currently emacs prefers the following ``` my_var = [ 'val1', 'val2', 'val3', ] ``` I would prefer ``` my_var = [ 'val1', 'val2', 'val3', ] ``` Also, when creati...
Something like this, perhaps? ``` (defadvice python-calculate-indentation (around outdent-closing-brackets) "Handle lines beginning with a closing bracket and indent them so that they line up with the line containing the corresponding opening bracket." (save-excursion (beginning-of-line) (let ((syntax (syn...
How to add custom parameters to an URL query string with Python?
4,293,460
20
2010-11-27T19:26:38Z
4,293,503
9
2010-11-27T19:36:03Z
[ "python" ]
I need to add custom parameters to an URL query string using Python Example: This is the URL that the browser is fetching (GET): ``` /scr.cgi?q=1&ln=0 ``` then some python commands are executed, and as a result I need to set following URL in the browser: ``` /scr.cgi?q=1&ln=0&SOMESTRING=1 ``` Is there some standar...
Use [`urlsplit()`](http://docs.python.org/library/urlparse.html#urlparse.urlsplit) to extract the query string, [`parse_qsl()`](http://docs.python.org/library/urlparse.html#urlparse.parse_qsl) to parse it (or `parse_qs()` if you don't care about argument order), add the new argument, [`urlencode()`](http://docs.python....
How to add custom parameters to an URL query string with Python?
4,293,460
20
2010-11-27T19:26:38Z
12,897,375
54
2012-10-15T14:05:38Z
[ "python" ]
I need to add custom parameters to an URL query string using Python Example: This is the URL that the browser is fetching (GET): ``` /scr.cgi?q=1&ln=0 ``` then some python commands are executed, and as a result I need to set following URL in the browser: ``` /scr.cgi?q=1&ln=0&SOMESTRING=1 ``` Is there some standar...
You can use [`urlsplit()`](http://docs.python.org/library/urlparse.html#urlparse.urlsplit) and [`urlunsplit()`](http://docs.python.org/library/urlparse.html#urlparse.urlunsplit) to break apart and rebuild a URL, then use [`urlencode()`](http://docs.python.org/library/urllib.html#urllib.urlencode) on the parsed query st...
How can I store an array of strings in a Django model?
4,294,039
12
2010-11-27T21:36:10Z
4,294,050
7
2010-11-27T21:39:21Z
[ "python", "django", "django-models" ]
I am building a Django data model and I want to be able to store an array of strings in one of the variables; how can I do that? e.g. ``` class myClass(models.Model): title = models.CharField(max_length=50) stringArr = models.??? ``` Thanks for the help.
Make another model that holds a string with an optional order, give it a `ForeignKey` back to `myClass`, and store your array in there.
How can I store an array of strings in a Django model?
4,294,039
12
2010-11-27T21:36:10Z
4,294,199
9
2010-11-27T22:13:52Z
[ "python", "django", "django-models" ]
I am building a Django data model and I want to be able to store an array of strings in one of the variables; how can I do that? e.g. ``` class myClass(models.Model): title = models.CharField(max_length=50) stringArr = models.??? ``` Thanks for the help.
You can use some serialization mechanism like JSON. There's a snippet with field definition that could be of some use to you: <http://djangosnippets.org/snippets/1478/> (take a look at the code in the last comment) With such field you can seamlessly put strings into a list and assign them to such field. The field abs...
Decreasing for loops in Python impossible?
4,294,082
36
2010-11-27T21:46:02Z
4,294,103
87
2010-11-27T21:48:30Z
[ "python", "loops", "for-loop" ]
I could be wrong (just let me know and I'll delete the question) but it seems python won't respond to ``` for n in range(6,0): print n ``` I tried using xrange and it didn't work either. How can I implement that?
``` for n in range(6,0,-1): print n # prints [6, 5, 4, 3, 2, 1] ```
Decreasing for loops in Python impossible?
4,294,082
36
2010-11-27T21:46:02Z
8,866,968
20
2012-01-15T01:53:16Z
[ "python", "loops", "for-loop" ]
I could be wrong (just let me know and I'll delete the question) but it seems python won't respond to ``` for n in range(6,0): print n ``` I tried using xrange and it didn't work either. How can I implement that?
This is very late, but I just wanted to add that there is a more elegant way: using `reversed` ``` for i in reversed(range(10)): print i ``` gives: ``` 4 3 2 1 0 ```
md5 from pil object
4,294,317
3
2010-11-27T22:43:29Z
5,359,301
8
2011-03-19T01:07:33Z
[ "python", "md5", "python-imaging-library" ]
how i can get md5 of the pil object without saving to file ? ``` imq.save('out.png') hash = hashlib.md5(open('out.png','rb').read()).hexdigest() ```
Actually there is simpler solution: ``` hashlib.md5(img.tostring()).hexdigest() ```
Python Multidimensional Arrays - most efficient way to count number of non-zero entries
4,294,482
5
2010-11-27T23:25:45Z
4,294,490
11
2010-11-27T23:28:37Z
[ "python", "arrays", "multidimensional-array" ]
Hi there on a Saturday Fun Night, I am getting around in python and I am quite enjoying it. Assume I have a python array: ``` x = [1, 0, 0, 1, 3] ``` What is the fastest way to count all non zero elements in the list (ans: 3) ? Also I would like to do it **without** for loops if possible - the most succint and ters...
For the single-dimensional case: ``` sum(1 for i in x if i) ``` For the multi-dimensional case, you can either nest: ``` sum(sum(1 for i in row if i) for row in rows) ``` or do it all within the one construct: ``` sum(1 for row in rows for i in row if i) ```
Python file.write() taking two tries?
4,294,781
2
2010-11-28T00:59:32Z
4,294,796
10
2010-11-28T01:03:11Z
[ "python", "file-io" ]
not sure how to explain this, any help will be appreciated! ``` Python 2.6.6 (r266:84292, Sep 15 2010, 16:22:56) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib2, pynotify, tempfile, os >>> opener = urllib2.build_opener() >>> page = opener.open('http://im...
If you open the `thumb` file, you'll see that there's one whole copy and a partial copy of the data that you are writing in it. flush the file instead of writing a second time. ``` temp.flush() ``` The file wasn't writing the first time because the contents aren't large enough to fill the buffer. The second write ov...
Python - Getting all images from an html file
4,295,139
7
2010-11-28T03:16:21Z
4,295,154
9
2010-11-28T03:21:41Z
[ "python", "image", "urllib" ]
Can someone help me parse a html file to get the links for all the images in the file in python? Preferably with out a 3rd party module... Thanks!
You can use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/). I know you said *without* a 3rd party module. However, this is an ideal tool for parsing HTML. ``` import urllib2 from BeautifulSoup import BeautifulSoup page = BeautifulSoup(urllib2.urlopen("http://www.url.com")) page.findAll('img') ```
Python - Getting all images from an html file
4,295,139
7
2010-11-28T03:16:21Z
4,295,213
8
2010-11-28T03:38:21Z
[ "python", "image", "urllib" ]
Can someone help me parse a html file to get the links for all the images in the file in python? Preferably with out a 3rd party module... Thanks!
only using PSL ``` from html.parser import HTMLParser class MyParse(HTMLParser): def handle_starttag(self, tag, attrs): if tag=="img": print(dict(attrs)["src"]) h=MyParse() page=open("index.html").read() h.feed(page) ```
Is there a tool in Python to create text tables like Powershell?
4,295,434
8
2010-11-28T04:50:47Z
12,273,842
13
2012-09-05T02:45:43Z
[ "python", "console" ]
Whenever PowerShell displays its objects, it formats them in a nice pretty manner in the monospaced console, e.g.: ``` > ps Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 101 5 1284 3656 32 0.03 3...
I think python [texttable](http://foutaise.org/code/texttable/) module does exactly what you were looking for. [For further information.](https://oneau.wordpress.com/2010/05/30/simple-formatted-tables-in-python-with-texttable/)
Understanding the difference between __getattr__ and __getattribute__
4,295,678
91
2010-11-28T06:23:07Z
4,295,743
149
2010-11-28T06:55:37Z
[ "python", "oop", "encapsulation", "getattr", "getattribute" ]
I am trying to understand the difference between `__getattr__` and `__getattribute__`, however, I am failing at it. Stack Overflow question *[Difference between **getattr** vs **getattribute**](http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute-in-python)* says, > `__getattribute__`...
### Some basics first: With objects, you need to deal with its attributes. Ordinarily we do `instance.attribute` ### Sometimes we need more control (when we do not know the name of the attribute in advance) `instance.attribute` would become `getattr(instance, attribute_name)` Using this model, we can get the attrib...
Understanding the difference between __getattr__ and __getattribute__
4,295,678
91
2010-11-28T06:23:07Z
4,295,757
56
2010-11-28T07:00:31Z
[ "python", "oop", "encapsulation", "getattr", "getattribute" ]
I am trying to understand the difference between `__getattr__` and `__getattribute__`, however, I am failing at it. Stack Overflow question *[Difference between **getattr** vs **getattribute**](http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute-in-python)* says, > `__getattribute__`...
`__getattribute__` is called whenever an attribute access occurs. ``` class Foo(object): def __init__(self, a): self.a = 1 def __getattribute__(self, attr): try: return self.__dict__[attr] except KeyError: return 'default' f = Foo(1) f.a ``` This will cause inf...
Understanding the difference between __getattr__ and __getattribute__
4,295,678
91
2010-11-28T06:23:07Z
4,295,821
36
2010-11-28T07:35:08Z
[ "python", "oop", "encapsulation", "getattr", "getattribute" ]
I am trying to understand the difference between `__getattr__` and `__getattribute__`, however, I am failing at it. Stack Overflow question *[Difference between **getattr** vs **getattribute**](http://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute-in-python)* says, > `__getattribute__`...
I think the other answers have done a great job of explaining the difference between `__getattr__` and `__getattribute__`, but one thing that might not be clear is why you would want to use `__getattribute__`. The cool thing about `__getattribute__` is that it essentially allows you to overload the dot when accessing a...
How to improve performance of this code?
4,295,799
29
2010-11-28T07:27:43Z
4,296,097
34
2010-11-28T09:03:26Z
[ "python", "performance", "optimization", "time-complexity" ]
Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in python). The example run in the bottom of the code takes a long time to be solved in my machine: ``` dumrat@dumrat:~/programming/p...
I've been tripped up by this before too. The bottleneck here is actually `if neighbor in closedlist`. The `in` statement is so easy to use, you forget that it's linear search, and when you're doing linear searches on lists, it can add up fast. What you can do is convert closedlist into a `set` object. This keeps hashe...
How to improve performance of this code?
4,295,799
29
2010-11-28T07:27:43Z
4,297,680
9
2010-11-28T16:14:02Z
[ "python", "performance", "optimization", "time-complexity" ]
Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in python). The example run in the bottom of the code takes a long time to be solved in my machine: ``` dumrat@dumrat:~/programming/p...
tkerwin is correct that you should be using a set for closedlist, which speeds things up a lot, but it is still kind of slow for 4 camels on each side. The next problem is that you are allowing a lot of solutions that aren't possible because you are allowing fCamels to go backwards and bCamels to go forward. To fix thi...
How to improve performance of this code?
4,295,799
29
2010-11-28T07:27:43Z
4,299,378
43
2010-11-28T22:04:07Z
[ "python", "performance", "optimization", "time-complexity" ]
Thanks to some help from people here, I was able to get my code for Tasmanian camels puzzle working. However, it is horribly slow (I think. I'm not sure because this is my first program in python). The example run in the bottom of the code takes a long time to be solved in my machine: ``` dumrat@dumrat:~/programming/p...
First let me tell you how to find the problem. Then I'll tell you where it is: I haven't even bothered to try to figure out your code. I just ran it and took 3 random-time stack samples. I did that by typing control-C and looking at the resulting stacktrace. One way to look at it is: if a statement appears on X% of r...
simplejson.loads() get Invalid \escape: 'x'
4,296,041
5
2010-11-28T08:49:15Z
4,296,045
7
2010-11-28T08:51:45Z
[ "python", "escaping", "simplejson" ]
I am learning how to use simplejson to decode JSON file. But I suffered the "invalid \escape" error. Here is the code ``` import simplejson as json def main(): json.loads(r'{"test":"\x27"}') if __name__ == '__main__': main() ``` And here is the error message ``` Traceback (most recent call last): File "h...
JSON has no hex escape (`\xNN`) like some languages (including JavaScript) and notations do, [details here](http://json.org). It has a unicode escape, `\uNNNN` where `NNNN` is four hex digits, but no `\x` hex escape.
Use wildcard with os.path.isfile()
4,296,138
16
2010-11-28T09:15:29Z
4,296,148
41
2010-11-28T09:17:26Z
[ "python", "path", "wildcard" ]
I'd like to check if there are any .rar files in a directory. it doesn’t need to be recursive. Using wildcard with os.path.isfile() was my best guess, but it doesn't work. What can I do then? Thanks.
[glob](http://docs.python.org/library/glob.html) is what you need. ``` >>> import glob >>> glob.glob('*.rar') # all rar files within the directory, in this case the current working one ``` `os.path.isfile()` returns `True` if a path is an existing regular file. So that is used for checking whether a file already ex...
How do I convert a hex triplet to an RGB tuple and back?
4,296,249
18
2010-11-28T09:55:12Z
4,296,263
51
2010-11-28T09:59:56Z
[ "python", "colors" ]
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
``` >>> import struct >>> rgbstr='aabbcc' >>> struct.unpack('BBB',rgbstr.decode('hex')) (170, 187, 204) ``` and ``` >>> rgb = (50,100,150) >>> struct.pack('BBB',*rgb).encode('hex') '326496' ```
How do I convert a hex triplet to an RGB tuple and back?
4,296,249
18
2010-11-28T09:55:12Z
4,296,268
7
2010-11-28T10:02:18Z
[ "python", "colors" ]
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
A very simplistic approach to convert rgb to hex ``` >>> rgb = (255, 255, 255) >>> r, g , b = rgb >>> hex(r) '0xff' >>> hex(r) + hex(g)[2:] + hex(b)[2:] '0xffffff' >>> ``` A simplistic approach to convert Hex to rgb ``` >>> h = '0xffffff' >>> h1, h2, h3 = h[0:4], '0x' + h[4:6], '0x' + h[6:8] >>> h1, h2, h3 ('0xff',...
How do I convert a hex triplet to an RGB tuple and back?
4,296,249
18
2010-11-28T09:55:12Z
4,296,727
14
2010-11-28T12:27:38Z
[ "python", "colors" ]
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
You can use a look-up table with some slicing and shifts — all relatively fast operations — to create a couple of functions that will work unchanged in both Python 2 and 3: ``` _NUMERALS = '0123456789abcdefABCDEF' _HEXDEC = {v: int(v, 16) for v in (x+y for x in _NUMERALS for y in _NUMERALS)} LOWERCASE, UPPERCASE = 'x'...
How do I convert a hex triplet to an RGB tuple and back?
4,296,249
18
2010-11-28T09:55:12Z
4,298,464
21
2010-11-28T19:05:31Z
[ "python", "colors" ]
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
Trying to be *pythonic*: ``` >>> rgbstr='aabbcc' >>> tuple(ord(c) for c in rgbstr.decode('hex')) (170, 187, 204) >>> tuple(map(ord, rgbstr.decode('hex')) (170, 187, 204) ``` and ``` >>> rgb=(12,50,100) >>> "".join(map(chr, rgb)).encode('hex') '0c3264' ```
when a function embedded in class be the "method" of the class?
4,296,477
4
2010-11-28T11:18:50Z
4,296,579
7
2010-11-28T11:47:16Z
[ "python" ]
When this is executed... ``` class A: def b(self, a): print a print dir(b) print dir(A.b) ``` It gives the result: ``` ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_...
In **Python 2**, the second case returns an unbound method, and the first case a function. From [the documentation](http://docs.python.org/reference/datamodel.html#index-849), emphasis mine: > User-defined method objects may be **created when getting an attribute of a class** (perhaps via an instance of that class), i...
Extrapolation from data plotted using matplotlib
4,296,603
5
2010-11-28T11:52:26Z
4,296,777
12
2010-11-28T12:43:18Z
[ "python", "numpy", "matplotlib" ]
I have 10 values of x and y in my file. Is there any way that I can extrapolate the graph ie make it into a continous function and increasing its range for other x-values in matplotlib ?? I would even be thankful if anyone can tell me if there is any other software that I can use. I basically want that these 10 value...
below i use *Scipy*, but the *same* functions (*polyval* and *polyfit*) are also in *NumPy*; NumPy is a Matplotlib dependency so you can import those two functions from there if you don't have SciPy installed. ``` import numpy as NP from scipy import polyval, polyfit from matplotlib import pyplot as PLT n=10 # 10 d...
Creating a class within a function and access a function defined in the containing function's scope
4,296,677
36
2010-11-28T12:14:52Z
4,296,729
13
2010-11-28T12:28:05Z
[ "python", "namespaces", "scope" ]
> **Edit**: > > See my full answer at the bottom of this question. > > **tl;dr answer**: Python has statically nested scopes. The **static** > aspect can interact with the implicit variable declarations, yielding non-obvious results. > > (This can be especially surprising because of the language's generally dynamic nat...
That's an artifact of Python's name resolution rules: you only have access to the global and the local scopes, but not to the scopes in-between, e.g. not to your immediate outer scope. **EDIT:** The above was poorly worded, you *do* have access to the variables defined in outer scopes, but by doing `x = x` or `mymetho...
Convert backward slash to forward slash in python
4,297,450
5
2010-11-28T15:20:39Z
4,297,463
11
2010-11-28T15:24:03Z
[ "python", "ruby", "path" ]
Hi I have read articles related converting backward to forward slashes. But sol was to use raw string. But Problem in my case is : I will get file path dynamically to a variable var='C:\dummy\_folder\a.txt' In this case i need to convert it to Forward slashes. But due to '\a',i am not able to convert to forward slash...
Don't do this. Just use [os.path](http://docs.python.org/library/os.path.html) and let it handle everything. You should not explicitly set the forward or backward slashes. ``` >>> var=r'C:\dummy_folder\a.txt' >>> var.replace('\\', '/') 'C:/dummy_folder/a.txt' ``` But again, don't. Just use os.path and be happy!
Convert backward slash to forward slash in python
4,297,450
5
2010-11-28T15:20:39Z
4,789,137
11
2011-01-25T01:32:59Z
[ "python", "ruby", "path" ]
Hi I have read articles related converting backward to forward slashes. But sol was to use raw string. But Problem in my case is : I will get file path dynamically to a variable var='C:\dummy\_folder\a.txt' In this case i need to convert it to Forward slashes. But due to '\a',i am not able to convert to forward slash...
There is also [os.path.normpath](http://docs.python.org/library/os.path.html#os.path.normpath)(), which converts backslashes and slashes depending on the local OS. Please see [here](http://docs.python.org/library/os.path.html#os.path.normpath) for detailed usage info. You would use it this way: ``` >>> string = r'C:/d...
Image on a button
4,297,949
7
2010-11-28T17:12:53Z
4,297,989
12
2010-11-28T17:20:45Z
[ "python", "image", "button", "tkinter" ]
``` from Tkinter import * class fe: def __init__(self,master): self.b=Button(master,justify = LEFT) photo=PhotoImage(file="mine32.gif") self.b.config(image=photo,width="10",height="10") self.b.pack(side=LEFT) root = Tk() front_end=fe(root) root.mainloop() from Tkinter import * root=Tk()...
The only reference to the image object is a local variable. When `__init__` exits, the local variable is garbage collected so the image no is destroyed. In the second example, because the image is created at the global level it never goes out of scope and is therefore never garbage collected. To work around this, save...
Why is __radd__ not working
4,298,264
5
2010-11-28T18:26:54Z
4,298,289
10
2010-11-28T18:31:10Z
[ "python" ]
HI Trying to understand how `__radd__` works. I have the code ``` >>> class X(object): def __init__(self, x): self.x = x def __radd__(self, other): return X(self.x + other.x) >>> a = X(5) >>> b = X(10) >>> a + b Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> ...
[Python docs for operators](http://docs.python.org/reference/datamodel.html#object.__radd__) "These functions are only called if the left operand does not support the corresponding operation and the operands are of different types." [See also Footnote 2](http://docs.python.org/reference/datamodel.html#id6) Since the...
Django: is_authenticated and is_anonymous both return true after logout
4,298,387
2
2010-11-28T18:47:09Z
4,300,495
8
2010-11-29T02:52:08Z
[ "python", "django", "templates", "authentication", "django-registration" ]
I am using django-registration, and just set it up. ``` {{user.is_authenticated }} ``` is true, even though i went already to /accounts/logout/ and logged the user out. ``` {{user.is_anonymous }} ``` returns true also. According to django docs, those two should be different: > is\_anonymous: Always returns False. ...
It seems like you are trying to figure out two things at once; what is the correct way to use jinja templates and what is the deal with User/AnonymousUser. Maybe try to figure out these problems one at a time. I have no experience with jinja but you may want to check and make sure that you are taking [differences betw...
Faster Development Rails or Django?
4,298,622
4
2010-11-28T19:35:36Z
4,298,635
7
2010-11-28T19:39:25Z
[ "python", "ruby-on-rails", "ruby", "django" ]
I Have around 2 Weeks of *Real* development time to churn out a contact database system to replace various spreadsheets and pieces of paper laying around.. also im gonna need to develop two websites (with dynamic content) and a small AJAXian web service I have no experience of rails or django but can learn fast.. bo...
The Django admin will generate a CRUD application that you can customize to suit almost any need, from your model definitions. I've used the admin for the main user interface for several projects and can tell you that it is a real timesaver. You don't have to spend any time whatsoever at writing templates or Javascript...
Modifying strings in Python
4,299,293
2
2010-11-28T21:50:04Z
4,299,310
8
2010-11-28T21:52:38Z
[ "python", "string" ]
I have a string here in python '#b9d9ff'. How do I remove the hash symbol (#)?
There are various trivially-different options. Each one does the same thing for your string but handles other strings differently. ``` # Strip any hashes on the left. string.lstrip('#') # Remove hashes anywhere in the string, not necessarily just from the front. string.replace('#', '') # Remove only the first hash i...
Merging items in a list - Python
4,299,741
4
2010-11-28T23:26:40Z
4,299,758
7
2010-11-28T23:29:17Z
[ "python", "list" ]
Say I have a list in python, like such: ``` list=[1,2,3,4,5] ``` How would I merge the list so that it becomes: ``` list= [12345] ``` If anyone has a way to do this, it would be greatly appreciated!!
``` >>> list=[1,2,3,4,5] >>> k = [str(x) for x in list] >>> k ['1', '2', '3', '4', '5'] >>> "".join(k) '12345' >>> ["".join(k)] ['12345'] >>> >>> [int("".join(k))] [12345] >>> ```
Merging items in a list - Python
4,299,741
4
2010-11-28T23:26:40Z
4,299,760
14
2010-11-28T23:29:27Z
[ "python", "list" ]
Say I have a list in python, like such: ``` list=[1,2,3,4,5] ``` How would I merge the list so that it becomes: ``` list= [12345] ``` If anyone has a way to do this, it would be greatly appreciated!!
``` reduce(lambda x,y:10*x+y, [1,2,3,4,5]) # returns 12345 ```
Merging items in a list - Python
4,299,741
4
2010-11-28T23:26:40Z
4,299,935
7
2010-11-29T00:14:20Z
[ "python", "list" ]
Say I have a list in python, like such: ``` list=[1,2,3,4,5] ``` How would I merge the list so that it becomes: ``` list= [12345] ``` If anyone has a way to do this, it would be greatly appreciated!!
This probably better: ``` "%s" * len(L) % tuple(L) ``` which can handle: ``` >>> L=[1, 2, 3, '456', '7', 8] >>> "%s"*len(L) % tuple(L) '12345678' ```
Python: convert string from UTF-8 to Latin-1
4,299,802
11
2010-11-28T23:37:33Z
4,299,809
14
2010-11-28T23:38:27Z
[ "python", "encoding" ]
I feel stacked here trying to change encodings with Python 2.5 I have XML response, which I encode to UTF-8: `response.encode('utf-8')`. That is fine, but the program which uses this info doesn't like this encoding and I have to convert it to other code page. Real example is that I use ghostscript python module to emb...
Instead of `.encode('utf-8')`, use `.encode('latin-1')`.
Python - which is the better way of calling superclass' method?
4,300,738
16
2010-11-29T03:56:06Z
4,300,823
18
2010-11-29T04:16:36Z
[ "python", "oop", "class" ]
All the while I have been using: ``` SuperClass.__init__(self, *args, **kwargs) ``` My reason is that this shows explicitly which superclass is used, especially in the case of multiple inheritance. However, other codes I came across use ``` super(MyClass, self).__init__(*args, **kwargs) ``` instead. This could be...
The reason that `super` is prefereable for modern (*new style*) classes is that it allows *cooperative* multiple inheritance. Here's an example. ``` >>> class Foo(object): ... def display(self): ... print "In Foo" ... >>> class Foo2(Foo): ... def display(self): ... print "In Foo2" ... ...
Any way to properly pretty-print ordered dictionaries in Python?
4,301,069
64
2010-11-29T05:27:27Z
4,301,173
7
2010-11-29T05:51:55Z
[ "python", "python-2.7", "pretty-print", "ordereddictionary", "pprint" ]
I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window. It has worked fine until they added the new [ordered dictionary type](http://www.python.org/dev/peps/pep-0372/) in Python 2.7 (another cool feat...
The following will work if the order of your OrderedDict is an alpha sort, since pprint will sort a dict before print. ``` pprint(dict(o.items())) ```
Any way to properly pretty-print ordered dictionaries in Python?
4,301,069
64
2010-11-29T05:27:27Z
4,303,996
8
2010-11-29T13:04:10Z
[ "python", "python-2.7", "pretty-print", "ordereddictionary", "pprint" ]
I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window. It has worked fine until they added the new [ordered dictionary type](http://www.python.org/dev/peps/pep-0372/) in Python 2.7 (another cool feat...
Here's another answer that works by overriding and using the stock `pprint()` function internally. Unlike my [earlier one](http://stackoverflow.com/a/4302635/355230) it *will* handle `OrderedDict`'s inside another container such as a `list` and should also be able to handle any optional keyword arguments given — howe...
Any way to properly pretty-print ordered dictionaries in Python?
4,301,069
64
2010-11-29T05:27:27Z
4,898,010
85
2011-02-04T12:33:49Z
[ "python", "python-2.7", "pretty-print", "ordereddictionary", "pprint" ]
I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window. It has worked fine until they added the new [ordered dictionary type](http://www.python.org/dev/peps/pep-0372/) in Python 2.7 (another cool feat...
As a temporary workaround you can try dumping in JSON format. You lose some type information, but it looks nice and keeps the order. ``` import json pprint(data, indent=4) # ^ugly print(json.dumps(data, indent=4)) # ^nice ```
How does jsfiddle mark up code? Is there a library for this?
4,301,347
3
2010-11-29T06:28:53Z
4,301,430
7
2010-11-29T06:42:10Z
[ "javascript", "jquery", "python", "mootools", "jsfiddle" ]
If you've ever used www.jsfiddle.net, you might notice that it marks up code with proper colorings, and various other helpers like translating tabs to four spaces or shift-tab. With Firebug I see that it's doing this with an iFrame. Is there an open source library to do this? I want to let people write Python on a web ...
Check out [CodeMirror](http://codemirror.net/).
Testing a python script in a specific version
4,301,681
2
2010-11-29T07:27:53Z
4,301,720
7
2010-11-29T07:38:16Z
[ "python", "tox" ]
I currently have Python 2.6.2 installed on my mac. I am writing a script which MUST run on Python 2.5.2. So I want to write a python script, and test is specifically against 2.5.2 and NOT 2.6.2. I was looking at virtualenv, but it doesn't seem to solve my problem. I ran `python virtualenv.py TEST` which made a TEST di...
Check out [tox](http://codespeak.net/tox/); it's designed to do exactly this.
python boolean expression not "short-circuit"?
4,301,921
9
2010-11-29T08:18:29Z
4,301,941
17
2010-11-29T08:22:35Z
[ "python", "short-circuiting" ]
For example: ``` def foo(): print 'foo' return 1 if any([f() for f in [foo]*3]): print 'bar' ``` I thought the above code should output: ``` foo bar ``` instead of : ``` foo foo foo bar ``` Why ? how can I make the "short-circuit" effect ?
Deconstruct your program to see what is happening: ``` >>> [f() for f in [foo]*3] foo foo foo [1, 1, 1] >>> ``` You are already creating a list and passing to any and have printed it 3 times. ``` >>> any ([1, 1, 1]) True ``` This is fed to if statement: ``` >>> if any([1, 1, 1]): ... print 'bar' ... bar >>> `...
how to open a url in python
4,302,027
32
2010-11-29T08:36:07Z
4,302,041
81
2010-11-29T08:37:55Z
[ "python", "bottle" ]
``` import urllib fun open(): return urllib.urlopen('http://example.com') ``` But when example.com opens it does not render css or js. How can I open the webpage in a web browser? ``` @error(404) def error404(error): return webbrowser.open('http://example.com') ``` I am using bottle. Giving me the error: `T...
with the [webbrowser](http://docs.python.org/library/webbrowser.html) module ``` import webbrowser webbrowser.open('http://example.com') # Go to example.com ```
Format string dynamically
4,302,166
15
2010-11-29T08:59:57Z
4,302,182
17
2010-11-29T09:02:19Z
[ "python", "string" ]
If I want to make my formatted string dynamically adjustable, I will change the following code from ``` print '%20s : %20s' % ("Python", "Very Good") ``` to ``` width = 20 print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good") ``` However, it seems that string concatenation is cumbersome he...
You can fetch the padding value from the argument list: ``` print '%*s : %*s' % (20, "Python", 20, "Very Good") ``` You can even insert the padding values dynamically: ``` width = 20 args = ("Python", "Very Good") padded_args = zip([width] * len(args), args) # Flatten the padded argument list. print "%*s : %*s" % tu...
If a python iterator returns iterable objects, how can I chain those objects into one big iterator?
4,302,201
4
2010-11-29T09:04:44Z
4,302,228
10
2010-11-29T09:09:25Z
[ "python", "iterator", "lazy-evaluation" ]
I'll give a simplified example here. Suppose I have an iterator in python, and each object that this iterator returns is itself iterable. I want to take all the objects returned by this iterator and chain them together into one long iterator. Is there a standard utility to make this possible? Here is a contrived examp...
You can use [`itertools.chain.from_iterable`](http://docs.python.org/library/itertools.html#itertools.chain.from_iterable) ``` >>> import itertools >>> x = iter([ xrange(0,5), xrange(5,10)]) >>> a = itertools.chain.from_iterable(x) >>> list(a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` If that's not available on your version...
doxygen syntax in python
4,302,870
8
2010-11-29T10:32:55Z
15,535,484
9
2013-03-20T21:52:36Z
[ "python", "doxygen" ]
Can somebody please help me to figure out how to comment python code correctly to get parsed by doxygen? Somehow it ignores the tags. The output (HTML) shows the tags: ``` @brief Creates a new Hello object. This Hello Object is beeing used to ... @param name The name of the user. ``` --- Both variants I tried do n...
Doxygen has also undocumented feature (or bug): It parses Doxygen syntax in docstring if you start docstring with an exclamation mark: ``` class Hello: def __init__(self, name): """!@brief Creates a new Hello object. This Hello Object is being used to... @param name The name of the user. """ ...
Encode keys of dictionaries inside a list from unicode to ascii
4,303,324
3
2010-11-29T11:34:29Z
4,303,400
8
2010-11-29T11:46:37Z
[ "python", "django", "unicode", "encoding", "dictionary" ]
I have sample response with friends list from facebook: ``` [{u'uid': 513351886, u'name': u'Mohammed Hossein', u'pic_small': u'http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs643.snc3/27383_513351886_4933_t.jpg'}, {u'uid': 516583220, u'name': u'Sim Salabim', u'pic_small': u'http://profile.ak.fbcdn.net/hprofile-ak-s...
First: do you really **need** to do this? The strings are in Unicode for a reason: you simply can't represent everything in plain ASCII that you can in Unicode. This probably won't be a problem for your dictionary keys 'uid', 'name' and 'pic\_small'; but it probably won't be a problem to leave them as Unicode, either. ...
How can I simplify this conversion from underscore to camelcase in Python?
4,303,492
25
2010-11-29T12:00:44Z
4,306,777
20
2010-11-29T18:25:42Z
[ "python" ]
I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get\_this\_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e. ``` "_get__this_value_" -> "_get_ThisValue_". ```...
Your code is fine. The problem I think you're trying to solve is that `if first_word_passed` looks a little bit ugly. One option for fixing this is a generator. We can easily make this return one thing for first entry and another for all subsequent entries. As Python has first-class functions we can get the generator ...
How can I simplify this conversion from underscore to camelcase in Python?
4,303,492
25
2010-11-29T12:00:44Z
6,425,628
30
2011-06-21T13:02:10Z
[ "python" ]
I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get\_this\_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e. ``` "_get__this_value_" -> "_get_ThisValue_". ```...
This one works except for leaving the first word as lowercase. ``` def convert(word): return ''.join(x.capitalize() or '_' for x in word.split('_')) ``` (I know this isn't exactly what you asked for, and this thread is quite old, but since it's quite prominent when searching for such conversions on Google I thoug...
How can I simplify this conversion from underscore to camelcase in Python?
4,303,492
25
2010-11-29T12:00:44Z
10,984,923
9
2012-06-11T17:40:31Z
[ "python" ]
I have written the function below that converts underscore to camelcase with first word in lowercase, i.e. "get\_this\_value" -> "getThisValue". Also I have requirement to preserve leading and trailing underscores and also double (triple etc.) underscores, if any, i.e. ``` "_get__this_value_" -> "_get_ThisValue_". ```...
I prefer a regular expression, personally. Here's one that is doing the trick for me: ``` import re def to_camelcase(s): return re.sub(r'(?!^)_([a-zA-Z])', lambda m: m.group(1).upper(), s) ``` Using `unutbu`'s tests: ``` tests = [('get__this_value', 'get_ThisValue'), ('_get__this_value', '_get_ThisValue...
3d game with Python, starting from nothing
4,303,851
11
2010-11-29T12:49:31Z
4,303,890
16
2010-11-29T12:53:46Z
[ "c++", "python", "3d" ]
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application. Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff. We are also possibly consi...
[Panda3D](http://www.panda3d.org/) is a nice, powerful game engine which allows for scripting in Python. This looks like a good place to start. If you seek something more low-level, there's still [PyOpenGL](http://pyopengl.sourceforge.net/) or [pygame](http://www.pygame.org/news.html).
3d game with Python, starting from nothing
4,303,851
11
2010-11-29T12:49:31Z
4,304,018
11
2010-11-29T13:06:23Z
[ "c++", "python", "3d" ]
So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application. Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff. We are also possibly consi...
**There's [Pygame](http://www.pygame.org/news.html):** A game framework for the Python language. If you need to know the basics for game development (engine, flow, ui, mathematics), this framework with all its examples will help you a lot. This won't take you by the hand and guide you step by step through game-developm...
Creating form using Generic_inlineformset_factory from the Model Form
4,304,148
7
2010-11-29T13:23:33Z
4,363,680
15
2010-12-06T05:55:13Z
[ "python", "django" ]
I wanted to create a edit form with the help of ModelForm. and my models contain a Generic relation b/w classes, so if any one could suggest me the view and a bit of template for the purpose I would be very thankful, as I am new to the language. My models look like:- ``` class Employee(Person): nickname = mode...
posting the solution I found out. After taking a look at the source of Generic\_inlineformset\_factory. I made my view as:- ``` def edit_contact(request): c={} profile = request.user.get_profile() EmployeeFormSet = generic_inlineformset_factory(PhoneNumber,extra=0,can_delete=False) EmployeeFormSet...
Why is equivalent Python code so much slower
4,305,518
19
2010-11-29T16:01:13Z
4,305,687
11
2010-11-29T16:20:49Z
[ "python", "ruby", "python-3.x" ]
can somebody explain why is the following trivial code (implementation of Euclid's algorithm to find greatest common denominator) about 3 times slower then equivalent code in Ruby ? contents of iter\_gcd.py: ``` from sys import argv,stderr def gcd(m, n): if n > m: m, n = n, m while n != 0: re...
I seem to remember that ruby handles integers differently than Python, so my guess would be it is simply that Python is spending a lot of time allocating memory while Ruby just mutates the integers in place. For what it is worth, using Pypy 1.4 reduces the runtime for the Python version on my system from about 15 seco...
Why is equivalent Python code so much slower
4,305,518
19
2010-11-29T16:01:13Z
4,306,668
22
2010-11-29T18:11:53Z
[ "python", "ruby", "python-3.x" ]
can somebody explain why is the following trivial code (implementation of Euclid's algorithm to find greatest common denominator) about 3 times slower then equivalent code in Ruby ? contents of iter\_gcd.py: ``` from sys import argv,stderr def gcd(m, n): if n > m: m, n = n, m while n != 0: re...
I can confirm that ruby1.9 is faster than CPython for this "microbenchmark" on [my machine](https://gist.github.com/735259): ``` | Interpreter | Time, s | Ratio | |---------------------------------+---------+-------| | python-2.6 (cython_gcd.gcd_int) | 2.8 | 0.33 | | pypy-1.4 ...
Why is equivalent Python code so much slower
4,305,518
19
2010-11-29T16:01:13Z
4,381,575
35
2010-12-07T21:07:19Z
[ "python", "ruby", "python-3.x" ]
can somebody explain why is the following trivial code (implementation of Euclid's algorithm to find greatest common denominator) about 3 times slower then equivalent code in Ruby ? contents of iter\_gcd.py: ``` from sys import argv,stderr def gcd(m, n): if n > m: m, n = n, m while n != 0: re...
## Summary "Because the function call overhead in Python is much larger than in Ruby." ## Details Being a microbenchmark, this really doesn't say much about the performance of either language in proper use. Likely you would want to rewrite the program to take advantage of the strengths of Python and Ruby, but this d...
How does Python keep track of modules installed with eggs?
4,305,610
8
2010-11-29T16:11:25Z
4,306,995
16
2010-11-29T18:53:18Z
[ "python", "module", "installation", "easy-install", "egg" ]
If I have a module, `foo`, in `Lib/site-packages`, I can just `import foo` and it will work. However, when I install stuff from eggs, I get something like `blah-4.0.1-py2.7-win32.egg` as a folder, with the module contents inside, yet I still only need do `import foo`, not anything more complicated. How does Python keep...
If you use the `easy_install` script provided by `setuptools` (or the `Distribute` fork of it) to install packages as eggs, you will see that, by default, it creates a file named `easy-install.pth` in the `site-packages` directory of your Python installation. [Path configuration files](http://docs.python.org/library/si...
How to see exception generated into django template variable?
4,305,948
15
2010-11-29T16:49:07Z
7,854,378
14
2011-10-21T19:32:13Z
[ "python", "django", "django-templates" ]
Inside a Django template, one can call an object method like this : ``` {{ my_object.my_method }} ``` The problem is when you get an exception/bug in 'def my\_method(self)', it is hidden when rendering the template (there is an empty string output instead, so no errors appears). As I want to debug what's wrong in 'd...
Here's a nice trick I just implemented for doing exactly this. Put this in your debug settings: ``` class InvalidString(str): def __mod__(self, other): from django.template.base import TemplateSyntaxError raise TemplateSyntaxError( "Undefined variable or unknown value for: %s" % other) ...
Python method/function arguments starting with asterisk and dual asterisk
4,306,574
53
2010-11-29T17:59:52Z
4,306,602
77
2010-11-29T18:03:04Z
[ "python" ]
I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly. Ex: ``` def method(self, *links, **locks): #some foo #some bar return ``` I know i c...
The `*args` and `**keywordargs` forms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function this: ``` def printlist(*args): for x in args: print x ``` I could call it like this: ``` printlist(1, 2, 3, 4, 5) # or as many more arguments as I'd like ``` ...
How To catch python stdout in c++ code
4,307,187
18
2010-11-29T17:54:20Z
4,307,737
13
2010-11-29T20:22:55Z
[ "c++", "python", "redirect", "python-c-api", "python-embedding" ]
I have a program which during it's run sometimes needs to call python in order to preform some tasks. I need a function that calls python and **catches pythons stdout** and puts it in some file. This is a declaration of the function ``` pythonCallBackFunc(const char* pythonInput) ``` My problem is to catch **all th...
If I'm reading your question correctly, you want to capture stdout/stderr into a variable within your C++? You can do this by redirecting stdout/stderr into a python variable and then querying this variable into your C++. Please not that I have not done the proper ref counting below: ``` #include <Python.h> #include <...
How To catch python stdout in c++ code
4,307,187
18
2010-11-29T17:54:20Z
8,335,297
19
2011-12-01T00:58:59Z
[ "c++", "python", "redirect", "python-c-api", "python-embedding" ]
I have a program which during it's run sometimes needs to call python in order to preform some tasks. I need a function that calls python and **catches pythons stdout** and puts it in some file. This is a declaration of the function ``` pythonCallBackFunc(const char* pythonInput) ``` My problem is to catch **all th...
Here is a C++ friendly solution I have developed lately. I explain a few details of it on my blog: [Python sys.stdout redirection in C++](http://mateusz.loskot.net/posts/2011/12/01/python-sys-stdout-redirection-in-cpp/index.html) where I also point to repository at my GitHub where most recent version can be found. Her...
Class decorators in Python 2.5?
4,307,419
5
2010-11-29T19:47:33Z
4,307,463
9
2010-11-29T19:53:44Z
[ "python", "google-app-engine", "python-2.5" ]
Is there a way I can make **class decorators** work on **Google App Engine**, which is limited to **`Python 2.5`**? Or let me rephrase that: is it possible to alter the behavior of Python's parser from the same process that it is already executing? Example: **good.py:** ``` alter_python_parser() import bad ``` **ba...
Decorators are just syntactic sugar. Just change instances of decorator usage, that is, ``` @decorated class Foo(object): pass ``` becomes ``` class Foo(object): pass Foo = decorated(Foo) ``` You can't, realistically, change the parser. Though, you could automate the above process using the [ast module](http://doc...
install cx_oracle for python
4,307,479
23
2010-11-29T19:55:28Z
4,309,403
8
2010-11-30T00:13:41Z
[ "python", "oracle" ]
Am on Debian 5, I've been trying to install cx\_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link [here](http://le-gall.net/pierrick/blog/index.php/2006/09/21/80-how-to-use-ubuntu-linux-as-an-oracle-client)). Then, I used the s...
I recommend that you grab the rpm files and install them with alien. That way, you can later on run `apt-get purge no-longer-needed`. [In my case](http://tshepang.net/accessing-oracle-db-using-python-in-debian), the only env variable I needed is `LD_LIBRARY_PATH`, so I did: ``` echo export LD_LIBRARY_PATH=/usr/lib/or...
install cx_oracle for python
4,307,479
23
2010-11-29T19:55:28Z
9,859,027
44
2012-03-25T09:10:26Z
[ "python", "oracle" ]
Am on Debian 5, I've been trying to install cx\_oracle module for python without any success. First, I installed oracle-xe-client and its dependency (followed tutorial in the following link [here](http://le-gall.net/pierrick/blog/index.php/2006/09/21/80-how-to-use-ubuntu-linux-as-an-oracle-client)). Then, I used the s...
The alternate way, that doesn't require RPMs. You need to be `root`. 1. **Dependencies** Install the following packages: ``` apt-get install python-dev build-essential libaio1 ``` 2. **Download *Instant Client for Linux x86-64*** Download the following files from Oracle's [download site](http://www.o...
Django + Google Federated Login
4,307,677
4
2010-11-29T20:16:49Z
4,356,626
10
2010-12-05T00:20:43Z
[ "python", "django", "openid", "single-sign-on" ]
I would like to enable the visitors of my website to login using their Google Accounts instead of having to sign up and create a new one. A few things: * I am NOT using the Django authentication framework, instead, I do my own authentication and keep information about users in my own set of tables * consequently, var...
I think your problem stems from a basic misunderstanding of how OpenID and/or OAuth work. It looks like you just want authentication, so let's stick to OpenID for now. You are correct to look at existing libraries. python-openid is the one to use if you only need OpenID and not OAuth, and you are not using Django's bu...
Platform independent tool to copy text to clipboard
4,308,152
13
2010-11-29T21:12:47Z
4,308,279
11
2010-11-29T21:27:36Z
[ "python", "wxpython", "tkinter", "clipboard" ]
I am trying to write a function that *copies a string parameter to the clipboard*. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post): ``` from tkinter import Tk def copy_to_clipboard(text): text = str(text...
Yes, there is one for you :) Use [**pyperclip**](http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/).
sigmoidal regression with scipy, numpy, python, etc
4,308,168
18
2010-11-29T21:15:01Z
4,308,561
31
2010-11-29T22:06:12Z
[ "python", "statistics", "numpy", "scipy", "scientific-computing" ]
I have two variables (x and y) that have a somewhat sigmoidal relationship with each other, and I need to find some sort of prediction equation that will enable me to predict the value of y, given any value of x. My prediction equation needs to show the somewhat sigmoidal relationship between the two variables. Therefo...
Using [scipy.optimize.leastsq](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq): ``` import numpy as np import matplotlib.pyplot as plt import scipy.optimize def sigmoid(p,x): x0,y0,c,k=p y = c / (1 + np.exp(-k*(x-x0))) + y0 return y def residuals(p,...
Getting the exception value in Python
4,308,182
89
2010-11-29T21:16:11Z
4,308,202
112
2010-11-29T21:18:18Z
[ "python", "exception" ]
If I have that code: ``` try: some_method() except Exception,e: ``` How can I get this Exception value (string representation I mean)? Thanks
use `str` ``` try: some_method() except Exception as e: s = str(e) ``` Also, most exception classes will have an `args` attribute. Often, `args[0]` will be an error message. It should be noted that just using `str` will return an empty string if there's no error message whereas using `repr` as pyfunc recomme...
Getting the exception value in Python
4,308,182
89
2010-11-29T21:16:11Z
4,308,203
74
2010-11-29T21:18:37Z
[ "python", "exception" ]
If I have that code: ``` try: some_method() except Exception,e: ``` How can I get this Exception value (string representation I mean)? Thanks
> Use repr() and The difference between using repr and str Using repr: ``` >>> try: ... print x ... except Exception, e: ... print repr(e) ... NameError("name 'x' is not defined",) >>> ``` Using str: ``` >>> >>> try: ... print x ... except Exception, e: ... print str(e) ... name 'x' is not define...
Getting the exception value in Python
4,308,182
89
2010-11-29T21:16:11Z
19,378,402
13
2013-10-15T10:05:01Z
[ "python", "exception" ]
If I have that code: ``` try: some_method() except Exception,e: ``` How can I get this Exception value (string representation I mean)? Thanks
Another way hasn't been given yet: ``` try: 1/0 except Exception, e: print e.message ``` Output: ``` integer division or modulo by zero ``` `args[0]` might actually not be a message. `str(e)` might return the string with surrounding quotes and possibly with the leading `u` if unicode: ``` 'integer divisio...
Getting the exception value in Python
4,308,182
89
2010-11-29T21:16:11Z
19,391,907
9
2013-10-15T22:04:07Z
[ "python", "exception" ]
If I have that code: ``` try: some_method() except Exception,e: ``` How can I get this Exception value (string representation I mean)? Thanks
Even though I realise this is an old question, I'd like to suggest using the [`traceback` module](http://docs.python.org/3/library/traceback.html) to handle output of the exceptions. Use `traceback.print_exc()` to print the current exception to standard error, just like it would be printed if it remained uncaught, or ...
How to organize the directory used for a distributable Python module?
4,308,301
3
2010-11-29T21:30:13Z
4,308,353
7
2010-11-29T21:38:02Z
[ "python", "module" ]
I'm creating a Python module. My question is how can I organize the distribution such that it has a directory structure similar to most of the standard Python modules. Is there anything similar to MakeFile in Python which has `setup.py` file name? Directory Structure: ``` pymodule_x-y.tar.gz/ + pym...
You have several options, including distributing egg files, tarballs, etc. A great resource on distributing Python packages is [The Hitchhiker's Guide to Packaging](https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/) (still under development, but good nonetheless).
Django: Model Form "object has no attribute 'cleaned_data'"
4,308,527
42
2010-11-29T22:01:53Z
4,308,731
89
2010-11-29T22:27:42Z
[ "python", "django", "django-forms" ]
I am trying to make a search form for one of my classes. The model of the form is: ``` from django import forms from django.forms import CharField, ModelMultipleChoiceField, ModelChoiceField from books.models import Book, Author, Category class SearchForm(forms.ModelForm): authors = ModelMultipleChoiceField(query...
For some reason, you're re-instantiating the form after you check `is_valid()`. Forms only get a `cleaned_data` attribute when `is_valid()` has been called, and you haven't called it on this new, second instance. Just get rid of the second `form = SearchForm(request.POST)` and all should be well.
win32: check if window is minimized
4,309,282
3
2010-11-29T23:52:25Z
4,309,299
8
2010-11-29T23:54:22Z
[ "python", "windows", "winapi", "pywin32" ]
How can one check whether a window is minimized using the win32 api?
Use the IsIconic Windows API.
win32: check if window is minimized
4,309,282
3
2010-11-29T23:52:25Z
4,309,305
13
2010-11-29T23:55:39Z
[ "python", "windows", "winapi", "pywin32" ]
How can one check whether a window is minimized using the win32 api?
use the [IsIconic](http://msdn.microsoft.com/en-us/library/ms633527(VS.85).aspx) function.
how in python to split a string with unknown number of spaces as separator?
4,309,684
16
2010-11-30T01:11:37Z
4,309,689
35
2010-11-30T01:12:45Z
[ "python" ]
I need a function similar to string.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like that: ``` s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 ' ss = s.magicSplit() print ss ['1234','Q-24','2010-11-29','563','abc'...
Try ``` >>> ' 1234 Q-24 2010-11-29 563 abc a6G47er15'.split() ['1234', 'Q-24', '2010-11-29', '563', 'abc', 'a6G47er15'] ``` Or if you want ``` >>> class MagicString(str): ... magicSplit = str.split ... >>> s = MagicString(' 1234 Q-24 2010-11-29 563 abc a6G47er15') >>> s.magicSplit() ...
how in python to split a string with unknown number of spaces as separator?
4,309,684
16
2010-11-30T01:11:37Z
4,309,692
9
2010-11-30T01:13:06Z
[ "python" ]
I need a function similar to string.split(' ') but there might be more than one space, and different number of them between the meaningful characters. Something like that: ``` s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 ' ss = s.magicSplit() print ss ['1234','Q-24','2010-11-29','563','abc'...
``` s = ' 1234 Q-24 2010-11-29 563 abc a6G47er15 ' ss = s.split() print ss ['1234','Q-24','2010-11-29','563','abc','a6G47er15'] ```
How do I remove the light grey border around my Canvas widget?
4,310,489
15
2010-11-30T04:20:33Z
4,311,134
12
2010-11-30T06:31:37Z
[ "python", "tkinter", "tkinter-canvas" ]
I've been messing with the Tkinter `Canvas` widget in order to see if I could make some aesthetically pleasing widgets, and I have a few questions. First, why is there a *light grey border* around my Canvas widget, and how do I get rid of it? Secondly, why is the top left most position in the Canvas (2,2)? It seems l...
Section `6.8` of the [Tk Usage FAQ](http://tcl.sourceforge.net/faqs/tk/) describes the phenomenon. I was able to eliminate the border artefact with slight changes to the posted source... Change this: ``` w = Canvas(master, width=150, height=40, bd=0, relief='ridge') w.pack() ``` to: ``` w = Canvas(master, width=15...
Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
4,310,744
11
2010-11-30T05:14:06Z
4,310,752
11
2010-11-30T05:16:08Z
[ "python" ]
I want the results of the function to be: * All values evaluate to False (None, 0, empty string) -> True * All values evaluate to True -> True * Every other case -> False This is my try at it: ``` >>> def consistent(x): ... x_filtered = filter(None, x) ... return len(x_filtered) in (0, len(x)) ... >>> consistent((...
``` def all_bools_equal(lst): return all(lst) or not any(lst) ``` See: <http://docs.python.org/library/functions.html#all> See: <http://docs.python.org/library/functions.html#any>
Pythonic way to check if: all elements evaluate to False -OR- all elements evaluate to True
4,310,744
11
2010-11-30T05:14:06Z
4,310,753
23
2010-11-30T05:16:52Z
[ "python" ]
I want the results of the function to be: * All values evaluate to False (None, 0, empty string) -> True * All values evaluate to True -> True * Every other case -> False This is my try at it: ``` >>> def consistent(x): ... x_filtered = filter(None, x) ... return len(x_filtered) in (0, len(x)) ... >>> consistent((...
``` def unanimous(it): it1, it2 = itertools.tee(it) return all(it1) or not any(it2) ```
django remove source files and generate pyc files
4,311,265
3
2010-11-30T06:55:29Z
4,311,362
9
2010-11-30T07:12:24Z
[ "python", "django", "django-models", "django-templates", "django-views" ]
I want to remove all .py files in my django project.But pyc files are not generated as yet.. What is the settings that needs to be changed to generate the .pyc files
`compileall` can be used to compile all Python scripts in the project directory. ``` python -m compileall path/to/project ```
Python unescape URL
4,312,197
4
2010-11-30T09:29:32Z
4,312,223
10
2010-11-30T09:33:55Z
[ "python", "url" ]
I have got a url in this form - `http:\\/\\/en.wikipedia.org\\/wiki\\/The_Truman_Show`. How can I make it normal url. I have tried using `urllib.unquote` without much success. I can always use regular expressions or some simple string replace stuff. But I believe that there is a better way to handle this...
`urllib.unquote` is for replacing `%xx` escape codes in URLs with the characters they represent. It won't be useful for this. Your "simple string replace stuff" is probably the best solution.
Is this string Base64? How can I tell what is the encoding used?
4,312,492
6
2010-11-30T10:08:56Z
4,312,535
13
2010-11-30T10:15:45Z
[ "python", "oracle", "encryption", "encoding", "base64" ]
This is a puzzle to me and I am really annoyed that I cannot solve it! So, if anyone has some free time I would like to here some suggestions on how to solve it! I use a software that stores the password in an oracle database. The password field is of type Varchar2(100 char). It seems to me that the software encodes t...
It is actually Base64 encoded. However, it is not the password itself that is encoded, but its SHA-1 hash. ``` from sha import sha print 'cRDtpNCeBiql5KOQsKVyrA0sAiA='.decode('base64').encode('hex') print sha('1234').hexdigest() ``` or for newer versions of Python: ``` from hashlib import sha1 print 'cRDtpNCeBiql5KO...
Should I use Pylons or Pyramid?
4,313,715
48
2010-11-30T12:25:46Z
4,314,028
8
2010-11-30T12:59:58Z
[ "python", "pylons", "pyramid" ]
I was planning to move from Django to Pylons, but then I bumped into Pyramid. What are the differences between Pylons and Pyramid? I read some text in [PylonsBook](http://pylonsbook.com), which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.
If you plan to start new project, migrate or just to learn framework I recommend to use Pyramid. Pylons will stop it's development. Meanwhile Pyramid is a continuation of Pylons. Thus, it's code is stable. It includes most features from Pylons, adds some new usefull features.
Should I use Pylons or Pyramid?
4,313,715
48
2010-11-30T12:25:46Z
4,320,798
34
2010-12-01T02:55:32Z
[ "python", "pylons", "pyramid" ]
I was planning to move from Django to Pylons, but then I bumped into Pyramid. What are the differences between Pylons and Pyramid? I read some text in [PylonsBook](http://pylonsbook.com), which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.
Pylons isn't being "cancelled", and it will continue to receive updates. That said, the "future" per se is in Pyramid. On the mailing list is has been referred to as Pylons 2.0. It is fully tested and better documented than Pylons 1.0, so you might as well jump aboard if you're fresh. Pyramid is essentially the merger...
Should I use Pylons or Pyramid?
4,313,715
48
2010-11-30T12:25:46Z
4,478,103
18
2010-12-18T12:54:56Z
[ "python", "pylons", "pyramid" ]
I was planning to move from Django to Pylons, but then I bumped into Pyramid. What are the differences between Pylons and Pyramid? I read some text in [PylonsBook](http://pylonsbook.com), which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.
You want to go with Pyramid most probably. It may seem like it's a more complicated system, but it's actually much cleaner and very intuitive. Furthermore, the documentation for the project is simply awesome and in my opinion, even better then the django project which is well known for it's documentation. That does no...