title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
157,099
<p>Not as terse as you are looking for, but more efficient, it actually works with any iterable, not just iterables you can loop over multiple times, and you can expand the things to check for without complicating it further:</p> <pre><code>r = xrange(1, 10) counts = { 2: 0, 3: 0, } for v in r: for q in co...
0
2008-10-01T10:56:46Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
157,121
<p>Alt 4! But maybe you should refactor the code to a function that takes an argument which should contain the divisible number (two and three). And then you could have a better functionname.</p> <pre><code>def methodName(divNumber, r): return sum(1 for v in r if v % divNumber == 0) print methodName(2, xrange(1, 1...
5
2008-10-01T11:04:46Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
157,141
<p>Having to iterate over the list multiple times isn't elegant IMHO.</p> <p>I'd probably create a function that allows doing:</p> <pre><code>twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) </code></pre> <p>A starting po...
14
2008-10-01T11:09:14Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
157,181
<pre><code>from itertools import groupby from collections import defaultdict def multiples(v): return 2 if v%2==0 else 3 if v%3==0 else None d = defaultdict(list) for k, values in groupby(range(10), multiples): if k is not None: d[k].extend(values) </code></pre>
0
2008-10-01T11:26:34Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
157,620
<p>The idea here is to use reduction to avoid repeated iterations. Also, this does not create any extra data structures, if memory is an issue for you. You start with a dictionary with your counters (<code>{'div2': 0, 'div3': 0}</code>) and increment them along the iteration.</p> <pre><code>def increment_stats(stats, ...
0
2008-10-01T13:32:41Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
158,250
<p>Inspired by the OO-stab above, I had to try my hands on one as well (although this is way overkill for the problem I'm trying to solve :)</p> <pre><code>class Stat(object): def update(self, n): raise NotImplementedError def get(self): raise NotImplementedError class TwoStat(Stat): def __init__(self...
0
2008-10-01T15:35:20Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
158,587
<p>True booleans are coerced to unit integers, and false booleans to zero integers. So if you're happy to use scipy or numpy, make an array of integers for each element of your sequence, each array containing one element for each of your tests, and sum over the arrays. E.g.</p> <pre><code>&gt;&gt;&gt; sum(scipy.arra...
1
2008-10-01T16:47:13Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
158,632
<p>Alt 3, for the reason that it doesn't use memory proportional to the number of "hits". Given a pathological case like xrange(one_trillion), many of the other offered solutions would fail badly.</p>
0
2008-10-01T16:59:00Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http:...
13
2008-10-01T10:37:20Z
163,273
<p>I would choose a small variant of your (alt 4):</p> <pre><code>def count(predicate, list): print sum(1 for x in list if predicate(x)) r = xrange(1, 10) count(lambda x: x % 2 == 0, r) count(lambda x: x % 3 == 0, r) # ... </code></pre> <p>If you want to change what count does, change its implementation in one ...
1
2008-10-02T16:16:40Z
[ "python", "list-comprehension" ]
Date change notification in a Tkinter app (win32)
157,116
<p>Does anyone know if it is possible (and if yes, how) to bind an event (Python + Tkinter on MS Windows) to a system date change?</p> <p>I know I can have .after events checking once in a while; I'm asking if I can somehow have an event fired whenever the system date/time changes, either automatically (e.g. for dayli...
0
2008-10-01T11:02:43Z
160,031
<blockquote> <p>I know, because if I have an .after timer waiting and I set the date/time after the timer's expiration, the timer event fires instantly.</p> </blockquote> <p>That could just mean that Tkinter (or Tk) is polling the system clock as part of the event loop to figure out when to run timers.</p> <p>If yo...
1
2008-10-01T22:21:02Z
[ "python", "windows", "events", "tkinter" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
157,362
<p>Have you tried <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a>, I don't have direct experience running it under Jython but there seem to be some people that do. </p>
2
2008-10-01T12:37:24Z
[ "python", "jython", "template-engine" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
160,496
<p>Jinja is pretty cool and seems to work on Jython.</p>
2
2008-10-02T01:35:51Z
[ "python", "jython", "template-engine" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
304,203
<p>Use StringTemplate, see <a href="http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf" rel="nofollow">http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf</a> for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).</p>
1
2008-11-20T02:50:53Z
[ "python", "jython", "template-engine" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
157,439
<p>time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond ...
11
2008-10-01T12:54:25Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
157,656
<p>Here is a thread about Python timing accuracy:<br><br> <a href="http://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy">http://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy</a></p>
2
2008-10-01T13:44:13Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
157,711
<p>You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it:</p> <ol> <li><p>Deal with i...
7
2008-10-01T13:55:57Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
157,871
<p>"timestamp should be accurate relative to each other "</p> <p>Why time? Why not a sequence number? If it's any client of client-server application, network latency makes timestamps kind of random.</p> <p>Are you matching some external source of information? Say a log on another application? Again, if there's a...
2
2008-10-01T14:24:59Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
160,208
<p>Thank you all for your contributions - they've all be very useful. Brian's answer seems closest to what I eventually went with (i.e. deal with it but use a sort of unique identifier - see below) so I've accepted his answer. I managed to consolidate all the various data receivers into a single thread which is where t...
5
2008-10-01T23:23:33Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
284,375
<p>I wanted to thank J. Cage for this last post. </p> <p>For my work, "reasonable" timing of events across processes and platforms is essential. There are obviously lots of places where things can go askew (clock drift, context switching, etc.), however this accurate timing solution will, I think, help to ensure that...
0
2008-11-12T15:51:52Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
22,194,015
<p>A few years past since the question has been asked and answered, and this has been dealt with, at least for CPython on Windows. Using the script below on both Win7 64bit and Windows Server 2008 R2, I got the same results:</p> <ul> <li><code>datetime.now()</code> gives a resolution of 1ms and a jitter smaller than 1...
0
2014-03-05T09:46:44Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, ...
12
2008-10-01T12:36:17Z
38,840,918
<p>If you want microsecond-<em>resolution</em> (NOT accuracy) timestamps in Python, in <em>Windows,</em> you can use Windows's QPC timer, as demonstrated in my answer here: <a href="http://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python">How to get millisecond...
0
2016-08-09T01:59:53Z
[ "python", "timestamp", "timer" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
157,445
<p>You can't sort dictionaries. You have to sort the list of items.</p> <p>Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric.</p> <pre><code>a = { 'key':1, 'another':2, 'key2':...
17
2008-10-01T12:56:01Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
157,462
<p>The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this:</p> <pre><code>def sortkey((k, v)): return (maxval - v, k) items = thedict.items() items.sort(key=sortkey) </code></pre> <p>but unless you already k...
1
2008-10-01T13:00:26Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
157,494
<p>You can use something like this:</p> <pre><code>dic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4} def sort_compare(a, b): c = cmp(dic[b], dic[a]) if c != 0: return c return cmp(a, b) for k in sorted(dic.keys(), cmp=sort_compare): print k, dic[k] </code></pre> <p>Don't know how pythonic it is how...
0
2008-10-01T13:08:50Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
157,792
<pre><code>data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])): print key, value </code></pre>
6
2008-10-01T14:11:59Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
158,022
<p>Building on Thomas Wouters and Ricardo Reyes solutions:</p> <pre><code>def combine(*cmps): """Sequence comparisons.""" def comparator(a, b): for cmp in cmps: result = cmp(a, b): if result: return result return 0 return comparator def reverse(cmp):...
0
2008-10-01T14:53:17Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort...
14
2008-10-01T12:50:19Z
280,027
<pre><code>&gt;&gt;&gt; keys = sorted(a, key=lambda k: (-a[k], k)) </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; keys = sorted(a) &gt;&gt;&gt; keys.sort(key=a.get, reverse=True) </code></pre> <p>then</p> <pre><code>print [(key, a[key]) for key in keys] [('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
0
2008-11-11T04:43:43Z
[ "python" ]
What is the best way to sample/profile a PyObjC application?
157,662
<p>Sampling with Activity Monitor/Instruments/Shark will show stack traces full of C functions for the Python interpreter. I would be helpful to see the corresponding Python symbol names. Is there some DTrace magic that can do that? Python's cProfile module can be useful for profiling individual subtrees of Python call...
6
2008-10-01T13:45:12Z
165,590
<p>The answer is "dtrace", but it won't work on sufficiently old macs.</p> <p><a href="http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-1/" rel="nofollow">http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-1/</a></p> <p><a href="http://tech.marshallfamily.com.au...
3
2008-10-03T03:33:35Z
[ "python", "cocoa", "osx", "pyobjc" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
157,974
<p>There are several ROT13 utilities written in Python on the 'Net -- just google for them. ROT13 encode the string offline, copy it into the source, decode at point of transmission.<br><br>But this is <em>really</em> weak protection...</p>
0
2008-10-01T14:43:20Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
157,975
<p><a href="http://docs.python.org/lib/module-base64.html">Base64 encoding</a> is in the standard library and will do to stop shoulder surfers:</p> <pre><code>&gt;&gt;&gt; import base64 &gt;&gt;&gt; print base64.b64encode("password") cGFzc3dvcmQ= &gt;&gt;&gt; print base64.b64decode("cGFzc3dvcmQ=") password </code></pr...
69
2008-10-01T14:43:51Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
158,180
<p>Your operating system probably provides facilities for encrypting data securely. For instance, on Windows there is DPAPI (data protection API). Why not ask the user for their credentials the first time you run then squirrel them away encrypted for subsequent runs?</p>
2
2008-10-01T15:22:32Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
158,221
<p>How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.</p>
10
2008-10-01T15:28:38Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
158,248
<p>Douglas F Shearer's is the generally approved solution in Unix when you need to specify a password for a remote login.<br /> You add a <strong>--password-from-file</strong> option to specify the path and read plaintext from a file.<br /> The file can then be in the user's own area protected by the operating system. ...
33
2008-10-01T15:34:13Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
158,387
<p>The best solution, assuming the username and password can't be given at runtime by the user, is probably a separate source file containing only variable initialization for the username and password that is imported into your main code. This file would only need editing when the credentials change. Otherwise, if you'...
15
2008-10-01T16:09:40Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
158,450
<p>This is a pretty common problem. Typically the best you can do is to either </p> <p>A) create some kind of ceasar cipher function to encode/decode (just not rot13) or B) the preferred method is to use an encryption key, within reach of your program, encode/decode the password. In which you can use file protectio...
4
2008-10-01T16:19:00Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
160,042
<p>base64 is the way to go for your simple needs. There is no need to import anything:</p> <pre><code>&gt;&gt;&gt; 'your string'.encode('base64') 'eW91ciBzdHJpbmc=\n' &gt;&gt;&gt; _.decode('base64') 'your string' </code></pre>
10
2008-10-01T22:26:09Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
160,053
<p>Place the configuration information in a encrypted config file. Query this info in your code using an key. Place this key in a separate file per environment, and don't store it with your code.</p>
1
2008-10-01T22:29:38Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
6,451,826
<p>If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed <a href="http://www.mavetju.org/unix/netrc.php">here</a>.</p> <p>Here is a small usage example:</p> <pre><code>import netrc #...
17
2011-06-23T09:17:55Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
16,844,309
<p>More homegrown appraoch rather than converting authentication / passwords / username to encrytpted details. <strong>FTPLIB</strong> is just the example. "<strong>pass.csv</strong>" is the csv file name</p> <p>Save password in CSV like below : </p> <p>user_name</p> <p>user_password</p> <p>(With no column heading)...
1
2013-05-30T19:24:20Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
22,821,470
<p>Here is a simple method:</p> <ol> <li>Create a python module - let's call it peekaboo.py. </li> <li>In peekaboo.py, include both the password and any code needing that password</li> <li>Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...).</li> <li>Now, delete peekab...
10
2014-04-02T19:45:46Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the pas...
75
2008-10-01T14:37:17Z
38,073,122
<p>Do you know pit?</p> <p><a href="https://pypi.python.org/pypi/pit" rel="nofollow">https://pypi.python.org/pypi/pit</a> (py2 only (version 0.3))</p> <p><a href="https://github.com/yoshiori/pit" rel="nofollow">https://github.com/yoshiori/pit</a> (it will work on py3 (current version 0.4))</p> <p>test.py</p> <pre><...
0
2016-06-28T10:03:26Z
[ "python", "security" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CP...
15
2008-10-01T15:38:58Z
158,326
<p>Do you actually need to reference the classes at class definition time? ie.</p> <pre><code> class CRoom(object): person = CPerson("a person") </code></pre> <p>Or (more likely), do you just need to use CPerson in the methods of your class (and vice versa). eg:</p> <pre><code>class CRoom(object): def getP...
7
2008-10-01T15:52:34Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CP...
15
2008-10-01T15:38:58Z
158,331
<p>You could just alias the second one.</p> <p>import CRoom</p> <p>CPerson = CRoom.CPerson</p>
1
2008-10-01T15:53:19Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CP...
15
2008-10-01T15:38:58Z
158,403
<p><strong>No need to import CRoom</strong></p> <p>You don't use <code>CRoom</code> in <code>person.py</code>, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time".</p> <p>If you actually <em>do</em> use <code>CRoom</code> in <code>person.py</code>, then chang...
16
2008-10-01T16:11:41Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CP...
15
2008-10-01T15:38:58Z
158,505
<p>First, naming your arguments with uppercase letters is confusing. Since Python does not have formal, static type checking, we use the <code>UpperCase</code> to mean a class and <code>lowerCase</code> to mean an argument.</p> <p>Second, we don't bother with CRoom and CPerson. Upper case is sufficient to indicate i...
2
2008-10-01T16:30:26Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CP...
15
2008-10-01T15:38:58Z
158,620
<p>@<a href="#158505" rel="nofollow">S.Lott</a> if i don't import anything into the room module I get an undefined error instead (I imported it into the main module like you showed)</p> <blockquote> <p>Traceback (most recent call last):<br /> File "C:\Projects\python\test\main.py", line 6, in <br /> Ben = R...
0
2008-10-01T16:55:17Z
[ "python", "module", "circular-dependency" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates...
4
2008-10-01T16:37:08Z
158,622
<p>Even though it is essentially a singleton at this point, the usual arguments against globals apply. For a pythonic singleton-substitute, look up the "borg" object. </p> <p>That's really the only difference. Once the dictionary object is created, you are only binding new references as you pass it along unless if ...
1
2008-10-01T16:55:23Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates...
4
2008-10-01T16:37:08Z
158,753
<p>If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can:</p> <pre><code>import dictionary dictionary.words[wh...
10
2008-10-01T17:30:41Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates...
4
2008-10-01T16:37:08Z
159,341
<p>Depending on what your dict contains, you may be interested in the 'shelve' or 'anydbm' modules. They give you dict-like interfaces (just strings as keys and items for 'anydbm', and strings as keys and any python object as item for 'shelve') but the data is actually in a DBM file (gdbm, ndbm, dbhash, bsddb, dependin...
0
2008-10-01T19:38:26Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates...
4
2008-10-01T16:37:08Z
159,441
<p>Adam, remember that in Python when you say:</p> <pre><code>a = read_dict_from_file() b = a </code></pre> <p>... you are not actually <em>copying</em> <code>a</code>, and thus using more memory, you are merely making <code>b</code> another reference to the same object.</p> <p>So basically <strong>any</strong> of t...
1
2008-10-01T20:00:11Z
[ "python" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
159,150
<p>netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.</p> <pre><code>&gt;&gt;&gt; import netifaces &gt;&gt;&gt; netifaces.interfaces() ['lo', 'eth0', 'tun2'] &gt;&gt;&gt; netifaces.ifaddresses('eth0')[netifaces....
13
2008-10-01T18:55:14Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
159,169
<p>I dont know of a unified way, but heres something that you might find useful:</p> <p><a href="http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451" rel="nofollow">http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451</a></p> <p>What I would do in this case would be to...
1
2008-10-01T19:02:33Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
159,195
<p>Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:</p> <pre><code>from uuid import getnode as get_mac mac = get_mac() </code></pre> <p>The return value is the mac address as 48 bit integer.</p>
92
2008-10-01T19:06:30Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
159,236
<p>For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.</p> <pre><code>struct ifreq ifr; uint8_t macaddr[6]; if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) &lt; 0) return -1; strcpy(ifr.ifr_name, "eth0"); if (ioctl(s, SIOCGIFHWADDR, (void *)&amp;ifr) == 0) { if (ifr.ifr_hwad...
-5
2008-10-01T19:12:56Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
159,992
<p>Note that you can build your own cross-platform library in python using conditional imports. e.g.</p> <pre><code>import platform if platform.system() == 'Linux': import LinuxMac mac_address = LinuxMac.get_mac_address() elif platform.system() == 'Windows': # etc </code></pre> <p>This will allow you to use os...
2
2008-10-01T22:09:58Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
160,821
<p>One other thing that you should note is that <code>uuid.getnode()</code> can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling <code>getnode()</code> twice and see...
17
2008-10-02T03:49:54Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
4,789,267
<p>The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in <a href="http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/">this activestate recipe</a></p> ...
57
2011-01-25T01:57:17Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
17,884,450
<p>For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).</p> <pre><code> ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\ -f2 00:26:6c:df:c3:95 </code></pre> <p>Cut arguements may dffer (I am not an expert) try:</p> <pre><code>ifconfig etho | grep HWaddr e...
2
2013-07-26T14:46:26Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
18,031,954
<p>Using my answer from here: <a href="http://stackoverflow.com/a/18031868/2362361">http://stackoverflow.com/a/18031868/2362361</a></p> <p>It would be important to know to which iface you want the MAC for since many can exist (bluetooth, several nics, etc.).</p> <p>This does the job when you know the IP of the iface ...
7
2013-08-03T10:40:10Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
27,617,579
<p>for Linux solution</p> <pre><code>INTERFACE_NAME = "eth0" ####################################### def get_mac_id(ifname=INTERFACE_NAME): import commands words = commands.getoutput("ifconfig " + ifname).split() if "HWaddr" in words: return words[ words.index("HWaddr") + 1 ] else: return 'No MAC Address Fo...
-1
2014-12-23T09:32:56Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of ano...
68
2008-10-01T18:51:36Z
32,080,877
<p>Sometimes we have more than one net interface.</p> <p>A simple method to find out the mac address of a specific interface, is:</p> <pre><code>def getmac(interface): try: mac = open('/sys/class/net/'+interface+'/address').readline() except: mac = "00:00:00:00:00:00" return mac[0:17] </code></pre> <...
5
2015-08-18T19:16:50Z
[ "python", "windows", "linux", "networking" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
159,819
<p>What fastcgi interface are you using and how. Is it flup? If yes, paste the way you spawn the server and how it's hooked into nginx. Without that information it's just guessing what could go wrong.</p> <p>Possible problems:</p> <ul> <li>nginx is buggy. At least lighttpd has horrible fastcgi bugs, I wouldn't wo...
3
2008-10-01T21:21:52Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
675,015
<p>try to raise "gzip_buffers" may help.</p> <p>see here: <a href="http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl" rel="nofollow">http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl</a></p>
2
2009-03-23T20:00:22Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
1,172,861
<p>I'm running very similar configurations to this both on my webhost (Webfaction) and on a local Ubuntu dev server and I don't see any problems. I'm guessing it's a time-out or full buffer that's causing this.</p> <p>Can you post the output of the nginx error log? Also what version of nginx are you using?</p> <p>As ...
0
2009-07-23T16:11:04Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
4,515,898
<p>Check your error logs for "Permission denied" errors writing to <code>.../nginx/tmp/...</code> files. Nginx will work fine unless it needs temporary space, and that typically happens at 32K boundaries. If you find these errors, make sure the tmp directory is writable by the user nginx runs as.</p>
5
2010-12-23T04:37:11Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
5,218,788
<p>I had the same exact problem running Nagios on nginx. I stumbled upon your question while googling for an answer, and reading "permission denied" related answers it struck me (and perhaps it will help you) : </p> <ul> <li><p>Nginx error.log was reporting :</p> <p>2011/03/07 11:36:02 [crit] 30977#0: *225952 open() ...
7
2011-03-07T10:54:59Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning ...
10
2008-10-01T20:26:12Z
6,033,063
<p>FastCGI is not to blame for this. </p> <p>I ran into exactly the same issue using nginx/gunicorn. Reducing the response size to less than 32k (in the specific case using the <code>spaceless</code> tag in the template) solved it.</p> <p>As dwc says, it's probably a hard limit due to the way nginx uses address space...
2
2011-05-17T15:17:05Z
[ "python", "django", "nginx", "fastcgi" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
159,745
<p>See Python <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>.</p> <blockquote> <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p> <p>mixedCase is allowed only in contexts where that's already the prevailing style</p> </blockq...
381
2008-10-01T21:05:24Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
159,756
<p>The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python. </p>
0
2008-10-01T21:08:19Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
159,778
<p>There is <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There...
26
2008-10-01T21:12:41Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
159,798
<p>Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head. </p> <p>I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to hav...
11
2008-10-01T21:16:21Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
160,769
<p>Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.</p>
9
2008-10-02T03:24:30Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
160,830
<p>David Goodger (in "Code Like a Pythonista" <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html">here</a>) describes the PEP 8 recommendations as follows:</p> <ul> <li><p><code>joined_lower</code> for functions, methods, attributes, variables</p></li> <li><p><code>joined_lower</code> or <...
150
2008-10-02T03:53:12Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
160,833
<p>Typically, one follow the conventions used in the language's standard library.</p>
2
2008-10-02T03:55:18Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
264,226
<p>As mentioned, PEP 8 says to use <code>lower_case_with_underscores</code> for variables, methods and functions.</p> <p>I prefer using <code>lower_case_with_underscores</code> for variables and <code>mixedCase</code> for methods and functions makes the code more explicit and readable. Thus following the <a href="htt...
23
2008-11-05T02:51:29Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
2,708,015
<p>As the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Style Guide for Python Code</a> admits,</p> <blockquote> <p>The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent</p> </blockquote> <p>Note that this refers just to Python's <em>st...
26
2010-04-25T11:23:57Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
8,423,697
<p><a href="https://google.github.io/styleguide/pyguide.html">Google Python Style Guide</a> has the following convention:</p> <blockquote> <p>module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_v...
252
2011-12-07T22:44:24Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
32,563,758
<p>I've varied the PEP system a little. </p> <pre><code>ThisIsAClass this_is_a_function </code></pre> <p>However, for variables I employ a system that goes a bit against Python's dynamic typing, but I find the improved readability at a glance so very useful, plus most variables don't ever change type in any case. I...
0
2015-09-14T11:32:36Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <...
326
2008-10-01T21:01:16Z
37,120,709
<p>There is a paper about this: <a href="http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf" rel="nofollow">http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf</a></p> <p>If you are lazy to read it it says that snake_case is more readable than camelCase. That's wh...
1
2016-05-09T16:20:04Z
[ "python", "variables", "function", "naming-conventions" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
159,809
<p>I'm not sure about an accepted standard, but I've found <a href="http://soapy.sourceforge.net/" rel="nofollow">SOAPpy</a> to be fairly straight-forward and useful library for handling SOAP-based web services.</p> <blockquote> <p>SOAPy is a SOAP/XML Schema Library for Python. Given either a WSDL or SDL document, S...
1
2008-10-01T21:20:36Z
[ "python", "web-services" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
160,059
<p>soaplib is very easy to use and seems to be active.</p> <p><a href="http://wiki.github.com/jkp/soaplib/" rel="nofollow">http://wiki.github.com/jkp/soaplib/</a></p>
0
2008-10-01T22:32:39Z
[ "python", "web-services" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
7,720,351
<p>Old question, but for anyone else who is asking this question I've had good success with suds: <a href="https://fedorahosted.org/suds/" rel="nofollow">https://fedorahosted.org/suds/</a></p>
0
2011-10-11T00:58:26Z
[ "python", "web-services" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Pyth...
6
2008-10-01T22:09:16Z
160,017
<p>Well, I don't know much about Ruby. But the obvious point about Python's "self" is that it's not a "keyword" ...it's just the name of an argument that's sent to your method.</p> <p>You can use any name you like for this argument. "Self" is just a convention.</p> <p>For example :</p> <pre><code>class X : def _...
5
2008-10-01T22:16:33Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Pyth...
6
2008-10-01T22:09:16Z
160,064
<p>self is used only as a convention, you can use spam, bacon or sausage instead of self and get the same result. It's just the first argument passed to bound methods. But stick to using self as it will confuse others and some editors.</p>
5
2008-10-01T22:34:42Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Pyth...
6
2008-10-01T22:09:16Z
160,227
<p>Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.</p> <p>Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). Th...
7
2008-10-01T23:32:01Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Pyth...
6
2008-10-01T22:09:16Z
165,574
<p>Despite webmat's claim, Guido <a href="http://markmail.org/message/n6fs5pec5233mbfg">wrote</a> that explicit self is "not an implementation hack -- it is a semantic device".</p> <blockquote> <p>The reason for explicit self in method definition signatures is semantic consistency. If you write</p> <p>class...
5
2008-10-03T03:24:23Z
[ "python", "ruby", "language-features" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
160,035
<p>Hmmm, I don't fully understand your question. But if you can't do it when you declare the model maybe you can achieve the same thing with overriding methods of the class of objects where you "send" the user object, maybe start with the constructor.</p>
-1
2008-10-01T22:24:08Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
160,421
<p>Model itself doesn't know anything about current user but you can give this user in a view to the form which operates models objects (and in form reset <code>choices</code> for necessary field). </p> <p>If you need this on admin site - you can try <code>raw_id_admin</code> along with <code>django-granular-permissio...
4
2008-10-02T00:47:35Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
160,435
<p>I'm not sure that I fully understand exactly what you want to do, but I think that there's a good chance that you'll get at least part the way there using a <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance" rel="nofollow">custom Manager</a>. In particular, don'...
0
2008-10-02T00:58:35Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
161,615
<p>Use threadlocals if you want to get <strong>current</strong> user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware</p> <pre><code>from threading import local _thread_locals = local() def get_current_user(): return getattr(getattr(_thread_locals, ...
1
2008-10-02T10:09:01Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
163,536
<p>Here is the <a href="http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser" rel="nofollow">CookBook Threadlocals And User</a></p>
1
2008-10-02T17:24:22Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = m...
10
2008-10-01T22:14:36Z
4,656,296
<p>This limiting of choices to current user is a kind of validation that needs to happen dynamically in the request cycle, not in the static Model definition.</p> <p>In other words: at the point where you are creating an <em>instance</em> of this model you will be in a View and at that point you will have access to th...
0
2011-01-11T09:52:59Z
[ "python", "django", "model", "user" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,271
<p>It works if you use os instead of commands:</p> <pre><code>import os print os.system("ps -u 0") </code></pre>
0
2008-10-01T23:45:01Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,284
<p>The cross-platform replacement for <code>commands</code> is <code>subprocess</code>. See the <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess module documentation</a>. The 'Replacing older modules' section includes <a href="http://docs.python.org/lib/node534.html" rel="nofollow">...
3
2008-10-01T23:52:13Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,316
<p>I've tried in on OS X (10.5.5) and seems to work just fine:</p> <pre><code>print commands.getoutput("ps -u 0") UID PID TTY TIME CMD 0 1 ?? 0:01.62 /sbin/launchd 0 10 ?? 0:00.57 /usr/libexec/kextd </code></pre> <p>etc.</p> <p>Python 2.5.1</p>
1
2008-10-02T00:06:46Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,375
<p>This works on Mac OS X 10.5.5. Note the capital <strong>-U</strong> option. Perhaps that's been your problem.</p> <pre><code>import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() </code></pre> <p>Here's the Python version</p> <p...
8
2008-10-02T00:29:39Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
3,710,903
<p>any of the above python calls - but try 'pgrep
0
2010-09-14T16:31:31Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
6,265,416
<p>If the OS support the /proc fs you can do:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; pids = [int(x) for x in os.listdir('/proc') if x.isdigit()] &gt;&gt;&gt; pids [1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444] &gt;&gt;&gt; </code></pre> <p>A cross-platform solution (linux, freebsd, osx, wi...
5
2011-06-07T12:51:23Z
[ "python" ]
Django/Python - Grouping objects by common set from a many-to-many relationships
160,298
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-i...
5
2008-10-01T23:59:52Z
160,552
<p>check <a href="http://docs.djangoproject.com/en/dev//ref/templates/builtins/#regroup" rel="nofollow">regroup</a>. it's only for templates, but i guess this kind of classification belongs to the presentation layer anyway.</p>
2
2008-10-02T01:58:49Z
[ "python", "django", "algorithm", "puzzle" ]
Django/Python - Grouping objects by common set from a many-to-many relationships
160,298
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-i...
5
2008-10-01T23:59:52Z
161,082
<p>Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.</p> <pre><code>import itertools cars = [ {'car': 'X2', 'mods': [1,2]}, {'car': 'Y2', 'mods': [2]}, {'car': 'W2', 'mods': [1]}, {'car': 'X1', 'mods': [1,2]}, {'car': 'W1', 'mods': [1...
4
2008-10-02T06:20:53Z
[ "python", "django", "algorithm", "puzzle" ]