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
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I h...
73
2009-04-27T14:31:00Z
33,218,555
<p>The value of <a href="https://docs.python.org/3/using/cmdline.html#envvar-PYTHONHASHSEED" rel="nofollow">PYTHONHASHSEED</a> might be used to initialize the hash values.</p> <p>Try:</p> <pre><code>PYTHONHASHSEED python -c 'print(hash('http://stackoverflow.com'))' </code></pre>
1
2015-10-19T15:39:15Z
[ "python", "google-app-engine", "hash" ]
Built in python hash() function
793,761
<p>Windows XP, Python 2.5:</p> <pre><code>hash('http://stackoverflow.com') Result: 1934711907 </code></pre> <p>Google App Engine (<a href="http://shell.appspot.com/">http://shell.appspot.com/</a>):</p> <pre><code>hash('http://stackoverflow.com') Result: -5768830964305142685 </code></pre> <p>Why is that? How can I h...
73
2009-04-27T14:31:00Z
33,763,349
<p>Most answers suggest this is because of different platforms, but there is more to it. From <a href="https://docs.python.org/3.5/reference/datamodel.html#object.__hash__" rel="nofollow">the documentation of <code>object.__hash__(self)</code></a>:</p> <blockquote> <p>By default, the <code>__hash__()</code> values o...
9
2015-11-17T17:29:46Z
[ "python", "google-app-engine", "hash" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class ...
3
2009-04-27T14:46:10Z
836,855
<p>You have:</p> <pre><code>backref='item' </code></pre> <p>Is this a typo for </p> <pre><code>backref='name' </code></pre> <p>?</p>
0
2009-05-07T20:29:12Z
[ "python", "sqlalchemy" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class ...
3
2009-04-27T14:46:10Z
884,728
<p>You want something like this:</p> <pre><code>from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): assert record.name is not None, "Record fails validation, must have a name" return record </code></pre> <p>With this, yo...
2
2009-05-19T19:58:56Z
[ "python", "sqlalchemy" ]
SQLAlchemy - MappedCollection problem
793,848
<p>I have some problems with setting up the dictionary collection in Python's SQLAlchemy:</p> <p>I am using declarative definition of tables. I have <code>Item</code> table in 1:N relation with <code>Record</code> table. I set up the relation using the following code:</p> <pre><code>_Base = declarative_base() class ...
3
2009-04-27T14:46:10Z
890,005
<p>I can't comment yet, so I'm just going to write this as a separate answer:</p> <pre>from sqlalchemy.orm import validates class Item(_Base): [...] @validates('records') def validate_record(self, key, record): record.name=key return record </pre> <p>This is basically a copy of Gunnlaugur's ...
1
2009-05-20T20:15:07Z
[ "python", "sqlalchemy" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
794,152
<p>If it's only going to be used in your application, and if you're going to create a <code>Coord3D</code> instance with the values anyway, I'd just return a <code>Coord3D</code> instance to save you the effort. If, however, you have any interest in making this portable/general, return a tuple. It'll be easy to create ...
1
2009-04-27T15:55:11Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
794,157
<p>I've asked myself the same question, albeit while doing 2D geometry stuff.</p> <p>The answer I found for myself was that if I was planning to write a larger library, with more functions and whatnot, go ahead and return the Point, or in your case the Coord3D object. If it's just a hacky implementation, the tuple wil...
1
2009-04-27T15:55:40Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
794,183
<p>If other people (aside form yourself) will be using this class, it seems to me that returning an object would encourage some kind of uniformity in data types. If the Coord3D class has a method or property to access these coordinates as a tuple, then that still gives them that option, should they need it:</p> <pre>...
2
2009-04-27T16:03:08Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
794,200
<p>The more fundamental question is "why do you have Coord3D class?" Why not just use a tuple?</p> <p>The general advice most of us give to Python n00bz is "don't invent new classes until you have to."</p> <p>Does your Coord3D have unique methods? Perhaps you need a new class. Or -- perhaps -- you only need some f...
2
2009-04-27T16:07:25Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
794,208
<p>Returning an object would be the best practice and would give you a better overall software design. I would recommend doing that</p> <p>But still, keep in mind that creating/returning an object will take more processing time. It could change something if you do this operation a LOT and in that case you might need t...
1
2009-04-27T16:09:14Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
795,805
<p>Compromise solution: Instead of a class, make Coord3D a <a href="http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields"><code>namedtuple</code></a> and return that :-)</p> <p>Usage:</p> <pre><code>Coord3D = namedtuple('Coord3D', 'x y z') def getCoordinate(index):...
12
2009-04-28T00:34:52Z
[ "python", "design" ]
Returning an object vs returning a tuple
794,132
<p>I am developing in python a file class that can read and write a file, containing a list of xyz coordinates. In my program, I already have a Coord3D class to hold xyz coordinates. </p> <p>My question is relative to the design of a getCoordinate(index) method. Should I return a tuple of floats, or a Coord3D object?<...
11
2009-04-27T15:48:48Z
799,336
<p>Take a look at Will McGugan's <a href="http://code.google.com/p/gameobjects/" rel="nofollow">Gameobjects library</a>. He has a <a href="http://code.google.com/p/gameobjects/source/browse/trunk/vector3.py" rel="nofollow">Vector3 class</a> that can be initialized with another Vector3 object, a tuple, individual float ...
2
2009-04-28T18:47:51Z
[ "python", "design" ]
Accessing MultipleChoiceField choices values
794,178
<p>How do I get the choices field values and not the key from the form?</p> <p>I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now):</p> <pre><code>class Contacts(f...
1
2009-04-27T16:00:53Z
794,189
<p>It might not be a beautiful solution, but I would imagine that the display names are all still available from <code>form.fields['emails'].choices</code> so you can loop through <code>form.cleaned_data['emails']</code> and get the choice name from the field's choices.</p>
0
2009-04-27T16:04:35Z
[ "python", "django" ]
Accessing MultipleChoiceField choices values
794,178
<p>How do I get the choices field values and not the key from the form?</p> <p>I have a form where I let the user select some user's emails for a company. For example I have a form like this (this reason for model form is that it's inside a formset - but that is not important for now):</p> <pre><code>class Contacts(f...
1
2009-04-27T16:00:53Z
794,589
<p>Ok, hopefully this is closer to what you wanted.</p> <pre><code>emails = filter(lambda t: t[0] in form.cleaned_data['emails'], form.fields['emails'].choices) </code></pre> <p>That should give you the list of selected choices that you want.</p>
6
2009-04-27T18:06:50Z
[ "python", "django" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element...
11
2009-04-27T18:46:27Z
794,871
<p>There isn't a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for <code>map</code> and <code>filter</code>. In other words, you'd use a list comprehension whenever you need to take a list and</p> <ul> <li><p>Use its elements as input for...
10
2009-04-27T19:12:32Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element...
11
2009-04-27T18:46:27Z
794,874
<p>You could use a helper object to store all the internal state while iterating over the sequence:</p> <pre><code>class Encryption: def __init__(self, key, init_value): self.key = key self.previous = init_value def next(self, element): self.previous = element ^ self.previous ^ self.key return self...
1
2009-04-27T19:13:12Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element...
11
2009-04-27T18:46:27Z
795,158
<p>You could have done this using <a href="http://docs.python.org/library/functions.html#reduce" rel="nofollow">reduce()</a>. It's not list comprehension, but it's the functional style approach:</p> <pre><code>cipher = [] def f(previous, element): previous = element ^ previous ^ key cipher.append(previous) ...
3
2009-04-27T20:29:11Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element...
11
2009-04-27T18:46:27Z
795,671
<p>It probably can be done; see <a href="http://code.activestate.com/recipes/204297/" rel="nofollow">The Secret Name of List Comprehensions</a>. It's very much not pythonic, though.</p>
2
2009-04-27T23:21:26Z
[ "python" ]
Python list comprehension - access last created element?
794,774
<p>Is it possible to access the previous element generated in a list comprehension.</p> <p>I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element...
11
2009-04-27T18:46:27Z
2,068,496
<p>As a generator:</p> <pre><code>def cypher(message, key, seed): for element in message: seed = element ^ seed ^ key yield seed list(cypher(message, key, initial_seed)) </code></pre>
2
2010-01-15T00:09:20Z
[ "python" ]
PyQT combobox only react on user interaction
794,813
<p>I have a listbox that you can select users in. To the left of that is a combobox listing the available groups the user can be put it. If the user is in a group, the combobox will automatically be set to that group. I want to make it so when you change the group selection, it will move the user to that group. I added...
2
2009-04-27T18:55:46Z
794,898
<p>Catch a signal from the QComboBox (<a href="https://doc.qt.io/qt-5/qcombobox.html#activated" rel="nofollow"><code>activated(int index)</code></a>), and update the selected user based on that. In you Handler function, don't do anything if the selected index in the combobox is the same as the group the selected user ...
6
2009-04-27T19:16:20Z
[ "python", "qt", "qcombobox" ]
Converting to Precomposed Unicode String using Python-AppKit-ObjectiveC
794,836
<p>This document by Apple <a href="http://developer.apple.com/qa/qa2001/qa1235.html" rel="nofollow">Technical Q&amp;A QA1235</a> describes a way to convert unicode strings from a composed to a decomposed version. Since I have a problem with file names containing some characters (e.g. an accent grave), I'd like to try ...
3
2009-04-27T19:02:54Z
796,392
<p>OC_PythonString (which is what Python strings are bridged to) is an NSString subclass, so you could get an NSMutableString with:</p> <pre><code>mutableString = NSMutableString.alloc().initWithString_("abc") </code></pre> <p>then use mutableString as the argument to CFStringNormalize.</p>
1
2009-04-28T05:52:59Z
[ "python", "objective-c" ]
How to convert datetime to string in python in django
794,995
<p>I have a datetime object at my model. I am sending it to the view, but in html i don't know what to write in order to format it.</p> <p>I am trying </p> <pre><code>{{ item.date.strftime("%Y-%m-%d")|escape }} </code></pre> <p>but I get </p> <pre><code>TemplateSyntaxError: Could not parse some characters: item.dat...
4
2009-04-27T19:42:52Z
795,000
<p>Try using the built-in Django <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date">date format filter</a> instead:</p> <pre><code>{{ item.date|date:"Y M d" }} </code></pre>
11
2009-04-27T19:44:51Z
[ "python", "django" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> ...
4
2009-04-27T20:38:03Z
795,213
<p>Version 1 - delegate everything.</p> <pre><code>class Subclass1(BaseClass): def __init__(self): super( Subclass1, self ).__init__() self.specific() super( Subclass1, self ).finalizeInitialization() </code></pre> <p>Version 2 - delegate just one step</p> <pre><code>class BaseClass: ...
4
2009-04-27T20:43:57Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> ...
4
2009-04-27T20:38:03Z
795,231
<p>What's wrong with calling finalInitilazation from the Subclass's init?</p> <pre><code> class BaseClass: def __init__(self): print 'base __init__' self.common1() def common1(self): print 'common 1' def finalizeInitialization(self): print 'fi...
0
2009-04-27T20:47:40Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> ...
4
2009-04-27T20:38:03Z
795,409
<p>If you have to call multiple methods in a specific order it typically means that the design has problems to begin with (it's leaking implementation detail). So I would try to work from that end.</p> <p>On the other hand if people derive from the class and have to modify the initialisation they should be aware of th...
0
2009-04-27T21:43:07Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> ...
4
2009-04-27T20:38:03Z
795,877
<p>Template Method Design Pattern to the rescue:</p> <pre><code>class BaseClass: def __init__(self, specifics=None): print 'base __init__' self.common1() if specifics is not None: specifics() self.finalizeInitialization() def common1(self): print 'common 1' ...
8
2009-04-28T01:17:47Z
[ "python", "inheritance", "initialization" ]
How to perform common post-initialization tasks in inherited Python classes?
795,190
<p>The initialization process of group of classes that share a common parent can be divided into three parts: common part1, class-specific part, common part2. Currently the first two parts are called from the __init__ function of each child class, but the second common part has to be called separately For example:</p> ...
4
2009-04-27T20:38:03Z
795,978
<p>Similar to S. Lott's approach, except there's no way (short of overriding <code>__init__</code>) for the derived classes to override (or even call) the common methods:</p> <pre><code>class BaseClass: def __init__(self): def common(): print "common initialization..." def final(): ...
1
2009-04-28T02:10:17Z
[ "python", "inheritance", "initialization" ]
python versus java runtime footprint
795,241
<p>Can anyone point to serious comparison of Python runtime footprint versus Java?</p> <p>Thanks, Avraham</p>
6
2009-04-27T20:49:30Z
35,581,985
<p>I can't compare memory footprint because it really depends on classes what you load/use. But what I can tell you that Python (IronPython 2.7 in particular) has real memory leak problems. Especially with third party well used ones like Financial. When Java application/server runs without issues with rare cases which ...
1
2016-02-23T15:47:38Z
[ "java", "python", "footprint", "memory-footprint" ]
How to compare value of 2 fields in Django QuerySet?
795,310
<p>I have a django model like this:</p> <pre><code>class Player(models.Model): name = models.CharField() batting = models.IntegerField() bowling = models.IntegerField() </code></pre> <p>What would be the Django QuerySet equivalent of the following SQL?</p> <pre><code>SELECT * FROM player WHERE batting &g...
7
2009-04-27T21:13:51Z
795,322
<p>In django 1.1 you can do the following:</p> <pre><code>players = Player.objects.filter(batting__gt=F('bowling')) </code></pre> <p>See the <a href="http://stackoverflow.com/questions/433294/column-comparison-in-django-queries">other question</a> for details</p>
15
2009-04-27T21:17:30Z
[ "python", "django", "model" ]
Is there an easy way to tell how much time is spent waiting for the Python GIL?
795,405
<p>I have a long-running Python service and I'd like to know how much cumulative wall clock time has been spent by any runnable threads (i.e., threads that weren't blocked for some other reason) waiting for the GIL. Is there an easy way to do this? E.g., perhaps I could periodically dump some counter to its log file....
4
2009-04-27T21:42:12Z
797,218
<p>I don't think there's an easy way. There's probably an awkward way, involving rebuilding Python to traverse the PyThreadState list and count the threads each time the lock is acquired, but I doubt it's worth the effort!</p> <p>I know this is a speculative question but if you are even moderately concerned about ther...
3
2009-04-28T10:19:59Z
[ "python", "multithreading" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What...
2
2009-04-27T22:43:38Z
795,649
<p>As David said, you should define the correlation you're using. I don't know of any definitions of correlation that gives sensible numbers when correlating empty and non-empty signals.</p>
0
2009-04-27T23:11:40Z
[ "python", "numpy" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What...
2
2009-04-27T22:43:38Z
797,939
<p>The simplest thing that I could find was using the scipy.stats package</p> <pre><code>In [8]: x Out[8]: array([[ 0. , 0. , 0. ], [-1. , 0. , -1. ], [-2. , 0. , -2. ], [-3. , 0. , -3. ], [-4. , 0.1, -4. ]]) In [9]: y Out[9]: array([[0. , 0. ], [1. , 0. ], [2. , 0. ],...
2
2009-04-28T13:28:54Z
[ "python", "numpy" ]
Correlate one set of vectors to another in numpy?
795,570
<p>Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).</p> <p>What...
2
2009-04-27T22:43:38Z
799,834
<p>Will this do what you want?</p> <pre><code>correlations = dot(transpose(a), b) </code></pre>
0
2009-04-28T21:10:06Z
[ "python", "numpy" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this ...
12
2009-04-28T00:44:43Z
795,849
<p>Use pagination like these examples <a href="http://google-appengine.googlegroups.com/web/efficient%5Fpaging%5Fusing%5Fkey%5Finstead%5Fof%5Fa%5Fdedicated%5Funique%5Fproperty.txt" rel="nofollow">here</a>.</p>
2
2009-04-28T01:00:12Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this ...
12
2009-04-28T00:44:43Z
796,588
<p>It is indeed a duplicate and the other post describes how to theoretically do it, but I'd like to stress that you should really not be doing counts this way. The reason being that BigTable by its distributed nature is really bad for aggregates. What you probably want to do is add a transactional counter to that enti...
14
2009-04-28T07:15:18Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this ...
12
2009-04-28T00:44:43Z
3,547,366
<p>I have write this method to count a query, but how said Nick Johnson maybe it's a bad idea...</p> <pre><code>def query_counter (q, cursor=None, limit=500): if cursor: q.with_cursor (cursor) count = q.count (limit=limit) if count == limit: return count + query_counter (q, q.cursor (), limit=limit) ...
0
2010-08-23T12:11:44Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this ...
12
2009-04-28T00:44:43Z
3,548,760
<p>Since version <a href="http://googleappengine.blogspot.com/2010/08/multi-tenancy-support-high-performance_17.html" rel="nofollow">1.3.6</a> of the SDK the limit of 1000 on the count function has been removed. So a call to the count function will now return the exact number of entities, even if there are more than 10...
2
2010-08-23T14:58:22Z
[ "python", "google-app-engine", "count" ]
Google AppEngine: how to count a database's entries beyond 1000?
795,817
<p><strong>Duplicate of</strong> <a href="http://stackoverflow.com/questions/751124/how-does-one-get-a-count-of-rows-in-a-datastore-model-in-google-appengine">"how does one get a count of rows in a datastore model in google appengine?"</a></p> <hr> <p>I want to know how many users I have. Previously, I achieved this ...
12
2009-04-28T00:44:43Z
12,845,268
<p>For Python GAE SDK, you can increase the argument "limit" of the count method: <a href="https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_count" rel="nofollow">https://developers.google.com/appengine/docs/python/datastore/queryclass#Query_count</a></p>
0
2012-10-11T17:32:29Z
[ "python", "google-app-engine", "count" ]
How do you open and transfer a file on the filesystem in mod_python?
795,837
<p>I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'application/o...
1
2009-04-28T00:53:59Z
795,876
<p>To debug this kind of thing, you need to gather all information from the running mod_python instance.</p> <p>Stop messing with "checking a dozen times that it [exists]". Some assumption isn't correct.</p> <p>Do something like this to get some debugging information.</p> <pre><code>def handler(req): req.conten...
4
2009-04-28T01:16:48Z
[ "python", "file-io", "mod-python" ]
How do you open and transfer a file on the filesystem in mod_python?
795,837
<p>I'm new to mod_python and Apache, and I'm having trouble returning a file to a user after a GET request. I've got a very simple setup right now, and was hoping to simply open the file and write it to the response:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'application/o...
1
2009-04-28T00:53:59Z
795,896
<p>Could you paste the error(s) you get?</p> <p>It's likely to be a permission error (if you tried using the full path to the file). Remember the script runs as the user running the web-server process - so you will be accessing the file as "www-data", or "nobody" usually.</p> <p>Check the permissions of the folder <c...
0
2009-04-28T01:27:47Z
[ "python", "file-io", "mod-python" ]
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
795,976
<p>I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:</p> <p><a href="http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing" rel="nofollow">http://simplepie.org/wik...
1
2009-04-28T02:09:21Z
795,990
<p><a href="http://www.djangosnippets.org/tags/rss/" rel="nofollow">http://www.djangosnippets.org/tags/rss/</a></p>
0
2009-04-28T02:19:12Z
[ "python", "django", "rss", "django-templates", "simplepie" ]
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
795,976
<p>I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:</p> <p><a href="http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing" rel="nofollow">http://simplepie.org/wik...
1
2009-04-28T02:09:21Z
1,819,895
<p>You are looking for <a href="http://feedparser.org" rel="nofollow">the universal feed parser</a>.</p>
1
2009-11-30T13:42:07Z
[ "python", "django", "rss", "django-templates", "simplepie" ]
Wrapping a script with subprocess.Popen()
795,977
<p>I have a script that's provided with another software package - which I would not like to modify in any way. I need to execute this script, provide a password, and then interact with it from the terminal (using raw_input, etc.).</p>
0
2009-04-28T02:09:29Z
795,984
<p><a href="http://pexpect.sourceforge.net/pexpect.html" rel="nofollow">pexpect</a> is what you want to use.</p> <blockquote> <p>Pexpect is a Python module for spawning child applications and controlling them automatically. Pexpect can be used for automating interactive applications such as ssh, ftp, passw...
2
2009-04-28T02:14:58Z
[ "python", "scripting" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
796,019
<p>have you tried to remove the timezone awareness?</p> <p>from <a href="http://pytz.sourceforge.net/">http://pytz.sourceforge.net/</a></p> <pre><code>naive = dt.replace(tzinfo=None) </code></pre> <p>may have to add time zone conversion as well.</p>
133
2009-04-28T02:36:07Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
797,233
<p>Is there some pressing reason why you can't handle the age calculation in PostgreSQL itself? Something like</p> <pre><code>select *, age(timeStampField) as timeStampAge from myTable </code></pre>
1
2009-04-28T10:24:24Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
17,752,647
<p>The psycopg2 module has its own timezone definitions, so I ended up writing my own wrapper around utcnow:</p> <pre><code>def pg_utcnow(): import psycopg2 return datetime.utcnow().replace( tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)) </code></pre> <p>and just use <code>pg_utcnow</cod...
4
2013-07-19T18:01:44Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
23,370,174
<p>I know this is old, but just thought I would add my solution just in case someone finds it useful.</p> <p>I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very...
0
2014-04-29T16:24:36Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
25,662,061
<p>The correct solution is to <em>add</em> the timezone info e.g., to get the current time as an aware datetime object in Python 3:</p> <pre><code>from datetime import datetime, timezone now = datetime.now(timezone.utc) </code></pre> <p>On older Python versions, you could define the <code>utc</code> tzinfo object yo...
27
2014-09-04T09:37:14Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
30,971,376
<p>I know some people use Django specifically as an interface to abstract this type of database interaction. Django provides utilities that can be used for this:</p> <pre><code>from django.utils import timezone now_aware = timezone.now() </code></pre> <p>You do need to set up a basic Django settings infrastructure, ...
16
2015-06-22T02:28:47Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
32,926,239
<p>Holá<br> I found a very simple solution</p> <pre><code>tz_info = your_timezone_aware_variable.tzinfo diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable </code></pre> <p>As explained by Sebastian you must add the timezone info to your now() time.<br> But you must add the same timezone of the varia...
1
2015-10-03T18:51:24Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
35,548,516
<p>I also faced the same problem. Then I found a solution after a lot of searching .</p> <p>The problem was that when we get the datetime object from model or form it is <strong>offset aware</strong> and if we get the time by system it is <strong>offset naive</strong>.</p> <p>So what I did is I got the current time u...
3
2016-02-22T08:01:18Z
[ "python", "postgresql", "datetime", "timezone" ]
Can't subtract offset-naive and offset-aware datetimes
796,008
<p>I have a timezone aware <code>timestamptz</code> field in PostgreSQL. When I pull data from the table, I then want to subtract the time right now so I can get it's age.</p> <p>The problem I'm having is that both <code>datetime.datetime.now()</code> and <code>datetime.datetime.utcnow()</code> seem to return timezone...
105
2009-04-28T02:28:08Z
38,576,091
<p>I've found <code>timezone.make_aware(datetime.datetime.now())</code> is helpful in django (I'm on 1.9.1). Unfortunately you can't simply make a <code>datetime</code> object offset-aware, then <code>timetz()</code> it. You have to make a <code>datetime</code> and make comparisons based on that.</p>
0
2016-07-25T19:39:16Z
[ "python", "postgresql", "datetime", "timezone" ]
IronPython - Convert int to byte array
796,197
<p>What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?</p>
2
2009-04-28T04:19:47Z
796,222
<p>using .Net: </p> <pre><code>byte[] buffer = System.BitConverter.GetBytes(string.Length) print System.BitConverter.ToString(buffer) </code></pre> <p>That will output the bytes as hex. You may have to clean up the syntax for IronPython.</p>
1
2009-04-28T04:29:20Z
[ ".net", "python", "ironpython", "bytearray" ]
IronPython - Convert int to byte array
796,197
<p>What is the correct way to get the length of a string in Python, and then convert that int to a byte array? What is the right way to print that to the console for testing?</p>
2
2009-04-28T04:19:47Z
796,254
<p>Use <a href="http://docs.python.org/library/struct" rel="nofollow">struct</a>.</p> <pre><code>import struct print struct.pack('L', len("some string")) # int to a (long) byte array </code></pre>
3
2009-04-28T04:40:15Z
[ ".net", "python", "ironpython", "bytearray" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = m...
9
2009-04-28T06:28:14Z
796,510
<p>Am thinking JavaScript/AJAX will be the best approach for this problem.</p>
0
2009-04-28T06:47:24Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = m...
9
2009-04-28T06:28:14Z
796,567
<p>Here is some javascript (JQuery based) to change the item option values when category changes:</p> <pre><code>&lt;script charset="utf-8" type="text/javascript"&gt; $(function(){ $("select#id_category").change(function(){ $.getJSON("/items/",{id: $(this).val(), view: 'json'}, function(j) { var op...
10
2009-04-28T07:07:33Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = m...
9
2009-04-28T06:28:14Z
797,007
<p>You will need to have some kind of non-server based mechanism of filtering the objects. Either that, or you can reload the page when the selection is made (which is likely to be done in JavaScript anyway).</p> <p>Otherwise, there is no way to get the subset of data from the server to the client.</p>
0
2009-04-28T09:30:30Z
[ "javascript", "python", "django", "django-admin" ]
How to limit choice field options based on another choice field in django admin
796,466
<p>I have the following models:</p> <pre><code>class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = m...
9
2009-04-28T06:28:14Z
18,093,010
<p>There is <a href="https://github.com/digi604/django-smart-selects" rel="nofollow">django-smart-selects</a>:</p> <p>If you have the following model:</p> <pre><code>class Location(models.Model) continent = models.ForeignKey(Continent) country = models.ForeignKey(Country) area = models.ForeignKey(Area) ...
2
2013-08-07T01:06:07Z
[ "javascript", "python", "django", "django-admin" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and the...
8
2009-04-28T06:40:28Z
796,530
<p>What is meaningful and what is not, it depends on the semantic of the page. If the semantics is crappy, your code won't "guess" what is meaningful. I use readability, which you linked in the comment, and I see that on many pages I try to read it does not provide any result, not talking about a decent one.</p> <p>If...
1
2009-04-28T06:52:49Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and the...
8
2009-04-28T06:40:28Z
796,810
<p>Try the <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> library for Python. It has very simple methods to extract information from an html file.</p> <p>Trying to generically extract data from webpages would require people to write their pages in a similar way... but there's an almost infi...
5
2009-04-28T08:28:45Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and the...
8
2009-04-28T06:40:28Z
797,700
<p>Have a look at templatemaker: <a href="http://www.holovaty.com/writing/templatemaker/" rel="nofollow">http://www.holovaty.com/writing/templatemaker/</a></p> <p>It's written by one of the founders of Django. Basically you feed it a few example html files and it will generate a "template" that you can then use to ex...
4
2009-04-28T12:43:09Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and the...
8
2009-04-28T06:40:28Z
4,239,655
<p>You might use the <a href="http://boilerpipe-web.appspot.com/" rel="nofollow">boilerpipe Web application</a> to fetch and extract content on the fly.</p> <p>(This is not specific to Python, as you only need to issue a HTTP GET request to a page on Google AppEngine).</p> <p>Cheers,</p> <p>Christian</p>
3
2010-11-21T18:59:34Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
python method to extract content (excluding navigation) from an HTML page
796,490
<p>Of course an HTML page can be parsed using any number of python parsers, but I'm surprised that there don't seem to be any public parsing scripts to extract meaningful content (excluding sidebars, navigation, etc.) from a given HTML doc. </p> <p>I'm guessing it's something like collecting DIV and P elements and the...
8
2009-04-28T06:40:28Z
24,899,593
<p><a href="https://github.com/grangier/python-goose" rel="nofollow">Goose</a> is just the library for this task. To quote their README:</p> <blockquote> <p>Goose will try to extract the following information:</p> <ul> <li>Main text of an article </li> <li>Main image of article</li> <li>Any Youtube/Vimeo ...
0
2014-07-22T23:39:26Z
[ "python", "html", "parsing", "semantics", "html-content-extraction" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the probl...
0
2009-04-28T09:02:13Z
797,041
<p>Web pages don't return values, and they aren't programs - a web page is just a static collection of HTML or something similar which a browser can display. Your CGI script can't wait for the user to send a response - it must send the web page to the user and terminate.</p> <p>However, if the browser performs a secon...
0
2009-04-28T09:39:17Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the probl...
0
2009-04-28T09:02:13Z
797,111
<p>I think you could modify the Python script to return an error if it needs a choice and accept choices as arguments. If you do that, you can check the return value from your cgi script and use that to call the python script appropriately and return the information to the user.</p> <p>Is there a reason why you can't ...
1
2009-04-28T09:58:42Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the probl...
0
2009-04-28T09:02:13Z
797,129
<p>Probably easier if you write your cgi in python then call your python script from the cgi script.</p> <p>Update your script to separate the UI from the logic. Then it should be relatively easy to interface your script with the (python) cgi script.</p> <p>For python cgi reference: <a href="http://gnosis.cx/publish/...
0
2009-04-28T10:00:42Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the probl...
0
2009-04-28T09:02:13Z
797,231
<p>"Does anybody know how can I open a webpage with python ? The second and most important question is: how can I return a value from a web page to my "original" python module ??"</p> <p>This is all very simple.</p> <p>However, you need to read about what the web really <em>is</em>. You need to read up on web serve...
9
2009-04-28T10:23:47Z
[ "python", "cgi" ]
CGI & Python
796,906
<p>here is my problem... I have a python script that, once executed from command line, performs the needed operations and exit. If, during the execution, the program is not able to perform a choice, he prompts the user and asks them to take a decision ! Now I have to implement a web interface, and here comes the probl...
0
2009-04-28T09:02:13Z
1,635,259
<p><a href="http://docs.python.org/library/cgihttpserver.html" rel="nofollow">http://docs.python.org/library/cgihttpserver.html</a></p> <p>I think first off you need to separate your code from your interface. When you run a script, it spits out a page. You can pass arguments to it using url parameters. Ideally you wan...
0
2009-10-28T04:49:21Z
[ "python", "cgi" ]
Is windows's setsockopt broken?
796,957
<p>I want to be able to reuse some ports, and that's why I'm using <strong>setsockopt</strong> on my sockets, with the following code:</p> <pre><code>sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) </code></pre> <p>However, this doesn't really work. I'm not getting a bind error either, but the server socket ...
2
2009-04-28T09:14:59Z
797,004
<p><code>setsockopt</code> is a method of a socket object. module <code>socket</code> doesn't have a <code>setsockopt</code> attribute.</p>
1
2009-04-28T09:30:02Z
[ "python", "windows", "sockets", "setsockopt" ]
Is windows's setsockopt broken?
796,957
<p>I want to be able to reuse some ports, and that's why I'm using <strong>setsockopt</strong> on my sockets, with the following code:</p> <pre><code>sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) </code></pre> <p>However, this doesn't really work. I'm not getting a bind error either, but the server socket ...
2
2009-04-28T09:14:59Z
2,292,896
<p>It appears that SO_REUSEADDR has different semantics on Windows vs Unix.</p> <p>See this <a href="http://msdn.microsoft.com/en-us/library/ms740621%28VS.85%29.aspx" rel="nofollow">msdn article</a> (particularly the chart below "Using SO_EXCLUSIVEADDRUSE") and this <a href="http://www.developerweb.net/forum/showthrea...
3
2010-02-18T23:00:36Z
[ "python", "windows", "sockets", "setsockopt" ]
How to query filter in django without multiple occurrences
796,971
<p>I have 2 models:</p> <p>ParentModel: 'just' sits there</p> <p>ChildModel: has a foreign key to ParentModel</p> <p><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all())</code> gives multiple occurrences of ParentModel.</p> <p>How do I query all ParentModels that have at least one ChildModel th...
1
2009-04-28T09:20:54Z
797,013
<p>You almost got it right...</p> <pre><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all()).distinct() </code></pre>
4
2009-04-28T09:31:16Z
[ "python", "django" ]
How to query filter in django without multiple occurrences
796,971
<p>I have 2 models:</p> <p>ParentModel: 'just' sits there</p> <p>ChildModel: has a foreign key to ParentModel</p> <p><code>ParentModel.objects.filter(childmodel__in=ChildModel.objects.all())</code> gives multiple occurrences of ParentModel.</p> <p>How do I query all ParentModels that have at least one ChildModel th...
1
2009-04-28T09:20:54Z
808,051
<p>You might want to avoid using <code>childmodel__in=ChildModel.objects.all()</code> if the number of <code>ChildModel</code> objects is large. This will generate SQL with all <code>ChildModel</code> id's enumerated in a list, possibly creating a huge SQL query.</p> <p>If you can use <a href="http://docs.djangoprojec...
0
2009-04-30T17:12:31Z
[ "python", "django" ]
string formatting
797,132
<p>I am not getting why the colon shifted left in the second time </p> <pre><code>&gt;&gt;&gt; print '%5s' %':' : &gt;&gt;&gt; print '%5s' %':' '%2s' %':' : : </code></pre> <p>Help me out of this please</p>
0
2009-04-28T10:01:34Z
797,156
<p>What are you trying to do?</p> <pre><code>&gt;&gt;&gt; print '%5s' % ':' : &gt;&gt;&gt; print '%5s%2s' % (':', ':') : : </code></pre> <p>You could achieve what you want by mixing them both into a single string formatting expression.</p>
2
2009-04-28T10:05:45Z
[ "python", "string", "format" ]
string formatting
797,132
<p>I am not getting why the colon shifted left in the second time </p> <pre><code>&gt;&gt;&gt; print '%5s' %':' : &gt;&gt;&gt; print '%5s' %':' '%2s' %':' : : </code></pre> <p>Help me out of this please</p>
0
2009-04-28T10:01:34Z
797,167
<p>In Python, juxtaposed strings are concatenated:</p> <pre><code>&gt;&gt;&gt; t = 'a' 'bcd' &gt;&gt;&gt; t 'abcd' </code></pre> <p>So in your second example, it is equivalent to:</p> <pre><code>&gt;&gt;&gt; print '%5s' % ':%2s' % ':' </code></pre> <p>which by the precedence rules for Python's % operator, is:</p> ...
9
2009-04-28T10:08:15Z
[ "python", "string", "format" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same dire...
2
2009-04-28T10:26:05Z
797,290
<p>I suspect that one of your other imports redefined <code>snipplets</code> with an assignment statement. Or one of your other modules changed <code>sys.path</code>.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>"so the flow goes like this: add snipplets packages to path import..." </p> <p>No.</p> <p>Do not ...
2
2009-04-28T10:48:42Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same dire...
2
2009-04-28T10:26:05Z
797,308
<p>your <a href="http://github.com/woodenbrick/snipplets/tree/68e40dcfa1195cc63d4e1155b8353bb1aa1f8797/snipplets" rel="nofollow">master branch</a> doesn't have <code>options.py</code>. could it be that you dev and master branches are conflicting?</p> <p><a href="http://github.com/woodenbrick/snipplets/blob/2c13a6de0ae...
2
2009-04-28T10:58:38Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same dire...
2
2009-04-28T10:26:05Z
797,336
<p>Does the following work?</p> <pre><code>import snipplets.options.Options </code></pre> <p>If so, one of your other snipplets files probably sets a global variable named options.</p>
1
2009-04-28T11:05:06Z
[ "python" ]
import statement fails for one module
797,241
<p>Ok I found the problem, it was an environmental issue, I had the same modules (minus options.py) on the sys.path and it was importing from there instead. Thanks everyone for your help.</p> <p>I have a series of import statements, the last of which will not work. Any idea why? options.py is sitting in the same dire...
2
2009-04-28T10:26:05Z
797,474
<p>Are you on windows? You might want to try defining an <code>__</code>all<code>__</code> list in your <code>__</code>init<code>__</code>.py file like noted <a href="http://docs.python.org/tutorial/modules.html#importing-from-a-package" rel="nofollow">here</a>. It shouldn't make a difference unless you're importing ...
1
2009-04-28T11:50:12Z
[ "python" ]
how can I debug more than one script in pyscripter?
797,754
<p>I installed portable python on my USB drive, and I really like pyscripter a lot. The thing is, after I start debugging a script, the IDE kind of freezes ( waiting for the code to reach a breakpoint ). This means I can't do anything with it ( I can't even save files ). It would be very useful to be able to debug more...
0
2009-04-28T12:52:22Z
802,044
<p>To solve your problem, use <a href="http://pyscripter.googlepages.com/remotepythonengines" rel="nofollow">Remote Interpreter and Debugger</a> and PyScripter will become much more responsive. Even if something goes wrong, IDE will not crash - just reinitialize remote interpreter and resume working.</p>
1
2009-04-29T12:02:23Z
[ "python", "ide", "debugging", "pyscripter" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,782
<p>Make an accessor method, unless I am missing something:</p> <pre><code>def get_private_attrib(self): return self.__privateWhatever </code></pre>
0
2009-04-28T12:57:45Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,799
<p>if the variable name is "__secret" and the class name is "MyClass" you can access it like this on an instance named "var"</p> <p>var._MyClass__secret</p> <p>The convention to suggest/emulate protection is to name it with a leading underscore: self._protected_variable = 10</p> <p>Of course, anybody can modify it i...
1
2009-04-28T13:00:58Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
797,814
<p>My understanding of Python convention is</p> <ul> <li>_member is protected</li> <li>__member is private</li> </ul> <p>Options for if you control the parent class</p> <ul> <li>Make it protected instead of private since that seems like what you really want</li> <li>Use a getter (@property def _protected_access_to_m...
52
2009-04-28T13:03:31Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
5,682,623
<p>Using <code>@property</code> and <code>@name.setter</code> to do what you want</p> <p>e.g</p> <pre><code>class Stock(object): def __init__(self, stockName): # '_' is just a convention and does nothing self.__stockName = stockName # private now @property # when you do Stock.name, it...
6
2011-04-15T21:39:30Z
[ "python" ]
Python "protected" attributes
797,771
<p>How do I access a private attribute of a parent class from a subclass (without making it public)?</p>
21
2009-04-28T12:55:50Z
21,217,121
<p>Some language designers subscribe to the following assumption:</p> <blockquote> <p><em>"Many programmers are irresponsible, dim-witted, or both."</em></p> </blockquote> <p>These language designers will feel tempted to protect programmers from each other by introducing a <code>private</code> specifier into their ...
13
2014-01-19T13:06:06Z
[ "python" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a si...
4
2009-04-28T12:56:05Z
797,882
<p>So you want to schedule something to run at a regular interval? At the cost of some CPU time, you can use <a href="http://code.google.com/p/django-cron/wiki/Install">this simple app</a>.</p> <p>Alternatively, if you can use it, the <a href="http://www.thesitewizard.com/general/set-cron-job.shtml">cron job</a> for ...
8
2009-04-28T13:17:09Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a si...
4
2009-04-28T12:56:05Z
798,462
<p>"I'm still unsure as to how I accomplish this with the python script I will be calling. "</p> <p>The issue is that your "significant delay of a few seconds while I go to the external site to parse the new data" has nothing to do with Django cache at all.</p> <p>You can cache it everywhere, and when you go to repar...
4
2009-04-28T15:09:15Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a si...
4
2009-04-28T12:56:05Z
803,162
<p>You can also use a python script to call your view and write it to a file, then deliver it staticaly with lightpd for example :</p> <pre><code>request = HttpRequest() request.path = url # the url of your view (detail_func, foo, params) = resolve(url) params['gmap_key'] = settings.GMAP_KEY_STATIC detail = detail_fun...
0
2009-04-29T16:20:31Z
[ "python", "django", "caching" ]
Django caching - can it be done pre-emptively?
797,773
<p>I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.</p> <p>This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a si...
4
2009-04-28T12:56:05Z
804,829
<p>I have no proof, but I've read BeautifulSoup is slow and consumes a lot of memory. You may want to look at using the lxml module instead. lxml is supposed to be much faster and efficient, and can do much more than BeautifulSoup.</p> <p>Of course, the parsing probably isn't your bottleneck here; the external I/O is....
4
2009-04-29T23:55:33Z
[ "python", "django", "caching" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,805
<p>a) You can start applications using <b>os.system</b>:</p> <pre><code> os.system("command") </code></pre> <p>or you can use the <b>subprocess</b> module. More information <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">here</a>.</p> <p>b) use sockets</p>
3
2009-04-28T13:01:40Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,824
<p>Depending on what you want to do you can use os.mkfifo to create a named pipe to share data between your two programs.</p> <p><a href="http://mail.python.org/pipermail/python-list/2006-August/568346.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2006-August/568346.html</a></p>
1
2009-04-28T13:04:44Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,825
<p>Before answering, I think we need some more information:</p> <ol> <li>Is there a definable pipeline of information here? <ol> <li>Does a user make an http request which queries the app for some data and return a result?</li> <li>Does the app collect data and store it somewhere?</li> </ol></li> </ol> <p>There are a...
2
2009-04-28T13:05:31Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,839
<p>Well, you can probably just use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess" rel="nofollow">subprocess</a> module. For the exchanging data, you may just be able to use the Popen.stdin and Popen.stdout streams. Of course, there's no limit to ways you /could/ do it. <a href="http:/...
3
2009-04-28T13:07:42Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,938
<p>When I write web applications in Python, I always keep my web server in the same process as my background tasks. I don't know what web server you're using, but I personally use <a href="http://cherrypy.org/" rel="nofollow">CherryPy</a>. Your application can have a bunch of its threads be the web server, with howev...
0
2009-04-28T13:28:34Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
How to make two python programs interact?
797,785
<p>I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:</p> <ol> <li>Write a script that would start the app and then the HTTP server;</li> <li>Make these programs exchange data in operation.</li> </ol> <p>How are these things usually done? I wo...
2
2009-04-28T12:58:44Z
797,999
<p>maybe <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> is what you're looking for</p>
1
2009-04-28T13:42:09Z
[ "python", "multithreading", "ipc", "process", "interaction" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyon...
19
2009-04-28T14:14:24Z
798,251
<p>I personally use <a href="http://www.sqlinform.com/" rel="nofollow">SQL Inform</a> for quick SQL formating, which is written in Java and is unfortunately not open source, so there is no access to the underlying algorithm.</p>
3
2009-04-28T14:25:56Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyon...
19
2009-04-28T14:14:24Z
798,301
<p>Perhaps part of the difficulty in finding a tool is that there are so many different "standard" SQL formatting conventions. Here are two SO questions that describe people's preferences:</p> <ul> <li><a href="http://stackoverflow.com/questions/519876/sql-formatting-standards">http://stackoverflow.com/questions/51987...
2
2009-04-28T14:35:22Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyon...
19
2009-04-28T14:14:24Z
798,363
<p>Don't know if it answers your question, but I generally use this strategy</p> <pre><code>SELECT what1, what2, etc, FROM table WHERE condition AND condition AND condition ORDER BY whatever </code></pre> <p>But that's just me. I don't think proper automatic tools exist.</p>
-2
2009-04-28T14:49:05Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyon...
19
2009-04-28T14:14:24Z
798,417
<p>You can try <a href="http://python-sqlparse.googlecode.com">sqlparse</a>. It's a Python module that provides simple SQL formatting. A online demo is available <a href="http://sqlformat.appspot.com">here</a>.</p>
33
2009-04-28T14:59:12Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Algorithm for neatly indenting SQL statements (Python implementation would be nice)
798,180
<p>I'd like to reformat some SQL statements that are a single string with newlines in to something that's much easier to read.</p> <p>I don't personally know of a good coding style for indenting SQL - how should nested queries / where clauses / left joins / etc by represented to maximise readability?</p> <p>Has anyon...
19
2009-04-28T14:14:24Z
16,567,609
<p>I have previously used SQL Complete by Devart for formatting SQL, but now there is a free online SQL beautifier powered by SQL Complete - <a href="http://www.sql-format.com/" rel="nofollow">SQL Formatter</a> it is really feature rich and easy to use even for a beginner. </p>
1
2013-05-15T14:20:42Z
[ "python", "sql", "coding-style", "indentation", "pretty-print" ]
Python tool that builds a dependency diagram for methods of a class
798,389
<p>I'm digging into a huge legacy Python class that has a lot of methods. I eventually break complex ones into smaller pieces so the amount of methods increases even more. I wonder if there is a tool that can scan the Python code and build some kind of dependency diagram for its methods.</p> <p>I define method <code>x...
16
2009-04-28T14:54:26Z
798,776
<p>Have you tried <a href="http://pydev.sourceforge.net/" rel="nofollow">pydev</a>? It's a python extension for eclipse. I believe it allows you to use the "call hierarchy" feature of Eclipse to view a call graph for a given method. It's not quite what you want but maybe it's enough to get started.</p>
1
2009-04-28T16:26:31Z
[ "python", "refactoring" ]