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
list
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to b...
2
2009-03-16T19:00:09Z
652,455
<p>I am using Python 2.5.1. It's working great for me for general scripting and some CherryPy web projects. </p>
0
2009-03-16T22:58:35Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to b...
2
2009-03-16T19:00:09Z
866,310
<p>I had some trouble installing PIL. I compiled it and it worked with the modification explained on this post <a href="http://passingcuriosity.com/2009/installing-pil-on-mac-os-x-leopard/" rel="nofollow">http://passingcuriosity.com/2009/installing-pil-on-mac-os-x-leopard/</a> After that it worked fine.</p>
1
2009-05-14T23:02:49Z
[ "python", "osx" ]
Which version of python is currently best for os x?
651,717
<p>After going through hell trying to install the latest version of postgresql and psycopg2 today I'm going for a complete reinstall of Leopard.</p> <p>I've been sticking with macpython 2.5 for the past year but now I'm considering macports even 2.6</p> <p>For me it's most important for Twisted, PIL and psycopg2 to b...
2
2009-03-16T19:00:09Z
1,115,314
<p>If your using Macports, I recommend downloading the python_select package, which facilitates easy switching between different versions <em>including</em> the built in apple versions. Makes life a lot easier.</p>
0
2009-07-12T04:31:27Z
[ "python", "osx" ]
Django: Access primary key in models.filefield(upload_to) location
651,949
<p>I'd like to save my files using the primary key of the entry.</p> <p>Here is my code:</p> <pre><code>def get_nzb_filename(instance, filename): if not instance.pk: instance.save() # Does not work. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+'...
9
2009-03-16T20:02:38Z
652,026
<p>It seems you'll need to pre-generate your <code>File</code> models with empty file fields first. Then pick up one and save it with the given file object.</p> <p>You can have a custom manager method like this;</p> <pre><code>def create_with_pk(self): instance = self.create() instance.save() # probably t...
2
2009-03-16T20:24:14Z
[ "python", "django", "file-io" ]
Django: Access primary key in models.filefield(upload_to) location
651,949
<p>I'd like to save my files using the primary key of the entry.</p> <p>Here is my code:</p> <pre><code>def get_nzb_filename(instance, filename): if not instance.pk: instance.save() # Does not work. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+'...
9
2009-03-16T20:02:38Z
5,410,715
<p>Ty, is there a reason you rolled your own slugify filter?</p> <p>Django ships with a built-in <code>slugify</code> filter, you can use it like so:</p> <pre><code>from django.template.defaultfilters import slugify slug = slugify(some_string) </code></pre> <p>Not sure if you were aware it was available to use...</...
-1
2011-03-23T19:41:58Z
[ "python", "django", "file-io" ]
Django: Access primary key in models.filefield(upload_to) location
651,949
<p>I'd like to save my files using the primary key of the entry.</p> <p>Here is my code:</p> <pre><code>def get_nzb_filename(instance, filename): if not instance.pk: instance.save() # Does not work. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+'...
9
2009-03-16T20:02:38Z
8,655,455
<h2>Context</h2> <p>Had the same issue. Solved it attributing an id to the current object by saving the object first.</p> <h2>Method</h2> <ol> <li>create a custom upload_to function</li> <li>detect if object has pk</li> <li>if not, save instance first, retrieve the pk and assign it to the object</li> <li>generate yo...
1
2011-12-28T11:41:13Z
[ "python", "django", "file-io" ]
Django: Access primary key in models.filefield(upload_to) location
651,949
<p>I'd like to save my files using the primary key of the entry.</p> <p>Here is my code:</p> <pre><code>def get_nzb_filename(instance, filename): if not instance.pk: instance.save() # Does not work. name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower() name_slug = re.sub('[-]+'...
9
2009-03-16T20:02:38Z
16,574,947
<p>You can do this by setting <code>upload_to</code> to a temporary location and by creating a custom save method.</p> <p>The save method should call super first, to generate the primary key (this will save the file to the temporary location). Then you can rename the file using the primary key and move it to it's prop...
2
2013-05-15T21:03:44Z
[ "python", "django", "file-io" ]
Simultaneously inserting and extending a list?
652,184
<p>Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):</p> <pre><code>&gt;&gt;&gt; a = ['1', '2', '3', '4'] &gt;&gt;&gt; b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'...
5
2009-03-16T21:17:23Z
652,200
<pre><code>&gt;&gt;&gt; a = ['1', '2', '3', '4'] &gt;&gt;&gt; a ['1', '2', '3', '4'] &gt;&gt;&gt; i = a.index('2') + 1 # after the item '2' &gt;&gt;&gt; a[i:i] = ['2.4', '2.6'] &gt;&gt;&gt; a ['1', '2', '2.4', '2.6', '3', '4'] &gt;&gt;&gt; </code></pre>
14
2009-03-16T21:23:15Z
[ "python" ]
Simultaneously inserting and extending a list?
652,184
<p>Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):</p> <pre><code>&gt;&gt;&gt; a = ['1', '2', '3', '4'] &gt;&gt;&gt; b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'...
5
2009-03-16T21:17:23Z
652,225
<p>I'm not entirely clear on what you're doing; if you want to add values, and have the list remain in order, it's cleaner (and probably still faster) to just sort the whole thing:</p> <pre><code>a.extend(['2.4', '2.6']) a.sort() </code></pre>
2
2009-03-16T21:29:32Z
[ "python" ]
Simultaneously inserting and extending a list?
652,184
<p>Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):</p> <pre><code>&gt;&gt;&gt; a = ['1', '2', '3', '4'] &gt;&gt;&gt; b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'...
5
2009-03-16T21:17:23Z
652,244
<p>You can easily insert a single element using <code>list.insert(i, x)</code>, which Python defines as <code>s[i:i] = [x]</code>.</p> <pre><code>a = ['1', '2', '3', '4'] for elem in reversed(['2.4', '2.6']): a.insert(a.index('2')+1, elem)) </code></pre> <p>If you want to insert a list, you can make your own func...
5
2009-03-16T21:34:32Z
[ "python" ]
Simultaneously inserting and extending a list?
652,184
<p>Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element):</p> <pre><code>&gt;&gt;&gt; a = ['1', '2', '3', '4'] &gt;&gt;&gt; b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'...
5
2009-03-16T21:17:23Z
652,253
<p>Have a look at the <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect module</a>. I think it does what you want.</p>
2
2009-03-16T21:39:56Z
[ "python" ]
Is it possible to create anonymous objects in Python?
652,276
<p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p> <p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p> <p>Is there a more concise way than this?</p> <pre><code>x1.foo = 1 x2.foo = 2 x3.foo = ...
27
2009-03-16T21:50:45Z
652,299
<p>Have a look at this:</p> <pre><code> class MiniMock(object): def __new__(cls, **attrs): result = object.__new__(cls) result.__dict__ = attrs return result def print_foo(x): print x.foo print_foo(MiniMock(foo=3)) </code></pre>
15
2009-03-16T21:59:28Z
[ "python", "anonymous-types" ]
Is it possible to create anonymous objects in Python?
652,276
<p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p> <p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p> <p>Is there a more concise way than this?</p> <pre><code>x1.foo = 1 x2.foo = 2 x3.foo = ...
27
2009-03-16T21:50:45Z
652,417
<p>I like Tetha's solution, but it's unnecessarily complex.</p> <p>Here's something simpler:</p> <pre><code>&gt;&gt;&gt; class MicroMock(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... &gt;&gt;&gt; def print_foo(x): ... print x.foo ... &gt;&gt;&gt; print_foo(MicroMock(f...
34
2009-03-16T22:40:38Z
[ "python", "anonymous-types" ]
Is it possible to create anonymous objects in Python?
652,276
<p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p> <p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p> <p>Is there a more concise way than this?</p> <pre><code>x1.foo = 1 x2.foo = 2 x3.foo = ...
27
2009-03-16T21:50:45Z
17,700,031
<p>Non classy:</p> <pre><code>def mock(**attrs): r = lambda:0 r.__dict__ = attrs return r def test(a, b, c, d): print a.foo, b.foo, c.foo, d.foo test(*[mock(foo=i) for i in xrange(1,5)]) # or test(mock(foo=1), mock(foo=2), mock(foo=3), mock(foo=4)) </code></pre>
3
2013-07-17T12:40:53Z
[ "python", "anonymous-types" ]
Is it possible to create anonymous objects in Python?
652,276
<p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p> <p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p> <p>Is there a more concise way than this?</p> <pre><code>x1.foo = 1 x2.foo = 2 x3.foo = ...
27
2009-03-16T21:50:45Z
29,480,317
<p>I found this: <a href="http://www.hydrogen18.com/blog/python-anonymous-objects.html">http://www.hydrogen18.com/blog/python-anonymous-objects.html</a>, and in my limited testing it seems like it works:</p> <pre><code>&gt;&gt;&gt; obj = type('',(object,),{"foo": 1})() &gt;&gt;&gt; obj.foo 1 </code></pre>
14
2015-04-06T21:54:38Z
[ "python", "anonymous-types" ]
Is it possible to create anonymous objects in Python?
652,276
<p>I'm debugging some Python that takes, as input, a list of objects, each with some attributes.</p> <p>I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number.</p> <p>Is there a more concise way than this?</p> <pre><code>x1.foo = 1 x2.foo = 2 x3.foo = ...
27
2009-03-16T21:50:45Z
35,059,764
<p>Another obvious hack:</p> <pre><code>class foo1: x=3; y='y' class foo2: y=5; x=6 print(foo1.x, foo2.y) </code></pre> <p>But for your exact usecase, calling a function with anonymous objects directly, I don't know any one-liner less verbose than</p> <pre><code>myfunc(type('', (object,), {'foo': 3},), type('', (ob...
2
2016-01-28T11:06:48Z
[ "python", "anonymous-types" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
652,327
<p>The training process of a back-propagation neural network works by minimizing the error from the optimal result. But having a trained neural network finding the minimum of an unknown function would be pretty hard.</p> <p>If you restrict the problem to a specific function class, it could work, and be pretty quick to...
1
2009-03-16T22:08:40Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
652,348
<p>They're pretty bad for the purpose; one of the big problems of neural networks is that they get stuck in local minima. You might want to look into support vector machines instead.</p>
0
2009-03-16T22:14:42Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
652,351
<p>It sounds to me like this is a problem more suited to <a href="http://en.wikipedia.org/wiki/Genetic%5Falgorithm" rel="nofollow">genetic algorithms</a> than neural networks. Neural nets tend to need a bounded problem to solve, requiring training against known data, etc. - whereas genetic algorithms work by finding be...
4
2009-03-16T22:15:08Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
652,362
<p>Neural networks are classifiers. They separate two classes of data elements. They learn this separation (usually) by preclassified data elements. Thus, I say: No, unless you do a major stretch beyond breakage.</p>
1
2009-03-16T22:17:49Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
709,482
<p>Actually you could use the NN to find a function minimum, but it would work best combined with genetic algorithms mentioned by <a href="http://#652351" rel="nofollow">Erik</a>.</p> <p>Basically NN tent to find solutions which correspond to a function local minimum or maximum but in doing so are pretty precise (to c...
0
2009-04-02T12:17:53Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
13,611,588
<p>Back-propagation works by minimizing the error. However, you can really minimize whatever you want. So, you could use back-prop-like update rules to find the Artificial Neural Network inputs that minimize the output.</p> <p>This is a big question, sorry for the short answer. I should also add that, my suggested ...
2
2012-11-28T18:04:47Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
18,789,493
<p>You can teach a NN to approximate a function. If a function is differentiable or your NN has more than one hidden layers, you can teach it to give derivative of a function.</p> <p>Example:</p> <pre><code>You can train a 1 input 1 output NN to give output=sin(input) You can train it also give output=cos(input) wh...
0
2013-09-13T15:02:25Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
Can a neural network be used to find a functions minimum(a)?
652,283
<p>I had been interested in neural networks for a bit and thought about using one in python for a light project that compares various minimization techniques in a time domain (which is fastest).</p> <p>Then I realized I didn't even know if a NN is good for minimization. What do you think?</p>
10
2009-03-16T21:53:30Z
24,077,082
<p>Although this comes a bit too late for the the author of this question. Maybe somebody wants to test some optimization algorithms, when he reads this...</p> <p>If you are working with regressions in machine learning (NN, SVM, Multiple Linear Regression, K Nearest Neighbor) and you want to minimize (maximize) your ...
0
2014-06-06T08:08:24Z
[ "python", "artificial-intelligence", "neural-network", "minimization" ]
sorting a list of dictionary values by date in python
652,291
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want t...
15
2009-03-16T21:56:51Z
652,302
<p>Sort the data (or a copy of the data) directly and build the list of dicts afterwards. Sort using the function sorted with an appropiate key function (operator.attrgetter probably)</p>
2
2009-03-16T22:02:45Z
[ "python", "django" ]
sorting a list of dictionary values by date in python
652,291
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want t...
15
2009-03-16T21:56:51Z
652,347
<p>You can do it this way:</p> <pre><code>list.sort(key=lambda item:item['date'], reverse=True) </code></pre>
35
2009-03-16T22:14:17Z
[ "python", "django" ]
sorting a list of dictionary values by date in python
652,291
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want t...
15
2009-03-16T21:56:51Z
652,463
<pre><code>from operator import itemgetter your_list.sort(key=itemgetter('date'), reverse=True) </code></pre> <h3>Related notes</h3> <ul> <li><p>don't use <code>list</code>, <code>dict</code> as variable names, they are builtin names in Python. It makes your code hard to read.</p></li> <li><p>you might need to repla...
13
2009-03-16T23:01:22Z
[ "python", "django" ]
sorting a list of dictionary values by date in python
652,291
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want t...
15
2009-03-16T21:56:51Z
652,478
<p>If you're into the whole brevity thing:</p> <pre><code>data = "data from database" sorted_data = sorted( [{'title': x.title, 'date': x.created_on} for x in data], key=operator.itemgetter('date'), reverse=True) </code></pre>
1
2009-03-16T23:06:37Z
[ "python", "django" ]
sorting a list of dictionary values by date in python
652,291
<p>I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys.</p> <p>ex: </p> <pre><code>data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) </code></pre> <p>I want t...
15
2009-03-16T21:56:51Z
654,675
<p>I actually had this almost exact question yesterday and <a href="http://stackoverflow.com/questions/72899/in-python-how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary">solved it using search</a>. The best answer applied to your question is this:</p> <pre><code>from operator import itemgetter list.sort...
2
2009-03-17T15:12:41Z
[ "python", "django" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,439
<p>You're using the wrong data type. Use a <code>dict</code> of <code>set</code>s instead:</p> <pre><code>def add(key, value, userdict): userdict.setdefault(key, set()) userdict[key].add(value) </code></pre> <p>Usage:</p> <pre><code>animaldict = {} add('bird', 'peck', animaldict) add('bird', 'screech', anim...
6
2009-03-16T22:49:44Z
[ "python" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,444
<pre><code>animals_dict = dict(animals) def add(key, action): animals_dict.setdefault(key, []) if action not in animals_dict[key]: animals_dict[key].append(action) </code></pre> <p>(Updated to use <code>setdefault</code> - nice one @recursive)</p>
0
2009-03-16T22:52:15Z
[ "python" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,445
<p>While it is possible to construct a generic function that finds the animal in the list using a.index or testing with "dog" in animals, you really want a dictionary here, otherwise the add function will scale abysmally as more animals are added:</p> <pre><code>animals = {'dog':set(['bite']), 'cat':set(['b...
4
2009-03-16T22:53:08Z
[ "python" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,446
<p>You really should use a dictionary for this purpose. Or alternatively a class <code>Animal</code>.</p> <p>You could improve your code like this:</p> <pre><code>if not any((animal[0] == "bird") for animal in animals): # append "bird" to animals </code></pre>
0
2009-03-16T22:54:02Z
[ "python" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,453
<p>Based on recursive's solution, in Python 2.5 or newer you can use the <code>defaultdict</code> class, something like this:</p> <pre><code>from collections import defaultdict a = defaultdict(set) def add(animal, behavior): a[animal].add(behavior) add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide'...
4
2009-03-16T22:58:03Z
[ "python" ]
Check if value exists in nested lists
652,423
<p>in my list:</p> <pre><code>animals = [ ['dog', ['bite'] ], ['cat', ['bite', 'scratch'] ], ['bird', ['peck', 'bite'] ], ] add('bird', 'peck') add('bird', 'screech') add('turtle', 'hide') </code></pre> <p>The add function should check that the animal and action haven't been added before a...
2
2009-03-16T22:41:50Z
652,803
<p>While I agree with the others re. your choice of data structure, here is an answer to your question:</p> <pre><code>def add(name, action): for animal in animals: if animal[0] == name: if action not in animal[1]: animal[1].append(action) return else: an...
0
2009-03-17T02:05:44Z
[ "python" ]
Separating Models and Request Handlers In Google App Engine
652,449
<p>I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily?</p> <p>Thanks, Collin</p>
2
2009-03-16T22:55:07Z
652,458
<p>I assume you're using the basic webkit and not Django or something fancy. In that case just create a subdirectory called models. Put any python files you use for your models in here. Create also one blank file in this folder called __init__.py.</p> <p>Then in your main.py or "controller" or what have you, put:</p> ...
7
2009-03-16T22:59:44Z
[ "python", "google-app-engine", "model" ]
Separating Models and Request Handlers In Google App Engine
652,449
<p>I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily?</p> <p>Thanks, Collin</p>
2
2009-03-16T22:55:07Z
1,566,716
<p>Brandon's answer is what I do. Furthermore, I rather like Rails's custom of one model per file. I don't stick to it completely but that is my basic pattern, especially since Python tends to encourage more-but-simpler lines of code than Ruby.</p> <p>So what I do is I make models a package too:</p> <pre><code>models...
1
2009-10-14T14:37:44Z
[ "python", "google-app-engine", "model" ]
Writing a binary buffer to a file in python
652,535
<p>I have some python code that:</p> <ol> <li>Takes a BLOB from a database which is compressed.</li> <li>Calls an uncompression routine in C that uncompresses the data.</li> <li>Writes the uncompressed data to a file.</li> </ol> <p>It uses <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>...
6
2009-03-16T23:30:36Z
652,565
<p>Slicing works for c_char_Arrays too:</p> <pre><code>myfile.write(c_uncompData_p[:c_uncompSize]) </code></pre>
6
2009-03-16T23:41:07Z
[ "python", "binary", "io" ]
Writing a binary buffer to a file in python
652,535
<p>I have some python code that:</p> <ol> <li>Takes a BLOB from a database which is compressed.</li> <li>Calls an uncompression routine in C that uncompresses the data.</li> <li>Writes the uncompressed data to a file.</li> </ol> <p>It uses <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>...
6
2009-03-16T23:30:36Z
652,987
<p><code>buffer()</code> might help to avoid unnecessary copying (caused by slicing as in <a href="http://stackoverflow.com/questions/652535/writing-a-binary-buffer-to-a-file-in-python/652565#652565">@elo80ka's answer</a>):</p> <pre><code>myfile.write(buffer(c_uncompData_p.raw, 0, c_uncompSize)) </code></pre> <p>In y...
5
2009-03-17T04:01:25Z
[ "python", "binary", "io" ]
How to unlock an sqlite3 db?
652,750
<p>OMG!</p> <p>What an apparent problem... my django based scripts have locked my sqlite db...</p> <p>Does anyone know how to fix?</p>
-1
2009-03-17T01:33:18Z
652,758
<p>Your database is locked because you have a transaction running somewhere. </p> <p>Stop all your Django apps. If necessary, reboot.</p> <p>It's also remotely possible that you crashed a SQLite client in the middle of a transaction and the file lock was left in place.</p>
6
2009-03-17T01:37:21Z
[ "python", "django" ]
How to unlock an sqlite3 db?
652,750
<p>OMG!</p> <p>What an apparent problem... my django based scripts have locked my sqlite db...</p> <p>Does anyone know how to fix?</p>
-1
2009-03-17T01:33:18Z
9,482,213
<p>Make sure the database file isn't read-only or that you don't have database already open by other application. E.g. </p> <pre><code>$ ps aux | grep sqlite martin 21118 0.0 0.3 $ kill -9 21118 </code></pre>
1
2012-02-28T12:49:00Z
[ "python", "django" ]
Effective way to iteratively append to a string in Python?
653,259
<p>I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?</p> <pre><code>def getwords(text, splitch...
2
2009-03-17T07:04:05Z
653,268
<p>You don't want to use re.split?</p> <pre><code>import re re.split("[,; ]+", "coucou1 , coucou2;coucou3") </code></pre>
4
2009-03-17T07:08:48Z
[ "python", "string", "split", "append", "generator" ]
Effective way to iteratively append to a string in Python?
653,259
<p>I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?</p> <pre><code>def getwords(text, splitch...
2
2009-03-17T07:04:05Z
653,269
<p><a href="http://www.skymind.com/~ocrow/python%5Fstring/">http://www.skymind.com/~ocrow/python_string/</a> talks about several ways of concatenating strings in Python and assesses their performance as well. </p>
5
2009-03-17T07:08:57Z
[ "python", "string", "split", "append", "generator" ]
Effective way to iteratively append to a string in Python?
653,259
<p>I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?</p> <pre><code>def getwords(text, splitch...
2
2009-03-17T07:04:05Z
653,287
<p>You can split the input using <a href="http://docs.python.org/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a>:</p> <pre><code>&gt;&gt;&gt; splitchars=' \t|!?.;:"' &gt;&gt;&gt; re.split("[%s]" % splitchars, "one\ttwo|three?four") ['one', 'two', 'three', 'four'] &gt;&gt;&gt; </code></pre> <p>EDI...
1
2009-03-17T07:25:01Z
[ "python", "string", "split", "append", "generator" ]
Effective way to iteratively append to a string in Python?
653,259
<p>I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?</p> <pre><code>def getwords(text, splitch...
2
2009-03-17T07:04:05Z
653,312
<p>You can use re.split</p> <pre><code>re.split('[\s|!\?\.;:"]', text) </code></pre> <p>However if the text is very large the resulting array may be consuming too much memory. Then you may consider re.finditer:</p> <pre><code>import re def getwords(text, splitchars=' \t|!?.;:"'): words_iter = re.finditer( "([%...
3
2009-03-17T07:36:10Z
[ "python", "string", "split", "append", "generator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,379
<p>Generally you can give default arguments in Python...</p> <pre><code>def redirect_output(fn, output = stderr): # whatever </code></pre> <p>Not sure if that works with decorators as well, though. I don't know of any reason why it wouldn't.</p>
-2
2009-03-17T08:18:44Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,381
<p>Have you tried keyword arguments with default values? Something like</p> <pre><code>def decorate_something(foo=bar, baz=quux): pass </code></pre>
-1
2009-03-17T08:19:36Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,433
<p>Building on vartec's answer:</p> <pre><code>imports sys def redirect_output(func, output=None): if output is None: output = sys.stderr if isinstance(output, basestring): output = open(output, 'w') # etc... # everything else... </code></pre>
-2
2009-03-17T08:53:57Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,478
<p>Using keyword arguments with default values (as suggested by kquinn) is a good idea, but will require you to include the parenthesis:</p> <pre><code>@redirect_output() def foo(): ... </code></pre> <p>If you would like a version that works without the parenthesis on the decorator you will have to account both s...
27
2009-03-17T09:13:19Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,511
<p>You need to detect both cases, for example using the type of the first argument, and accordingly return either the wrapper (when used without parameter) or a decorator (when used with arguments).</p> <pre><code>from functools import wraps import inspect def redirect_output(fn_or_output): def decorator(fn): ...
11
2009-03-17T09:25:42Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
653,553
<p>A python decorator is called in a fundamentally different way depending on whether you give it arguments or not. The decoration is actually just a (syntactically restricted) expression.</p> <p>In your first example:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>the function...
8
2009-03-17T09:41:39Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
14,412,901
<p>I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read.</p> <p>Like thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see...
17
2013-01-19T09:24:01Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
19,017,908
<p>I know this is an old question, but I really don't like any of the techniques proposed so I wanted to add another method. I saw that django uses a really clean method in their <a href="https://github.com/django/django/blob/1.5.4/django/contrib/auth/decorators.py#L44" rel="nofollow"><code>login_required</code> decora...
2
2013-09-26T01:35:52Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
38,414,401
<p>In fact, the caveat case in @bj0's solution can be checked easily:</p> <pre><code>def meta_wrap(decor): @functools.wraps(decor) def new_decor(*args, **kwargs): if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # this is the double-decorated f. # Its first argumen...
0
2016-07-16T18:39:43Z
[ "python", "decorator" ]
How to create a Python decorator that can be used either with or without parameters?
653,368
<p>I'd like to create a Python decorator that can be used either with parameters:</p> <pre><code>@redirect_output("somewhere.log") def foo(): .... </code></pre> <p>or without them (for instance to redirect the output to stderr by default):</p> <pre><code>@redirect_output def foo(): .... </code></pre> <p>Is ...
41
2009-03-17T08:10:19Z
39,335,652
<p>Several answers here already address your problem nicely. With respect to style, however, I prefer solving this decorator predicament using <code>functools.partial</code>, as suggested in David Beazley's <em>Python Cookbook 3</em>:</p> <pre><code>from functools import partial, wraps def decorator(func=None, foo='s...
1
2016-09-05T17:59:30Z
[ "python", "decorator" ]
How can I profile a multithread program in Python?
653,419
<p>I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?</p>
38
2009-03-17T08:45:24Z
653,484
<p>I don't know any profiling-application that supports such thing for python - but You could write a Trace-class that writes log-files where you put in the information of when an operation is started and when it ended and how much time it consumed.</p> <p>It's a simple and quick solution for your problem.</p>
0
2009-03-17T09:16:20Z
[ "python", "multithreading", "profiling" ]
How can I profile a multithread program in Python?
653,419
<p>I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?</p>
38
2009-03-17T08:45:24Z
653,497
<p>Instead of running one <code>cProfile</code>, you could run separate <code>cProfile</code> instance in each thread, then combine the stats. <code>Stats.add()</code> does this automatically.</p>
14
2009-03-17T09:21:43Z
[ "python", "multithreading", "profiling" ]
How can I profile a multithread program in Python?
653,419
<p>I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?</p>
38
2009-03-17T08:45:24Z
654,217
<p>If you're okay with doing a bit of extra work, you can write your own profiling class that implements <code>profile(self, frame, event, arg)</code>. That gets called whenever a function is called, and you can fairly easily set up a structure to gather statistics from that.</p> <p>You can then use <a href="http://d...
4
2009-03-17T13:22:20Z
[ "python", "multithreading", "profiling" ]
How can I profile a multithread program in Python?
653,419
<p>I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?</p>
38
2009-03-17T08:45:24Z
656,057
<p>Given that your different threads' main functions differ, you can use the very helpful <code>profile_func()</code> decorator from <a href="https://translate.svn.sourceforge.net/svnroot/translate/src/trunk/virtaal/devsupport/profiling.py" rel="nofollow">here</a>.</p>
1
2009-03-17T21:19:20Z
[ "python", "multithreading", "profiling" ]
How can I profile a multithread program in Python?
653,419
<p>I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?</p>
38
2009-03-17T08:45:24Z
1,658,540
<p>Please see <a href="https://pypi.python.org/pypi/yappi/" rel="nofollow">yappi</a> (Yet Another Python Profiler).</p>
23
2009-11-01T22:09:51Z
[ "python", "multithreading", "profiling" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
653,539
<p>In SciPy you can use <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html">sparse matrices</a>. Also note, that there are more efficient ways of multiplying matrix by itself. Anyway, what you're trying to do can by done by SVD decomposition. </p> <p><a href="http://expertvoices.nsdl.org/cornell-cs322/2008...
7
2009-03-17T09:37:00Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
653,724
<p>Why not use a real graph library, like <a href="http://code.google.com/p/python-graph/">Python-Graph</a>? It has a <a href="http://www.linux.ime.usp.br/~matiello/python-graph/docs/graph.algorithms.accessibility-module.html#connected_components">function to determine connected components</a> (though no example is pro...
12
2009-03-17T10:50:17Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
653,851
<p>Looks like there is a library <a href="http://mathema.tician.de/software/pymetis" rel="nofollow">PyMetis</a>, which will partition your graph for you, given a list of links. It should be fairly easy to extract the list of links from your graph by passing it your original list of linked nodes (not the matrix-multiply...
0
2009-03-17T11:34:58Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
654,595
<p>Here's some naive implementation, which finds the connected components using <a href="http://en.wikipedia.org/wiki/Depth%5Ffirst%5Fsearch" rel="nofollow">depth first search</a>, i wrote some time ago. Although it's very simple, it scales well to ten thousands of vertices and edges...</p> <pre><code> import sys from...
1
2009-03-17T14:57:04Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
656,768
<p>The SVD algorithm is not applicable here, but otherwise Phil H is correct. </p>
0
2009-03-18T02:28:41Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
656,895
<p>As others have pointed out, no need to reinvent the wheel. A lot of thought has been put into optimal clustering techniques. <a href="http://www.micans.org/mcl/" rel="nofollow">Here</a> is one well-known clustering program.</p>
2
2009-03-18T03:39:18Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
7,507,451
<p>Finding an optimal graph partition is an NP-hard problem, so whatever the algorithm, it is going to be an approximation or a heuristic. Not surprisingly, different clustering algorithms produce (wildly) different results. </p> <p>Python implementation of Newman's modularity algorithm: <a href="http://perso.crans.or...
2
2011-09-21T22:25:38Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
How can I cluster a graph in Python?
653,496
<p>Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. </p> <p>So, what I...
13
2009-03-17T09:21:07Z
29,882,547
<p>There's also <a href="http://graph-tool.skewed.de/" rel="nofollow">graph_tool</a> and <a href="http://networkit.iti.kit.edu/" rel="nofollow">networkit</a> that have efficient routines for connected components, and both store the network efficiently. If you're going to work with millions of nodes, networkx will likel...
2
2015-04-26T19:37:21Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
Django Forms, set an initial value to request.user
653,735
<p>Is there some way to make the following possible, or should it be done elsewhere?</p> <pre><code>class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = reque...
13
2009-03-17T10:53:00Z
653,767
<p>You might want to handle this in your view function. Since your view function must create the initial form, and your view function knows the user.</p> <pre><code>form = JobRecordForm( {'supervisor':request.user} ) </code></pre> <p>This will trigger validation of this input, BTW, so you can't provide hint values t...
5
2009-03-17T11:04:13Z
[ "python", "django-forms" ]
Django Forms, set an initial value to request.user
653,735
<p>Is there some way to make the following possible, or should it be done elsewhere?</p> <pre><code>class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = reque...
13
2009-03-17T10:53:00Z
1,188,305
<p>If you do this in your view.py instead:</p> <pre><code>form = JobRecordForm( initial={'supervisor':request.user} ) </code></pre> <p>Then you won't trigger the validation.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values">http://docs.djangoproject.com/en/dev/ref/forms/...
29
2009-07-27T13:58:31Z
[ "python", "django-forms" ]
Django Forms, set an initial value to request.user
653,735
<p>Is there some way to make the following possible, or should it be done elsewhere?</p> <pre><code>class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = reque...
13
2009-03-17T10:53:00Z
1,233,143
<p>An Another solution with Middleware and save rewriting : With middleware solution You can call "request" everywhere.</p> <p><hr /></p> <p>""" Middleware """</p> <pre><code> # coding: utf-8 from django.utils.thread_support import currentThread _requests = {} def get_request(): return _requests[currentThr...
5
2009-08-05T13:06:58Z
[ "python", "django-forms" ]
Django Forms, set an initial value to request.user
653,735
<p>Is there some way to make the following possible, or should it be done elsewhere?</p> <pre><code>class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = reque...
13
2009-03-17T10:53:00Z
14,402,474
<p>For a complete answer, here's the CBV solution:</p> <pre><code>class MyFormView(TemplateView, FormMixin): def get_initial(self): self.initial.update({'your_field': self.request.user}) return super(MyFormView, self).get_initial() </code></pre>
4
2013-01-18T15:47:15Z
[ "python", "django-forms" ]
Python - Acquire value from dictionary depending on location/index in list
653,765
<p>From MySQL query I get data which I put into a dictionary "d":</p> <blockquote> <p>d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)...
1
2009-03-17T11:03:54Z
653,827
<p>Are you asking for</p> <pre><code>def hms( td ): h = dt.seconds // 3600 m = dt.seconds%3600 // 60 s = dt.seconds%60 return h+td.days*24, m, s [ hms(d[ m[i] ]) for i in m ] </code></pre> <p>?</p>
-1
2009-03-17T11:26:13Z
[ "python", "list", "dictionary" ]
Python - Acquire value from dictionary depending on location/index in list
653,765
<p>From MySQL query I get data which I put into a dictionary "d":</p> <blockquote> <p>d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)...
1
2009-03-17T11:03:54Z
653,829
<p>I'm not entirely sure if this is what you're looking for, but I'll take a shot:</p> <pre><code>&gt;&gt;&gt; indices = [index for index, i in enumerate(m) if i == 4] &gt;&gt;&gt; h = [d[i][0] for i in indices] </code></pre> <p>Then you have to process the timedeltas as you want to.</p>
2
2009-03-17T11:27:11Z
[ "python", "list", "dictionary" ]
Python - Acquire value from dictionary depending on location/index in list
653,765
<p>From MySQL query I get data which I put into a dictionary "d":</p> <blockquote> <p>d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)...
1
2009-03-17T11:03:54Z
653,832
<pre><code>deltas = [str(d[i][0]) for i, j in enumerate(m) if j == 4] </code></pre> <p>produces list of delta representation as strings.</p>
0
2009-03-17T11:28:08Z
[ "python", "list", "dictionary" ]
Python - Acquire value from dictionary depending on location/index in list
653,765
<p>From MySQL query I get data which I put into a dictionary "d":</p> <blockquote> <p>d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.timedelta(0, 25800),), 3: (datetime.timedelta(0, 26100),), 4: (datetime.timedelta(0, 26400),), 5: (datetime.timedelta(0, 26700),)...
1
2009-03-17T11:03:54Z
3,224,406
<p>So at each index is an n-tuple of <code>timedeltas</code> right? Assuming, from the code, that potentially there could be more than one <code>timedelta</code> at each index. import datetime</p> <pre><code>import datetime d = {0: (datetime.timedelta(0, 25200),), 1: (datetime.timedelta(0, 25500),), 2: (datetime.time...
0
2010-07-11T19:48:39Z
[ "python", "list", "dictionary" ]
A simple freeze behavior decorator
653,783
<p>I'm trying to write a freeze decorator for Python.</p> <p>The idea is as follows :</p> <p><strong>(In response to the two comments)</strong></p> <p>I might be wrong but I think there is two main use of test case.</p> <ul> <li><p>One is the test-driven development : Ideally , developers are writing case before ...
2
2009-03-17T11:08:54Z
654,608
<p>Are you looking to implement <strong>invariants</strong> or post conditions?</p> <p>You should specify the result explicitly, this wil remove most of you problems.</p>
0
2009-03-17T14:59:44Z
[ "python", "testing", "decorator", "freeze" ]
A simple freeze behavior decorator
653,783
<p>I'm trying to write a freeze decorator for Python.</p> <p>The idea is as follows :</p> <p><strong>(In response to the two comments)</strong></p> <p>I might be wrong but I think there is two main use of test case.</p> <ul> <li><p>One is the test-driven development : Ideally , developers are writing case before ...
2
2009-03-17T11:08:54Z
654,633
<p><strong>"In general, would you use such a feature, knowing its limitation...?"</strong></p> <p>Frankly speaking -- never.</p> <p>There are no circumstances under which I would "freeze" results of a function in this way.</p> <p>The use case appears to be based on two wrong ideas: (1) that unit testing is either h...
3
2009-03-17T15:04:36Z
[ "python", "testing", "decorator", "freeze" ]
Equivalent for LinkedHashMap in Python
653,887
<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html">LinkedHashMap</a> is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additio...
11
2009-03-17T11:46:11Z
653,902
<p>Although you can do the same thing by maintaining a list to keep track of insertion order, <a href="https://docs.python.org/2/library/collections.html" rel="nofollow">Python 2.7</a> and <a href="https://docs.python.org/3/library/collections.html" rel="nofollow">Python >=3.1</a> have an OrderedDict class in the colle...
10
2009-03-17T11:50:44Z
[ "python" ]
Equivalent for LinkedHashMap in Python
653,887
<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html">LinkedHashMap</a> is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additio...
11
2009-03-17T11:46:11Z
653,905
<p>I don't think so; you'd have to use a dict plus a list. But you could pretty easily wrap that in a class, and define <code>keys</code>, <code>__getitem__</code>, <code>__setitem__</code>, etc. to make it work the way you want.</p>
1
2009-03-17T11:51:35Z
[ "python" ]
Equivalent for LinkedHashMap in Python
653,887
<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html">LinkedHashMap</a> is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additio...
11
2009-03-17T11:46:11Z
653,910
<p>I am not sure whether this is what you are asking for:</p> <pre><code>&gt;&gt;&gt; dic = {1: 'one', 2: 'two'} &gt;&gt;&gt; for k, v in dic.iteritems(): ... print k, v </code></pre> <p>you can order the dic in the order of the insertion using <a href="http://www.xs4all.nl/~anthon/Python/ordereddict/" rel="nofol...
2
2009-03-17T11:53:21Z
[ "python" ]
Equivalent for LinkedHashMap in Python
653,887
<p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html">LinkedHashMap</a> is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additio...
11
2009-03-17T11:46:11Z
653,987
<p>If you're on Python 2.7 or Python >=3.1 you can use <a href="https://docs.python.org/2/library/collections.html#collections.OrderedDict" rel="nofollow">collections.OrderedDict</a> in the standard library.</p> <p><a href="http://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-ord...
6
2009-03-17T12:21:59Z
[ "python" ]
Python Hash Functions
654,128
<p>What is a good way of hashing a hierarchy (similar to a file structure) in python?</p> <p>I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time?</p> <p>An example of a structure I might want...
0
2009-03-17T13:00:41Z
654,184
<p>If you have access to your hierarchy components as a tuple, just hash it - tuples are hashable. You may not gain a lot over conversion to and from a delimited string, but it's a start.</p> <p>If this doesn't help, perhaps you could provide more information about how you store the hierarchy/path information.</p>
8
2009-03-17T13:12:32Z
[ "python", "hash" ]
Python Hash Functions
654,128
<p>What is a good way of hashing a hierarchy (similar to a file structure) in python?</p> <p>I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time?</p> <p>An example of a structure I might want...
0
2009-03-17T13:00:41Z
654,570
<p>You can make any object hashable by implementing the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fhash%5F%5F" rel="nofollow"><code>__hash__()</code> method</a></p> <p>So you can simply add a suitable <code>__hash__()</code> method to the objects storing your hierarchy, e.g. compute the hash...
1
2009-03-17T14:51:34Z
[ "python", "hash" ]
Python Hash Functions
654,128
<p>What is a good way of hashing a hierarchy (similar to a file structure) in python?</p> <p>I could convert the whole hierarchy into a dotted string and then hash that, but is there a better (or more efficient) way of doing this without going back and forth all the time?</p> <p>An example of a structure I might want...
0
2009-03-17T13:00:41Z
655,085
<p>How do you want to access your hierarchy? </p> <p>If you're always going to be checking for a full path, then as suggested, use a tuple: eg:</p> <pre><code>&gt;&gt;&gt; d["a","b1","c",1,"d"] = value </code></pre> <p>However, if you're going to be doing things like "quickly find all the items below "a -> b1", it ...
4
2009-03-17T16:48:32Z
[ "python", "hash" ]
Python file modes detail
654,499
<p>In Python, the following statements do not work:</p> <pre><code>f = open("ftmp", "rw") print &gt;&gt; f, "python" </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 9] Bad file descriptor </code></pre> <p>But with ...
12
2009-03-17T14:32:48Z
654,518
<p>Better yet, let the documentation do it for you: <a href="http://docs.python.org/library/functions.html#open">http://docs.python.org/library/functions.html#open</a>. Your issue in the question is that there is no "rw" mode... you probably want 'r+' as you wrote (or 'a+' if the file does not yet exist).</p>
16
2009-03-17T14:38:28Z
[ "python", "file-io" ]
Python file modes detail
654,499
<p>In Python, the following statements do not work:</p> <pre><code>f = open("ftmp", "rw") print &gt;&gt; f, "python" </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 9] Bad file descriptor </code></pre> <p>But with ...
12
2009-03-17T14:32:48Z
655,524
<p>In fact, this is okay, but I found an "rw" mode on the socket in following code (for Python on <a href="http://en.wikipedia.org/wiki/S60_%28software_platform%29" rel="nofollow">S60</a>) at lines 42 and 45:</p> <p><a href="http://www.mobilenin.com/mobilepythonbook/examples/057-btchat.html" rel="nofollow">http://www....
0
2009-03-17T18:31:35Z
[ "python", "file-io" ]
Python file modes detail
654,499
<p>In Python, the following statements do not work:</p> <pre><code>f = open("ftmp", "rw") print &gt;&gt; f, "python" </code></pre> <p>I get the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 9] Bad file descriptor </code></pre> <p>But with ...
12
2009-03-17T14:32:48Z
656,289
<p>As an addition to <a href="http://stackoverflow.com/questions/654499/python-file-modes-detail/654518#654518">@Jarret Hardie's answer</a> here's how Python check file mode in the function <a href="http://hg.python.org/cpython/file/3.2/Modules/_io/fileio.c#l286">fileio_init()</a>:</p> <pre><code>s = mode; while (*s) ...
10
2009-03-17T22:30:32Z
[ "python", "file-io" ]
Is there any preferable way to get user/group information from an Active Directory domain in Python?
654,520
<p>For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this:</p> <pre><code>&gt;&gt;&gt; import win32net &gt;&gt;&gt; win32net.NetUserGetGroups('domain_name.com', 'userna...
4
2009-03-17T14:39:46Z
654,739
<p>AD's LDAP interface has quite a few 'quirks' that make it more difficult to use than it might appear on the surface, and it tends to lag significantly behind on features. When I worked with it, I mostly dealt with authentication, but it's probably the same no matter what you're doing. There's a lot of weirdness in...
3
2009-03-17T15:27:17Z
[ "python", "winapi", "active-directory", "ldap", "pywin32" ]
Is there any preferable way to get user/group information from an Active Directory domain in Python?
654,520
<p>For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this:</p> <pre><code>&gt;&gt;&gt; import win32net &gt;&gt;&gt; win32net.NetUserGetGroups('domain_name.com', 'userna...
4
2009-03-17T14:39:46Z
1,391,300
<p>Check out <a href="http://timgolden.me.uk/python/active%5Fdirectory.html" rel="nofollow">Tim Golden's Python Stuff</a>.</p> <pre><code>import active_directory user = active_directory.find_user(user_name) groups = user.memberOf </code></pre>
1
2009-09-07T23:27:43Z
[ "python", "winapi", "active-directory", "ldap", "pywin32" ]
Is there any preferable way to get user/group information from an Active Directory domain in Python?
654,520
<p>For a Django application that I'm working on, I wanted to allow group membership to be determined by Active Directory group. After a while of digging through the pywin32 documentation, I came up with this:</p> <pre><code>&gt;&gt;&gt; import win32net &gt;&gt;&gt; win32net.NetUserGetGroups('domain_name.com', 'userna...
4
2009-03-17T14:39:46Z
5,170,066
<pre><code>import wmi oWMI = wmi.WMI(namespace="directory\ldap") ADUsers = oWMI.query("select ds_name from ds_user") for user in ADUsers: print user.ds_name </code></pre>
2
2011-03-02T15:59:21Z
[ "python", "winapi", "active-directory", "ldap", "pywin32" ]
splitting a ManyToManyField over multiple form fields in a ModelForm
654,576
<p>So I have a model with a ManyToManyField called tournaments. I have a ModelForm with two tournament fields:</p> <pre><code>pay_tourns = forms.ModelMultipleChoiceField( queryset=Tourn.objects.all().active().pay_tourns(), widget=forms.CheckboxSelectMultiple()) rep_tourn...
1
2009-03-17T14:52:53Z
655,249
<p>You could do something like this to the ModelForm: </p> <pre><code>def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: self.fields['pay_tourns'].queryset.filter(post=instance) self.fields['rep_tourns'].queryse...
2
2009-03-17T17:27:47Z
[ "python", "django", "django-forms", "modelform" ]
splitting a ManyToManyField over multiple form fields in a ModelForm
654,576
<p>So I have a model with a ManyToManyField called tournaments. I have a ModelForm with two tournament fields:</p> <pre><code>pay_tourns = forms.ModelMultipleChoiceField( queryset=Tourn.objects.all().active().pay_tourns(), widget=forms.CheckboxSelectMultiple()) rep_tourn...
1
2009-03-17T14:52:53Z
655,544
<p>Paolo Bergantino was on the right track, and helped me find it. This was the solution:</p> <pre><code>def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) instance = kwargs.get('instance') if instance: self.fields['pay_tourns'].initial = [ o.id for o in instance.to...
1
2009-03-17T18:37:23Z
[ "python", "django", "django-forms", "modelform" ]
How do I create a unique value for each key using dict.fromkeys?
654,646
<p>First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use <code>dict.fromkeys</code> (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the ...
9
2009-03-17T15:06:46Z
654,686
<p>Check out <a href="http://docs.python.org/library/collections.html#collections.defaultdict">defaultdict</a> (requires Python 2.5 or greater).</p> <pre><code>from collections import defaultdict def benchmark(input): ... return time_taken runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = defaultd...
12
2009-03-17T15:15:24Z
[ "python", "dictionary", "fromkeys" ]
How do I create a unique value for each key using dict.fromkeys?
654,646
<p>First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use <code>dict.fromkeys</code> (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the ...
9
2009-03-17T15:06:46Z
654,689
<p>The problem is that in </p> <pre><code>results = dict.fromkeys(inputs, []) </code></pre> <p>[] is evaluated only once, right there. </p> <p>I'd rewrite this code like that:</p> <pre><code>runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = {} for run in range(runs): for i in inputs: result...
9
2009-03-17T15:16:09Z
[ "python", "dictionary", "fromkeys" ]
How do I create a unique value for each key using dict.fromkeys?
654,646
<p>First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use <code>dict.fromkeys</code> (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the ...
9
2009-03-17T15:06:46Z
654,726
<p>You can also do this if you don't want to learn anything new (although I recommend you do!) I'm curious as to which method is faster?</p> <pre><code>results = dict.fromkeys(inputs) for run in range(0, runs): for i in inputs: if not results[i]: results[i] = [] results[i].append(bench...
2
2009-03-17T15:24:09Z
[ "python", "dictionary", "fromkeys" ]
Python process management
654,738
<p>Is there any way python is natively, or through some code available online (preferably under the GPL), capable of doing process management. The goal is similar to the functionality of ps, but preferably in arrays, lists, and/or dicts.</p>
6
2009-03-17T15:26:44Z
654,767
<p>There is something out there called <a href="http://www.humanized.com/ProcessManager/" rel="nofollow">ProcessManager</a>, but I have not used it before.</p>
0
2009-03-17T15:32:38Z
[ "python", "process", "ps" ]
Python process management
654,738
<p>Is there any way python is natively, or through some code available online (preferably under the GPL), capable of doing process management. The goal is similar to the functionality of ps, but preferably in arrays, lists, and/or dicts.</p>
6
2009-03-17T15:26:44Z
654,813
<p><a href="http://pypi.python.org/pypi/PSI" rel="nofollow">http://pypi.python.org/pypi/PSI</a></p>
2
2009-03-17T15:41:29Z
[ "python", "process", "ps" ]
Python process management
654,738
<p>Is there any way python is natively, or through some code available online (preferably under the GPL), capable of doing process management. The goal is similar to the functionality of ps, but preferably in arrays, lists, and/or dicts.</p>
6
2009-03-17T15:26:44Z
10,543,775
<p>This one is cross-platform: <a href="http://code.google.com/p/psutil/" rel="nofollow">http://code.google.com/p/psutil/</a></p>
2
2012-05-11T00:10:51Z
[ "python", "process", "ps" ]
Python process management
654,738
<p>Is there any way python is natively, or through some code available online (preferably under the GPL), capable of doing process management. The goal is similar to the functionality of ps, but preferably in arrays, lists, and/or dicts.</p>
6
2009-03-17T15:26:44Z
10,543,890
<p>If you're not interested in a module, you might also have a look at the <code>/proc</code> filesystem, procfs.</p>
0
2012-05-11T00:29:09Z
[ "python", "process", "ps" ]