title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to set timeout for urlfetch in Google App Engine?
2,162,115
<p>I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this:</p> <blockquote> <p>ApplicationError: 2 timed out Request</p> <p>Method: GET</p> <p>Request URL:http://localhost:8080/</p> <p>Exception Type: DownloadError</p> <p>Exception V...
14
2010-01-29T13:14:15Z
2,162,160
<p>You can set it using the <code>deadline</code> argument of the <a href="http://code.google.com/appengine/docs/python/urlfetch/fetchfunction.html">fetch function</a>. From <a href="http://code.google.com/appengine/docs/python/urlfetch/overview.html">the docs</a>:</p> <blockquote> <p>The deadline can be up to a max...
20
2010-01-29T13:22:56Z
[ "python", "django", "google-app-engine", "timeout" ]
How to set timeout for urlfetch in Google App Engine?
2,162,115
<p>I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this:</p> <blockquote> <p>ApplicationError: 2 timed out Request</p> <p>Method: GET</p> <p>Request URL:http://localhost:8080/</p> <p>Exception Type: DownloadError</p> <p>Exception V...
14
2010-01-29T13:14:15Z
2,162,360
<p>It seems short but you have to know that the timeout of a request on GAE is around 30 seconds. As you probably need to do some operations on the response of your urlfetch, there's no need to have a timeout more than 10 seconds I think.</p>
-1
2010-01-29T14:00:35Z
[ "python", "django", "google-app-engine", "timeout" ]
How to set timeout for urlfetch in Google App Engine?
2,162,115
<p>I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this:</p> <blockquote> <p>ApplicationError: 2 timed out Request</p> <p>Method: GET</p> <p>Request URL:http://localhost:8080/</p> <p>Exception Type: DownloadError</p> <p>Exception V...
14
2010-01-29T13:14:15Z
12,980,842
<p>Seeing as this is a <code>Python</code> question, I thought I'd provide a Python answer for anyone who comes across this problem.</p> <p>Just import <code>urlfetch</code> and then define a deadline before doing anything else in your code:</p> <pre><code>from google.appengine.api import urlfetch urlfetch.set_defau...
24
2012-10-19T19:06:54Z
[ "python", "django", "google-app-engine", "timeout" ]
How to set timeout for urlfetch in Google App Engine?
2,162,115
<p>I'm trying to have Django (on top of GAE) fetch data from another web service. I'm often hit with error like this:</p> <blockquote> <p>ApplicationError: 2 timed out Request</p> <p>Method: GET</p> <p>Request URL:http://localhost:8080/</p> <p>Exception Type: DownloadError</p> <p>Exception V...
14
2010-01-29T13:14:15Z
17,256,413
<p>For Go, you might want to try below code.</p> <pre><code>// createClient is urlfetch.Client with Deadline func createClient(context appengine.Context, t time.Duration) *http.Client { return &amp;http.Client{ Transport: &amp;urlfetch.Transport{ Context: context, Deadline: t, ...
6
2013-06-22T23:44:51Z
[ "python", "django", "google-app-engine", "timeout" ]
Library like fakeweb for Python
2,162,250
<p>I really like the way fakeweb in Ruby can be used to fake http requests when testing. Is there a similar library or an alternative for Python?</p>
7
2010-01-29T13:42:15Z
2,163,185
<p>I recomend you produce a fake inteface to HTTP request like in <a href="http://stackoverflow.com/questions/1016765/how-to-use-cookielib-with-httplib-in-python">questions 1016765 how-to-use-cookielib-with-httplib-in-python</a>.</p>
1
2010-01-29T16:04:47Z
[ "python", "testing", "fakeweb" ]
Library like fakeweb for Python
2,162,250
<p>I really like the way fakeweb in Ruby can be used to fake http requests when testing. Is there a similar library or an alternative for Python?</p>
7
2010-01-29T13:42:15Z
2,269,837
<p>See also <a href="http://stackoverflow.com/questions/295438/how-can-one-mock-stub-python-module-like-urllib/295503">http://stackoverflow.com/questions/295438/how-can-one-mock-stub-python-module-like-urllib/295503</a> . The answer that recommends <a href="http://code.google.com/p/pymox/" rel="nofollow">Mox</a> seems ...
3
2010-02-16T00:10:28Z
[ "python", "testing", "fakeweb" ]
Library like fakeweb for Python
2,162,250
<p>I really like the way fakeweb in Ruby can be used to fake http requests when testing. Is there a similar library or an alternative for Python?</p>
7
2010-01-29T13:42:15Z
13,296,758
<p><a href="http://falcao.it/HTTPretty/" rel="nofollow">HTTPretty</a> works in the exact same way that FakeWeb does. HTTPretty works in the socket layer, so it should work intercepting any python http client libraries. It's battle tested against urllib2, httplib2 and requests</p>
2
2012-11-08T19:58:25Z
[ "python", "testing", "fakeweb" ]
Getting DISTINCT users on Google App Engine
2,162,409
<p>How to do this on Google App Engine (Python):</p> <pre><code>SELECT COUNT(DISTINCT user) FROM event WHERE event_type = "PAGEVIEW" AND t &gt;= start_time AND t &lt;= end_time </code></pre> <p>Long version:</p> <p>I have a Python Google App Engine application with users that generate events, such as pageviews. I w...
4
2010-01-29T14:09:42Z
2,162,542
<p>Google App Engine and more particular <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">GQL</a> does not support a <code>DISTINCT</code> function.</p> <p>But you can use Python's <code>set</code> function as described in <a href="http://junalontherun.com/tag/gql-disti...
1
2010-01-29T14:33:34Z
[ "python", "google-app-engine", "scaling" ]
Getting DISTINCT users on Google App Engine
2,162,409
<p>How to do this on Google App Engine (Python):</p> <pre><code>SELECT COUNT(DISTINCT user) FROM event WHERE event_type = "PAGEVIEW" AND t &gt;= start_time AND t &lt;= end_time </code></pre> <p>Long version:</p> <p>I have a Python Google App Engine application with users that generate events, such as pageviews. I w...
4
2010-01-29T14:09:42Z
2,162,736
<p>Here is a possibly-workable solution. It relies to an extent on using memcache, so there is always the possibility that your data would get evicted in an unpredictable fashion. <em>Caveat emptor.</em></p> <p>You would have a memcache variable called <strong>unique_visits_today</strong> or something similar. Every t...
1
2010-01-29T15:01:02Z
[ "python", "google-app-engine", "scaling" ]
Getting DISTINCT users on Google App Engine
2,162,409
<p>How to do this on Google App Engine (Python):</p> <pre><code>SELECT COUNT(DISTINCT user) FROM event WHERE event_type = "PAGEVIEW" AND t &gt;= start_time AND t &lt;= end_time </code></pre> <p>Long version:</p> <p>I have a Python Google App Engine application with users that generate events, such as pageviews. I w...
4
2010-01-29T14:09:42Z
13,878,600
<p>As of SDK v1.7.4, there is now experimental support for the DISTINCT function.</p> <p>See : <a href="https://developers.google.com/appengine/docs/python/datastore/gqlreference" rel="nofollow">https://developers.google.com/appengine/docs/python/datastore/gqlreference</a></p>
4
2012-12-14T12:21:27Z
[ "python", "google-app-engine", "scaling" ]
Getting DISTINCT users on Google App Engine
2,162,409
<p>How to do this on Google App Engine (Python):</p> <pre><code>SELECT COUNT(DISTINCT user) FROM event WHERE event_type = "PAGEVIEW" AND t &gt;= start_time AND t &lt;= end_time </code></pre> <p>Long version:</p> <p>I have a Python Google App Engine application with users that generate events, such as pageviews. I w...
4
2010-01-29T14:09:42Z
14,506,364
<p>NDB still does not support DISTINCT. I have written a small utility method to be able to use distinct with GAE.</p> <p>See here. <a href="http://verysimplescripts.blogspot.jp/2013/01/getting-distinct-properties-with-ndb.html" rel="nofollow">http://verysimplescripts.blogspot.jp/2013/01/getting-distinct-properties-wi...
1
2013-01-24T16:42:11Z
[ "python", "google-app-engine", "scaling" ]
Python NLTK code snippet to train a classifier (naive bayes) using feature frequency
2,162,718
<p>I was wondering if anyone could help me through a code snippet that demonstrates how to train Naive Bayes classifier using a feature frequency method as opposed to feature presence.</p> <p>I presume the below as shown in Chap 6 <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html#document-classify-all-w...
2
2010-01-29T14:58:20Z
2,165,625
<p>In the link you sent it says this function is feature extractor that simply checks whether each of these words is present in a given document. </p> <p>Here is the whole code with numbers for each line:</p> <pre><code>1 all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words()) 2 word_features = al...
3
2010-01-29T22:26:03Z
[ "python", "nlp", "nltk", "stanford-nlp" ]
Python NLTK code snippet to train a classifier (naive bayes) using feature frequency
2,162,718
<p>I was wondering if anyone could help me through a code snippet that demonstrates how to train Naive Bayes classifier using a feature frequency method as opposed to feature presence.</p> <p>I presume the below as shown in Chap 6 <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html#document-classify-all-w...
2
2010-01-29T14:58:20Z
2,226,115
<p>For training, create appropriate FreqDists that you can use to create ProbDists, than can then be passed in to the NaiveBayesClassifier. But the classification actually works on feature sets, which use boolean values, not frequencies. So if you want to classify based on a FreqDist, you'll have to implement your own ...
3
2010-02-09T01:18:35Z
[ "python", "nlp", "nltk", "stanford-nlp" ]
Python NLTK code snippet to train a classifier (naive bayes) using feature frequency
2,162,718
<p>I was wondering if anyone could help me through a code snippet that demonstrates how to train Naive Bayes classifier using a feature frequency method as opposed to feature presence.</p> <p>I presume the below as shown in Chap 6 <a href="http://nltk.googlecode.com/svn/trunk/doc/book/ch06.html#document-classify-all-w...
2
2010-01-29T14:58:20Z
5,890,759
<p>Here's a method which will help you :</p> <pre><code>''' Returns the frequency of letters ''' def get_freq_letters(words): fdist = nltk.FreqDist([char.lower() for word in words for char in word if char.isalpha()]) freq_letters = {} for key,value in fdist.iteritems(): freq_letters[key] = value ...
0
2011-05-04T22:50:06Z
[ "python", "nlp", "nltk", "stanford-nlp" ]
Modpython and virtualenv
2,162,790
<p>Is it any way to run django site on virtualenv without administration rights? How can I do it? Virtualenv is already installed.</p>
2
2010-01-29T15:08:44Z
2,162,913
<p>Yes, but <a href="http://code.google.com/p/modwsgi/wiki/VirtualEnvironments" rel="nofollow">not with mod_python</a>.</p>
0
2010-01-29T15:27:49Z
[ "python", "django", "mod-python", "virtualenv" ]
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
<p>I have the following Python script that reads numbers and outputs an error if the input is not a number.</p> <pre><code>import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) </code></pre> <p>If I g...
13
2010-01-29T15:27:55Z
2,162,957
<p>The first time it considers it to be input, the second time it's for keeps! </p> <p>This only occurs when the input is from a tty. It is likely because of the terminal settings where characters are buffered until a newline (carriage return) is entered.</p>
0
2010-01-29T15:34:02Z
[ "python", "bash", "stdin" ]
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
<p>I have the following Python script that reads numbers and outputs an error if the input is not a number.</p> <pre><code>import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) </code></pre> <p>If I g...
13
2010-01-29T15:27:55Z
2,163,007
<p>I wrote an explanation about this in my answer to this question.</p> <p><a href="http://stackoverflow.com/questions/1516122/how-to-capture-controld-signal">http://stackoverflow.com/questions/1516122/how-to-capture-controld-signal</a></p> <p>In short, Control-D at the terminal simply causes the terminal to flush th...
4
2010-01-29T15:40:32Z
[ "python", "bash", "stdin" ]
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
<p>I have the following Python script that reads numbers and outputs an error if the input is not a number.</p> <pre><code>import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) </code></pre> <p>If I g...
13
2010-01-29T15:27:55Z
2,164,353
<p>In Python 3, this was due to <a href="http://bugs.python.org/issue5505" rel="nofollow">a bug in Python's standard I/O library</a>. The bug was fixed in Python 3.3.</p> <hr> <p>In a Unix terminal, typing Ctrl+D doesn't actually close the process's stdin. But typing either Enter or Ctrl+D does cause the OS <code>rea...
11
2010-01-29T18:52:52Z
[ "python", "bash", "stdin" ]
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
<p>I have the following Python script that reads numbers and outputs an error if the input is not a number.</p> <pre><code>import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) </code></pre> <p>If I g...
13
2010-01-29T15:27:55Z
2,171,030
<p>Most likely this has to do with Python the following Python issues:</p> <ul> <li><a href="http://bugs.python.org/issue5505">5505</a>: <code>sys.stdin.read()</code> doesn't return after first EOF on Windows, and</li> <li><a href="http://bugs.python.org/issue1633941">1633941</a>: <code>for line in sys.stdin:</code> d...
9
2010-01-31T08:25:11Z
[ "python", "bash", "stdin" ]
Why do I have to press Ctrl+D twice to close stdin?
2,162,914
<p>I have the following Python script that reads numbers and outputs an error if the input is not a number.</p> <pre><code>import fileinput import sys for line in (txt.strip() for txt in fileinput.input()): if not line.isdigit(): sys.stderr.write("ERROR: not a number: %s\n" % line) </code></pre> <p>If I g...
13
2010-01-29T15:27:55Z
19,058,876
<p>Using the "for line in file:" form of reading lines from a file, Python uses a hidden read-ahead buffer (see <a href="http://docs.python.org/2.7/library/stdtypes.html#file-objects" rel="nofollow">http://docs.python.org/2.7/library/stdtypes.html#file-objects</a> at the file.next function). First of all, this explain...
0
2013-09-27T19:44:44Z
[ "python", "bash", "stdin" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,163,000
<p>Execution of C certainly is sequential, for actual statements. There are even rules that define the <a href="http://en.wikipedia.org/wiki/Sequence_point" rel="nofollow">sequence points</a>, so you can know how individual expressions evaluate. </p>
3
2010-01-29T15:39:54Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,163,019
<p>CPython itself is written in such a way that any effects like those you mention are minimized; code always executes top to bottom barring literal evaluation during compilation, objects are GCed as soon as their refcount hits 0, etc.</p>
2
2010-01-29T15:41:35Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,163,073
<p>The only thing I can think of that may surprise some people is:</p> <pre><code>def test(): try: return True finally: return False print test() </code></pre> <p>Output:</p> <pre><code>False </code></pre> <p><code>finally</code> clauses really are executed last, even if a <code>return</cod...
10
2010-01-29T15:49:24Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,163,972
<p>"if I open a file of data, read in the data, close the file, then do other stuff do I know for sure that the file is closed before the lines after I close the file are executed??"</p> <p>Closed yes.</p> <p>Released from memory. No. No guarantees about when garbage collection will occur.</p> <p>Further, closing ...
1
2010-01-29T17:55:49Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,163,991
<p>If the data consists of columns and rows, why not use the built in file iterator to fetch one line at a time?</p> <pre><code>f = open('file.txt') first_line = f.next() </code></pre>
0
2010-01-29T17:58:50Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,164,499
<p>Execution in the cpython vm is very linear. I do not think whatever problem you have has to do with order of execution.</p> <p>One thing you should be careful about in Python but not C: exceptions can be raised everywhere, so just because you see a <code>close()</code> call below the corresponding <code>open()</cod...
2
2010-01-29T19:16:55Z
[ "python", "order", "execution" ]
Python order of execution
2,162,975
<p>I was wondering if Python has similar issues as C regarding the order of execution of certain elements of code.</p> <p>For example, I know in C there are times say when it's not guaranteed that some variable is initialized before another. Or just because one line of code is above another it's not guaranteed that it...
2
2010-01-29T15:36:28Z
2,164,760
<p><a href="http://svn.python.org/view/python/tags/r25/Lib/popen2.py?view=markup#Popen4" rel="nofollow">popen2.py</a>:</p> <pre><code>class Popen4(Popen3): childerr = None def __init__(self, cmd, bufsize=-1): _cleanup() self.cmd = cmd p2cread, p2cwrite = os.pipe() c2pread, c2pw...
0
2010-01-29T19:55:57Z
[ "python", "order", "execution" ]
Signal handling in Python
2,163,194
<p>In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below:</p> <pre><code>def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') ret...
4
2010-01-29T16:06:11Z
2,163,245
<p>Mixing signals and threads is always a little precarious. What you describe should not happen, however. Python only handles signals in the main thread. If the OS delivered the signal to another thread, that thread may be briefly interrupted (when it's performing, say, a systemcall) but it won't execute the signal ha...
2
2010-01-29T16:14:33Z
[ "python", "multithreading", "signals" ]
Signal handling in Python
2,163,194
<p>In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below:</p> <pre><code>def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') ret...
4
2010-01-29T16:06:11Z
2,163,252
<p>You should probably use a threading.Condition variable instead of sending signals. Have your main thread check it every loop and perform its special operation if it's been set.</p> <p>If you insist on using signals, you'll want to move to using subprocess instead of threads, as your problem is likely due to the GIL...
0
2010-01-29T16:15:35Z
[ "python", "multithreading", "signals" ]
Signal handling in Python
2,163,194
<p>In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below:</p> <pre><code>def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') ret...
4
2010-01-29T16:06:11Z
2,176,869
<p>I'll sort-of answer my own question: In my first attempt at this I was using time.sleep(run_time) in the main thread to control how long the threads ran until they were stopped. By adding debug I could see that the sleep loop seemed to be exiting as soon as the signal handler returned so everything was shutting down...
1
2010-02-01T13:19:38Z
[ "python", "multithreading", "signals" ]
Signal handling in Python
2,163,194
<p>In my program I have a bunch of threads running and I'm trying to interrupt the main thread to get it to do something asynchronously. So I set up a handler and send the main process a SIGUSR1 - see the code below:</p> <pre><code>def SigUSR1Handler(signum, frame): self._logger.debug('Received SIGUSR1') ret...
4
2010-01-29T16:06:11Z
2,177,041
<p>Watch this presentation by David Beazley.</p> <p><a href="http://blip.tv/file/2232410" rel="nofollow">http://blip.tv/file/2232410</a></p> <p>It also explains some quirky behavior related to threads and signals (Python specific, not the general quirkiness of the subject :-) ).</p> <p><a href="http://pyprocessing.b...
0
2010-02-01T13:45:40Z
[ "python", "multithreading", "signals" ]
Timeout when using urllib2.urlopen with Django in GAE
2,163,413
<p>When I run this code</p> <pre><code>url = ('http://maps.google.com/maps/nav?'+ 'q=from%3A'+from_address+ '+to%3A'+to_address+ '&amp;output=json&amp;oe=utf8&amp;key='+api_key) request = urllib2.Request(url) response = urllib2.urlopen(request) </code></pre> <p>In a simple view in Django running ...
2
2010-01-29T16:39:25Z
2,391,148
<p>This is because App Engine has a default timeout of 5 seconds for these calls. If you use UrlFetch [1] you can use the deadline parameter to set the timeout up to a maximum of 10 seconds. If the page you are trying to get takes longer than that, you are out of luck.</p> <p>[1] <a href="http://code.google.com/appeng...
2
2010-03-06T02:38:09Z
[ "python", "django", "google-app-engine", "urllib2" ]
Timeout when using urllib2.urlopen with Django in GAE
2,163,413
<p>When I run this code</p> <pre><code>url = ('http://maps.google.com/maps/nav?'+ 'q=from%3A'+from_address+ '+to%3A'+to_address+ '&amp;output=json&amp;oe=utf8&amp;key='+api_key) request = urllib2.Request(url) response = urllib2.urlopen(request) </code></pre> <p>In a simple view in Django running ...
2
2010-01-29T16:39:25Z
23,441,194
<p>you can avoid the 10 second deadline by using googles asynchronous fetch service, which accepts deadlines of up to 60 seconds. <a href="https://developers.google.com/appengine/docs/python/urlfetch/asynchronousrequests" rel="nofollow">https://developers.google.com/appengine/docs/python/urlfetch/asynchronousrequests</...
1
2014-05-03T06:43:12Z
[ "python", "django", "google-app-engine", "urllib2" ]
Python path in environment
2,163,429
<p>I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script. </p> <p>e.g. </p> <pre><code>c:\python26\python.exe test.py $PYTHONPATH\python.exe test.py </code></pre> <p>Is there any way to have PYTHONPATH like setting ? </p>
0
2010-01-29T16:41:22Z
2,163,458
<p>The simplest thing is to add c:\python26 to you system's PATH.</p> <p>Also, depending on how you installed Python, you should be able to just use test.py on the command line.</p>
4
2010-01-29T16:46:07Z
[ "python", "windows", "scripting", "development-environment", "environment-variables" ]
Python path in environment
2,163,429
<p>I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script. </p> <p>e.g. </p> <pre><code>c:\python26\python.exe test.py $PYTHONPATH\python.exe test.py </code></pre> <p>Is there any way to have PYTHONPATH like setting ? </p>
0
2010-01-29T16:41:22Z
2,163,461
<pre><code>set PYTHON_INSTALL=D:\python26 </code></pre> <p>then:</p> <pre><code>%PYTHON_INSTALL%\python.exe test.py </code></pre> <p>You could set up the PYTHON_INSTALL var using My Computer | Advanced | Environment Variables if you want it to persist.</p> <p>EDIT: And building on the other post (put the path to Py...
3
2010-01-29T16:46:32Z
[ "python", "windows", "scripting", "development-environment", "environment-variables" ]
Python path in environment
2,163,429
<p>I want to call a python script from batch script, but I dont want to hard-code path to python executable (python.exe) in my calling script. </p> <p>e.g. </p> <pre><code>c:\python26\python.exe test.py $PYTHONPATH\python.exe test.py </code></pre> <p>Is there any way to have PYTHONPATH like setting ? </p>
0
2010-01-29T16:41:22Z
2,163,462
<p>Try</p> <pre><code>set PYTHONPATH=c:\python26 %PYTHONPATH%\python.exe test.py </code></pre> <p>Or</p> <pre><code>set PATH=%PATH%;C:\python26; python test.py </code></pre> <p><strong>Note</strong>: environment variable <strong>PYTHONPATH</strong> has different purpose for searching python modules/extensions, So s...
0
2010-01-29T16:46:38Z
[ "python", "windows", "scripting", "development-environment", "environment-variables" ]
Running external subprocesses and reading return code
2,163,579
<p>I'm creating a python script to sort a lot of images (game screenshots).</p> <p>I found a way to do that in imagemagick : I know that, if a specific square of the image is the same as the reference crop, then the image is of category one. If not, I check for another crop and another category, and if that doesn't fi...
1
2010-01-29T17:02:59Z
2,163,675
<pre><code>import subprocess retcode = subprocess.call(['convert', 'file.jpg', '-crop', '80x10+90+980', '+repage', 'crop.jpg']) if retcode != 0: print 'error on convert' else: retcode = subprocess.call(['compare', '-metric', 'PSNR', 'reference.jpg', '...
4
2010-01-29T17:15:09Z
[ "python", "process", "subprocess", "return", "popen" ]
Python: subprocess loops forever
2,163,582
<p>I'm trying to start/stop <code>rsyslog</code> through a python script:</p> <pre><code>RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd' subprocess.call([RSYSLOG_INIT_SCRIPT,'stop']) </code></pre> <p><code>/etc/init.d/rsyslogd</code> is a regular init script. The problem is that it continues executing this script again an...
0
2010-01-29T17:03:13Z
2,163,633
<p>Are you sure the script isn't looping itself? The python code looks like it's just waiting for the sub-process to exit.</p> <p>Get the PID of the python script, then do:</p> <pre><code>watch pstree -ap &lt;PID&gt; </code></pre> <p>Look to see if the PID of the start/stop script is the same - maybe the python code...
0
2010-01-29T17:10:14Z
[ "python", "subprocess", "rsyslog" ]
Python: subprocess loops forever
2,163,582
<p>I'm trying to start/stop <code>rsyslog</code> through a python script:</p> <pre><code>RSYSLOG_INIT_SCRIPT='/etc/init.s/rsyslogd' subprocess.call([RSYSLOG_INIT_SCRIPT,'stop']) </code></pre> <p><code>/etc/init.d/rsyslogd</code> is a regular init script. The problem is that it continues executing this script again an...
0
2010-01-29T17:03:13Z
2,163,660
<p>Not sure what is going on, but try creating your shell script like this:</p> <pre><code>#!/bin/sh while : do echo "Sleeping..." sleep 1 done </code></pre> <p>Then confirm that your python program when running this script does the same thing.</p> <p>Then confirm the python call with this script:</p> <pre>...
1
2010-01-29T17:13:25Z
[ "python", "subprocess", "rsyslog" ]
How can I run a loop against 2 random elements from a list at a time?
2,163,765
<p>Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string? </p> <p>What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for th...
2
2010-01-29T17:26:20Z
2,163,786
<p>you need to look into <a href="http://docs.python.org/library/random.html" rel="nofollow"><code>random</code></a> module. It has for example a <code>random.choice</code> function that lets you select a random element from a sequence or a <a href="http://docs.python.org/library/random.html#random.sample" rel="nofollo...
4
2010-01-29T17:29:21Z
[ "python", "probability" ]
How can I run a loop against 2 random elements from a list at a time?
2,163,765
<p>Let's say I have a list in python with several strings in it. I do not know the size. How can I run a loop to do an operation on 2 random elements of this string? </p> <p>What if I wanted to favour a certain subset of the strings in this randomization, to be selected more often, but still make it possible for th...
2
2010-01-29T17:26:20Z
2,163,823
<p>explain better your problem, what operations and what elements you're focusing?</p> <p>regarding the problem with the elements beeing chosen more often, give each string an "chance multiplier", each comparison you multiply a number between 1 and 10 and the chance multiplyer of the string, if the result is higher th...
0
2010-01-29T17:33:42Z
[ "python", "probability" ]
Check if a file is setuid root in Python
2,163,800
<p>I'm trying to check if a file has the setuid bit in Python.</p> <p><a href="http://docs.python.org/library/stat.html" rel="nofollow">The stat doc</a> mentions a <code>S_ISUID</code> function but it only works with <code>os.chmod()</code>, not to actually read the setuid bit. It also lists <code>S_IMODE</code>, but ...
1
2010-01-29T17:31:02Z
2,163,835
<p>stat.S_ISUID is the mode bit for 'setuid'. You compare the stat result's mode to see if it contains that bit:</p> <pre><code>&gt;&gt;&gt; ping = os.stat('/bin/ping') &gt;&gt;&gt; ping.st_mode &amp; stat.S_ISUID 2048 &gt;&gt;&gt; echo = os.stat('/bin/echo') &gt;&gt;&gt; echo.st_mode &amp; stat.S_ISUID 0 </code></pre...
6
2010-01-29T17:35:12Z
[ "python", "file", "setuid", "stat" ]
Can I write browser plugins with Python?
2,163,816
<p>I'm thinking about writing a browser plugin, but I don't know any C. Can I write browser plugins with Java or Python?</p> <p>I was thinking... All those websites store cookies on my browser to identify me. If I wrote a plugin that would supply a browser GUID in the http headers, webservers could identify the browse...
3
2010-01-29T17:32:51Z
2,164,271
<p>You can certainly write an ActiveX plugin for IE in Python using the win32com interfaces. But you'd have to install Python and <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> along with your plugin for it to work, so it'd be pretty bulky. I don't think it's going to be popular to instal...
1
2010-01-29T18:40:41Z
[ "java", "python", "browser-plugin" ]
Best way to make Django's login_required the default
2,164,069
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
73
2010-01-29T18:08:37Z
2,164,175
<p>You can't really win this. You simply <em>must</em> make a declaration of the authorization requirements. Where else would you put this declaration except right by the view function?</p> <p>Consider replacing your view functions with callable objects.</p> <pre><code>class LoginViewFunction( object ): def __...
0
2010-01-29T18:22:40Z
[ "python", "django" ]
Best way to make Django's login_required the default
2,164,069
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
73
2010-01-29T18:08:37Z
2,164,224
<p>Middleware may be your best bet. I've used this piece of code in the past, modified from a snippet found elsewhere:</p> <pre><code>import re from django.conf import settings from django.contrib.auth.decorators import login_required class RequireLoginMiddleware(object): """ Middleware component that wrap...
76
2010-01-29T18:33:20Z
[ "python", "django" ]
Best way to make Django's login_required the default
2,164,069
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
73
2010-01-29T18:08:37Z
2,164,750
<p>It's hard to change the built-in assumptions in Django without reworking the way url's are handed off to view functions.</p> <p>Instead of mucking about in Django internals, here's an audit you can use. Simply check each view function.</p> <pre><code>import os import re def view_modules( root ): for path, di...
2
2010-01-29T19:54:09Z
[ "python", "django" ]
Best way to make Django's login_required the default
2,164,069
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
73
2010-01-29T18:08:37Z
2,165,855
<p>There is an alternative to putting a decorator on each view function. You can also put the <code>login_required()</code> decorator in the <code>urls.py</code> file. While this is still a manual task, at least you have it all in one place, which makes it easier to audit.</p> <p>e.g.,</p> <pre> from my_views imp...
24
2010-01-29T23:07:47Z
[ "python", "django" ]
Best way to make Django's login_required the default
2,164,069
<p>I'm working on a large Django app, the vast majority of which requires a login to access. This means that all throughout our app we've sprinkled:</p> <pre><code>@login_required def view(...): </code></pre> <p>That's fine, and it works great <em>as long as we remember to add it everywhere</em>! Sadly sometimes we...
73
2010-01-29T18:08:37Z
23,164,811
<p>Inspired by Ber's answer I wrote a little snippet that replaces the <code>patterns</code> function, by wrapping all of the URL callbacks with the <code>login_required</code> decorator. This works in Django 1.6.</p> <pre><code>def login_required_patterns(*args, **kw): for pattern in patterns(*args, **kw): ...
1
2014-04-19T01:38:59Z
[ "python", "django" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,421
<p>Do it in two passes: first count how many total files/folders are in the tree, and then during the second pass do actual processing.</p>
2
2010-01-29T19:04:24Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,511
<p>You need to know the total number of files to do a meaningful progress indicator.<br> You can get the number of files like this</p> <pre><code>len(list(os.walk(os.path.abspath(root)))) </code></pre> <p>but that is going to take some time and you probably need a progress indicator for that...</p> <p>To find the nu...
0
2010-01-29T19:19:28Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,595
<p>It depends!</p> <p>If the files and directories are distributed more or less evenly you could show rough process by assuming every toplevel directory is going to take the same amount of time. But if they are not distributed evenly you cannot find out about it cheaply. You either have to know roughly how populated e...
5
2010-01-29T19:29:35Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,691
<p>Just show an indeterminate progress bar (i.e. the ones that show a blob bouncing back and forth or the barber pole effect). That way users know that the program is doing something useful but doesn't mislead them as far as time to complete and such.</p>
4
2010-01-29T19:45:51Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,893
<p>I suggest you avoid walking the directory. Instead use an indexed-based app for quickly finding files. You can use the app's command-line interface via subprocess and find the files almost instantaneously.</p> <p>On Windows, see <a href="http://www.voidtools.com/" rel="nofollow">Everything</a>. On UNIX, check ou...
0
2010-01-29T20:22:21Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,937
<p>as I said in the comment, the performance bottle neck likely lies outside of the <code>locate</code> function. your <code>returnMatches</code> is a fairly expensive function. I think you'd be better off replacing it with the following code:</p> <pre><code>def locate(filelist, root=os.curdir) fileset = set(filel...
0
2010-01-29T20:30:52Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,164,941
<p>Thinking out of the box here...what if you did it based on <strong><em>size</em></strong>:</p> <ul> <li>Use <strong>subprocess</strong> to run 'du -sb' and get the total_size of your root directory</li> <li>As you walk, check the size of each file and decrement from your total_size (giving you remaining_size)</li> ...
0
2010-01-29T20:31:46Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,165,062
<p>I figured this out.</p> <p>I used os.listdir to get a list of toplevel directories, and then used the .split function on the path that os.walk returned, returning the first level directory that it was currently in.</p> <p>That left me with a list of toplevel directories, which I could find the index of the current...
3
2010-01-29T20:49:52Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,165,093
<p>One optimisation you could do - you are converting filelist into a set on every call to returnMatches, even though it never changes. move the conversion to the start of the 'locate' function and pass the set in on every iteration.</p>
0
2010-01-29T20:54:43Z
[ "python", "os.walk" ]
How to get progress of os.walk in python?
2,164,391
<p>I have a piece of code which I'm using to search for the executables of game files and returning the directories. I would really like to get some sort of progress indicator as to how far along <code>os.walk</code> is. How would I accomplish such a thing?</p> <p>I tried doing <code>startpt = root.count(os.sep)</co...
9
2010-01-29T18:58:26Z
2,165,324
<p>Well, this was fun. Here is another silly way of doing it, but as everything else, it only calculates the right progress for uniform paths.</p> <pre><code>import os, sys, time def calc_progress(progress, root, dirs): prog_start, prog_end, prog_slice = 0.0, 1.0, 1.0 current_progress = 0.0 parent_path, ...
0
2010-01-29T21:36:09Z
[ "python", "os.walk" ]
Reprojecting polar to cartesian grid
2,164,570
<p>I have a polar (r,theta) grid (which means that each cell is an annulus section) containing values of some physical quantity (e.g. temperature), and I would like to re-grid (or re-project) these values onto a cartesian grid. Are there any Python packages that can do this?</p> <p>I am not interested in converting th...
13
2010-01-29T19:26:16Z
2,165,351
<p>Thanks for your answers - after thinking a bit more about this I came up with the following code:</p> <pre><code>import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as mpl from scipy.interpolate import interp1d from scipy.ndimage import map_coordinates def polar2cartesian(r, t, g...
6
2010-01-29T21:40:44Z
[ "python", "image" ]
Reprojecting polar to cartesian grid
2,164,570
<p>I have a polar (r,theta) grid (which means that each cell is an annulus section) containing values of some physical quantity (e.g. temperature), and I would like to re-grid (or re-project) these values onto a cartesian grid. Are there any Python packages that can do this?</p> <p>I am not interested in converting th...
13
2010-01-29T19:26:16Z
2,418,537
<p>You can do this more compactly with <code>scipy.ndimage.geometric_transform</code>. Here is some sample code:</p> <pre><code>import numpy as N import scipy as S import scipy.ndimage temperature = &lt;whatever&gt; # This is the data in your polar grid. # The 0th and 1st axes correspond to r and θ, respectively. #...
3
2010-03-10T16:20:50Z
[ "python", "image" ]
Reprojecting polar to cartesian grid
2,164,570
<p>I have a polar (r,theta) grid (which means that each cell is an annulus section) containing values of some physical quantity (e.g. temperature), and I would like to re-grid (or re-project) these values onto a cartesian grid. Are there any Python packages that can do this?</p> <p>I am not interested in converting th...
13
2010-01-29T19:26:16Z
16,695,217
<p>I came to this post some time ago when trying to do something similar, this is, reprojecting polar data into a cartesian grid and vice-versa. The solution proposed here works fine. However, it takes some time to perform the coordinate transform. I just wanted to share another approach which can reduce the processing...
1
2013-05-22T15:00:17Z
[ "python", "image" ]
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?
2,164,767
<p>In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?</p> <p>e.g.:</p> <pre> def Factotum(models.Model): id_ref = models.IntegerField() def calculateSeniorityFactor(): return (1000 - id_ref) * 1000 </pre> <p>I want to b...
14
2010-01-29T19:56:53Z
2,164,802
<p>Well, things you can introspect are many, not just one.</p> <p>Good things to start with are:</p> <pre><code>&gt;&gt;&gt; help(object) &gt;&gt;&gt; dir(object) &gt;&gt;&gt; object.__dict__ </code></pre> <p>Also take a look at the inspect module in the standard library.</p> <p>That should make 99% of all the base...
27
2010-01-29T20:06:01Z
[ "python", "django" ]
In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?
2,164,767
<p>In python django how do you print out an object's inrospection? The list of all public methods of that object (variable and/or functions)?</p> <p>e.g.:</p> <pre> def Factotum(models.Model): id_ref = models.IntegerField() def calculateSeniorityFactor(): return (1000 - id_ref) * 1000 </pre> <p>I want to b...
14
2010-01-29T19:56:53Z
2,165,398
<p>Use <a href="http://docs.python.org/library/inspect.html?highlight=inspect#inspect.getmembers">inspect</a>:</p> <pre><code>import inspect def introspect(something): methods = inspect.getmembers(something, inspect.ismethod) others = inspect.getmembers(something, lambda x: not inspect.ismethod(x)) print 'Variab...
6
2010-01-29T21:48:14Z
[ "python", "django" ]
Am I passing the string correctly to the python library?
2,164,899
<p>I'm using a python library called Guess Language: <a href="http://pypi.python.org/pypi/guess-language/0.1" rel="nofollow">http://pypi.python.org/pypi/guess-language/0.1</a></p> <p>"justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japa...
-1
2010-01-29T20:23:12Z
2,165,205
<p>It looks like you should be able to pass your unicode as-is. <code>guessLanguage</code> decodes an input that is <code>str</code> as utf-8. So your <code>.encode('utf-8')</code> is safe but unnecessary.</p> <p>I skimmed the source code and assumed it relies exclusively on the data in its "trigrams" directory for la...
0
2010-01-29T21:14:47Z
[ "python", "unicode", "encoding", "nlp" ]
Am I passing the string correctly to the python library?
2,164,899
<p>I'm using a python library called Guess Language: <a href="http://pypi.python.org/pypi/guess-language/0.1" rel="nofollow">http://pypi.python.org/pypi/guess-language/0.1</a></p> <p>"justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japa...
-1
2010-01-29T20:23:12Z
2,165,936
<p>Looking at the main page, it says """Detects over 60 languages; Greek (el), Korean (ko), Japanese (ja), Chinese (zh) and all the languages listed in the trigrams directory. """</p> <p>It doesn't use trigrams for those 4 languages; it relies on what script blocks are present in the input text. Looking at the source ...
7
2010-01-29T23:21:40Z
[ "python", "unicode", "encoding", "nlp" ]
Am I passing the string correctly to the python library?
2,164,899
<p>I'm using a python library called Guess Language: <a href="http://pypi.python.org/pypi/guess-language/0.1" rel="nofollow">http://pypi.python.org/pypi/guess-language/0.1</a></p> <p>"justwords" is a string with unicode text. I stick it in the package, but it always returns English, even though the web page is in Japa...
-1
2010-01-29T20:23:12Z
2,179,762
<p>Google says your example is in chinese. They have a (much more advanced) <a href="http://translate.google.com/#" rel="nofollow">webservice</a> to translate text and guess the language.</p> <p>They have an <a href="http://code.google.com/apis/ajaxlanguage/documentation/#Detect" rel="nofollow">API</a> and <a href="ht...
-1
2010-02-01T20:18:38Z
[ "python", "unicode", "encoding", "nlp" ]
Replacing one character of a string in python
2,165,172
<p>In python, are strings mutable? The line <code>someString[3] = "a"</code> throws the error </p> <blockquote> <p>TypeError: 'str' object does not support item assignment</p> </blockquote> <p>I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method...
7
2010-01-29T21:09:33Z
2,165,206
<p>Python strings are immutable, and so they do not support item or slice assigment. You'll have to build a new string using i.e. <code>someString[:3] + 'a' + someString[4:]</code> or some other suitable approach.</p>
12
2010-01-29T21:14:51Z
[ "python" ]
Replacing one character of a string in python
2,165,172
<p>In python, are strings mutable? The line <code>someString[3] = "a"</code> throws the error </p> <blockquote> <p>TypeError: 'str' object does not support item assignment</p> </blockquote> <p>I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method...
7
2010-01-29T21:09:33Z
2,165,236
<p>Instead of storing your value as a string, you could use a list of characters:</p> <pre><code>&gt;&gt;&gt; l = list('foobar') &gt;&gt;&gt; l[3] = 'f' &gt;&gt;&gt; l[5] = 'n' </code></pre> <p>Then if you want to convert it back to a string to display it, use this:</p> <pre><code>&gt;&gt;&gt; ''.join(l) 'foofan' </...
7
2010-01-29T21:20:02Z
[ "python" ]
Replacing one character of a string in python
2,165,172
<p>In python, are strings mutable? The line <code>someString[3] = "a"</code> throws the error </p> <blockquote> <p>TypeError: 'str' object does not support item assignment</p> </blockquote> <p>I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method...
7
2010-01-29T21:09:33Z
2,165,263
<p>In new enough pythons you can also use the builtin <code>bytearray</code> type, which is mutable. See the stdlib documentation. But "new enough" here means 2.6 or up, so that's not necessarily an option.</p> <p>In older pythons you have to create a fresh <code>str</code> as mentioned above, since those are immutabl...
2
2010-01-29T21:24:18Z
[ "python" ]
Replacing one character of a string in python
2,165,172
<p>In python, are strings mutable? The line <code>someString[3] = "a"</code> throws the error </p> <blockquote> <p>TypeError: 'str' object does not support item assignment</p> </blockquote> <p>I can see why (as I could have written someString[3] = "test" and that would obviously be illegal) but is there a method...
7
2010-01-29T21:09:33Z
26,172,552
<pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; s = "1234567890" &gt;&gt;&gt; mutable = ctypes.create_string_buffer(s) &gt;&gt;&gt; mutable[3] = "a" &gt;&gt;&gt; print mutable.value 123a567890 </code></pre>
0
2014-10-03T02:41:31Z
[ "python" ]
Modifying a Python class
2,165,200
<p>I'd like to modify all classes in Python. For example str and int and others like Person(object).</p> <p>I'd like to add an attribute to them and to change the way its methods works.</p> <p>Which is the best approach for this? Metaclasses?</p>
2
2010-01-29T21:13:54Z
2,165,257
<p>You can't edit the class directly like you might with javascript's prototype attribute, it's better if you subclass them. This let's you add the functionality you want and not force it to be used everywhere.</p>
0
2010-01-29T21:23:24Z
[ "python", "metaclass" ]
Modifying a Python class
2,165,200
<p>I'd like to modify all classes in Python. For example str and int and others like Person(object).</p> <p>I'd like to add an attribute to them and to change the way its methods works.</p> <p>Which is the best approach for this? Metaclasses?</p>
2
2010-01-29T21:13:54Z
2,165,347
<p>Built-in classes can't be modified, but you can "hide" a built-in class (or any other of course) by one of the same name.</p> <p>For example, suppose that the change is to add to a bunch of classes a new attribute "foobar" whose initial value is 23, and to every <em>instance</em> of those classes a new attribute "m...
1
2010-01-29T21:39:55Z
[ "python", "metaclass" ]
Modifying a Python class
2,165,200
<p>I'd like to modify all classes in Python. For example str and int and others like Person(object).</p> <p>I'd like to add an attribute to them and to change the way its methods works.</p> <p>Which is the best approach for this? Metaclasses?</p>
2
2010-01-29T21:13:54Z
2,165,399
<p>While you can do this for classes defined in python code (it will not work for builtin ones) by reassigning their attributes please do not actually do so. Just subclass and use the subclass, or write functions that take an instance of the class as argument instead of adding your own methods. Doing what you have to m...
3
2010-01-29T21:48:20Z
[ "python", "metaclass" ]
Modifying a Python class
2,165,200
<p>I'd like to modify all classes in Python. For example str and int and others like Person(object).</p> <p>I'd like to add an attribute to them and to change the way its methods works.</p> <p>Which is the best approach for this? Metaclasses?</p>
2
2010-01-29T21:13:54Z
2,165,617
<p>subclass:</p> <pre><code> class int(int): def foo(self): print "foo" int(2).foo() </code></pre>
0
2010-01-29T22:25:17Z
[ "python", "metaclass" ]
How to force python's VM to print a stack trace?
2,165,202
<p>I'm dealing with a python-written server that locks up, and stops working, including logging. I wonder if there's a python equivalent to java's "kill -3" signal that at least prints the current stacktrace.</p>
4
2010-01-29T21:14:24Z
2,165,260
<p>You can find a (Unix-only) solution in <a href="http://stackoverflow.com/questions/132058/getting-stack-trace-from-a-running-python-application">this question</a>.</p>
0
2010-01-29T21:23:57Z
[ "python", "debugging" ]
How to force python's VM to print a stack trace?
2,165,202
<p>I'm dealing with a python-written server that locks up, and stops working, including logging. I wonder if there's a python equivalent to java's "kill -3" signal that at least prints the current stacktrace.</p>
4
2010-01-29T21:14:24Z
2,165,302
<pre><code>import signal, traceback def quit_handler(signum,frame): traceback.print_stack() signal.signal(signal.SIGQUIT,quit_handler) </code></pre>
2
2010-01-29T21:32:33Z
[ "python", "debugging" ]
How to force python's VM to print a stack trace?
2,165,202
<p>I'm dealing with a python-written server that locks up, and stops working, including logging. I wonder if there's a python equivalent to java's "kill -3" signal that at least prints the current stacktrace.</p>
4
2010-01-29T21:14:24Z
21,122,891
<p>Use the <strong>faulthandler</strong> module. <a href="https://pypi.python.org/pypi/faulthandler/" rel="nofollow">https://pypi.python.org/pypi/faulthandler/</a></p> <pre><code>import faulthandler faulthandler.register(signal.SIGUSR1) </code></pre> <p>This works outside of Python's interpreter loop's signal handli...
3
2014-01-14T20:03:53Z
[ "python", "debugging" ]
Custom address field in Django Model
2,165,252
<p>What's the common practice to represent postal addresses in Django models? Is there a library for custom model fields that include postal address fields and potentially handle validation and formatting?</p> <p>If no library exists, how can I write one? Can I represent a composite field (a field that gets serializ...
4
2010-01-29T21:22:54Z
2,165,319
<p>I don't know of a single form field for addresses, but you can use <a href="https://docs.djangoproject.com/en/1.5/ref/contrib/localflavor/" rel="nofollow"><code>localflavor</code></a> to validate the input and a combo of <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.MultiWidget" rel="...
6
2010-01-29T21:35:28Z
[ "python", "django", "django-models", "field" ]
After handshake of websocket, chrome disconnects. Is this due to domain mismatch? Or Chrome bug?
2,165,308
<p>I made my own simple WebSocket server in Python but Chrome 4.0.249.78 dev (36714) ALWAYS disconnects after the handshake. To make sure it wasn't my code I used the WebSocket server found at <a href="http://stackoverflow.com/questions/2153294?tab=newest#tab-top">http://stackoverflow.com/questions/2153294?tab=newest#t...
3
2010-01-29T21:33:23Z
2,167,089
<p>I upgraded Chrome to a new build (4.0.302.3 dev) and now I am getting proper javascript errors in the console. It was indeed a domain mismatch error.</p> <p>To anyone else getting this same issue, make sure to update your browser first and then check your urls.</p>
2
2010-01-30T06:35:31Z
[ "javascript", "python", "google-chrome", "websocket" ]
Multiplying a subset of a list of integers together in python
2,165,449
<p>Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)</p>
3
2010-01-29T21:57:24Z
2,165,471
<p>Lot's of ways. Here's one:</p> <pre><code>&gt;&gt;&gt; a = range(1,10) &gt;&gt;&gt; reduce(lambda x,y: x*y, a[:5]) 120 </code></pre>
4
2010-01-29T22:01:07Z
[ "python" ]
Multiplying a subset of a list of integers together in python
2,165,449
<p>Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)</p>
3
2010-01-29T21:57:24Z
2,165,472
<h3>Using reduce:</h3> <pre><code>reduce(lambda x, y: x*y, mylist[:5]) </code></pre> <p>e.g., </p> <pre><code>&gt;&gt;&gt; reduce(lambda x,y:x*y, range(1,5)) 24 </code></pre> <p>the <code>reduce()</code> function applies the given function (here, multiplication) over the first two items of the list, hereby reducing...
0
2010-01-29T22:01:10Z
[ "python" ]
Multiplying a subset of a list of integers together in python
2,165,449
<p>Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)</p>
3
2010-01-29T21:57:24Z
2,165,481
<pre><code>import operator l = [1, 2, 3, 4, 5, 6, 7, 8, 9] print reduce(operator.mul, [v for (k, v,) in enumerate(l) if k &lt; 5]) &gt;&gt; 120 </code></pre> <p>Edit: Better way to do it</p> <pre><code>print reduce(operator.mul, l[:5]) &gt;&gt; 120 </code></pre>
9
2010-01-29T22:03:09Z
[ "python" ]
Multiplying a subset of a list of integers together in python
2,165,449
<p>Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)</p>
3
2010-01-29T21:57:24Z
2,165,602
<p>When there are many ways to do something, I turn to criteria such as readability or speed to decide which code to use. Here is some code which suggests that <code>use_loop</code> and <code>use_reduce</code> are roughly tied in terms of speed (at least for the values tested!)</p> <pre><code>import operator import it...
2
2010-01-29T22:21:54Z
[ "python" ]
Multiplying a subset of a list of integers together in python
2,165,449
<p>Let's say I have a list of 10 integers and I want the result of multiplying the first 5 together. Is there a pythonic way of doing this? Python seems to be great with lists :)</p>
3
2010-01-29T21:57:24Z
15,283,765
<p>This is a simple function that will do what you want.</p> <pre><code>def multiply(args): x= 1 for arg in args: x*= arg return x l = [1, 2, 3, 4, 5, 6, 7, 8, 9] multiply(l) &gt;&gt;&gt;362880 multiply(l[:5]) &gt;&gt;&gt;120 </code></pre>
0
2013-03-07T23:17:41Z
[ "python" ]
How do I retrieve Hotmail contacts with python
2,165,517
<p>How can I retrieve contacts from hotmail with python?</p> <p>Is there any example?</p>
2
2010-01-29T22:08:57Z
2,165,533
<p>Hotmail: <a href="http://msdn.microsoft.com/en-us/library/bb463989.aspx" rel="nofollow">Windows Live Contacts API</a></p> <p>If a python interface doesn't exist you may have to resort to screen scraping.</p>
1
2010-01-29T22:11:28Z
[ "python", "hotmail" ]
How do I retrieve Hotmail contacts with python
2,165,517
<p>How can I retrieve contacts from hotmail with python?</p> <p>Is there any example?</p>
2
2010-01-29T22:08:57Z
2,458,380
<p>use octazen, but you have to pay for it</p>
0
2010-03-16T21:43:19Z
[ "python", "hotmail" ]
How do I retrieve Hotmail contacts with python
2,165,517
<p>How can I retrieve contacts from hotmail with python?</p> <p>Is there any example?</p>
2
2010-01-29T22:08:57Z
2,495,176
<p>IIRC Hotmail has POP access, so just use the <a href="http://docs.python.org/library/poplib.html" rel="nofollow">poplib</a> library.</p> <p>Usage is something like this (NOT tested):</p> <pre><code>hotmail = poplib.POP3_SSL('pop3.live.com', 995) hotmail.user(USERNAME) hotmail.pass_(PASSWORD) message_count = len(h...
-1
2010-03-22T19:43:12Z
[ "python", "hotmail" ]
What does this Openid error mean: Error attempting to use stored discovery information
2,165,809
<p>I'm attempting to setup an app using django-openid and openid. I'm getting the following errors and I can't figure out what is causing them.</p> <pre><code>[Fri Jan 29 13:29:20 2010] [error] Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication XXXXXXXXXXXXXX [Fri Jan 29 13:29...
4
2010-01-29T22:57:36Z
2,166,089
<p>Hmm. That's actually not a fatal error; I get the same thing when using the python-openid consumer example against google's OP Identifier (the /accounts/o8/id one that generates the funny directed identifiers), but it successfully logs in. </p> <p>That probably causes some log spam if you have a "log in with goog...
0
2010-01-29T23:51:17Z
[ "python", "openid", "django-openid-auth" ]
What does this Openid error mean: Error attempting to use stored discovery information
2,165,809
<p>I'm attempting to setup an app using django-openid and openid. I'm getting the following errors and I can't figure out what is causing them.</p> <pre><code>[Fri Jan 29 13:29:20 2010] [error] Generated checkid_setup request to https://www.google.com/accounts/o8/ud with assocication XXXXXXXXXXXXXX [Fri Jan 29 13:29...
4
2010-01-29T22:57:36Z
26,221,410
<p>This happens when the URL given is the server's URL, instead of the Claimed Identifier. It's a genuine error for the pathway that generates it, because the URL can't be used as an identifier, but it gets caught internally and used to request a true identifier from the server, so it's safe to ignore the log messages...
0
2014-10-06T17:21:14Z
[ "python", "openid", "django-openid-auth" ]
What would be the jquery equivalent of 'Dive into python'?
2,165,811
<p>I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery?</p> <p>I see that jquery 1.4 has been released. Does this change anything w.r.t answers?</p>
2
2010-01-29T22:58:06Z
2,165,829
<p><a href="http://docs.jquery.com/Main_Page" rel="nofollow">jQuery's main documentation</a> is quite good. You might start with <a href="http://docs.jquery.com/Tutorials%3aHow_jQuery_Works" rel="nofollow">How jQuery works</a>.<br> If you have a certain problem and you google for it, you mostly find plenty of tutorials...
1
2010-01-29T23:02:54Z
[ "javascript", "jquery", "python" ]
What would be the jquery equivalent of 'Dive into python'?
2,165,811
<p>I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery?</p> <p>I see that jquery 1.4 has been released. Does this change anything w.r.t answers?</p>
2
2010-01-29T22:58:06Z
2,165,832
<p>Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery:</p> <p>This book should be a required read for front end devs:</p> <p><a href="http://rads.stackoverflow.com/amzn/click/0596517742" rel="nofollow">JavaScript: The Good Parts by Douglas Crockfo...
4
2010-01-29T23:03:21Z
[ "javascript", "jquery", "python" ]
Removing html tags from a text using Regular Expression in python
2,165,943
<p>I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far.</p> <pre><code>import urllib.request, re def test(url): html = str(urllib.request.urlopen(url).read()) print(re.findall('&lt;[\w\/\.\w]*&gt;',html)) </c...
6
2010-01-29T23:22:10Z
2,166,133
<p>Use <a href="http://stackoverflow.com/questions/tagged/beautifulsoup">BeautifulSoup</a>. Use <a href="http://stackoverflow.com/questions/tagged/lxml">lxml</a>. Do not use <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">regular expressions</a...
13
2010-01-30T00:01:34Z
[ "python", "html", "regex", "tags" ]
Removing html tags from a text using Regular Expression in python
2,165,943
<p>I'm trying to look at a html file and remove all the tags from it so that only the text is left but I'm having a problem with my regex. This is what I have so far.</p> <pre><code>import urllib.request, re def test(url): html = str(urllib.request.urlopen(url).read()) print(re.findall('&lt;[\w\/\.\w]*&gt;',html)) </c...
6
2010-01-29T23:22:10Z
2,166,245
<pre><code>import re patjunk = re.compile("&lt;.*?&gt;|&amp;nbsp;|&amp;amp;",re.DOTALL|re.M) url="http://www.yahoo.com" def test(url,pat): html = urllib2.urlopen(url).read() return pat.sub("",html) print test(url,patjunk) </code></pre>
-1
2010-01-30T00:29:14Z
[ "python", "html", "regex", "tags" ]
Python: namedtuple._replace() doesn't work as descrbed in the documentation
2,166,147
<p>I was having trouble implementing <code>namedtuple._replace()</code>, so I copied the code right off of the documentation:</p> <pre><code>Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p </code></pre> <p>and I got:</p> <pre><code>Point(x=11, y=22) </code></pre> <p>instead of:<...
19
2010-01-30T00:03:53Z
2,166,158
<p><a href="http://docs.python.org/library/collections.html#collections.somenamedtuple._replace"><code>namedtuple._replace()</code></a> returns a new tuple; the original is unchanged.</p>
8
2010-01-30T00:07:17Z
[ "python", "namedtuple" ]
Python: namedtuple._replace() doesn't work as descrbed in the documentation
2,166,147
<p>I was having trouble implementing <code>namedtuple._replace()</code>, so I copied the code right off of the documentation:</p> <pre><code>Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p </code></pre> <p>and I got:</p> <pre><code>Point(x=11, y=22) </code></pre> <p>instead of:<...
19
2010-01-30T00:03:53Z
2,166,160
<p>A tuple is immutable. <code>_replace()</code> returns a new tuple with your modifications:</p> <pre><code>p = p._replace(x=33) </code></pre>
10
2010-01-30T00:07:24Z
[ "python", "namedtuple" ]
Python: namedtuple._replace() doesn't work as descrbed in the documentation
2,166,147
<p>I was having trouble implementing <code>namedtuple._replace()</code>, so I copied the code right off of the documentation:</p> <pre><code>Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p </code></pre> <p>and I got:</p> <pre><code>Point(x=11, y=22) </code></pre> <p>instead of:<...
19
2010-01-30T00:03:53Z
2,166,161
<p>Yes it does, it works exactly as documented.</p> <p><code>._replace</code> <em>returns</em> a new namedtuple, it does not modify the original, so you need to write this:</p> <pre><code>p = p._replace(x=33) </code></pre> <p>See here: <a href="http://docs.python.org/dev/library/collections.html#collections.somename...
50
2010-01-30T00:07:43Z
[ "python", "namedtuple" ]
Python: namedtuple._replace() doesn't work as descrbed in the documentation
2,166,147
<p>I was having trouble implementing <code>namedtuple._replace()</code>, so I copied the code right off of the documentation:</p> <pre><code>Point = namedtuple('Point', 'x,y') p = Point(x=11, y=22) p._replace(x=33) print p </code></pre> <p>and I got:</p> <pre><code>Point(x=11, y=22) </code></pre> <p>instead of:<...
19
2010-01-30T00:03:53Z
2,166,175
<p>It looks to me as if namedtuple is immutable, like its forebear, tuple.</p> <pre><code>&gt;&gt;&gt; from collections import namedtuple &gt;&gt;&gt; Point = namedtuple('Point', 'x,y') &gt;&gt;&gt; &gt;&gt;&gt; p = Point(x=11, y=22) &gt;&gt;&gt; &gt;&gt;&gt; p._replace(x=33) Point(x=33, y=22) &gt;&gt;&gt; print(p) Po...
6
2010-01-30T00:11:37Z
[ "python", "namedtuple" ]
New to Python; Beginners Project ideas
2,166,180
<p>I am new to python, This Project is a Free user-contributed multilingual dictionary, Located <a href="http://github.com/klanestro/vortaro" rel="nofollow">http://github.com/klanestro/vortaro</a> I have a few Ideas that I would use php But don't know where to start studying. </p> <p>Like in this code </p> <ol> <li...
1
2010-01-30T00:12:57Z
2,166,200
<p>This is a <a href="http://www.djangoproject.com/" rel="nofollow">Django</a> project; I recommend going through the <a href="http://docs.python.org/tutorial/index.html" rel="nofollow">Python tutorial</a> a few times before getting your hands dirty with <a href="http://docs.djangoproject.com/en/1.1/" rel="nofollow">Dj...
4
2010-01-30T00:17:18Z
[ "python" ]
What vim plugins mix results in this interface
2,166,201
<p>I saw this VIM UI and thought it was awesome and now I want it. Anyone know what plugins the author is using?</p> <p><a href="http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4" rel="nofollow">http://werkzeug.pocoo.org/wiki30/files/wiki30.mp4</a></p>
0
2010-01-30T00:17:36Z
2,168,896
<p>A bit dated, but this is his blog post that I was referring to: <a href="http://lucumr.pocoo.org/2007/4/2/vim-as-development-environment" rel="nofollow">Vim as Development Environment</a></p>
0
2010-01-30T18:23:35Z
[ "python", "ide", "plugins", "vim" ]
Windows live api for python
2,166,232
<p>I have read documentation about Windows Live API: <a href="http://msdn.microsoft.com/en-us/library/bb463989.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb463989.aspx</a></p> <p>But how can I retrieve contacts from hotmail with python ?</p> <p>Is there any example ?</p>
0
2010-01-30T00:27:16Z
2,166,646
<p>Your program will first need to obtain "delegated authentication", for which the Python samples are <a href="http://msdn.microsoft.com/en-us/library/cc287653.aspx" rel="nofollow">here</a>.</p> <p>After that, the interface is REST-like: you only need to HTTP GET the appropriate URI (per <a href="http://msdn.microsof...
4
2010-01-30T02:51:28Z
[ "python", "hotmail" ]