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
Function parameter types in Python
2,489,669
76
2010-03-22T02:17:20Z
2,489,691
12
2010-03-22T02:22:42Z
[ "python", "function", "parameters" ]
Unless I'm mistaken, creating a function in Python works like this: ``` def my_func(param1, param2): # stuff ``` However, you don't actually give the types of those parameters. Also, if I remember, Python is a strongly typed language, as such, it seems like Python shouldn't let you pass in a parameter of a differ...
You don't specify a type. The method will only fail (at runtime) if it tries to access attributes that are not defined on the parameters that are passed in. So this simple function: ``` def no_op(param1, param2): pass ``` ... will not fail no matter what two args are passed in. However, this function: ``` def ...
Function parameter types in Python
2,489,669
76
2010-03-22T02:17:20Z
2,489,718
73
2010-03-22T02:33:15Z
[ "python", "function", "parameters" ]
Unless I'm mistaken, creating a function in Python works like this: ``` def my_func(param1, param2): # stuff ``` However, you don't actually give the types of those parameters. Also, if I remember, Python is a strongly typed language, as such, it seems like Python shouldn't let you pass in a parameter of a differ...
Python is strongly typed because every object *has* a type, every object *knows* its type, it's impossible to accidentally or deliberately use an object of a type "as if" it was an object of a *different* type, and all elementary operations on the object are delegated to its type. This has nothing to do with **names**...
Function parameter types in Python
2,489,669
76
2010-03-22T02:17:20Z
21,384,492
112
2014-01-27T15:16:18Z
[ "python", "function", "parameters" ]
Unless I'm mistaken, creating a function in Python works like this: ``` def my_func(param1, param2): # stuff ``` However, you don't actually give the types of those parameters. Also, if I remember, Python is a strongly typed language, as such, it seems like Python shouldn't let you pass in a parameter of a differ...
The other answers have done a good job at explaining duck typing and the simple answer by tzot: > Python does not have variables, like other languages where variables have a type and a value; it has names pointing to objects, which know their type. **However**, one interesting thing has changed since 2010 (when the q...
Parse http GET and POST parameters from BaseHTTPHandler?
2,490,162
20
2010-03-22T05:32:24Z
7,168,126
64
2011-08-23T22:04:28Z
[ "python", "http", "basehttpserver" ]
BaseHTTPHandler from the BaseHTTPServer module doesn't seem to provide any convenient way to access http request parameters. What is the best way to parse the GET parameters from the path, and the POST parameters from the request body? Right now, I'm using this for GET: ``` def do_GET(self): parsed_path = urlpars...
You may want to use [urlparse.parse\_qs](https://docs.python.org/2/library/urlparse.html?highlight=urlparse#urlparse.parse_qs "urlparse.parse_qs"): ``` >>> from urlparse import urlparse, parse_qs >>> url = 'http://example.com/?foo=bar&one=1' >>> parse_qs(urlparse(url).query) {'foo': ['bar'], 'one': ['1']} ```
Simple way to encode a string according to a password?
2,490,334
35
2010-03-22T06:23:04Z
2,490,376
26
2010-03-22T06:34:51Z
[ "python", "encryption", "passwords" ]
Does Python have a built-in, simple way of encoding/decoding strings using a password? Something like this: ``` >>> encode('John Doe', password = 'mypass') 'sjkl28cn2sx0' >>> decode('sjkl28cn2sx0', password = 'mypass') 'John Doe' ``` So the string "John Doe" gets encrypted as 'sjkl28cn2sx0'. To get the original stri...
As you explicitly state that you want obscurity not security, we'll avoid reprimanding you for the weakness of what you suggest :) So, using PyCrypto: ``` from Crypto.Cipher import AES import base64 msg_text = 'test some plain text here'.rjust(32) secret_key = '1234567890123456' # create new & store somewhere safe ...
Simple way to encode a string according to a password?
2,490,334
35
2010-03-22T06:23:04Z
2,490,718
18
2010-03-22T08:11:36Z
[ "python", "encryption", "passwords" ]
Does Python have a built-in, simple way of encoding/decoding strings using a password? Something like this: ``` >>> encode('John Doe', password = 'mypass') 'sjkl28cn2sx0' >>> decode('sjkl28cn2sx0', password = 'mypass') 'John Doe' ``` So the string "John Doe" gets encrypted as 'sjkl28cn2sx0'. To get the original stri...
Assuming you are *only* looking for simple obfuscation that will obscure things from the *very* casual observer, and you aren't looking to use third party libraries. I'd recommend something like the Vigenere cipher. It is one of the strongest of the simple ancient ciphers. [https://en.wikipedia.org/wiki/Vigenère\_cip...
Simple way to encode a string according to a password?
2,490,334
35
2010-03-22T06:23:04Z
16,321,853
20
2013-05-01T16:07:29Z
[ "python", "encryption", "passwords" ]
Does Python have a built-in, simple way of encoding/decoding strings using a password? Something like this: ``` >>> encode('John Doe', password = 'mypass') 'sjkl28cn2sx0' >>> decode('sjkl28cn2sx0', password = 'mypass') 'John Doe' ``` So the string "John Doe" gets encrypted as 'sjkl28cn2sx0'. To get the original stri...
The "encoded\_c" mentioned in the @smehmood's Vigenere cipher answer should be "key\_c". Here are working encode/decode functions. ``` import base64 def encode(key, clear): enc = [] for i in range(len(clear)): key_c = key[i % len(key)] enc_c = chr((ord(clear[i]) + ord(key_c)) % 256) en...
Simple way to encode a string according to a password?
2,490,334
35
2010-03-22T06:23:04Z
21,754,610
9
2014-02-13T12:43:54Z
[ "python", "encryption", "passwords" ]
Does Python have a built-in, simple way of encoding/decoding strings using a password? Something like this: ``` >>> encode('John Doe', password = 'mypass') 'sjkl28cn2sx0' >>> decode('sjkl28cn2sx0', password = 'mypass') 'John Doe' ``` So the string "John Doe" gets encrypted as 'sjkl28cn2sx0'. To get the original stri...
As has been mentioned the PyCrypto library contains a suite of ciphers. The XOR cipher can be used to do the dirty work if you don't want to do it yourself: ``` from Crypto.Cipher import XOR import base64 def encrypt(key, plaintext): cipher = XOR.new(key) return base64.b64encode(cipher.encrypt(plaintext)) def de...
Enforce "spaces" or "tabs" only in python files?
2,490,686
3
2010-03-22T08:04:26Z
2,491,548
10
2010-03-22T10:50:34Z
[ "python", "tabs", "indentation", "spaces" ]
In Python, is there a mean to enforce the use of spaces or tabs indentation with a per file basis ? Well, perhaps "enforce" is too strong, more like a "recommendation". I keep receiving patch files with mixed indentation and this is annoying... (to say the least) Python itself can tell when there is a problem, but I ...
Tim Peters has written a nifty script called [reindent.py](http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py) which converts .py files to use 4-space indents and no tabs. It is available [here](http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py), but check your distribution first ...
How to read and write a file using python?
2,491,141
3
2010-03-22T09:47:56Z
2,491,155
11
2010-03-22T09:51:35Z
[ "python", "django" ]
I want to write the text (which I get from AJAX) to a file, and then read it.
The tutorial [covers this](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files).
How to rename a file using Python
2,491,222
36
2010-03-22T09:59:23Z
2,491,231
18
2010-03-22T10:00:41Z
[ "python", "file-rename" ]
I want to change `a.txt` to `b.kml`.
``` import shutil shutil.move('a.txt', 'b.kml') ``` This will work to rename or move a file.
How to rename a file using Python
2,491,222
36
2010-03-22T09:59:23Z
2,491,232
75
2010-03-22T10:00:52Z
[ "python", "file-rename" ]
I want to change `a.txt` to `b.kml`.
Use [`os.rename`](http://docs.python.org/library/os.html#os.rename)`('a.txt','b.kml')`
How to rename a file using Python
2,491,222
36
2010-03-22T09:59:23Z
2,491,233
8
2010-03-22T10:00:55Z
[ "python", "file-rename" ]
I want to change `a.txt` to `b.kml`.
`os.rename(old, new)` From <http://docs.python.org/library/os.html>. This really isn't hard to find...
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
2,491,831
43
2010-03-22T11:37:52Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
`__init__` returns the newly created object. You cannot (or at least shouldn't) return something else. Try making whatever you want to return an instance variable (or function). ``` >>> class Foo: ... def __init__(self): ... return 42 ... >>> foo = Foo() Traceback (most recent call last): File "<stdin>...
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
2,491,843
8
2010-03-22T11:39:51Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
`__init__` doesn't return anything and should always return `None`.
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
2,491,855
27
2010-03-22T11:41:16Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
From the [documentation of `__init__`](http://docs.python.org/reference/datamodel.html#object.__init__): > *As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.* As a proof, this code: ``` class Foo(object): def __init__(self): return...
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
2,491,881
61
2010-03-22T11:46:09Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
Why would you want to do that? If you want to return some other object when a class is called, then use the `__new__()` method: ``` class MyClass(object): def __init__(self): print "never called in this case" def __new__(cls): return 42 obj = MyClass() print obj ```
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
2,491,913
8
2010-03-22T11:52:08Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
The `__init__` method, like other methods and functions returns None by default in the absence of a return statement, so you can write it like either of these: ``` class Foo: def __init__(self): self.value=42 class Bar: def __init__(self): self.value=42 return None ``` But, of course,...
How to return a value from __init__ in Python?
2,491,819
38
2010-03-22T11:35:10Z
17,512,201
12
2013-07-07T12:37:09Z
[ "python", "class", "init" ]
I have a class with an `__init__` function. How can I return an integer value from this function when an object is created? I wrote a program, where `__init__` does command line parsing and I need to have some value set. Is it OK set it in global variable and use it in other member functions? If so how to do that? So...
Sample Usage of the matter in question can be like: ``` class SampleObject(object) def __new__(cls,Item) if self.IsValid(Item): return super(SampleObject, cls).__new__(cls) else: return None def __init__(self,Item) self.InitData(Item) #large amount of data and ...
How to get the nth element of a python list or a default if not available
2,492,087
55
2010-03-22T12:17:00Z
2,492,093
60
2010-03-22T12:18:48Z
[ "python", "list" ]
I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5 if myList is an empty list.
``` x[index] if len(x) > index else default ``` to support negative indices we can use: ``` x[index] if -len(l) <= index < len(l) else default ```
How to get the nth element of a python list or a default if not available
2,492,087
55
2010-03-22T12:17:00Z
2,492,094
27
2010-03-22T12:18:55Z
[ "python", "list" ]
I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5 if myList is an empty list.
``` try: a = b[n] except IndexError: a = default ``` Edit: I removed the check for TypeError - probably better to let the caller handle this.
How to get the nth element of a python list or a default if not available
2,492,087
55
2010-03-22T12:17:00Z
2,492,102
10
2010-03-22T12:19:45Z
[ "python", "list" ]
I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5 if myList is an empty list.
``` (L[n:n+1] or [somedefault])[0] ```
How to get the nth element of a python list or a default if not available
2,492,087
55
2010-03-22T12:17:00Z
2,492,141
13
2010-03-22T12:25:46Z
[ "python", "list" ]
I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5 if myList is an empty list.
``` (a[n:]+[default])[0] ``` This is probably better as `a` gets larger ``` (a[n:n+1]+[default])[0] ``` This works because if `a[n:]` is an empty list if `n => len(a)` Here is an example of how this works with `range(5)` ``` >>> range(5)[3:4] [3] >>> range(5)[4:5] [4] >>> range(5)[5:6] [] >>> range(5)[6:7] [] ``` ...
How to get the nth element of a python list or a default if not available
2,492,087
55
2010-03-22T12:17:00Z
22,865,211
10
2014-04-04T14:12:40Z
[ "python", "list" ]
I'm looking for an equivalent in python of dictionary.get(key, default) for lists. Is there any one liner idiom to get the nth element of a list or a default value if not available? For example, given a list myList I would like to get myList[0], or 5 if myList is an empty list.
Just dicovered that : ``` next(iter(myList), 5) ``` `iter(l)` returns an iterator on `myList`, `next()` consumes the first element of the iterator, and raises a `StopIteration` error except if called with a default value, which is the case here, the second argument, `5` This only works when you want the 1st element,...
Python: Split by 1 or more occurrences of a delimiter
2,492,415
14
2010-03-22T13:12:16Z
2,492,429
12
2010-03-22T13:14:56Z
[ "python", "string", "split", "delimiter" ]
I have a formatted string from a log file, which looks like: ``` >>> a="test result" ``` That is, the test and the result are split by some spaces - it was probably created using formatted string which gave `test` some constant spacing. Simple splitting won't do the trick: ``` >>> a.split...
Just this should work: ``` a.split() ``` Example: ``` >>> 'a b'.split(' ') ['a', '', '', '', '', '', 'b'] >>> 'a b'.split() ['a', 'b'] ``` From the [documentation](http://docs.python.org/library/stdtypes.html#str.split): > If sep is not specified or is None, a different splitting algorithm is applied: ru...
Python: Split by 1 or more occurrences of a delimiter
2,492,415
14
2010-03-22T13:12:16Z
2,492,430
15
2010-03-22T13:15:01Z
[ "python", "string", "split", "delimiter" ]
I have a formatted string from a log file, which looks like: ``` >>> a="test result" ``` That is, the test and the result are split by some spaces - it was probably created using formatted string which gave `test` some constant spacing. Simple splitting won't do the trick: ``` >>> a.split...
``` >>> import re >>> a="test result" >>> re.split(" +",a) ['test', 'result'] >>> a.split() ['test', 'result'] ```
Python: Split by 1 or more occurrences of a delimiter
2,492,415
14
2010-03-22T13:12:16Z
2,492,447
26
2010-03-22T13:16:16Z
[ "python", "string", "split", "delimiter" ]
I have a formatted string from a log file, which looks like: ``` >>> a="test result" ``` That is, the test and the result are split by some spaces - it was probably created using formatted string which gave `test` some constant spacing. Simple splitting won't do the trick: ``` >>> a.split...
Just do not give any delimeter? ``` >>> a="test result" >>> a.split() ['test', 'result'] ```
How can you do Co-routines using C#?
2,493,294
9
2010-03-22T15:07:51Z
2,494,660
13
2010-03-22T18:12:39Z
[ "c#", "python", "system.reactive", "coroutine" ]
In python the yield keyword can be used in both push and pull contexts, I know how to do the pull context in c# but how would I achieve the push. I post the code I am trying to replicate in c# from python: ``` def coroutine(func): def start(*args,**kwargs): cr = func(*args,**kwargs) cr.next() return cr ...
If what you want is an "observable collection" -- that is, a collection which pushes results at you rather than letting the consumer pull them -- then you probably want to look into the Reactive Framework extensions. Here's an article on it: <http://www.infoq.com/news/2009/07/Reactive-Framework-LINQ-Events> Now, as y...
complex if statement in python
2,493,404
17
2010-03-22T15:21:27Z
2,493,420
14
2010-03-22T15:23:16Z
[ "python" ]
I need to realize a *complex* if-elif-else statement in Python but I don't get it working. The elif line I need has to check a variable for this conditions: **80, 443 or 1024-65535 inclusive** I tried ``` if ... # several checks ... elif (var1 > 65535) or ((var1 < 1024) and (var1 != 80) and (var1 != 443)): ...
It's often easier to think in the positive sense, and wrap it in a not: ``` elif not (var1 == 80 or var1 == 443 or (1024 <= var1 <= 65535)): # fail ``` You could of course also go all out and be a bit more object-oriented: ``` class PortValidator(object): @staticmethod def port_allowed(p): if p == 80: retu...
complex if statement in python
2,493,404
17
2010-03-22T15:21:27Z
2,493,434
26
2010-03-22T15:24:20Z
[ "python" ]
I need to realize a *complex* if-elif-else statement in Python but I don't get it working. The elif line I need has to check a variable for this conditions: **80, 443 or 1024-65535 inclusive** I tried ``` if ... # several checks ... elif (var1 > 65535) or ((var1 < 1024) and (var1 != 80) and (var1 != 443)): ...
This should do it: ``` elif var == 80 or var == 443 or 1024 <= var <= 65535: ```
How to make Twisted use Python logging?
2,493,644
20
2010-03-22T15:51:43Z
2,493,725
22
2010-03-22T16:01:20Z
[ "python", "twisted" ]
I've got a project where I'm using Twisted for my web server. When exceptions occur (such as network errors), it's printing to the console. I've already got logging through Python's built-in log module - is there any way to tell the reactor to use that instead? What's the usual pattern for this?
Found it. It's actually quite easy: ``` from twisted.python import log observer = log.PythonLoggingObserver(loggerName='logname') observer.start() ``` You just set loggerName to the same logger name that you're using in logging.getLogger().
How to switch position of two items in a Python list?
2,493,920
81
2010-03-22T16:25:14Z
2,493,962
69
2010-03-22T16:30:05Z
[ "python", "list", "order" ]
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words). It’s rather simple – I have this list: ``` ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] ``` I’d like to...
The simple Python swap looks like this: ``` foo[i], foo[j] = foo[j], foo[i] ``` Now all you need to do is figure what `i` is, and that can easily be done with `index`: ``` i = foo.index("password2") ```
How to switch position of two items in a Python list?
2,493,920
81
2010-03-22T16:25:14Z
2,493,980
161
2010-03-22T16:31:49Z
[ "python", "list", "order" ]
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words). It’s rather simple – I have this list: ``` ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] ``` I’d like to...
``` i = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] a, b = i.index('password2'), i.index('password1') i[b], i[a] = i[a], i[b] ```
How to switch position of two items in a Python list?
2,493,920
81
2010-03-22T16:25:14Z
2,494,003
11
2010-03-22T16:35:28Z
[ "python", "list", "order" ]
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words). It’s rather simple – I have this list: ``` ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] ``` I’d like to...
Given your specs, I'd use slice-assignment: ``` >>> L = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] >>> i = L.index('password2') >>> L[i:i+2] = L[i+1:i-1:-1] >>> L ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter'] ``` The ri...
Properly using subprocess.PIPE in python?
2,493,976
13
2010-03-22T16:31:27Z
2,494,023
13
2010-03-22T16:38:22Z
[ "python", "subprocess" ]
I'm trying to use `subprocess.Popen` to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: ``` import sys import os import subprocess def main(): the_file = "/Volumes/Fo...
Using `subprocess.PIPE` will not magically wire the correct pipes for you. You must pass the output pipe of the first process as the value for the parameter `stdin` of the second process. [See the docs for an example](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline).
Properly using subprocess.PIPE in python?
2,493,976
13
2010-03-22T16:31:27Z
2,494,110
12
2010-03-22T16:49:56Z
[ "python", "subprocess" ]
I'm trying to use `subprocess.Popen` to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: ``` import sys import os import subprocess def main(): the_file = "/Volumes/Fo...
stderr needs to be redirected to stdout. Also, there's no need to call other tools like `cut/sed` etc. do your string manipulation in Python ``` import subprocess .... the_file = "/Volumes/Footage/Acura/MDX/2001/Crash Test/01 Acura MDX Front Crash.mov" ffmpeg = subprocess.Popen(['/usr/bin/ffmpeg', '-i', the_file], std...
Properly using subprocess.PIPE in python?
2,493,976
13
2010-03-22T16:31:27Z
18,070,129
19
2013-08-06T00:51:45Z
[ "python", "subprocess" ]
I'm trying to use `subprocess.Popen` to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: ``` import sys import os import subprocess def main(): the_file = "/Volumes/Fo...
As others have pointed out, you need to pass the PIPE from one process to the next. The stdout (PIPE) from one process becomes the stdin for the following task. Something like this (starting from your example): ``` import sys import os import subprocess def main(): the_file = "/Volumes/Footage/Acura/MDX/ ...
ctypes and pointer manipulation
2,494,288
5
2010-03-22T17:18:04Z
2,494,481
8
2010-03-22T17:45:57Z
[ "python", "ctypes" ]
I am dealing with image buffers, and I want to be able to access data a few lines into my image for analysis with a c library. I have created my 8-bit pixel buffer in Python using create\_string\_buffer. Is there a way to get a pointer to a location within that buffer without re-creating a new buffer? My goal is to ana...
[create\_string\_buffer](http://docs.python.org/library/ctypes.html?highlight=ctypes#ctypes.create_string_buffer) gives you a ctypes object (an array of chars), then [byref](http://docs.python.org/library/ctypes.html?highlight=ctypes#ctypes.byref), and I quote, > Returns a light-weight pointer to obj, > which must be ...
ssh-rsa public key validation using a regular expression
2,494,450
7
2010-03-22T17:41:02Z
2,494,645
9
2010-03-22T18:10:07Z
[ "python", "regex", "validation", "ssh-keys" ]
What regular expression can I use (if any) to validate that a given string is a legal ssh rsa public key? I only need to validate the actual key - I don't care about the key type the precedes it or the username comment after it. Ideally, someone will also provide the python code to run the regex validation. Thanks.
A "good enough" check is to see if the key starts with the correct header. The data portion of the keyfile should decode from base64, or it will fail with a base64.binascii.Error Unpack the first 4 bytes (an int), which should be 7. This is the length of the following string (I guess this could be different, but you'...
Modify default queryset in django
2,494,501
14
2010-03-22T17:48:12Z
2,494,558
21
2010-03-22T17:56:29Z
[ "python", "django", "django-models", "metaprogramming" ]
I have added a 'cancelled' field to my model, is there a way to modify the model default query to something like cancelled=False ? without having to modify all my filter/exclude queries ?
You can do this with a custom model manager and override the `get_query_set` function to always filter canceled=False. ``` class CustomManager(models.Manager): def get_query_set(self): return super(CustomManager, self).get_queryset().filter(canceled=False) class MyModel(models.Model): # Blah blah ...
Sort a list of tuples without case sensitivity
2,494,740
4
2010-03-22T18:26:30Z
2,494,764
9
2010-03-22T18:30:44Z
[ "python", "sorting", "tuples", "case-insensitive" ]
How can I efficiently and easily sort a list of tuples *without* being sensitive to case? For example this: ``` [('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] ``` Should look like this once sorted: ``` [('a', 5), ('a', 'a'), ('A', 'b'), ('a', 'c')] ``` The regular lexicographic sort will put 'A' before 'a' and yie...
You can use `sort`'s `key` argument to define how you wish to regard each element with respect to sorting: ``` def lower_if_possible(x): try: return x.lower() except AttributeError: return x L=[('a', 'c'), ('A', 'b'), ('a', 'a'), ('a', 5)] L.sort(key=lambda x: map(lower_if_possible,x)) print(...
Displaying a list of items vertically in a table instead of horizonally
2,495,046
4
2010-03-22T19:18:41Z
2,495,133
9
2010-03-22T19:34:15Z
[ "python", "html", "table" ]
I have a list of items sorted alphabetically: ``` mylist = [a,b,c,d,e,f,g,h,i,j] ``` I'm able to output the list in an html table horizonally like so: ``` | a , b , c , d | | e , f , g , h | | i , j , , | ``` What's the algorithm to create the table vertically like this: ``` | a , d , g , j | | b , e , h , |...
``` >>> l = [1,2,3,4,5,6,7,8,9,10] >>> [l[i::3] for i in xrange(3)] [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]] ``` Replace `3` by the number of lines you want as a result: ``` >>> [l[i::5] for i in xrange(5)] [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]] ```
Writing Strings to files in python
2,495,290
3
2010-03-22T19:58:51Z
2,495,327
13
2010-03-22T20:04:46Z
[ "python", "string", "file", "io", "python-3.x" ]
I'm getting the following error when trying to write a string to a file in pythion: ``` Traceback (most recent call last): File "export_off.py", line 264, in execute save_off(self.properties.path, context) File "export_off.py", line 244, in save_off primary.write(file) File "export_off.py", line 181, in ...
What version of Python are you using? In Python 3.x a string contains Unicode text in no particular encoding. To write it out to a stream of bytes (a file) you must convert it to a byte encoding such as UTF-8, UTF-16, and so on. Fortunately this is easily done with the `encode()` method: ``` Python 3.1.1 (...) >>> s =...
Python or Ruby for webbased Artificial Intelligence?
2,495,350
4
2010-03-22T20:09:21Z
2,497,026
8
2010-03-23T01:46:14Z
[ "python", "ruby-on-rails", "artificial-intelligence", "prolog" ]
A new web application may require adding Artificial Intelligence (AI) in the future, e.g. using ProLog. I know it can be done from a Java environment, but I am wondering about the opportunities with modern web languages like Ruby or Python. The latter is considered to be "more scientific" (at least used in that environ...
The selection of language is completely irrelevant, all other things being equal. If you're trying to do X and there's a library for it in language Y and meshes well with your Web-based framework, then use it. Without knowing more about what specific areas of AI you're interested in, the question is far too vague to ...
Variable alpha blending in pylab
2,495,656
7
2010-03-22T20:52:46Z
2,495,884
7
2010-03-22T21:27:34Z
[ "python", "alphablending", "matplotlib" ]
How does one control the transparency over a 2D image in pylab? I'd like to give two sets of values `(X,Y,Z,T)` where `X,Y` are arrays of positions, `Z` is the color value, and `T` is the transparency to a function like `imshow` but it seems that the function only takes alpha as a scalar. As a concrete example, conside...
One thing that you can do is modify what you put into imshow. The first variable can be grayscale values as you have used or it can be RGB or RGBA values. If you RGB/RGBA values then the cmap is ignored. So for instance, ``` imshow(Z1, cmap=cm.hsv, alpha=.6, extent=extent) ``` will generate the same image as ``` ims...
Filtering documents against a dictionary key in MongoDB
2,495,932
3
2010-03-22T21:33:50Z
2,496,018
7
2010-03-22T21:48:51Z
[ "python", "mongodb", "pymongo" ]
I have a collection of articles in MongoDB that has the following structure: ``` { 'category': 'Legislature', 'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000), 'byline': None, 'tags': { 'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Ric...
If the "geography" field doesn't exist when there aren't any tags in it (i.e., it's created when you add a location), you could do: ``` db.articles.find({tags.geography : {$exists : true}}) ``` If it does exists and is empty (i.e., `"geography" : []`) you should add a `geography_size` field or something and do: ``` ...
Asynchronous background processes in Python?
2,496,772
6
2010-03-23T00:40:48Z
2,496,824
15
2010-03-23T00:50:32Z
[ "python", "asynchronous", "background-process" ]
I have been using this as a reference, but not able to accomplish exactly what I need: <http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395> I also was reading this: <http://www.python.org/dev/peps/pep-3145/> For our project, we have 5 svn checkouts that need to update before w...
Don't use `shell=True`. It will needlessy invoke the shell to call your `svn` program, and that will give you the shell's return code instead of svn's. ``` repos = ['/repo1', '/repo2', '/repo3'] # launch 3 async calls: procs = [subprocess.Popen(['svn', 'update', repo]) for repo in repos] # wait. for proc in procs: ...
read a binary file (python)
2,497,027
5
2010-03-23T01:46:20Z
2,497,038
10
2010-03-23T01:49:40Z
[ "python", "file", "io" ]
I cant read a file, and I dont understand why: ``` f = open("test/test.pdf", "r") data = list(f.read()) print data ``` Returns : `[]` I would like to open a PDF, and extract every bytes, and put it in a List. What's wrong with my code ? :( Thanks,
``` f = open("test/test.pdf", "rb") ``` You must include the pseudo-mode "b" for binary when reading and writing on Windows. Otherwise the OS silently translates what it considers to be "line endings", causing i/o corruption.
How can I tell [G]vim where to look for python26.dll?
2,497,551
8
2010-03-23T04:20:55Z
2,497,651
8
2010-03-23T04:50:51Z
[ "python", "vim" ]
I have a version of Vim compiled with python 2.6 support enabled ([from here](http://www.gooli.org/blog/)). however vim cannot find the python26.dll. ``` :version confirms +python/dyn :version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll" echo PATH confirms python26.dll is in the search path. (both c:\wi...
Be sure that any dll you try to load is compiled for the same architecture as the exe. e.g. If you have x86 Vim installed. Make sure that the python dll you are loading is not x64, or vice-versa.
Python overriding class (not instance) special methods
2,497,790
8
2010-03-23T05:35:25Z
2,497,807
15
2010-03-23T05:41:34Z
[ "python", "class", "override" ]
How do I override a class special method? I want to be able to call the `__str__()` method of the class without creating an instance. Example: ``` class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' class ClassFoo: @classmethod ...
Special method `__str__` defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5) ``` class Meta(type): def __str__(self): return "Klass" class A(object): __metaclass__ = Meta ...
How to Pythonically yield all values from a list?
2,498,388
17
2010-03-23T08:17:57Z
2,498,412
21
2010-03-23T08:24:34Z
[ "python", "generator", "yield" ]
Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that? Here is what I mean. Thanks to some non-lazy computation I have computed the list `['a', 'b', 'c', 'd']`, but my code through the project uses lazy computation, so I'd like to yield values from my functi...
Use `iter` to create a list iterator e.g. ``` return iter(List) ``` though if you already have a list, you can just return that, which will be more efficient.
How to Pythonically yield all values from a list?
2,498,388
17
2010-03-23T08:17:57Z
18,620,655
20
2013-09-04T17:53:31Z
[ "python", "generator", "yield" ]
Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that? Here is what I mean. Thanks to some non-lazy computation I have computed the list `['a', 'b', 'c', 'd']`, but my code through the project uses lazy computation, so I'd like to yield values from my functi...
Since this question doesn't specify; I'll provide an answer that applies in [Python >= 3.3](http://www.python.org/dev/peps/pep-0380/) If you need only to return that list, do as [Anurag suggests](http://stackoverflow.com/a/2498412/65696), but if for some reason the function in question really needs to be a generator, ...
How to invert colors of image with PIL (Python-Imaging)?
2,498,875
18
2010-03-23T09:54:25Z
2,498,909
32
2010-03-23T10:01:24Z
[ "python", "python-imaging-library" ]
I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?
Try the following from the docs: <http://effbot.org/imagingbook/imageops.htm> ``` from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') inverted_image = PIL.ImageOps.invert(image) inverted_image.save('new_name.png') ``` Note: "The ImageOps module contains a number of 'ready-made' image...
How to invert colors of image with PIL (Python-Imaging)?
2,498,875
18
2010-03-23T09:54:25Z
12,880,019
8
2012-10-14T06:57:45Z
[ "python", "python-imaging-library" ]
I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?
If the image is RGBA transparent this will fail... This should work though: ``` from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') if image.mode == 'RGBA': r,g,b,a = image.split() rgb_image = Image.merge('RGB', (r,g,b)) inverted_image = PIL.ImageOps.invert(rgb_image) ...
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
9
2010-03-23T12:20:07Z
2,499,833
10
2010-03-23T12:34:19Z
[ "python", "perl", "unix", "batch-file" ]
I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner. On Unix I could do this: ``` cut -d " " -f 1-3 <my file> ``` How can I do this on Windows?
Here is a Perl one-liner to print the first 3 whitespace-delimited columns of a file. This can be run on Windows (or Unix). Refer to [perlrun](http://perldoc.perl.org/perlrun.html). ``` perl -ane "print qq(@F[0..2]\n)" file.txt ```
in Python find number of same elements in 2 lists
2,500,124
4
2010-03-23T13:17:40Z
2,500,136
9
2010-03-23T13:18:49Z
[ "python", "arrays", "array-intersect" ]
In Python if I have 2 lists say: ``` l1 = ['a', 'b', 'c', 'd'] l2 = ['c', 'd', 'e'] ``` is there a way to find out how many elements they have the same. In the case about it would be 2 (c and d) I know I could just do a nested loop but is there not a built in function like in php with the array\_intersect function ...
You can use a set intersection for that :) ``` l1 = ['a', 'b', 'c', 'd'] l2 = ['c', 'd', 'e'] set(l1).intersection(l2) set(['c', 'd']) ```
Bash or python for changing spacing in files
2,500,358
3
2010-03-23T13:47:52Z
2,500,416
9
2010-03-23T13:55:44Z
[ "python", "bash" ]
I have a set of 10000 files. In all of them, the second line, looks like: ``` AAA 3.429 3.84 ``` so there is just one space (requirement) between AAA and the two other columns. The rest of lines on each file are completely different and correspond to 10 columns of numbers. Randomly, in around 20% of the files, and d...
Performing line-based changes to text files is often simplest to do in `sed`. ``` sed -e '2s/ */ /g' infile.txt ``` will replace any runs of multiple spaces with a single space. This may be changing more than you want, though. ``` sed -e '2s/^\([^ ]*\) /\1 /' infile.txt ``` should just replace instances of two sp...
Getting libstdc++-v3/python
2,500,521
5
2010-03-23T14:08:23Z
2,500,691
7
2010-03-23T14:33:23Z
[ "c++", "python", "svn", "download", "gdb" ]
I am trying to download libstdc++-v3/python to enable pretty printing of stl containers. However, my provider returns: **svn: Unknown hostname 'gcc.gnu.org'** error. This is the command: ``` svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python ``` **Is there an alternative way to get this package?**
try http:// instead of svn:// that would be : svn co <http://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python>
How to step through debug twisted?
2,501,136
4
2010-03-23T15:26:12Z
2,501,863
9
2010-03-23T16:49:34Z
[ "python", "netbeans", "debugging", "twisted" ]
I'd like to be able to debug Punjab, a twisted python application, in Netbeans so that I can step through the code. How can I do that? Alternatively, how could I do it in a different debugger?
Since you're trying to debug a twisted application, you have a few options: 1. If you're running via twistd you can use the -b command-line options: ``` -b, --debug run the application in the Python Debugger (implies nodaemon), sending SIGUSR2 will drop into debugger ...
Copying and pasting code into the Python interpreter
2,501,208
21
2010-03-23T15:34:15Z
2,503,794
21
2010-03-23T21:33:45Z
[ "python" ]
There is a snippet of code that I would like to copy and paste into my Python interpreter. Unfortunately due to Python's sensitivity to whitespace it is not straightforward to copy and paste it a way that makes sense. (I think the whitespace gets mangled) Is there a better way? Maybe I can load the snippet from a file....
You can usually easily and safely do copy-pasting with [IPython](http://ipython.scipy.org/moin/), through the commands `%cpaste` and `%paste`. This is very handy for testing code that you copy from web pages, for instance, or from your editor. IPython also has a `%run` command that runs a program and leaves you in a Py...
String comparison in Numpy
2,501,362
3
2010-03-23T15:50:20Z
2,501,540
9
2010-03-23T16:07:48Z
[ "python", "numpy" ]
In the following example ``` In [8]: import numpy as np In [9]: strings = np.array(['hello ', 'world '], dtype='|S10') In [10]: strings == 'hello' Out[10]: array([False, False], dtype=bool) ``` The comparison fails because of the whitespace. Is there a Numpy built-in function that does the equivalent of ``` ...
Numpy provides vectorised string operations for arrays similar to Python's string methods. They are in the numpy.char module. <http://docs.scipy.org/doc/numpy/reference/routines.char.html> ``` import numpy as np strings = np.array(['hello ', 'world '], dtype='|S10') print np.char.strip(strings) == 'hello' # p...
What do I use for a max-heap implementation in Python?
2,501,457
65
2010-03-23T15:58:02Z
2,501,527
63
2010-03-23T16:05:39Z
[ "python", "data-structures", "heap", "recursive-datastructures" ]
Python includes the heapq module for min-heaps, but I need a max heap. What should I use for a max-heap implementation in Python?
The easiest way is to invert the value of the keys and use heapq. For example, turn 1000.0 into -1000.0 and 5.0 into -5.0.
What do I use for a max-heap implementation in Python?
2,501,457
65
2010-03-23T15:58:02Z
23,636,408
48
2014-05-13T16:10:52Z
[ "python", "data-structures", "heap", "recursive-datastructures" ]
Python includes the heapq module for min-heaps, but I need a max heap. What should I use for a max-heap implementation in Python?
You can use ``` import heapq listForTree = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] heapq.heapify(listForTree) # for a min heap heapq._heapify_max(listForTree) # for a maxheap!! ```
Deleting python modules?
2,501,746
9
2010-03-23T16:32:26Z
2,501,894
11
2010-03-23T16:54:38Z
[ "python" ]
Can you delete python modules? I've installed one that I would like to remove, and can't seem to figure out how. Thanks
To find where the module is, just do a: ``` $ python >> import module >> print module.__file__ '/some/directory' ``` or if it is a package: ``` >> import package >> print package.__path__ ``` and delete it.
Python: HTTP Post a large file with streaming
2,502,596
13
2010-03-23T18:31:57Z
2,504,133
22
2010-03-23T22:40:46Z
[ "python", "http", "urllib2" ]
I'm uploading potentially large files to a web server. Currently I'm doing this: ``` import urllib2 f = open('somelargefile.zip','rb') request = urllib2.Request(url,f.read()) request.add_header("Content-Type", "application/zip") response = urllib2.urlopen(request) ``` However, this reads the entire file's contents i...
Reading through the mailing list thread linked to by systempuntoout, I found a clue towards the solution. The `mmap` module allows you to open file that acts like a string. Parts of the file are loaded into memory on demand. Here's the code I'm using now: ``` import urllib2 import mmap # Open the file as a memory m...
Store output of subprocess.Popen call in a string
2,502,833
155
2010-03-23T19:05:01Z
2,502,872
25
2010-03-23T19:12:58Z
[ "python", "subprocess" ]
I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program. ``` #!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") ``` I've tried a few things including some of the suggestions here: [Retrieving the output of subprocess.call()](http://sta...
This worked for me for redirecting stdout (stderr can be handled similarly): ``` from subprocess import Popen, PIPE pipe = Popen(path, stdout=PIPE) text = pipe.communicate()[0] ``` If it doesn't work for you, please specify exactly the problem you're having.
Store output of subprocess.Popen call in a string
2,502,833
155
2010-03-23T19:05:01Z
2,502,881
17
2010-03-23T19:14:00Z
[ "python", "subprocess" ]
I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program. ``` #!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") ``` I've tried a few things including some of the suggestions here: [Retrieving the output of subprocess.call()](http://sta...
Assuming that `pwd` is just an example, this is how you can do it: ``` import subprocess p = subprocess.Popen("pwd", stdout=subprocess.PIPE) result = p.communicate()[0] print result ``` See the [subprocess documentation](http://docs.python.org/library/subprocess.html) for [another example](http://docs.python.org/lib...
Store output of subprocess.Popen call in a string
2,502,833
155
2010-03-23T19:05:01Z
2,502,883
265
2010-03-23T19:14:14Z
[ "python", "subprocess" ]
I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program. ``` #!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") ``` I've tried a few things including some of the suggestions here: [Retrieving the output of subprocess.call()](http://sta...
**In Python 2.7 or Python 3** Instead of making a `Popen` object directly, you can use the [`subprocess.check_output()` function](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) to store output of a command in a string: ``` from subprocess import check_output out = check_output(["ntpq", "-p...
Store output of subprocess.Popen call in a string
2,502,833
155
2010-03-23T19:05:01Z
16,266,707
10
2013-04-28T19:14:19Z
[ "python", "subprocess" ]
I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program. ``` #!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") ``` I've tried a few things including some of the suggestions here: [Retrieving the output of subprocess.call()](http://sta...
subprocess.Popen: <http://docs.python.org/2/library/subprocess.html#subprocess.Popen> ``` import subprocess command = "ntpq -p" # the shell command process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True) #Launch the shell command: output = process.communicate() print output[0] ``` In ...
What is your strategy to avoid dynamic typing errors in Python (NoneType has no attribute x)?
2,503,444
8
2010-03-23T20:40:59Z
2,503,704
7
2010-03-23T21:19:36Z
[ "python" ]
I'm not sure if I like Python's dynamic-ness. It often results in me forgetting to check a type, trying to call an attribute and getting the NoneType (or any other) has no attribute x error. A lot of them are pretty harmless but if not handled correctly they can bring down your entire app/process/etc. Over time I got ...
> forgetting to check a type This doesn't make much sense. You so rarely need to "check" a type. You simply run unit tests and if you've provided the wrong type object, things fail. You never need to "check" much, in my experience. > trying to call an attribute and > getting the NoneType (or any other) > has no attri...
Pygtk entry placeholder
2,503,562
2
2010-03-23T20:56:15Z
2,504,473
8
2010-03-23T23:52:43Z
[ "python", "pygtk" ]
How to create pygtk entry with placeholder like in HTML 5 input element?
Try this code if it does what you need: ``` import gtk class PlaceholderEntry(gtk.Entry): placeholder = 'Username' _default = True def __init__(self, *args, **kwds): gtk.Entry.__init__(self, *args, **kwds) self.connect('focus-in-event', self._focus_in_event) self.connect('focus-...
How to resize and draw an image using wxpython?
2,504,143
8
2010-03-23T22:41:50Z
2,504,607
20
2010-03-24T00:27:04Z
[ "python", "image", "wxpython", "resize", "draw" ]
I want to load an image, resize it to a given size and after draw it in a specific position in a panel. All this using wxpython. How can I do it? Thanks in advance!
`wx.Image` has a `Scale` method that will do the resizing. The rest is normal wx coding. Here's a complete example for you. ``` import wx def scale_bitmap(bitmap, width, height): image = wx.ImageFromBitmap(bitmap) image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH) result = wx.BitmapFromImage(image...
Proper indentation for Python multiline strings
2,504,411
307
2010-03-23T23:35:28Z
2,504,454
163
2010-03-23T23:45:46Z
[ "python", "string" ]
What is the proper indentation for Python multiline strings within a function? ``` def method(): string = """line one line two line three""" ``` or ``` def method(): string = """line one line two line three""" ``` or something else? It looks kind of weird to have the string ...
The [`textwrap.dedent`](http://docs.python.org/library/textwrap.html#textwrap.dedent) function allows one to start with **correct indentation in the source**, and then strip it from the text before use. The trade-off, as noted by some others, is that this is an extra function call on the literal; take this into accoun...
Proper indentation for Python multiline strings
2,504,411
307
2010-03-23T23:35:28Z
2,504,457
338
2010-03-23T23:46:35Z
[ "python", "string" ]
What is the proper indentation for Python multiline strings within a function? ``` def method(): string = """line one line two line three""" ``` or ``` def method(): string = """line one line two line three""" ``` or something else? It looks kind of weird to have the string ...
You probably want to line up with the `"""` ``` def foo(): string = """line one line two line three""" ``` Since the newlines and spaces are included in the string itself, you will have to postprocess it. If you don't want to do that and you have a whole lot of text, you might want to st...
Proper indentation for Python multiline strings
2,504,411
307
2010-03-23T23:35:28Z
16,829,814
12
2013-05-30T06:56:58Z
[ "python", "string" ]
What is the proper indentation for Python multiline strings within a function? ``` def method(): string = """line one line two line three""" ``` or ``` def method(): string = """line one line two line three""" ``` or something else? It looks kind of weird to have the string ...
Some more options. In Ipython with pylab enabled, dedent is already in the namespace. I checked and it is from matplotlib. Or it can be imported with: ``` from matplotlib.cbook import dedent ``` In documentation it states that it is faster than the textwrap equivalent one and in my tests in ipython it is indeed 3 tim...
Proper indentation for Python multiline strings
2,504,411
307
2010-03-23T23:35:28Z
32,926,139
8
2015-10-03T18:41:07Z
[ "python", "string" ]
What is the proper indentation for Python multiline strings within a function? ``` def method(): string = """line one line two line three""" ``` or ``` def method(): string = """line one line two line three""" ``` or something else? It looks kind of weird to have the string ...
One option which seems to missing from the other answers (only mentioned deep down in a comment by naxa) is the following: ``` def foo(): string = ("line one\n" # Add \n in the string "line two" "\n" # Add "\n" after the string "line three\n") ``` This will allow proper ...
Why allow concatenation of string literals?
2,504,536
11
2010-03-24T00:08:04Z
2,504,553
17
2010-03-24T00:12:02Z
[ "python", "c++", "c", "d", "string-literals" ]
I was recently bitten by a subtle bug. ``` char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( int2str[1] == std::string("one") ); // passes assert( int2str[2] == std::string("two") ); // fails ``` If you have godlike code review powers you'll notice I forgot the...
It's a great feature that allows you to combine preprocessor strings with your strings. ``` // Here we define the correct printf modifier for time_t #ifdef TIME_T_LONG #define TIME_T_MOD "l" #elif defined(TIME_T_LONG_LONG) #define TIME_T_MOD "ll" #else #define TIME_T_MOD "" #endif // And he we merge the m...
Why allow concatenation of string literals?
2,504,536
11
2010-03-24T00:08:04Z
2,504,555
22
2010-03-24T00:12:54Z
[ "python", "c++", "c", "d", "string-literals" ]
I was recently bitten by a subtle bug. ``` char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( int2str[1] == std::string("one") ); // passes assert( int2str[2] == std::string("two") ); // fails ``` If you have godlike code review powers you'll notice I forgot the...
Sure, it's the easy way to make your code look good: ``` char *someGlobalString = "very long " "so broken " "onto multiple " "lines"; ``` The best reason, though, is for weird printf formats, like type forcing: ``` uint64_t num = 5; printf("H...
How do I set up a Python development environment on Linux?
2,504,800
11
2010-03-24T01:31:36Z
2,504,835
14
2010-03-24T01:44:02Z
[ "python", "programming-languages", "development-environment" ]
I'm a .NET developer who knows very little about Python, but want to give it a test drive for a small project I'm working on. What tools and packages should I install on my machine? I'm looking for a common, somewhat comprehensive, development environment. I'll likely run Ubuntu 9.10, but I'm flexible. If Windows is ...
Your system already has Python on it. Use the text editor or IDE of your choice; I like vim. I can't tell you what third-party modules you need without knowing what kind of development you will be doing. Use apt as much as you can to get the libraries. --- To speak to your edit: This isn't minimalistic, like handin...
Python ldap AttributeError
2,505,317
4
2010-03-24T04:22:20Z
2,505,330
17
2010-03-24T04:24:55Z
[ "python", "openldap" ]
I have an python error **AttributeError: 'module' object has no attribute 'initialize'** I am running Python 2.6.2 on Solaris 10 UNIX and recently installed the pythonldap 2.3.9. The script is very basic, only has these 2 lines. Can anyone tell me why?? Traceback error below. ``` #!/usr/local/bin/python import ldap, ...
Did you name a file in the current directory ldap.py that is shadowing the one that you want?
Appending item to lists within a list comprehension
2,505,529
9
2010-03-24T05:23:23Z
2,505,542
7
2010-03-24T05:27:17Z
[ "python", "list", "append", "list-comprehension" ]
I have a list, let's say, `a = [[1,2],[3,4],[5,6]]` I want to add the string `'a'` to each item in the list `a`. When I use: ``` a = [x.append('a') for x in a] ``` it returns `[None,None,None]`. But if I use: ``` a1 = [x.append('a') for x in a] ``` then it does something odd. `a`, but not `a1` is `[[1,2,'a'],[...
For the first case, the reason it returns `[None, None, None]` is because the `list.append` function returns `None`, and that's what it stores in the list. In the second case, it's because the list is mutable, and each time you append the value, the original list is modified. What you need is a non-in-place append op...
Appending item to lists within a list comprehension
2,505,529
9
2010-03-24T05:23:23Z
2,505,556
19
2010-03-24T05:29:29Z
[ "python", "list", "append", "list-comprehension" ]
I have a list, let's say, `a = [[1,2],[3,4],[5,6]]` I want to add the string `'a'` to each item in the list `a`. When I use: ``` a = [x.append('a') for x in a] ``` it returns `[None,None,None]`. But if I use: ``` a1 = [x.append('a') for x in a] ``` then it does something odd. `a`, but not `a1` is `[[1,2,'a'],[...
`list.append` mutates the list itself and returns `None`. List comprehensions are for storing the result, which isn't what you want in this case if you want to just change the original lists. ``` >>> x = [[1, 2], [3, 4], [5, 6]] >>> for sublist in x: ... sublist.append('a') ... >>> x [[1, 2, 'a'], [3, 4, 'a'], [5,...
Add params to given URL in Python
2,506,379
61
2010-03-24T09:06:21Z
2,506,398
7
2010-03-24T09:10:24Z
[ "python", "url" ]
Suppose I was given a URL. It might already have GET parameters (e.g. `http://example.com/search?q=question`) or it might not (e.g. `http://example.com/`). And now I need to add some parameters to it like `{'lang':'en','tag':'python'}`. In the first case I'm going to have `http://example.com/search?q=question&lang=e...
Yes: use [urllib](http://docs.python.org/library/urllib.html). From the [examples](http://docs.python.org/library/urllib.html#examples) in the documentation: ``` >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % para...
Add params to given URL in Python
2,506,379
61
2010-03-24T09:06:21Z
2,506,425
28
2010-03-24T09:15:15Z
[ "python", "url" ]
Suppose I was given a URL. It might already have GET parameters (e.g. `http://example.com/search?q=question`) or it might not (e.g. `http://example.com/`). And now I need to add some parameters to it like `{'lang':'en','tag':'python'}`. In the first case I'm going to have `http://example.com/search?q=question&lang=e...
You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded). Check out urllib.urlencode: ``` >>> import urllib >>> urllib.urlencode({'lang':'en','tag':'python'}) 'lang=en&tag=python' ```
Add params to given URL in Python
2,506,379
61
2010-03-24T09:06:21Z
2,506,477
100
2010-03-24T09:23:15Z
[ "python", "url" ]
Suppose I was given a URL. It might already have GET parameters (e.g. `http://example.com/search?q=question`) or it might not (e.g. `http://example.com/`). And now I need to add some parameters to it like `{'lang':'en','tag':'python'}`. In the first case I'm going to have `http://example.com/search?q=question&lang=e...
There are couple quirks with urllib and urlparse modules. Here's working example: ``` try: import urlparse from urllib import urlencode except: # For Python 3 import urllib.parse as urlparse from urllib.parse import urlencode url = "http://stackoverflow.com/search?q=question" params = {'lang':'en','ta...
Add params to given URL in Python
2,506,379
61
2010-03-24T09:06:21Z
24,791,840
9
2014-07-16T22:23:57Z
[ "python", "url" ]
Suppose I was given a URL. It might already have GET parameters (e.g. `http://example.com/search?q=question`) or it might not (e.g. `http://example.com/`). And now I need to add some parameters to it like `{'lang':'en','tag':'python'}`. In the first case I'm going to have `http://example.com/search?q=question&lang=e...
You can also use the furl module <https://github.com/gruns/furl> ``` >>> from furl import furl >>> print furl('http://example.com/search?q=question').add({'lang':'en','tag':'python'}).url http://example.com/search?q=question&lang=en&tag=python ```
Add params to given URL in Python
2,506,379
61
2010-03-24T09:06:21Z
25,580,545
16
2014-08-30T08:32:57Z
[ "python", "url" ]
Suppose I was given a URL. It might already have GET parameters (e.g. `http://example.com/search?q=question`) or it might not (e.g. `http://example.com/`). And now I need to add some parameters to it like `{'lang':'en','tag':'python'}`. In the first case I'm going to have `http://example.com/search?q=question&lang=e...
## Why I've been not satisfied with all the solutions on this page (*come on, where is our favorite copy-paste thing?*) so I wrote my own based on answers here. It tries to be complete and more Pythonic. I've added a handler for **dict** and **bool** values in arguments to be more consumer-side (*JS*) friendly, but th...
ways to execute python
2,506,437
6
2010-03-24T09:18:05Z
2,506,444
17
2010-03-24T09:19:06Z
[ "python" ]
So far to execute a Python program, I'm using ``` > python file.py ``` I want to run the Python script simply using file name, like ``` > file.py ``` similar to shell scripts like ``` > sh file.sh > chmod +x file.sh > ./file.sh ``` or move file.sh to bin and then run ``` > file.sh ```
Put this at the top of your Python script: ``` #!/usr/bin/env python ``` The #! part is called a [shebang](http://en.wikipedia.org/wiki/Shebang_%28Unix%29), and the `env` command will simply locate `python` on your `$PATH` and execute the script through it. You could hard-code the path to the python interpreter, too,...
How do I forward a request to a different url in python
2,506,932
12
2010-03-24T10:40:01Z
2,507,022
11
2010-03-24T10:57:21Z
[ "python", "url", "redirect", "simplehttpserver" ]
I have been looking for the syntax to redirect a special url to a remote server to do some XSS testing. Any ideas? ``` import SimpleHTTPServer import SocketServer class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): print self.path if self.path == '/analog': -------------...
For a redirect, you have to return a code 301, plus a `Location` header. Probably you can try something like: ``` class myHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): self.send_response(301) self.send_header('Location','http://www.example.com') self.end_headers() ```
increment a variable in django templates
2,507,284
11
2010-03-24T11:43:18Z
2,507,305
18
2010-03-24T11:47:13Z
[ "python", "django", "django-templates" ]
All, How Can we increment a value like the following in django templates, ``` {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} ``` thanks..
I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the `forloop.counter` variable. For example: ``` {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template{{forloop.counter}}" value="template{{forloop.counter}}"/> {% e...
increment a variable in django templates
2,507,284
11
2010-03-24T11:43:18Z
2,507,308
7
2010-03-24T11:47:48Z
[ "python", "django", "django-templates" ]
All, How Can we increment a value like the following in django templates, ``` {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} ``` thanks..
You explicitly can't do that in a template. Variable assignment is not allowed. However if all you want is a counter in your loop, you just need to use `{{ forloop.counter }}`.
Use BeautifulSoup to extract sibling nodes between two nodes
2,507,301
5
2010-03-24T11:46:00Z
2,507,405
8
2010-03-24T12:03:45Z
[ "python", "beautifulsoup" ]
I've got a document like this: ``` <p class="top">I don't want this</p> <p>I want this</p> <table> <!-- ... --> </table> <img ... /> <p> and all that stuff too</p> <p class="end>But not this and nothing after it</p> ``` I want to extract everything between the p[class=top] and p[class=end] paragraphs. Is ther...
`node.nextSibling` attribute is your solution: ``` from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(html) nextNode = soup.find('p', {'class': 'top'}) while True: # process nextNode = nextNode.nextSibling if getattr(nextNode, 'name', None) == 'p' and nextNode.get('class', None) == 'end': ...
Detecting Infinite recursion in Python or dynamic languages
2,507,395
8
2010-03-24T12:01:23Z
2,507,436
12
2010-03-24T12:07:54Z
[ "python", "gcc", "compiler-construction" ]
Recently I tried compiling program something like this with GCC: ``` int f(int i){ if(i<0){ return 0;} return f(i-1); f(100000); ``` and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only ...
The optimisation you're talking about is known as tail call elimination - a recursive call is unfolded into an iterative loop. There has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See [Guido's blog entry](http://neopythonic.blogspot.com/2009/04/t...
python how to check file empty or not
2,507,808
103
2010-03-24T13:03:55Z
2,507,819
72
2010-03-24T13:05:41Z
[ "python", "file" ]
I have a text file. How may I check whether the file is empty or not empty?
``` import os os.path.getsize(fullpathhere) > 0 ```
python how to check file empty or not
2,507,808
103
2010-03-24T13:03:55Z
2,507,871
114
2010-03-24T13:12:31Z
[ "python", "file" ]
I have a text file. How may I check whether the file is empty or not empty?
``` >>> import os >>> os.stat("file").st_size == 0 True ```
python how to check file empty or not
2,507,808
103
2010-03-24T13:03:55Z
11,895,272
13
2012-08-10T03:56:17Z
[ "python", "file" ]
I have a text file. How may I check whether the file is empty or not empty?
if for some reason you already had the file open you could try this: ``` >>> with open('New Text Document.txt') as my_file: ... # I already have file open at this point.. now what? ... my_file.seek(0) #ensure you're at the start of the file.. ... first_char = my_file.read(1) #get the first character ... ...
python how to check file empty or not
2,507,808
103
2010-03-24T13:03:55Z
15,924,160
44
2013-04-10T11:08:00Z
[ "python", "file" ]
I have a text file. How may I check whether the file is empty or not empty?
Both `getsize()` and `stat()` will throw an exception if the file does not exist. This function will return True/False without throwing: ``` import os def is_non_zero_file(fpath): return os.path.isfile(fpath) and os.path.getsize(fpath) > 0 ```
Need to understand Python signals and modules
2,508,748
3
2010-03-24T15:03:25Z
2,508,775
7
2010-03-24T15:06:39Z
[ "python", "module", "signals" ]
I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is: ``` import sys, signal sigterm_caught = False def SignalHandler(signum, stackframe...
You need to add a `global` statement to the handler: ``` def SignalHandler(signum, stackframe): global sigterm_caught if signum == signal.SIGTERM: sigterm_caught = True sys.stdout.write("SIGTERM caught\n") ``` The Python compiler, by default, deems each name (like `sigterm_caught`) to be *local* to a func...
Convert or strip out "illegal" Unicode characters
2,508,847
7
2010-03-24T15:14:59Z
2,508,870
11
2010-03-24T15:18:08Z
[ "python", "unicode", "pymssql" ]
I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 1916: ordinal ...
When you decode, just pass 'ignore' to strip those characters there is some more way of stripping / converting those are ``` 'replace': replace malformed data with a suitable replacement marker, such as '?' or '\ufffd' 'ignore': ignore malformed data and continue without further notice 'backslashreplace': replace...
Convert or strip out "illegal" Unicode characters
2,508,847
7
2010-03-24T15:14:59Z
2,508,901
11
2010-03-24T15:22:13Z
[ "python", "unicode", "pymssql" ]
I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 1916: ordinal ...
Once you have the string of bytes `s`, instead of using it as a unicode obj directly, convert it explicitly with the right codec, e.g.: ``` u = s.decode('latin-1') ``` and use `u` instead of `s` in the code that follows this point (presumably the part that writes to sqlite). That's assuming `latin-1` is the encoding ...