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
python logarithm
961,972
<p>i want to find out a log10 of an integer in python and i get an error like math domain error </p> <p>my code is this w=math.log10(q*q1)/math.log10(2)</p> <p>where q1,q2 are integers</p> <p>yeah q1 is 0 sometimes</p>
1
2009-06-07T14:29:43Z
27,588,519
<p>try to make sure the value whose log you are trying to find can never be 0. As log(0) tends to negative infinity, the function call will give you a math domain error. Correct that and I think you'll be fine.</p>
0
2014-12-21T10:27:22Z
[ "python" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pic...
1
2009-06-07T14:34:19Z
962,006
<p>My suggestion would be not to rely on having an object structure. Instead have a byte array (or mmap'd file etc) which you can do random access operations on and implement the cross-referencing using pointers inside that structure.</p> <p>True, it will introduce the concept of pointers to your code, but it will mea...
2
2009-06-07T14:45:46Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pic...
1
2009-06-07T14:34:19Z
962,011
<p>You can dump it in a memory cache (such as <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>).</p> <p>This method has the advantage of cache key invalidation. When underlying data changes you can invalidate your cached data.</p> <h3>EDIT</h3> <p>Here's the python implementation of memcached: ...
4
2009-06-07T14:46:53Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pic...
1
2009-06-07T14:34:19Z
962,041
<p>If you can rebuild your Python runtime with the patches offered in the <a href="http://code.google.com/p/unladen-swallow/" rel="nofollow">Unladen Swallow</a> project, you should see speedups of 40% to 150% in pickling, 36% to 56% in unpickling, according to <a href="http://code.google.com/p/unladen-swallow/wiki/Rele...
3
2009-06-07T15:02:05Z
[ "python", "apache", "web-applications", "pickle" ]
How can I speed up a web-application? (Avoid rebuilding a structure.)
961,981
<p>After having successfully build a static data structure (<a href="http://stackoverflow.com/questions/960963/trie-prefix-tree-in-python">see here</a>), I would want to avoid having to build it from scratch every time a user requests an operation on it. My naïv first idea was to dump the structure (using python's pic...
1
2009-06-07T14:34:19Z
962,510
<p>The number one way to speed up your web application, especially when you have lots of mostly-static modules, classes and objects that need to be initialized: use a way of serving files that supports serving multiple requests from a single interpreter, such as mod_wsgi, mod_python, SCGI, FastCGI, Google App Engine, a...
2
2009-06-07T18:40:06Z
[ "python", "apache", "web-applications", "pickle" ]
How to enumerate a list of non-string objects in Python?
962,082
<p>There is a nice class <code>Enum</code> from <code>enum</code>, but it only works for strings. I'm currently using:</p> <pre><code> for index in range(len(objects)): # do something with index and objects[index] </code></pre> <p>I guess it's not the optimal solution due to the premature use of <code>len<...
5
2009-06-07T15:18:15Z
962,087
<p>Here is the pythonic way to write this loop:</p> <pre><code>for index, obj in enumerate(objects): # Use index, obj. </code></pre> <p><a href="http://docs.python.org/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> works on any sequence regardless of the types of its elements. It is a b...
11
2009-06-07T15:20:01Z
[ "python", "loops", "enumeration", "sequence" ]
Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?
962,179
<p>I'm reading some documentation on a service I'm trying to use, and it reads something like this:</p> <blockquote> <p>All requests must be sent using HTTP Post. </p> <p>The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not acceptable.</p> </blockquote> <p>All request...
0
2009-06-07T16:05:37Z
962,195
<p>"plain ASCII UTF-8" is a contradiction in terms, IMHO -- ASCII is a subset of UTF-8, though. Try sending UTF-8 including some "special" (non-ASCII) character and see what happens (or, if you can, do ask them to reword said contradition-in-terms!-).</p>
1
2009-06-07T16:12:28Z
[ "python", "http" ]
Making a plain ASCII/UTF-8 request/stream HTTP POST request in Python?
962,179
<p>I'm reading some documentation on a service I'm trying to use, and it reads something like this:</p> <blockquote> <p>All requests must be sent using HTTP Post. </p> <p>The XML engine only accepts plain ASCII (text) UTF-8 requests/streams. Encoded streams are not acceptable.</p> </blockquote> <p>All request...
0
2009-06-07T16:05:37Z
962,212
<p>using <a href="http://docs.python.org/library/urllib2.html#urllib2.Request" rel="nofollow">urllib2.Request</a></p> <pre><code>import urllib2 req = urllib2.Request("http://foo.com/post_here", "&lt;xml data to post&gt;") response = urllib2.urlopen(req) the_page = response.read() </code></pre>
2
2009-06-07T16:21:32Z
[ "python", "http" ]
Bazaar: Modify file content before commit via hook?
962,228
<p>I'm switching from SVN to Bzr for my private projects. There is one feature missing for me, which SVN provides: The replacement of a $Id:$ placeholder with the latest version identification. So far, Bzr provides hooks to do some tricks within the commit process. I've managed to get a list of modified files an manipu...
0
2009-06-07T16:28:15Z
962,697
<p>Use this extension: <a href="http://launchpad.net/bzr-keywords" rel="nofollow">http://launchpad.net/bzr-keywords</a></p>
3
2009-06-07T20:01:34Z
[ "python", "bazaar", "bazaar-plugins" ]
Instance methods called in a separate thread than the instantiation thread
962,323
<p>I'm trying to wrap my head around what is happening in <a href="http://code.activestate.com/recipes/286201/" rel="nofollow">this recipe</a>, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops need ...
1
2009-06-07T17:07:07Z
962,862
<p>The sole act of passing instance methods between threads is safe as long as you properly synchronize eventual destruction of those instances (threads share memory so it really doesn't matter which one did the allocation/initialization of a bit of it).</p> <p>The overall thread safety depends on what those methods a...
0
2009-06-07T21:23:13Z
[ "python", "multithreading", "wxpython", "twisted" ]
Instance methods called in a separate thread than the instantiation thread
962,323
<p>I'm trying to wrap my head around what is happening in <a href="http://code.activestate.com/recipes/286201/" rel="nofollow">this recipe</a>, because I'm planning on implementing a wx/twisted app similar to this (ie. wx and twisted running in separate threads). I understand that both twisted and wx event-loops need ...
1
2009-06-07T17:07:07Z
1,004,947
<p>I wouldn't say that it's a "good idea". You should just run the reactor and the GUI in the same thread with wxreactor.</p> <p>The timer-driven event-loop starving approach described by Mr. Schroeder is the worst possible fail-safe way to implement event-loop integration. If you use <code>wxreactor</code> (not <co...
0
2009-06-17T03:20:12Z
[ "python", "multithreading", "wxpython", "twisted" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
962,359
<p>haven't used numpy, but in standard python you can filter out <code>None</code> using list comprehensions or the filter function</p> <pre><code>&gt;&gt;&gt; [i for i in [1, 2, None] if i != None] [1, 2] &gt;&gt;&gt; filter(lambda x: x != None, [1, 2, None]) [1, 2] </code></pre> <p>and then average the result to i...
3
2009-06-07T17:28:06Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
962,442
<p>You are looking for <a href="http://docs.scipy.org/doc/numpy/reference/maskedarray.html" rel="nofollow">masked arrays</a>. Here's an example.</p> <pre><code>import MA a = MA.array([1, 2, None], mask = [0, 0, 1]) print "average =", MA.average(a) </code></pre> <p>Unfortunately, masked arrays aren't thoroughly suppo...
11
2009-06-07T18:10:31Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
1,854,145
<p>You might also be able to kludge with values like NaN or Inf.</p> <pre><code>In [1]: array([1, 2, None]) Out[1]: array([1, 2, None], dtype=object) In [2]: array([1, 2, NaN]) Out[2]: array([ 1., 2., NaN]) </code></pre> <p>Actually, it might not even be a kludge. <a href="http://en.wikipedia.org/wiki/NaN" rel=...
3
2009-12-06T02:26:13Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
1,854,153
<p>You can also use filter, pass None to it, it will filter non True objects, also 0, :D So, use it when you dont need 0 too.</p> <pre><code>&gt;&gt;&gt; filter(None,[1, 2, None]) [1, 2] </code></pre>
1
2009-12-06T02:30:31Z
[ "python", "numpy", "mean" ]
How to use numpy with 'None' value in Python?
962,343
<p>I'd like to calculate the mean of an array in Python in this form:</p> <pre><code>Matrice = [1, 2, None] </code></pre> <p>I'd just like to have my <code>None</code> value ignored by the <code>numpy.mean</code> calculation but I can't figure out how to do it.</p>
21
2009-06-07T17:21:44Z
8,234,619
<p>You can use scipy for that:</p> <pre><code>import scipy.stats.stats as st m=st.nanmean(vec) </code></pre>
6
2011-11-22T22:15:38Z
[ "python", "numpy", "mean" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
962,379
<p>In your <code>insert_or_replace</code>. try this:</p> <pre><code>WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key LIMIT 1) </code></pre> <p>instead of</p> <pre><code>WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) </code></pre> <p>As noted in comments, that will probably do nothing. All I have to add, then,...
1
2009-06-07T17:39:09Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
962,430
<p>In Oracle, locking the table would definitely help. You might want to try that with PostgreSQL, too.</p>
1
2009-06-07T18:05:02Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
962,535
<p>I had a similar situation a few months ago and ended up getting the largest speed boost from a tuned chunk/transaction size. You may also want to check the log for a checkpoint warning during the test and tune appropriately. </p>
2
2009-06-07T18:55:14Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
962,688
<p>Sounds like you'd see benefits from using WAL (Write Ahead Logging) with a UPS to cache your updates between disk writes.</p> <blockquote> <p>wal_buffers This setting decides the number of buffers WAL(Write ahead Log) can have. If your database has many write transactions, setting this value bit higher than def...
2
2009-06-07T19:59:32Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
962,699
<p>The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit.</p> <p>I wrote a merge_by_key function specifically for these situations:</p> <p><a href="http://mbk.projects.postgresql.org/" rel="nofollow">http://mbk.projects.p...
4
2009-06-07T20:01:59Z
[ "python", "sql", "postgresql", "psycopg2" ]
How can I speed up update/replace operations in PostgreSQL?
962,361
<p>We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects).</p> <p>For sanity reasons we have created our own <a href="http://martinfow...
19
2009-06-07T17:28:56Z
3,520,889
<p>For updates, you can lower your fillfactor for the tables and the indexes and that might help</p> <p><a href="http://www.postgresql.org/docs/current/static/sql-createtable.html" rel="nofollow">http://www.postgresql.org/docs/current/static/sql-createtable.html</a></p> <p><a href="http://www.postgresql.org/docs/curr...
1
2010-08-19T10:34:02Z
[ "python", "sql", "postgresql", "psycopg2" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
962,662
<p>You could create a <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/" rel="nofollow">manager</a> on your model to do this sort of thing. To first understand what a manager is, the <code>Painting.objects</code> method is a manager that contains <code>all()</code>, <code>filter()</code>, <code>get()</...
8
2009-06-07T19:49:53Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
962,672
<p>Simply use:</p> <pre><code>MyModel.objects.order_by('?').first() </code></pre> <p>It is documented in <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields">QuerySet API</a>.</p>
174
2009-06-07T19:54:50Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
962,675
<p>You could simply do:</p> <pre><code>models.Painting.objects.all().order_by('?')[:1].get() </code></pre> <p>which is much more efficient.</p>
5
2009-06-07T19:55:38Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
971,671
<p>The solutions with order_by('?')[:N] are extremely slow even for medium-sized tables if you use MySQL (don't know about other databases).</p> <p><code>order_by('?')[:N]</code> will be translated to <code>SELECT ... FROM ... WHERE ... ORDER BY RAND() LIMIT N</code> query.</p> <p>It means that for every row in table...
23
2009-06-09T18:16:49Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
2,118,712
<p>Using <code>order_by('?')</code> will kill the db server on the second day in production. A better way is something like what is described in <a href="http://web.archive.org/web/20110802060451/http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/">Getting a random row from a relational dat...
79
2010-01-22T16:27:08Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
10,530,328
<p>This is Highly recomended <s><a href="http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/" rel="nofollow">Getting a random row from a relational database</a></s></p> <p>Because using django orm to do such a thing like that, will makes your db server angry specially if you have big data ...
1
2012-05-10T08:38:57Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
10,836,811
<p>Just to note a (fairly common) special case, if there is a indexed auto-increment column in the table with no deletes, the optimum way to do a random select is a query like:</p> <pre><code>SELECT * FROM table WHERE id = RAND() LIMIT 1 </code></pre> <p>that assumes such a column named id for table. In django you ca...
0
2012-05-31T15:39:13Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
30,741,675
<p>Just a simple idea how I do it:</p> <pre><code>def _get_random_service(self, professional): services = Service.objects.filter(professional=professional) i = randint(0, services.count()-1) return services[i] </code></pre>
0
2015-06-09T19:58:13Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
32,537,380
<p>The other answers are either potentially slow (using <code>order_by('?')</code>) or use more than one SQL query. Here's a sample solution with no ordering and just one query (assuming Postgres):</p> <pre class="lang-py prettyprint-override"><code>Model.objects.raw(''' select * from {0} limit 1 offset floor(...
0
2015-09-12T09:43:56Z
[ "python", "django", "django-models" ]
How to pull a random record using Django's ORM?
962,619
<p>I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. </p> <p>I'm using Django 1.0.2.</p> <p>While first 3 of them are easy to pull using django models, last one (random) c...
109
2009-06-07T19:25:15Z
34,099,143
<p>You may want to use the <a href="http://stackoverflow.com/a/12583436/623735">same approach</a> that you'd use to sample any iterator, especially if you plan to sample multiple items to create a <em>sample set</em>. @MatijnPieters and @DzinX put a lot of thought into this:</p> <pre><code>def random_sampling(qs, N=1)...
0
2015-12-04T23:22:05Z
[ "python", "django", "django-models" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no l...
2
2009-06-07T19:38:54Z
962,726
<p>There is no function <code>clickEvent</code> in QWidget/QLabel. You could connect that function to a Qt signal, or you could do:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent=None): QtGui.QLabel.__init__(self, parent) self.setText('Lorem Ipsum') def mouseReleaseEven...
1
2009-06-07T20:15:51Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no l...
2
2009-06-07T19:38:54Z
962,816
<p>Answering your second question, I'll continue based on @gnud example:</p> <ul> <li>subclass QLabel, override mouseReleaseEvent and add a signal to the class, let's call it clicked.</li> <li>check which button was clicked in mouseReleaseEvent, if it's the left one emit the clicked signal.</li> <li>connect a slot to ...
1
2009-06-07T21:04:12Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
PyQt - QLabel inheriting
962,640
<p>i wanna inherit QLabel to add there click event processing. I'm trying this code:</p> <pre><code>class NewLabel(QtGui.QLabel): def __init__(self, parent): QtGui.QLabel.__init__(self, parent) def clickEvent(self, event): print 'Label clicked!' </code></pre> <p>But after clicking I have no l...
2
2009-06-07T19:38:54Z
9,038,610
<p>The answer from the <a href="http://diotavelli.net/PyQtWiki/Making%20non-clickable%20widgets%20clickable" rel="nofollow">PyQt Wiki</a> works very well but I would add that the <code>clickable</code> class should call <code>widget.mouseReleaseEvent</code> (right before <code>return True</code>), just in case the user...
1
2012-01-27T19:00:20Z
[ "python", "qt", "inheritance", "pyqt", "label" ]
How to call up attributes in python 3.1 -- easy
962,877
<p>Python 2.5 all you needed to do was type "dir(filename)" and that pulls up the attributes.</p> <p>What is the command in 3.1?</p>
-1
2009-06-07T21:31:05Z
962,912
<p>Just <code>dir(whateverobject)</code>. Example:</p> <pre><code>Python 3.1rc1 (r31rc1:73141, Jun 2 2009, 12:50:02) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; x=23 &gt;&gt;&gt; dir(x) ['__abs__', '__add__', '__and__', '__bool__'...
3
2009-06-07T21:52:16Z
[ "python" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
962,966
<p>This example shows the differences between adding a method to a class and to an instance. </p> <pre><code>&gt;&gt;&gt; class Dog(): ... def __init__(self, name): ... self.name = name ... &gt;&gt;&gt; skip = Dog('Skip') &gt;&gt;&gt; spot = Dog('Spot') &gt;&gt;&gt; def talk(self): ... print 'Hi, m...
107
2009-06-07T22:42:51Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
963,199
<p>A possibly interesting alternative to using <code>types.MethodType</code> in:</p> <pre><code>&gt;&gt;&gt; f = types.MethodType(talk, puppy, Dog) &gt;&gt;&gt; puppy.talk = f # add method to specific instance </code></pre> <p>would be to exploit the fact that functions are <a href="http://users.rcn.com/python/downlo...
26
2009-06-08T01:32:40Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
964,049
<blockquote> <p>I wish to create a class in Python that I can add and remove attributes and methods.</p> </blockquote> <pre><code>import types class SpecialClass(object): @classmethod def removeVariable(cls, name): return delattr(cls, name) @classmethod def addMethod(cls, func): ret...
39
2009-06-08T09:24:15Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
966,464
<blockquote> <p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> </blockquote> <p>You can add and remove attributes and methods to any class, and they'll be available to all instances of the class:</p> <pre><code>&gt;&gt;&gt; def method1(self): ...
5
2009-06-08T19:16:46Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
13,221,989
<p>another alternative, if you need to replace the class wholesale is to modify the <strong>class</strong> attribute:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def foo(self): ... print 'A' ... &gt;&gt;&gt; class B(object): ... def foo(self): ... print 'Bar' ... &gt;&gt;&gt; a = A() &gt...
0
2012-11-04T19:23:36Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
14,436,426
<p>Simply: </p> <pre><code>f1 = lambda:0 #method for instances f2 = lambda _:0 #method for class class C: pass #class c1,c2 = C(),C() #instances print dir(c1),dir(c2) #add to the Instances c1.func = f1 c1.any = 1.23 print dir(c1),dir(c2) print c1...
0
2013-01-21T10:15:26Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
15,956,467
<p>you can just assign directly to the class (either by accessing the original class name or via <code>__class__</code> ):</p> <pre><code>class a : pass ob=a() ob.__class__.blah=lambda self,k: (3, self,k) ob.blah(5) ob2=a() ob2.blah(7) </code></pre> <p>will print</p> <pre><code>(3, &lt;__main__.a instance at 0x7f18e...
3
2013-04-11T18:46:17Z
[ "python", "reflection", "runtime" ]
Python: changing methods and attributes at runtime
962,962
<p>I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?</p> <p>Oh, and please don't ask why.</p>
63
2009-06-07T22:39:01Z
25,836,670
<p>Does the class itself necessarily need to be modified? Or is the goal simply to replace what object.method() does at a particular point during runtime? </p> <p>I ask because I sidestep the problem of actually modifying the class to monkey patch specific method calls in my framework with <strong>getattribute</strong...
0
2014-09-14T18:35:11Z
[ "python", "reflection", "runtime" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide c...
0
2009-06-08T00:08:03Z
963,107
<p>Module variables may (or may not) persist between requests (the same app instance may or may not stay alive between requests), but you can explicitly clear them (<code>del</code>, or set to <code>None</code>, say) at the start of your handling a request, or when you know you're done with one. At worst (if your code ...
1
2009-06-08T00:30:44Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide c...
0
2009-06-08T00:08:03Z
963,706
<p>use local list to store data and do a model.put at end of your request processing. save multiple db trips</p>
0
2009-06-08T06:56:32Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide c...
0
2009-06-08T00:08:03Z
965,582
<p>What I usually do is just create a new attribute on the request object. However, I use django with AppEngine, so I'm not sure if there is anything different about the appengine webapp framework.</p> <pre><code>def view_handler(request): if hasattr(request, 'mycache'): request.mycache['counter'] += 1 ...
2
2009-06-08T15:46:20Z
[ "python", "google-app-engine" ]
How can I create a variable that is scoped to a single request in app engine?
963,080
<p>I'm creating a python app for google app engine and I've got a performance problem with some expensive operations that are repetitive within a single request. To help deal with this I'd like to create a sort of mini-cache that's scoped to a single request. This is as opposed to a session-wide or application-wide c...
0
2009-06-08T00:08:03Z
972,243
<p>If you're using the 'webapp' framework included with App Engine (or, actually, most other WSGI-baesd frameworks), a new RequestHandler is instantiated for each request. Thus, you can use class variables on your handler class to store per-request data.</p>
2
2009-06-09T20:10:03Z
[ "python", "google-app-engine" ]
Python display string multiple times
963,161
<p>I want to print a character or string like '-' n number of times.</p> <p>Can I do it without using a loop?.. Is there a function like</p> <pre><code>print('-',3) </code></pre> <p>..which would mean printing the <code>-</code> 3 times, like this:</p> <pre><code>--- </code></pre>
40
2009-06-08T01:11:57Z
963,166
<p>Python 2.x:</p> <pre><code>print '-' * 3 </code></pre> <p>Python 3.x:</p> <pre><code>print('-' * 3) </code></pre>
78
2009-06-08T01:13:45Z
[ "python" ]
Python display string multiple times
963,161
<p>I want to print a character or string like '-' n number of times.</p> <p>Can I do it without using a loop?.. Is there a function like</p> <pre><code>print('-',3) </code></pre> <p>..which would mean printing the <code>-</code> 3 times, like this:</p> <pre><code>--- </code></pre>
40
2009-06-08T01:11:57Z
28,652,751
<p>To print a string 3 times in Python 3.x, in this case the string is "hello"</p> <blockquote> <blockquote> <blockquote> <p>print("hello " * 3)</p> </blockquote> </blockquote> </blockquote>
0
2015-02-21T23:41:57Z
[ "python" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the r...
9
2009-06-08T02:07:35Z
992,462
<p>You can use "request.getSession()" to get a componentized object.</p> <p>You can read more about componentized in <a href="http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentize...
4
2009-06-14T08:50:06Z
[ "python", "twisted" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the r...
9
2009-06-08T02:07:35Z
1,300,087
<p>Calling getSession() will generate a session and add the cookie to the request:</p> <p><a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.1.0/twisted/web/server.py#L315" rel="nofollow">getSession() source code</a></p> <p>If the clients already has a session cookie then calling getSession() will...
4
2009-08-19T13:50:46Z
[ "python", "twisted" ]
how to use session/cookie in twisted.web?
963,236
<p>I am implementing an http server with twisted.web. Here comes the problem: there is a login operation; after that, I want the http server to remember each client using acookie/session, until the user closes the browser.</p> <p>I've read the twisted.web document, but I can't figure out how to do this. I know the r...
9
2009-06-08T02:07:35Z
10,748,955
<p>See this related question <a href="http://stackoverflow.com/questions/4936994/store-an-instance-of-a-connection-twisted-web">Store an instance of a connection - twisted.web</a>. The answer there links to this blog post <a href="http://jcalderone.livejournal.com/53680.html" rel="nofollow">http://jcalderone.livejourna...
2
2012-05-25T05:32:45Z
[ "python", "twisted" ]
HTML tags within JSON (in Python)
963,448
<p>I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.:</p> <pre><code>{ "node": { "list":"&lt;ul&gt;&lt;li class="lists"&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>is this possible to do in Python without requiring to ...
2
2009-06-08T04:48:15Z
963,476
<p>You can have arbitrary strings there, including ones which happen to contain HTML tags (the only issue with your example is the inner <code>"</code> which would confuse any parser).</p>
0
2009-06-08T05:00:50Z
[ "python", "json", "escaping", "markup" ]
HTML tags within JSON (in Python)
963,448
<p>I understand its not a desirable circumstance, however if I NEEDED to have some kind of HTML within JSON tags, e.g.:</p> <pre><code>{ "node": { "list":"&lt;ul&gt;&lt;li class="lists"&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>is this possible to do in Python without requiring to ...
2
2009-06-08T04:48:15Z
963,482
<p>Well, depending on how varied your HTML is, you can use single quotes in HTML fine, so you could do:</p> <pre><code>{ "node": { "list": "&lt;ul&gt;&lt;li class='lists'&gt;Hello World&lt;/li&gt;&lt;ul&gt;" } } </code></pre> <p>However, with <code>simplejson</code>, which is built into Python 2.6...
4
2009-06-08T05:02:45Z
[ "python", "json", "escaping", "markup" ]
Tab view in CSS with tables
963,506
<p>I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in loop only. The development is ...
0
2009-06-08T05:20:43Z
963,558
<p>Just of the top of my head, check out what some of the Javascript toolkits have to offer. Things like jQuery with a few plugins or Dojo might have something like that in its Dijit library.</p>
0
2009-06-08T05:44:06Z
[ "python", "html", "css", "tabs", "css-tables" ]
Tab view in CSS with tables
963,506
<p>I need a tab view in CSS with each tab showing a dynamic table. The complete table is dynamically constructed in loop and only after that should the tabs should hide and show each of the table corresponding to each tab. Any suggestions? The content of the tab is within list item and in loop only. The development is ...
0
2009-06-08T05:20:43Z
963,566
<p>Check out <a href="http://docs.jquery.com/UI/Tabs" rel="nofollow">jQuery UI Tabs</a>; this will do what you're looking for. It's not possible to do this using pure CSS.</p>
1
2009-06-08T05:48:33Z
[ "python", "html", "css", "tabs", "css-tables" ]
How can I instantiate a comment element programatically using lxml?
963,621
<p>I'm using lxml to programatically build HTML and I need to include a custom comment in the output. Whilst there is code in lxml to cope with comments (they can be instantiated when parsing existing HTML code) I cannot find a way to instantiate one programatically.</p> <p>Can anyone help?</p>
2
2009-06-08T06:15:45Z
963,680
<p>You can use the <a href="http://lxml.de/api/lxml.etree._Comment-class.html" rel="nofollow"><code>lxml.etree.Comment()</code></a> factory function. It will return a comment element that you can use like any other element.</p>
4
2009-06-08T06:44:34Z
[ "python", "html", "xml", "lxml" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to cr...
6
2009-06-08T07:38:02Z
963,842
<p>You can add whatever you want to a zip file using <a href="http://docs.python.org/library/zipfile#zipfile.ZipFile.writestr"><code>ZipFile.writestr()</code></a>:</p> <pre><code>my_data = "&lt;html&gt;&lt;body&gt;&lt;p&gt;Hello, world!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;" z.writestr("hello.html", my_data) </code></pr...
7
2009-06-08T08:01:28Z
[ "python", "google-app-engine", "zipfile" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to cr...
6
2009-06-08T07:38:02Z
964,084
<p>In addition to Schnouki's excellent answer, you can also pass ZipFile a file-like object, such as one created by <a href="http://docs.python.org/library/stringio.html" rel="nofollow">StringIO.StringIO</a>.</p>
3
2009-06-08T09:38:06Z
[ "python", "google-app-engine", "zipfile" ]
Zipping dynamic files in App Engine (Python)
963,800
<p>Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile?</p> <p>There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all?</p> <p>One more question: Is it possible to cr...
6
2009-06-08T07:38:02Z
964,418
<p>The working code: (for app engine:)</p> <pre><code>output = StringIO.StringIO() z = zipfile.ZipFile(output,'w') my_data = "&lt;html&gt;&lt;body&gt;&lt;p&gt;Hello, world!&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;" z.writestr("hello.html", my_data) z.close() self.response.headers["Content-Type"] = "multipart/x-zip" self.r...
14
2009-06-08T11:16:36Z
[ "python", "google-app-engine", "zipfile" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
964,005
<p>A set object to list is converted like so:</p> <pre><code>my_list = list(my_set) </code></pre> <p>I don't understand your example though. Converting a string to a list results in a list of characters:</p> <pre><code>&gt;&gt;&gt; list('abc') ['a', 'b', 'c'] </code></pre>
1
2009-06-08T09:11:22Z
[ "python", "django", "google-app-engine", "list" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
964,194
<p>if the list() command is not working for you, you could work around it like this:</p> <pre><code>my_list = [] for item in my_set: my_list.append(item) </code></pre> <p>hth</p>
0
2009-06-08T10:11:45Z
[ "python", "django", "google-app-engine", "list" ]
Can't seem to get list() working
963,932
<p>I am trying to convert a set object to list...for example "p=list('abc')" is not working. any ideas or is it inherent in appengine</p>
0
2009-06-08T08:47:33Z
965,860
<p>There is no specific change "inherent" in appengine with respect to common aspects like lists. It is as just the same, plain python.</p>
0
2009-06-08T16:48:48Z
[ "python", "django", "google-app-engine", "list" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute ...
27
2009-06-08T08:58:40Z
964,033
<p>The example in Python is not so different of the others. To mock the PHP script:</p> <pre><code>class StrategyExample: def __init__(self, func=None): if func: self.execute = func def execute(self): print("Original execution") def executeReplacement1(): print("Strategy 1") ...
40
2009-06-08T09:18:07Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute ...
27
2009-06-08T08:58:40Z
964,325
<p>For clarity, I would still use a pseudo-interface:</p> <pre><code>class CommunicationStrategy(object): def execute(self, a, b): raise NotImplementedError('execute') class ConcreteCommunicationStrategyDuck(CommunicationStrategy): def execute(self, a, b): print "Quack Quack" class ConcreteCo...
9
2009-06-08T10:53:38Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute ...
27
2009-06-08T08:58:40Z
964,345
<p>You're right, the wikipedia example isn't helpful. It conflates two things.</p> <ol> <li><p><strong>Strategy</strong>.</p></li> <li><p>Features of Python that simplify the implementation of <strong>Strategy</strong>. The "there's no need to implement this pattern explicitly" statement is incorrect. You often nee...
26
2009-06-08T10:59:30Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute ...
27
2009-06-08T08:58:40Z
8,919,545
<p>Answering an old question for the Googlers who searched "python strategy pattern" and landed here...</p> <p>This pattern is practically non-existent in languages that support first class functions. You may want to consider taking advantage of this feature in Python:</p> <pre><code>def strategy_add(a, b): retur...
30
2012-01-19T00:30:47Z
[ "python", "design-patterns" ]
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
<p>In the 2009 Wikipedia entry for the Strategy Pattern, there's a example <a href="http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP" rel="nofollow">written in PHP</a>.</p> <p>Most other code samples do something like:</p> <pre><code>a = Context.new(StrategyA.new) a.execute ...
27
2009-06-08T08:58:40Z
36,996,245
<p>I've tried to convert the 'Duck' example from the 1st chapter (covering Strategy Pattern) of <a href="http://rads.stackoverflow.com/amzn/click/0596007124" rel="nofollow">Head First Design Pattern</a> in Python:</p> <pre><code>class FlyWithRocket(): def __init__(self): pass def fly(self): pri...
0
2016-05-03T05:26:53Z
[ "python", "design-patterns" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have no...
4
2009-06-08T09:49:05Z
964,191
<p>Usually, we unit test first.</p> <p>Then, we write log messages to diagnose problems.</p> <p>We generally don't depend heavily on debugging because it's often hard to do in situations where Python scripts are embedded in a larger product.</p>
0
2009-06-08T10:11:12Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have no...
4
2009-06-08T09:49:05Z
964,546
<p>I've found that <a href="http://winpdb.org/about/" rel="nofollow">Winpdb</a> is a decent python debugger. </p> <p>But as S.Lott points out, debuggers may not be very useful to you when your project is embedded within a larger one. </p>
0
2009-06-08T11:56:45Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have no...
4
2009-06-08T09:49:05Z
964,583
<p>Trac contains good examples of Python code, using it as a guideline will help avoid bugs. Just be sure to test your code, and do it often since you are new to Python... You'll find you don't need a debugger.</p> <p>For unit testing, check out <a href="http://wiki.python.org/moin/PyUnit" rel="nofollow">PyUnit</a>.</...
0
2009-06-08T12:05:02Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have no...
4
2009-06-08T09:49:05Z
964,957
<p>You can create a wrapper wsgi script and run it in a debugger. For example:</p> <pre><code>import os import trac.web.main os.environ['TRAC_ENV'] = '/path/to/your/trac/env' application = trac.web.main.dispatch_request from flup.server.fcgi import WSGIServer server = WSGIServer(application, bindAddress=("127.0.0.1...
2
2009-06-08T13:33:59Z
[ "python", "trac", "netbeans6.5" ]
How should I debug Trac plugins?
964,123
<p>I'm about to start a fair amount of work extending Trac to fit our business requirements. So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.</p> <p><em>I'm totally new to Python</em> so probably have no...
4
2009-06-08T09:49:05Z
17,024,225
<p>I found it most useful to add those fancy Trac messageboxes at runtime as debugging help or tracing, just like this:</p> <pre><code>from trac.web.chrome import add_notice ... def any_function_somewhere(self, req, ...anyother args...): ... var = ...some value... add_notice(req, "my variable value I am tr...
0
2013-06-10T12:46:40Z
[ "python", "trac", "netbeans6.5" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem ...
-5
2009-06-08T11:05:02Z
964,412
<p>if you want decimal precision use the python <a href="http://docs.python.org/library/decimal.html" rel="nofollow"><code>decimal</code></a> module:</p> <pre><code>from decimal import Decimal x = Decimal('3.00') print x </code></pre> <p>That prints:</p> <pre><code>Decimal('3.00') </code></pre>
1
2009-06-08T11:15:37Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem ...
-5
2009-06-08T11:05:02Z
964,417
<p>If you want to print a floating-point number to a desired precision you can use output formatting codes like the following:</p> <p>Assuming x = 3.125</p> <pre><code>print "%.1f" % (x) # prints 3.1 print "%.2f" % (x) # prints 3.12 print "%.3f" % (x) # prints 3.125 print "%.4f" % (x) # prints 3.1250 </co...
0
2009-06-08T11:16:32Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem ...
-5
2009-06-08T11:05:02Z
964,419
<p>I suppose that what you want is to convert a float to a string with the number of decimals that you want. You can achieve that using %.3f (here 3 is the number of decimals that you want to print. For example:</p> <pre><code>&gt;&gt;&gt; print "Value: %.2f" % 3.0000 </code></pre> <p>Value: 3.00</p>
1
2009-06-08T11:16:43Z
[ "python", "floating" ]
python formating float numbers
964,372
<p>my input is 3.23 , but when i use float on it , it becomes 3.2 , </p> <p>when my input is 3.00 , when i do float on it , it becomes 3.0 </p> <p>when i convert to float from string , i still want it to be 3.00 and not 3.0 is it possible? i want to know the code to make it possible , and when i am doing a problem ...
-5
2009-06-08T11:05:02Z
13,901,648
<p>Since this thread is first on the words "string formating decimal python", I think it's good to provide a more recent answer :</p> <pre><code>&gt;&gt;&gt; P=34.3234564 &gt;&gt;&gt; string="{:.2f}".format(P) &gt;&gt;&gt; string '34.32' </code></pre>
3
2012-12-16T13:17:49Z
[ "python", "floating" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,473
<p>You can do this with the <a href="http://docs.python.org/library/htmlparser.html" rel="nofollow">HTMLParser</a> module (complicated) or use regular expressions:</p> <pre><code>import re content = "asdf &lt;script&gt; bla &lt;/script&gt; end" x=re.search("&lt;script&gt;.*?&lt;/script&gt;", content, re.DOTALL) span =...
0
2009-06-08T11:35:43Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,478
<p>I don't know Python good enough to tell you a solution. But if you want to use that to sanitize the user input you have to be very, very careful. Removing stuff between and just doesn't catch everything. Maybe you can have a look at existing solutions (I assume Django includes something like this).</p>
-1
2009-06-08T11:37:14Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,485
<p>You can use <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> with this (and other) methods:</p> <pre><code>soup = BeautifulSoup(source.lower()) to_extract = soup.findAll('script') for item in to_extract: item.extract() </code></pre> <p>This actually removes the nodes from the HTML. If...
25
2009-06-08T11:38:55Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,487
<p>If you're removing everything between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> why not just remove the entire node? </p> <p>Are you expecting a resig-style src and body?</p>
0
2009-06-08T11:39:43Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,518
<pre><code>example_text = "This is some text &lt;script&gt; blah blah blah &lt;/script&gt; this is some more text." import re myre = re.compile("(^.*)&lt;script&gt;(.*)&lt;/script&gt;(.*$)") result = myre.match(example_text) result.groups() &lt;52&gt; ('This is some text ', ' blah blah blah ', ' this is some more te...
-1
2009-06-08T11:48:16Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,699
<p>If you don't want to import any modules:</p> <pre><code>string = "&lt;script&gt; this is some js. begone! &lt;/script&gt;" string = string.split(' ') for i, s in enumerate(string): if s == '&lt;script&gt;' or s == '&lt;/script&gt;' : del string[i] print ' '.join(string) </code></pre>
-1
2009-06-08T12:34:37Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
964,727
<p>According to answers posted by Pev and wr, why not to upgrade a regular expression, e.g.:</p> <pre><code>pattern = r"(?is)&lt;script[^&gt;]*&gt;(.*?)&lt;/script&gt;" text = """&lt;script&gt;foo bar baz bar foo &lt;/script&gt;""" re.sub(pattern, '', text) </code></pre> <p>(?is) - added to ignore case and allow n...
0
2009-06-08T12:41:20Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
965,236
<p>Are you trying to prevent <a href="http://en.wikipedia.org/wiki/Cross-site%5Fscripting" rel="nofollow">XSS</a>? Just eliminating the <code>&lt;script&gt;</code> tags will not solve all possible attacks! Here's a great list of the many ways (some of them very creative) that you could be vulnerable <a href="http://ha....
5
2009-06-08T14:45:21Z
[ "javascript", "python" ]
how to remove text between <script> and </script> using python?
964,459
<p>how to remove text between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> using python?</p>
5
2009-06-08T11:30:28Z
965,840
<p><a href="http://diveintopython3.org/xml.html" rel="nofollow">Element Tree</a> is the best simplest and sweetest package to do this. Yes, there are other ways to do it too; but don't use any 'coz they suck! (via Mark Pilgrim)</p>
0
2009-06-08T16:45:19Z
[ "javascript", "python" ]
Patching classes in Python
964,532
<p>Suppose I have a Python class that I want to add an extra property to.</p> <p>Is there any difference between </p> <pre><code>import path.MyClass MyClass.foo = bar </code></pre> <p>and using something like :</p> <pre><code>import path.MyClass setattr(MyClass, 'foo', bar) </code></pre> <p>?</p> <p>If not, why d...
6
2009-06-08T11:53:38Z
964,551
<p>The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.)</p> <p>See: <a href="http://docs.python.org/library/functions.html#setattr">http://docs.python.org/library/functions.html#setattr</a></p>
11
2009-06-08T11:57:28Z
[ "python", "class", "monkeypatching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44...
2
2009-06-08T12:01:52Z
964,619
<p>The usual way of the having site-specific user fields is to specify a user profile table in your settings.py. You can then retrieve the specific settings via a the u.user_profile() method. It's very well documented in the docs.</p>
2
2009-06-08T12:13:04Z
[ "python", "django", "django-authentication", "patching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44...
2
2009-06-08T12:01:52Z
965,245
<p>You probably just need to make sure that you do the replacement/addition/monkey patch as early as you can (before the auth application is actually installed). The trouble though is that the model classes do some meta-class stuff that'd probably explain why the UserManager has the wrong class - as it will generate t...
2
2009-06-08T14:47:17Z
[ "python", "django", "django-authentication", "patching" ]
Django : Adding a property to the User class. Changing it at runtime and UserManager.create_user
964,569
<p>For various complicated reasons[1] I need to add extra properties to the Django User class.</p> <p>I can't use either Profile nor the "inheritance" way of doing this. (As in <a href="http://stackoverflow.com/questions/44109/extending-the-user-model-with-custom-fields-in-django">http://stackoverflow.com/questions/44...
2
2009-06-08T12:01:52Z
966,806
<p>If Django 1.1 beta isn't too bleeding edge for you, try proxy models.</p>
2
2009-06-08T20:23:34Z
[ "python", "django", "django-authentication", "patching" ]
Find a HAL object based on /dev node path
964,801
<p>I'm using <code>python-dbus</code> to interface with HAL, and I need to find a device's UDI based on it's path in the <code>/dev</code> hierarchy.</p> <p>So given a path such as <code>/dev/sdb</code>, I want to get a value back like <code>/org/freedesktop/Hal/devices/usb_device_10</code>.</p>
2
2009-06-08T13:02:18Z
964,992
<p>I would spawn a <code>hal-find-by-property</code> call from Python:</p> <pre><code>import subprocess def get_UDI(path): cmd = 'hal-find-by-property --key block.device --string %s' % path proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = proc.communicate() # stdout return ...
1
2009-06-08T13:44:30Z
[ "python", "dbus", "hal" ]
Find a HAL object based on /dev node path
964,801
<p>I'm using <code>python-dbus</code> to interface with HAL, and I need to find a device's UDI based on it's path in the <code>/dev</code> hierarchy.</p> <p>So given a path such as <code>/dev/sdb</code>, I want to get a value back like <code>/org/freedesktop/Hal/devices/usb_device_10</code>.</p>
2
2009-06-08T13:02:18Z
965,110
<p>Pure python solution:</p> <pre><code>import dbus bus = dbus.SystemBus() obj = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/Manager") iface = dbus.Interface(obj, "org.freedesktop.Hal.Manager") print iface.FindDeviceStringMatch("block.device", "/dev/sda") </code></pre>
3
2009-06-08T14:15:25Z
[ "python", "dbus", "hal" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,005
<p>I'd suggest using the regular expression module: <a href="http://docs.python.org/library/re.html" rel="nofollow">re</a></p> <p>Something along these lines perhaps?</p> <pre><code>#!/usr/bin/python import re if __name__ == '__main__': data = open('x').read() RE = re.compile('.*form="(.*)" lemma="(.*)" post...
2
2009-06-08T13:48:01Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,029
<p>Is your file proper XML? If so, try a SAX parser:</p> <pre><code>import xml.sax class Handler (xml.sax.ContentHandler): def startElement (self, tag, attrs): if tag == 'word': print 'form=', attrs['form'] print 'lemma=',attrs['lemma'] print 'postag=',attrs['postag'] ch = ...
1
2009-06-08T13:54:49Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,036
<p>In addition to the usual RegEx answer, since this appears to be a form of XML, you might try something like BeautifulSoup ( <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a> )</p> <p>It's very easy to use, and find tags/attributes in things like...
1
2009-06-08T13:55:51Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,040
<p>Parsing xml by hand is usually the wrong thing. For one thing, your code will break if there's an escaped quote in any of the attributes. Getting the attributes from an xml parser is probably cleaner and less error-prone.</p> <p>An approach like this can also run into problems parsing the entire f...
0
2009-06-08T13:56:49Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,041
<p>Just to highlight your problem:</p> <pre><code>finished = False counter = 0 while not finished: counter += 1 finished=True print counter </code></pre>
0
2009-06-08T13:56:59Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,047
<p>With regular expressions, this is the gist (you can do the file.readline() part):</p> <pre><code>import re line = '&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt;' r = re.compile( 'form="([^"]*)".*lemma="([^"]*)".*postag="([^"]*)"' ) match = r.search( line ) print m...
0
2009-06-08T13:58:29Z
[ "python" ]
Python: Reading part of a text file
964,993
<p>HI all</p> <p>I'm new to python and programming. I need to read in chunks of a large text file, format looks like the following: </p> <pre><code>&lt;word id="8" form="hibernis" lemma="hibernus1" postag="n-p---nb-" head-"7" relation="ADV"/&gt; </code></pre> <p>I need the <code>form</code>, <code>lemma</code> and <...
4
2009-06-08T13:44:32Z
965,048
<p>First, don't spend a lot of time rewriting your file. It's generally a waste of time. The processing to clean up and parse the tags is so fast, that you'll be perfectly happy working from the source file all the time.</p> <pre><code>source= open( "blank.txt", "r" ) for line in source: # line has a tag-line st...
0
2009-06-08T13:58:32Z
[ "python" ]