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
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase?
891,690
<p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p> <p>I'm not the first to ask a question on this subject [see <a href="htt...
6
2009-05-21T07:03:24Z
904,863
<p>According to Leonard Richardson, creator|maintainer of Beautiful Soup, you <a href="http://groups.google.com/group/beautifulsoup/browse%5Fthread/thread/ff6910752566df78" rel="nofollow">can't</a>.</p>
3
2009-05-24T23:30:54Z
[ "python", "xml", "beautifulsoup" ]
Can I change BeautifulSoup's behavior regarding converting XML tags to lowercase?
891,690
<p>I'm working on code to parse a configuration file written in XML, where the XML tags are mixed case and the case is significant. Beautiful Soup appears to convert XML tags to lowercase by default, and I would like to change this behavior.</p> <p>I'm not the first to ask a question on this subject [see <a href="htt...
6
2009-05-21T07:03:24Z
1,223,014
<p>It's much better to use <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a>. It's much, much faster than BeautifulSoup. It has a compatibility API for BeautifulSoup too if you don't want to learn the lxml API.</p> <p><a href="http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-libra...
1
2009-08-03T15:35:17Z
[ "python", "xml", "beautifulsoup" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p...
2
2009-05-21T08:28:20Z
891,897
<p>You can do this with <a href="http://www.python.org/doc/2.5.2/lib/typesseq-strings.html" rel="nofollow">string formatting</a> operators</p> <pre><code>f=open('filename.txt','w') for item in aList: print &gt;&gt;f, "%-20s : ..." % item </code></pre> <p>The 20 is the field width, while the "-" indicates to left ...
5
2009-05-21T08:29:38Z
[ "python", "string", "order" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p...
2
2009-05-21T08:28:20Z
891,907
<p>Do you mean this?</p> <pre><code>&gt;&gt;&gt; languages = ['Python','C','C++','Java'] &gt;&gt;&gt; f = open('myfile.txt', 'w') &gt;&gt;&gt; print('\n'.join('%-10s: ...' % l for l in languages), file=f) &gt;&gt;&gt; f.close() &gt;&gt;&gt; print(open('myfile.txt').read()) Python : ... C : ... C++ : ....
5
2009-05-21T08:33:24Z
[ "python", "string", "order" ]
Strings and file
891,895
<p>Suppose this is my list of languages.</p> <pre><code>aList = ['Python','C','C++','Java'] </code></pre> <p>How can i write to a file like :</p> <pre><code>Python : ... C : ... C++ : ... Java : ... </code></pre> <p>I have used rjust() to achieve this. Without it how can i do ?</p> <p...
2
2009-05-21T08:28:20Z
892,218
<p>Automatically determine colon position (using max width) and language order (sorted alphabetically):</p> <pre><code>languages = ['Python','C','C++','Java'] maxlen = max(map(len, languages)) with open('langs.txt', 'w') as f: for L in sorted(languages): f.write('%-*s: ...\n'% (maxlen, L)) print open('la...
0
2009-05-21T10:13:19Z
[ "python", "string", "order" ]
Satchmo donations
891,934
<p>Can anyone share some pointers on building a Donations module for Satchmo? I'm comfortable customizing Satchmo's product models etc but unable to find anything related to Donations</p> <p>I realize it's possible to create a Donations virtual product but as far as I can tell this still requires setting the amount be...
1
2009-05-21T08:46:17Z
901,050
<p>It looks like the *satchmo_cart_details_query* signal is the way to go about doing this. It allows you to add a price change value (in my case, donation amount) to a cart item</p> <p>I'll post the full solution if anyone is interested</p>
2
2009-05-23T07:08:55Z
[ "python", "django", "e-commerce", "satchmo" ]
filter with string return nothing
891,935
<p>I run into follow problem. Did I miss anything?</p> <pre><code>Association.all().count() 1 Association.all().fetch(1) [Association(**{'server_url': u'server-url', 'handle': u'handle2', 'secret': 'c2VjcmV0\n', 'issued': 1242892477L, 'lifetime': 200L, 'assoc_type': u'HMAC-SHA1'})] Association.all().filter('server_u...
0
2009-05-21T08:46:18Z
892,459
<p>What kind of property is "server_url"?</p> <p>If it is a TextProperty, then it cannot be used in filters.</p> <blockquote> <p>Unlike StringProperty, a TextProperty value can be more than 500 bytes long. However, TextProperty values are not indexed, and cannot be used in filters or sort orders.</p> </bloc...
5
2009-05-21T11:28:19Z
[ "python", "google-app-engine" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,230
<p>If you want the Python standard library to do the work for you (recommended!), use <a href="http://docs.python.org/library/smtplib.html" rel="nofollow">smtplib</a>. To see whether sending the mail worked, just open your inbox ;)</p> <p>If you want to implement the protocol yourself (is this homework?), then read up...
1
2009-05-21T10:17:32Z
[ "python", "smtp" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,264
<p>Depends what you mean by "received". It's possible to verify "delivery" of a message to a server but there is no 100% reliable guarantee it actually ended up in a mailbox. smtplib will throw an exception on certain conditions (like the remote end reporting user not found) but just as often the remote end will accept...
0
2009-05-21T10:30:51Z
[ "python", "smtp" ]
How would one build an smtp client in python?
892,196
<p>buildin an smtp client in python . which can send mail , and also show that mail has been received through any mail service for example gmail !!</p>
0
2009-05-21T10:04:53Z
892,306
<p>Create mail messages (possibly with multipart attachments) with <a href="http://docs.python.org/library/email.html" rel="nofollow">email</a>.</p> <blockquote> <p>The <code>email</code> package is a library for managing email messages, including MIME and other RFC 2822-based message documents.</p> </blockquote> <...
2
2009-05-21T10:43:14Z
[ "python", "smtp" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with t...
49
2009-05-21T10:05:32Z
892,293
<p>I believe the WAVE module does not support recording, just processing existing files. You might want to look at <a href="http://people.csail.mit.edu/hubert/pyaudio/">PyAudio</a> for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and c...
36
2009-05-21T10:39:35Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with t...
49
2009-05-21T10:05:32Z
892,400
<p>You might want to look at <a href="http://www.csounds.com/" rel="nofollow">csounds</a>, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.</p>
0
2009-05-21T11:08:23Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with t...
49
2009-05-21T10:05:32Z
6,743,593
<p>As a follow up to Nick Fortescue's answer, here's a more complete example of how to record from the microphone and process the resulting data:</p> <pre><code>from sys import byteorder from array import array from struct import pack import pyaudio import wave THRESHOLD = 500 CHUNK_SIZE = 1024 FORMAT = pyaudio.paIn...
64
2011-07-19T07:24:04Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with t...
49
2009-05-21T10:05:32Z
15,693,662
<p>The pyaudio website has many examples that are pretty short and clear: <a href="http://people.csail.mit.edu/hubert/pyaudio/" rel="nofollow">http://people.csail.mit.edu/hubert/pyaudio/</a></p>
2
2013-03-28T23:01:19Z
[ "python", "wav", "audio-recording" ]
Detect & Record Audio in Python
892,199
<p>I need to capture audio clips as WAV files that I can then pass to another bit of python for processing. The problem is that I need to determine when there is audio present and then record it, stop when it goes silent and then pass that file to the processing module.</p> <p>I'm thinking it should be possible with t...
49
2009-05-21T10:05:32Z
16,385,946
<p>Thanks to cryo for improved version that I based my tested code below:</p> <pre><code>#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is &gt;0. See trim() #I also fixed issue with the previous code - accumulated silence cou...
11
2013-05-05T15:14:56Z
[ "python", "wav", "audio-recording" ]
to send emails from Google appengine
892,266
<p>I have a web server with Django(Python programming language), hosted with Apache server. I would like to configure Google Appengine for the email server. My web server should be able to use Google Appengine, when it makes any email send using EmailMessage or sendmail infrastructure of Google mail api. I learnt that ...
0
2009-05-21T10:31:09Z
892,427
<p>The example code for the remote APi gives you an interactive console from which you can access <em>any</em> of the modules in your application. I see no requirement that they be only datastore operations.</p>
2
2009-05-21T11:18:57Z
[ "python", "django", "google-app-engine", "mail-server" ]
to send emails from Google appengine
892,266
<p>I have a web server with Django(Python programming language), hosted with Apache server. I would like to configure Google Appengine for the email server. My web server should be able to use Google Appengine, when it makes any email send using EmailMessage or sendmail infrastructure of Google mail api. I learnt that ...
0
2009-05-21T10:31:09Z
894,179
<p>You may want to use a third-party SMTP relaying service. <a href="http://www.birds-eye.net/article%5Farchive/smtp%5Fmail%5Frelay%5Fservices.htm" rel="nofollow">Here's a list</a>.</p> <p>Most of them have a simple API that lets you forward your email to their service. That way, you're not bound by the AppEngine's li...
0
2009-05-21T17:47:33Z
[ "python", "django", "google-app-engine", "mail-server" ]
Unit testing with nose: tests at compile time?
892,297
<p>Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module?</p> <p>In fact, I'd like to test something with the following structure:</p> <pre><code>x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I don't want to clutter the ...
3
2009-05-21T10:40:21Z
892,416
<p>A simple way to handle this would be to have a TESTING flag, and write:</p> <pre><code>if not TESTING: del x </code></pre> <p>However, you won't really be properly testing your modules as the tests will be running under different circumstances to your code.</p> <p>The proper answer is that you shouldn't reall...
2
2009-05-21T11:14:36Z
[ "python", "unit-testing", "nose" ]
Unit testing with nose: tests at compile time?
892,297
<p>Is it possible for the nose unit testing framework to perform tests during the compilation phase of a module?</p> <p>In fact, I'd like to test something with the following structure:</p> <pre><code>x = 123 # [x is used here...] def test_x(): assert (x == 123) del x # Deleted because I don't want to clutter the ...
3
2009-05-21T10:40:21Z
904,574
<p>According to nose's main developer Jason Pellerin, the nose unit testing framework <a href="http://groups.google.com/group/nose-users/browse%5Fthread/thread/5fd8e112fe8f5c88?hl=en" rel="nofollow">cannot run tests during compilation</a>. This is a potential annoyance if both the module "construction" and the test ro...
2
2009-05-24T20:23:12Z
[ "python", "unit-testing", "nose" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" ...
27
2009-05-21T13:47:09Z
893,060
<p>In the form that you are using there, you are explicitly specifying what class's static <code>method_two</code> to call. If <code>method_three</code> was a classmethod, and you called <code>cls.method_two</code>, you would get the results that you wanted:</p> <pre><code>class Test: def method_one(self): ...
37
2009-05-21T13:56:59Z
[ "python", "static", "override" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" ...
27
2009-05-21T13:47:09Z
893,074
<p>The behavior you see is the expected behavior. Static methods are... static. When you call <code>method_three()</code> defined in <code>Test</code> it will certainly call <code>method_two()</code> defined by <code>Test</code>.</p> <p>As for how to "get around" this proper behavior...</p> <p>The very best way is to...
4
2009-05-21T14:00:27Z
[ "python", "static", "override" ]
Overriding a static method in python
893,015
<p>Referring to the <a href="http://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static/114267#114267">first answer</a> about python's bound and unbound methods here, I have a question:</p> <pre><code>class Test: def method_one(self): print "Called method_one" ...
27
2009-05-21T13:47:09Z
38,119,459
<p>Additionally, if you want to call the "virtual static" function without an instance, you could proceed like so:</p> <ol> <li><p>Declare the function in the base class non-static like so:</p> <pre><code>class Base: def my_fun(self): print('my_fun base') class Derived(Base): def my_fun(self): ...
0
2016-06-30T09:45:09Z
[ "python", "static", "override" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
893,067
<p>Have you tried using a different SSH client? Some SSH clients have special, built-in keymappings for different remote processes. I ran into this one a lot with emacs.</p> <p>What client are you using? I'd recommend trying Putty and SecureCRT to compare their behavior.</p>
1
2009-05-21T13:57:57Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
893,089
<p>How's your env variable $TERM set [a] when things work fine and [b] when they don't? Env settings are often the key to such problems.</p>
0
2009-05-21T14:03:52Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
893,175
<p>Did you call ssh with the <em>-t</em> parameter to tell ssh to allocate a virtual terminal for you?</p> <p>From the man page:</p> <blockquote> <p>-t<br /> Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implement...
1
2009-05-21T14:22:24Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
893,200
<p>Looks like readline is not enabled. Check if <strong>PYTHONSTARTUP</strong> variable is defined, for me it points to <strong>/etc/pythonstart</strong> and that file is executed by the python process before going interactive, which setups readline/history handling.</p> <p>Thanks to @chown here is the docs on this: <...
15
2009-05-21T14:27:22Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
2,806,049
<ol> <li>install readline-devel package. </li> <li>recompile python with readline module</li> <li>Bingo!</li> </ol>
13
2010-05-10T20:04:31Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
17,307,271
<p>Try getting a key code library running on the server. If that does not work try to download a library with read-key ability.</p>
0
2013-06-25T20:49:56Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
17,394,195
<p>Here are the steps which worked for me in ubuntu 12.04 for python 3.3.</p> <p>1) open teminal and write <code>sudo apt-get install libreadline-dev</code></p> <p>2) download the source file of python 3.3.2 from <a href="http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz" rel="nofollow">http://www.python.org...
6
2013-06-30T19:44:05Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
26,356,378
<p>I've solved this issue by installing <code>readline</code> package:</p> <pre><code>pip install readline </code></pre>
33
2014-10-14T08:46:59Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
28,131,012
<p>On CentOS, I fix this by </p> <p><code>yum install readline-devel</code></p> <p>and then recompile python 3.4.</p> <p>On OpenSUSE, I fix this by</p> <pre><code>pip3 install readline </code></pre> <p>following Valerio Crini's answer.</p> <p>Perhaps "pip3 install readline" is a general solution. Haven't tried on...
3
2015-01-24T22:32:03Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
30,220,207
<p>I was trying build Python 2.7 on Ubuntu 14.0. You will need libreadline-dev. However, if you get it from apt-get, the current version is 6.3, which is incompatible with Python 2.7 (not sure about Python 3). For example, the data type "Function" and "CPPFunction", which were defined in previous versions of readline h...
0
2015-05-13T16:14:22Z
[ "python", "shell", "ssh", "arrow-keys" ]
Seeing escape characters when pressing the arrow keys in python shell
893,053
<p>In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.</p> <p>But after I ssh into another machine and start <code>python</code> there, I get sessions like:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; ...
47
2009-05-21T13:55:32Z
34,803,894
<p>I fixed this by doing the following:</p> <ul> <li>yum install readline-devel</li> <li><p>pip install readline</p> <ul> <li><p>I encountered another error here:</p> <p><code>gcc: readline/libreadline.a: No such file or directory</code></p> <p><code>gcc: readline/libhistory.a: No such file or directory</code></p> ...
2
2016-01-15T03:24:25Z
[ "python", "shell", "ssh", "arrow-keys" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis",...
0
2009-05-21T14:16:00Z
893,166
<p>You can easily make a list of numbers from a string like your first example, just <code>[float(x) for x in thestring.split()]</code> -- but the "Something like" is nothing like the first example and appears to have nothing to do with the question's Subject.</p>
2
2009-05-21T14:20:25Z
[ "python", "sqlite" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis",...
0
2009-05-21T14:16:00Z
893,182
<pre><code>In [1]: s = "20040701 0 20040701 0 1 52.965366 61.777687 57.540783" In [2]: strings = s.split(" ") In [3]: strings Out[3]: ['20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540783'] In [6]: tuple(strings) Out[6]: ('20040701', '0', '20040701', '0', '1', '52.965366', '61.777687', '57.540...
2
2009-05-21T14:23:55Z
[ "python", "sqlite" ]
How to make a dynamic array with different values in Python
893,143
<p>I have rows in file like :</p> <pre><code>20040701 0 20040701 0 1 52.965366 61.777687 57.540783 </code></pre> <p>I want to put that in a dynamic array if it's possible ?</p> <p>Something like </p> <pre><code>try: clients = [ (107, "Ella", "Fitzgerald"), (108, "Louis",...
0
2009-05-21T14:16:00Z
893,213
<p>From my reading for your question, I think you want something like:</p> <pre>rows=[map(Decimal,x.split(' ')) for x in lines]</pre>
1
2009-05-21T14:29:26Z
[ "python", "sqlite" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or...
146
2009-05-21T14:51:27Z
893,356
<p>I think you want to do this instead:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt") as file_out: with open("in.txt") as file_in: for line in file_in: file_out.write(line) </code></pre>
17
2009-05-21T14:55:22Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or...
146
2009-05-21T14:51:27Z
893,360
<p><a href="http://docs.python.org/2/library/contextlib.html#contextlib.nested"><code>contextlib.nested</code></a> supports this:</p> <pre><code>import contextlib with contextlib.nested(open("out.txt","wt"), open("in.txt")) as (file_out, file_in): ... </code></pre> <p><strong>Update:</strong><br> To quote the do...
52
2009-05-21T14:55:42Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or...
146
2009-05-21T14:51:27Z
893,520
<pre><code>open('out.txt', 'w').writelines(open('in.txt')) </code></pre> <p>Both files will be implicity, immediately closed just after execution of this line, in CPython.</p>
-4
2009-05-21T15:21:10Z
[ "python", "with-statement" ]
Multiple variables in Python 'with' statement
893,333
<p>Is it possible to declare more than one variable using a <code>with</code> statement in Python?</p> <p>Something like:</p> <pre><code>from __future__ import with_statement with open("out.txt","wt"), open("in.txt") as file_out, file_in: for line in file_in: file_out.write(line) </code></pre> <p>... or...
146
2009-05-21T14:51:27Z
1,073,814
<p>It is possible in <a href="http://docs.python.org/3.1/reference/compound_stmts.html#with">Python 3 since v3.1</a> and <a href="http://docs.python.org/dev/whatsnew/2.7.html#other-language-changes">Python 2.7</a>. The new <code>with</code> syntax supports multiple context managers:</p> <pre><code>with A() as a, B() ...
296
2009-07-02T11:25:50Z
[ "python", "with-statement" ]
Python doctest fails on 0.0 != -0.0--what gives?
893,398
<p>Given the following code:</p> <pre><code>def slope(x1, y1, x2, y2): """ &gt;&gt;&gt; slope(5, 3, 4, 2) 1.0 &gt;&gt;&gt; slope(1, 2, 3, 2) 0.0 &gt;&gt;&gt; slope(1, 2, 3, 3) 0.5 &gt;&gt;&gt; slope(2, 4, 1, 2) 2.0 """ xa = float (x1) xb = float (x2) ...
2
2009-05-21T15:01:39Z
893,413
<p>It fails because <a href="http://docs.python.org/3.0/library/doctest.html" rel="nofollow">doctest</a> does <em>string comparison</em>. It merely checks whether the output is identical to what would have been outputted if the code had been executed at the Python interactive interpreter:</p> <pre><code>&gt;&gt;&gt; 0...
9
2009-05-21T15:04:23Z
[ "python" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
893,449
<p>If you don't want to use the standard dictionary method (looping through the list incrementing the proper dict. key), you can try this:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; myList = words.split() # ['apple', 'banana', 'apple', 'strawberry', 'banana', 'lemon'] &gt;&gt;&gt; [(k, len(...
5
2009-05-21T15:09:57Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
893,459
<p><a href="http://docs.python.org/library/collections.html#defaultdict-objects">defaultdict</a> to the rescue!</p> <pre><code>from collections import defaultdict words = "apple banana apple strawberry banana lemon" d = defaultdict(int) for word in words.split(): d[word] += 1 </code></pre> <p>This runs in O(n)....
73
2009-05-21T15:10:59Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
893,463
<p>Standard approach:</p> <pre><code>from collections import defaultdict words = "apple banana apple strawberry banana lemon" words = words.split() result = collections.defaultdict(int) for word in words: result[word] += 1 print result </code></pre> <p>Groupby oneliner:</p> <pre><code>from itertools import gro...
10
2009-05-21T15:11:47Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
893,499
<p>If you are using python 2.7+/3.1+, there is a <a href="http://docs.python.org/dev/py3k/library/collections.html#collections.Counter">Counter Class</a> in the collections module which is purpose built to solve this type of problem:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; words = "app...
96
2009-05-21T15:16:59Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
893,676
<p>Without defaultdict:</p> <pre><code>words = "apple banana apple strawberry banana lemon" my_count = {} for word in words.split(): try: my_count[word] += 1 except KeyError: my_count[word] = 1 </code></pre>
1
2009-05-21T15:59:30Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
983,434
<pre><code>freqs = {} for word in words: freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize </code></pre> <p>I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weige...
6
2009-06-11T20:21:44Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
5,576,479
<p>Can't you just use count?</p> <pre><code>words = 'the quick brown fox jumps over the lazy gray dog' words.count('z') #output: 1 </code></pre>
0
2011-04-07T05:36:08Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
15,103,041
<p><strong>The answer below takes some extra cycles, but it is another method</strong></p> <pre class="lang-py prettyprint-override"><code>def func(tup): return tup[-1] def print_words(filename): f = open("small.txt",'r') whole_content = (f.read()).lower() print whole_content list_content = whole...
0
2013-02-27T02:17:20Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
31,065,989
<p>I happened to work on some Spark exercise, here is my solution.</p> <pre><code>tokens = ['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog'] print {n: float(tokens.count(n))/float(len(tokens)) for n in tokens} </code></pre> <p>**#output of the above **</p> <pre><code>{'brown': 0.16666666666666666, 'lazy': 0.1666666...
0
2015-06-26T06:02:07Z
[ "python", "count", "frequency", "counting" ]
item frequency count in python
893,417
<p>I'm a python newbie, so maybe my question is very noob. Assume I have a list of words, and I want to find the number of times each word appears in that list. Obvious way to do this is:</p> <pre><code>words = "apple banana apple strawberry banana lemon" uniques = set(words.split()) freqs = [(item, words.split.count(...
40
2009-05-21T15:04:36Z
35,584,925
<p>Use reduce() to convert the list to a single dict.</p> <pre><code>words = "apple banana apple strawberry banana lemon" reduce( lambda d, c: d.update([(c, d.get(c,0)+1)]) or d, words.split(), {}) </code></pre> <p>returns</p> <pre><code>{'strawberry': 1, 'lemon': 1, 'apple': 2, 'banana': 2} </code></pre>
0
2016-02-23T18:03:45Z
[ "python", "count", "frequency", "counting" ]
Replacing Microsoft Word Newline Character in Python
893,514
<p>This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the <kbd>CTRL ENTER</kbd> character that shows up as a return arrow in Word. I've tried <code>chr(10)</code>, <code>chr(13)</code>, <code>\u000D</code>...
0
2009-05-21T15:19:08Z
893,535
<p>Run this:</p> <pre><code>print repr(mystringobject) </code></pre> <p>That will give a hint of which character you want to remove.</p> <p>If still no clue, paste the result of the command above in the question, and I'll edit my answer.</p>
4
2009-05-21T15:24:51Z
[ "python", "ms-word", "sanitize" ]
Replacing Microsoft Word Newline Character in Python
893,514
<p>This feels like it should be an easy one, but I'm having trouble cleaning out the newline character in content pasted from Microsoft Word. Not a full line-break, but the <kbd>CTRL ENTER</kbd> character that shows up as a return arrow in Word. I've tried <code>chr(10)</code>, <code>chr(13)</code>, <code>\u000D</code>...
0
2009-05-21T15:19:08Z
893,564
<p>you can get the ASCII value of the character like this:</p> <pre><code>for c in 'string': print ord(c), hex(ord(c)) </code></pre> <p>once you know the code, it should be easy to kill the offender.</p>
2
2009-05-21T15:31:36Z
[ "python", "ms-word", "sanitize" ]
How to define a system-wide alias for a Python script?
893,543
<p>I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with</p> <pre><code>python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 </code></pre> <p>Since the location of the script might change, I want to de...
2
2009-05-21T15:27:01Z
893,553
<p>I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)</p> <p>(In a terminal. You may have to use <em>sudo ln -s</em> depending on the permissions.</p> <pre><code>ln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py </code></pre> <p>If you take <a href="http...
6
2009-05-21T15:29:19Z
[ "python", "osx" ]
How to define a system-wide alias for a Python script?
893,543
<p>I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with</p> <pre><code>python /Users/xyz/long/absolute/path/to/script.py arg1 arg2 </code></pre> <p>Since the location of the script might change, I want to de...
2
2009-05-21T15:27:01Z
893,563
<p>As well as doing a symlink, you can put "#! /path/to/python" at the start of the script and make it executabe. Then you don't have to call it with "python /Users/big/long/path/script.py"</p>
3
2009-05-21T15:31:24Z
[ "python", "osx" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
893,923
<p>R-squared is a statistic that only applies to linear regression.</p> <p>Essentially, it measures how much variation in your data can be explained by the linear regression.</p> <p>So, you calculate the "Total Sum of Squares", which is the total squared deviation of each of your outcome variables from their mean. . ...
3
2009-05-21T16:54:49Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
895,063
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html">numpy.polyfit</a> documentation, it is fitting linear regression. Specifically, numpy.polyfit with degree 'd' fits a linear regression with the mean function</p> <p>E(y|x) = p_d * x**d + p_{d-1} * x **(d-1) + ... + p_1 * x +...
25
2009-05-21T20:48:35Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
1,326,331
<p>The wikipedia article on <a href="http://en.wikipedia.org/wiki/Coefficient_of_determination" rel="nofollow">r-squareds</a> suggests that it may be used for general model fitting rather than just linear regression.</p>
3
2009-08-25T06:06:24Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
1,517,401
<p>A very late reply, but just in case someone needs a ready function for this:</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html">scipy.stats.stats.linregress</a></p> <p>i.e.</p> <pre><code>slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) </cod...
54
2009-10-04T21:15:51Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
13,918,150
<p>I have been using this successfully, where x and y are array-like.</p> <pre><code>def rsquared(x, y): """ Return R^2 where x and y are array-like.""" slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y) return r_value**2 </code></pre>
9
2012-12-17T16:37:46Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
30,804,603
<p>From yanl (yet-another-library) <code>sklearn.metrics</code> has an <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.html"><code>r2_square</code></a> function;</p> <pre><code>from sklearn.metrics import r2_score coefficient_of_dermination = r2_score(y, p(x)) </code></pre>
7
2015-06-12T13:41:03Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
How do I calculate r-squared using Python and Numpy?
893,657
<p>I'm using Python and Numpy to calculate a best fit polynomial of arbitrary degree. I pass a list of x values, y values, and the degree of the polynomial I want to fit (linear, quadratic, etc.).</p> <p>This much works, but I also want to calculate r (coefficient of correlation) and r-squared(coefficient of determin...
38
2009-05-21T15:55:54Z
34,617,603
<p>I originally posted the benchmarks below with the purpose of recommending <code>numpy.corrcoef</code>, foolishly not realizing that the original question already uses <code>corrcoef</code> and was in fact asking about higher order polynomial fits. I've added an actual solution to the polynomial r-squared question u...
3
2016-01-05T17:21:45Z
[ "python", "math", "statistics", "numpy", "curve-fitting" ]
Python PySerial readline function wrong use
893,747
<p>I'm using a script importing PySerial to read from COM4</p> <p>messages I would like to intercept end with a couple of #</p> <p>so I tried to use </p> <pre><code>bus.readline(eol='##') </code></pre> <p>where bus is my connection.</p> <p>I expected to read like:</p> <ol> <li>*#*3##</li> <li>*#*3##</li> <li>*#*3...
2
2009-05-21T16:12:34Z
893,793
<p>The <code>readline()</code> method in pyserial reads one character at a time and compares it to the EOL character. You cannot specify multiple characters as the EOL. You'll have to read in and then split later using <code>string.split()</code> or <code>re.split()</code></p>
3
2009-05-21T16:25:22Z
[ "python", "pyserial" ]
Python: Stopping miniDOM from expanding escape sequences
893,930
<p>When xml.dom.minidom parses a piece of xml, it automagically converts escape characters for greater than and less than into their visual representation. For example: </p> <pre><code>&gt;&gt;&gt; import xml.dom.minidom &gt;&gt;&gt; s = "&lt;example&gt;4 &amp;lt; 5&lt;/example&gt;" &gt;&gt;&gt; x = xml.dom.mini...
0
2009-05-21T16:55:53Z
894,328
<pre><code>&gt;&gt;&gt; import xml.dom.minidom &gt;&gt;&gt; s = "&lt;example&gt;4 &amp;lt; 5&lt;/example&gt;" &gt;&gt;&gt; x = xml.dom.minidom.parseString(s) &gt;&gt;&gt; x.firstChild.firstChild.toxml() u'4 &amp;lt; 5' </code></pre>
3
2009-05-21T18:20:27Z
[ "python", "xml", "minidom" ]
PyQt: Show menu in a system tray application
893,984
<p>First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.</p> <p>This code work...
20
2009-05-21T17:05:35Z
895,721
<p>Well, after some debugging I found the problem. The QMenu object it is destroyed after finish <code>__init__</code> function because it doesn't have a parent. While the parent of a QSystemTrayIcon can be an object for the QMenu it has to be a Qwidget. This code works (see how QMenu gets the same parent as the QSyste...
24
2009-05-21T23:08:33Z
[ "python", "menu", "pyqt", "system-tray" ]
PyQt: Show menu in a system tray application
893,984
<p>First of all, I'm an experienced C programmer but new to python. I want to create a simple application in python using pyqt. Let's imagine this application it is as simple as when it is run it has to put an icon in the system tray and it has offer an option in its menu to exit the application.</p> <p>This code work...
20
2009-05-21T17:05:35Z
3,230,687
<p>I think I would prefer the following as it doesn't seem to depend upon QT's internal garbage collection decisions.</p> <pre><code>import sys from PyQt4 import QtGui class SystemTrayIcon(QtGui.QSystemTrayIcon): def __init__(self, icon, parent=None): QtGui.QSystemTrayIcon.__init__(self, icon, parent) ...
6
2010-07-12T17:32:23Z
[ "python", "menu", "pyqt", "system-tray" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,108
<pre><code>self.__class__.__name__ # name of class i'm in </code></pre> <p>for the rest the sys and trace modules</p> <p><a href="http://docs.python.org/library/sys.html" rel="nofollow">http://docs.python.org/library/sys.html</a> <a href="http://docs.python.org/library/trace.html" rel="nofollow">http://docs.python.o...
5
2009-05-21T17:28:33Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,137
<p>Here is an example of each:</p> <pre><code>from inspect import stack class Foo: def __init__(self): print __file__ print self.__class__.__name__ print stack()[0][3] f = Foo() </code></pre>
30
2009-05-21T17:34:00Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
894,138
<pre><code>import sys class A: def __init__(self): print __file__ print self.__class__.__name__ print sys._getframe().f_code.co_name a = A() </code></pre>
9
2009-05-21T17:34:10Z
[ "python", "filenames" ]
How do I get the current file, current class, and current method with Python?
894,088
<ul> <li>Name of the file from where code is running</li> <li>Name of the class from where code is running</li> <li>Name of the method (attribute of the class) where code is running</li> </ul>
28
2009-05-21T17:23:59Z
895,318
<p>Be <em>very</em> careful. Consider:</p> <pre><code>class A: pass B = A b = B() </code></pre> <p>What is the 'class name' of <code>b</code> here? Is it A, or B? Why?</p> <p>The point is, you shouldn't need to know or care. An object is what it is: its name is very rarely useful.</p>
4
2009-05-21T21:39:35Z
[ "python", "filenames" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,209
<p>You can try to implement some sort of <a href="http://www.oreillynet.com/pub/a/python/2003/07/31/declarative%5Fpython.html" rel="nofollow">declarative syntax</a> for your data.</p> <p>Which may result in something like:</p> <pre><code>class Image(SomeClassWithMetamagic): type = PackedValue(2) attribute = P...
4
2009-05-21T17:52:09Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,237
<p>You could refactor your code to wrap boilerplate in a class. Something like:</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' binary = BinaryWrapper() # Binary version number. binary.pack('&lt;I', [2]) # alternatively, you can pass an array stuff = [ ...
0
2009-05-21T17:58:25Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,358
<pre><code>def to_binary(self): struct_i_pack = struct.Struct('&lt;I').pack struct_ii_pack = struct.Struct('&lt;II').pack struct_h_pack = struct.Struct('&lt;H').pack struct_ih_pack = struct.Struct('&lt;IH').pack struct_ihi_pack = struct.Struct('&lt;IHI').pack return ''.join([ struct_i_p...
1
2009-05-21T18:24:41Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,469
<pre><code>from StringIO import StringIO import struct class BinaryIO(StringIO): def writepack(self, fmt, *values): self.write(struct.pack('&lt;' + fmt, *values)) def to_binary_example(): data = BinaryIO() data.writepack('I', 42) data.writepack('II', 1, 2) return data.getvalue() </code></p...
4
2009-05-21T18:48:11Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,584
<p>The worst problem is that you need corresponding code in C++ to read the output. Can you reasonably arrange to have both the reading and writing code mechanically derive from or use a common specification? How to go about that depends on your C++ needs as much as Python.</p>
0
2009-05-21T19:12:22Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,844
<p>You can get rid of the repetition while still as readable easily like this:</p> <pre><code>def to_binary(self): output = struct.pack( '&lt;IIII', 2, self.image.size[0], self.image.size[1], len(self.attributes) ) return output + ''.join( struct.pack('&lt;IHI', attribute.id, attribute...
0
2009-05-21T20:05:05Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,890
<p>If you just want nicer syntax, you can abuse generators/decorators:</p> <pre><code>from functools import wraps def packed(g): '''a decorator that packs the list data items that is generated by the decorated function ''' @wraps(g) def wrapper(*p, **kw): data = [] for params in g(*p, **kw): ...
2
2009-05-21T20:12:34Z
[ "python" ]
More Pythonic conversion to binary?
894,157
<p>Here is a contrived example of how a lot of our classes return binary representations (to be read by C++) of themselves.</p> <pre><code>def to_binary(self): 'Return the binary representation as a string.' data = [] # Binary version number. data.append(struct.pack('&lt;I', [2])) # Image size. ...
6
2009-05-21T17:39:34Z
894,908
<p>How about <a href="http://code.google.com/p/protobuf/" rel="nofollow">protocol buffers</a> google's extensive cross language format and protocol of sharing data. </p>
2
2009-05-21T20:15:31Z
[ "python" ]
Programmatically make HTTP requests through proxies with Python
894,168
<p>How do I use Python to make an HTTP request through a proxy?</p> <p>What do I need to do to the following code?</p> <pre><code>urllib.urlopen('http://www.google.com') </code></pre>
4
2009-05-21T17:43:26Z
894,170
<p>The <code>urlopen</code> function supports proxies. Try something like this:</p> <pre><code>urllib.urlopen(your_url, proxies = {"http" : "http://192.168.0.1:80"}) </code></pre>
6
2009-05-21T17:44:42Z
[ "python", "http", "proxy" ]
Programmatically make HTTP requests through proxies with Python
894,168
<p>How do I use Python to make an HTTP request through a proxy?</p> <p>What do I need to do to the following code?</p> <pre><code>urllib.urlopen('http://www.google.com') </code></pre>
4
2009-05-21T17:43:26Z
894,173
<p>You could look at <a href="http://pycurl.sourceforge.net/" rel="nofollow">PycURL</a>. I use cURL a lot in PHP and i love it. Though there is probably a neat way to do this currently in Python.</p>
1
2009-05-21T17:45:03Z
[ "python", "http", "proxy" ]
How does setuptools decide which files to keep for sdist/bdist?
894,323
<p>I'm working on a Python package that uses <code>namespace_packages</code> and <code>find_packages()</code> like so in setup.py:</p> <pre><code>from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['package'], ...) </code></pre> ...
6
2009-05-21T18:19:08Z
894,341
<p>You need to add a package_data directive. For example, if you want to include files with .txt or .rst extensions:</p> <pre><code>from setuptools import setup, find_packages setup(name="package", version="1.3.3.7", package=find_packages(), namespace_packages=['package'], package_data = { #...
4
2009-05-21T18:22:38Z
[ "python", "setuptools", "distutils" ]
Multi-server monitor/auto restarter in python
894,474
<p>I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python code to kill the extraneous screen session and r...
3
2009-05-21T18:51:07Z
894,648
<p>You really shouldn't run production software on a screen. If the server gets rebooted, how will You start it up? Manually? Also I think that You are trying to re-invent the wheel. There are already pretty good tools that do the thing You need.</p> <blockquote> <p><a href="http://freshmeat.net/projects/launchtool/...
3
2009-05-21T19:23:00Z
[ "python", "linux", "bash", "restart" ]
Multi-server monitor/auto restarter in python
894,474
<p>I have 2 server programs that must be started with the use of GNU Screen. I'd like to harden these servers against crashes with a Python based program that kicks off each screen session then monitors the server process. If the server process crashes, I need the python code to kill the extraneous screen session and r...
3
2009-05-21T18:51:07Z
894,722
<p>"need to be multi-threaded to handle the restarting of two separate programs" </p> <p>Don't see why.</p> <pre><code>import subprocess commands = [ ["p1"], ["p2"] ] programs = [ subprocess.Popen(c) for c in commands ] while True: for i in range(len(programs)): if programs[i].returncode is None: ...
5
2009-05-21T19:37:16Z
[ "python", "linux", "bash", "restart" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,541
<p>I'm not sure that I buy the argument that Ruby is more object-oriented than Python. There's more to being object-oriented than just using objects and dot syntax. A common argument that I see is that in Python to get the length of a list, you do something like this:</p> <pre><code>len(some_list) </code></pre> <p>...
12
2009-05-21T19:03:43Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,618
<p>Hold on, both Ruby and Python are object oriented. Objects are objects. There isn't more object oriented 'comparison function' that will lead you to the better one. <em>Syntax</em> is not only thing which makes some language to look like object oriented one, but also <em>data model</em>.</p> <blockquote> <p>Objec...
2
2009-05-21T19:18:40Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,692
<p>Jian Lin — the answer is "Yes", Python is more object-oriented than when Matz decided he wanted to create Ruby, and both languages now feature "everything is an object". Back when Python was younger, "types" like strings and numbers lacked methods, whereas "objects" were built with the "class" statement (or by de...
39
2009-05-21T19:32:01Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,711
<p>This is an incorrect belief.</p> <p>See my previous answer here for more in-depth explanation:</p> <p><a href="http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby/865963#865963">http://stackoverflow.com/questions/865911/is-everything-an-object-in-python-like-ruby/865963#865963</a>...
2
2009-05-21T19:35:39Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,716
<p>Although this is not properly an answer... Why do you care about Python being more or less OO? The cool thing about Python is that it's <em>pythonic</em>, not object oriented or funcitonal or whichever paradigm that is fashionable at the moment! :-)</p> <p>I learnt to program with Java and Object Orientation, but n...
7
2009-05-21T19:36:28Z
[ "python", "ruby", "oop" ]
Has Python changed to more object oriented?
894,502
<p>I remember that at one point, <a href="http://www.linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html" rel="nofollow">it was said that Python is less object oriented than Ruby</a>, since in Ruby, everything is an object. Has this changed for Python as well? Is the latest Python more object oriented than the previo...
9
2009-05-21T18:56:03Z
894,784
<p>I have the same <strong>"perception"</strong> perhaps derived from this:</p> <p><a href="http://www.python.org/doc/faq/general/#why-was-python-created-in-the-first-place" rel="nofollow">Why was python created in the first place:</a></p> <blockquote> <p><em>It occurred to me that a scripting language with a synta...
1
2009-05-21T19:51:10Z
[ "python", "ruby", "oop" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pr...
0
2009-05-21T19:54:47Z
894,830
<p>Why not just pass the <code>-i</code> option (<code>man sed</code>) to sed and be done with it? If it doesn't find Masi in a file, the file will just be rewritten with no modification. Or am I missing something?</p> <p>If you don't want to replace the files' contents inline (which is what the <code>-i</code> will...
3
2009-05-21T20:02:50Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pr...
0
2009-05-21T19:54:47Z
894,834
<p><strong>To replace the word in all files found in the current directory and subdirectories</strong></p> <pre><code>perl -p -i -e 's/Masi/Bond/g' $(grep -rl Masi *) </code></pre> <p>The above won't work if you have spaces in filenames. Safer to do:</p> <pre><code>find . -type f -exec perl -p -i -e 's/Masi/Bond/g'...
12
2009-05-21T20:03:13Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pr...
0
2009-05-21T19:54:47Z
894,850
<p><strong>A solution tested on Windows</strong></p> <p>Requires CPAN module File::Slurp. Will work with standard Unix shell wildcards. Like ./replace.pl PATH/replace.txt PATH2/replace*</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use File::Glob ':glob'; use File::Slurp; foreach my $dir (@ARGV) { my @f...
0
2009-05-21T20:05:43Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pr...
0
2009-05-21T19:54:47Z
894,982
<p>Renaming a folder full of files:</p> <pre><code>use warnings; use strict; use File::Find::Rule; my @list = File::Find::Rule-&gt;new()-&gt;name(qr/Masi/)-&gt;file-&gt;in('./'); for( @list ){ my $old = $_; my $new = $_; $new =~ s/Masi/Bond/g; rename $old , $new ; } </code></pre> <p>Replacing Strings in...
3
2009-05-21T20:30:43Z
[ "python", "perl", "sed", "replace" ]
Unable to replace the word in a given folder's contents by Sed/Python/Perl
894,802
<p>I have a project where I have folders, subfolders, and files. I need to replace the word Masi by the word Bond in each files.</p> <p>I run the following Sed script called replace unsuccessfully</p> <pre><code>s/Masi/Bond/ </code></pre> <p>in Zsh by </p> <pre><code>sed -f PATH/replace PATH2/project/** </code></pr...
0
2009-05-21T19:54:47Z
941,257
<pre><code>import glob import os # Change the glob for different filename matching for filename in glob.glob("*"): dst=filename.replace("Masi","Bond") os.rename(filename, dst) </code></pre>
0
2009-06-02T18:52:01Z
[ "python", "perl", "sed", "replace" ]
How can I launch a python script on windows?
894,845
<p>I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime?</p>
1
2009-05-21T20:05:17Z
894,869
<p>If you're looking to do recurring scheduled tasks, then the Task Scheduler (Vista) or Scheduled Tasks (XP and, I think, earlier) is the appropriate method on Windows.</p>
5
2009-05-21T20:09:00Z
[ "python" ]
How can I launch a python script on windows?
894,845
<p>I have run a few using batch jobs, but, I am wondering what would be the most appropriate? Maybe using time.strftime?</p>
1
2009-05-21T20:05:17Z
895,987
<p>I'd second using the Task Scheduler. </p> <p>I have also read about a 'cron-like' python based application PyCron - <a href="http://www.bigbluehost.com/article4.html" rel="nofollow">http://www.bigbluehost.com/article4.html</a> . If you're from the Unix end of town you might find it more familiar than the Windows sc...
0
2009-05-22T00:57:34Z
[ "python" ]
Circular dependency in Python
894,864
<p>I have two files, <code>node.py</code> and <code>path.py</code>, which define two classes, <code>Node</code> and <code>Path</code>, respectively.</p> <p>Up to today, the definition for <code>Path</code> referenced the <code>Node</code> object, and therefore I had done</p> <pre><code>from node.py import * </code></...
40
2009-05-21T20:08:08Z
894,885
<p><em><a href="http://effbot.org/zone/import-confusion.htm">Importing Python Modules</a></em> is a great article that explains circular imports in Python.</p> <p>The easiest way to fix this is to move the path import to the end of the node module.</p>
67
2009-05-21T20:11:55Z
[ "python", "circular-dependency" ]
Circular dependency in Python
894,864
<p>I have two files, <code>node.py</code> and <code>path.py</code>, which define two classes, <code>Node</code> and <code>Path</code>, respectively.</p> <p>Up to today, the definition for <code>Path</code> referenced the <code>Node</code> object, and therefore I had done</p> <pre><code>from node.py import * </code></...
40
2009-05-21T20:08:08Z
37,812,931
<p>One other approach is importing one of the two modules <strong>only in the function</strong> where you need it in the other. Sure, this works best if you only need it in one or a small number of functions:</p> <pre><code># in node.py from path import Path class Node ... # in path.py class Path def method_n...
4
2016-06-14T13:05:35Z
[ "python", "circular-dependency" ]
CreateDatabase often fails on the google data api
894,881
<p>The following test program is suppossed to create a new spreadsheet:</p> <pre><code>#!/usr/bin/python import gdata.spreadsheet.text_db import getpass import atom import gdata.contacts import gdata.contacts.service import smtplib import time password = getpass.getpass() client = gdata.spreadsheet.text_db.DatabaseC...
0
2009-05-21T20:11:43Z
897,671
<p>Someone clued me in that this is a <a href="http://code.google.com/p/gdata-issues/issues/detail?id=1147" rel="nofollow">known bug</a> in gdata.</p>
1
2009-05-22T12:48:36Z
[ "python", "gdata-api" ]
Compiled Python CGI
895,163
<p>Assuming the webserver is configured to handle <strong><em>.exe</em></strong>, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession?</p>
0
2009-05-21T21:06:11Z
895,177
<p>There is <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> (<a href="http://www.ehow.com/how%5F2091641%5Fcompile-python-code.html" rel="nofollow">and a tutorial on how to use it</a>), but there is no guarentee that it will make your script any faster. Really its more of an executable interpreter that wraps...
1
2009-05-21T21:10:07Z
[ "python" ]