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
sequence
Parsing fixed-format data embedded in HTML in python
409,769
<p>I am using google's appengine api</p> <pre><code>from google.appengine.api import urlfetch </code></pre> <p>to fetch a webpage. The result of</p> <pre><code>result = urlfetch.fetch("http://www.example.com/index.html") </code></pre> <p>is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces.</p> <p><strong>EDIT:</strong> Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way... <strong>END EDIT</strong></p> <p>If the document is something like this:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; AAA 123 888 2008-10-30 ABC BBB 987 332 2009-01-02 JSE ... A4A 288 AAA &lt;/body&gt;&lt;/html&gt; </code></pre> <p>result.content will be this, after urlfetch fetches it:</p> <pre><code>'&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA&lt;/body&gt;&lt;/html&gt;' </code></pre> <p>Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried</p> <pre><code>result.content.split('\n') </code></pre> <p>and</p> <pre><code>result.content.split('\r') </code></pre> <p>but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines.</p> <p>Any ideas how I can parse this data? Maybe I need to fetch it differently?</p> <p>Thanks in advance!</p>
0
2009-01-03T20:32:20Z
410,210
<p>EDIT: Reading comprehension is a desirable thing. I missed the bit about the lines being run together with no separator between them, which would kinda be the whole point of this, wouldn't it? So, nevermind my answer, it's not actually relevant.</p> <p><hr /></p> <p>If you know that each line is 5 space-separated columns, then (once you've stripped out the html) you could do something like (untested):</p> <pre><code>def generate_lines(datastring): while datastring: splitresult = datastring.split(' ', 5) if len(splitresult) &gt;= 5: datastring = splitresult[5] else: datastring = None yield splitresult[:5] for line in generate_lines(data): process_data_line(line) </code></pre> <p>Of course, you can change the split character and number of columns as needed (possibly even passing them into the generator function as additional parameters), and add error handling as appropriate. </p>
0
2009-01-04T01:08:14Z
[ "python", "html", "google-app-engine", "parsing", "html-content-extraction" ]
Parsing fixed-format data embedded in HTML in python
409,769
<p>I am using google's appengine api</p> <pre><code>from google.appengine.api import urlfetch </code></pre> <p>to fetch a webpage. The result of</p> <pre><code>result = urlfetch.fetch("http://www.example.com/index.html") </code></pre> <p>is a string of the html content (in result.content). The problem is the data that I want to parse is not really in HTML form, so I don't think using a python HTML parser will work for me. I need to parse all of the plain text in the body of the html document. The only problem is that urlfetch returns a single string of the entire HTML document, removing all newlines and extra spaces.</p> <p><strong>EDIT:</strong> Okay, I tried fetching a different URL and apparently urlfetch does not strip the newlines, it was the original webpage I was trying to parse that served the HTML file that way... <strong>END EDIT</strong></p> <p>If the document is something like this:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; AAA 123 888 2008-10-30 ABC BBB 987 332 2009-01-02 JSE ... A4A 288 AAA &lt;/body&gt;&lt;/html&gt; </code></pre> <p>result.content will be this, after urlfetch fetches it:</p> <pre><code>'&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;AAA 123 888 2008-10-30 ABCBBB 987 2009-01-02 JSE...A4A 288 AAA&lt;/body&gt;&lt;/html&gt;' </code></pre> <p>Using an HTML parser will not help me with the data between the body tags, so I was going to use regular expresions to parse my data, but as you can see the last part of one line gets combined with the first part of the next line, and I don't know how to split it. I tried</p> <pre><code>result.content.split('\n') </code></pre> <p>and</p> <pre><code>result.content.split('\r') </code></pre> <p>but the resulting list was all just 1 element. I don't see any options in google's urlfetch function to not remove newlines.</p> <p>Any ideas how I can parse this data? Maybe I need to fetch it differently?</p> <p>Thanks in advance!</p>
0
2009-01-03T20:32:20Z
485,465
<p>Further suggestions for splitting the string <code>s</code> into 26-character blocks:</p> <p>As a list:</p> <pre><code>&gt;&gt;&gt; [s[x:x+26] for x in range(0, len(s), 26)] ['AAA 123 888 2008-10-30 ABC', 'BBB 987 2009-01-02 JSE', 'A4A 288 AAA'] </code></pre> <p>As a generator:</p> <pre><code>&gt;&gt;&gt; for line in (s[x:x+26] for x in range(0, len(s), 26)): print line AAA 123 888 2008-10-30 ABC BBB 987 2009-01-02 JSE A4A 288 AAA </code></pre> <p>Replace <code>range()</code> with <code>xrange()</code> in Python 2.x if <code>s</code> is very long.</p>
0
2009-01-27T21:52:46Z
[ "python", "html", "google-app-engine", "parsing", "html-content-extraction" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
409,843
<p>Here's one <a href="http://publib.boulder.ibm.com/infocenter/systems/index.jsp?topic=/com.ibm.aix.progcomm/doc/progcomc/skt_shutdn.htm">explanation</a>:</p> <blockquote> <p>Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.</p> </blockquote>
21
2009-01-03T21:10:08Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
410,231
<p>Explanation of shutdown and close: <a href="http://msdn.microsoft.com/en-us/library/ms738547(VS.85).aspx">Graceful shutdown (msdn)</a></p> <p>Shutdown (in your case) indicates to the other end of the connection there is no further intention to read from or write to the socket. Then close frees up any memory associated with the socket.</p> <p>Omitting shutdown may cause the socket to linger in the OSs stack until the connection has been closed gracefully.</p> <p>IMO the names 'shutdown' and 'close' are misleading, 'close' and 'destroy' would emphasise their differences.</p>
16
2009-01-04T01:28:29Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
410,271
<p>there are some flavours of shutdown: <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.shutdown.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.shutdown.aspx</a>. *nix is similar.</p>
3
2009-01-04T01:52:19Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
598,759
<p>Calling <code>close</code> and <code>shutdown</code> have two different effects on the underlying socket.</p> <p>The first thing to point out is that the socket is a resource in the underlying OS and <strong>multiple processes can have a handle for the same underlying socket.</strong></p> <p>When you call <code>close</code> it decrements the handle count by one and if the handle count has reached zero then the socket and associated connection goes through the normal close procedure (effectively sending a FIN / EOF to the peer) and the socket is deallocated.</p> <p>The thing to pay attention to here is that if the handle count does not reach zero because another process still has a handle to the socket then the connection <strong>is not closed and the socket is not deallocated.</strong></p> <p>On the other hand calling <code>shutdown</code> for reading and writing closes the underlying connection and sends a FIN / EOF to the peer regardless of how many processes have handles to the socket. However, it <strong>does not</strong> deallocate the socket and you still need to call close afterward.</p>
159
2009-02-28T21:58:05Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
2,554,482
<p>Shutdown(1) , forces the socket no to send any more data</p> <p>This is usefull in</p> <p>1- Buffer flushing</p> <p>2- Strange error detection</p> <p>3- Safe guarding</p> <p>Let me explain more , when you send a data from A to B , it's not guaranteed to be sent to B , it's only guaranteed to be sent to the A os buffer , which in turn sends it to the B os buffer</p> <p>So by calling shutdown(1) on A , you flush A's buffer and an error is raised if the buffer is not empty ie: data has not been sent to the peer yet</p> <p>Howoever this is irrevesable , so you can do that after you completely sent all your data and you want to be sure that it's atleast at the peer os buffer</p>
1
2010-03-31T16:03:46Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
2,605,939
<p>Isn't this code above wrong?</p> <p>The close call directly after the shutdown call might make the kernel discard all outgoing buffers anyway.</p> <p>According to <a href="http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable" rel="nofollow">http://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable</a> one needs to wait between the shutdown and the close until read returns 0.</p>
2
2010-04-09T08:21:53Z
[ "python", "sockets", "asynchronous" ]
socket.shutdown vs socket.close
409,783
<p>I recently saw a bit of code that looked like this (with sock being a socket object of course):</p> <pre><code>sock.shutdown(socket.SHUT_RDWR) sock.close() </code></pre> <p>What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.</p>
87
2009-01-03T20:37:55Z
19,009,869
<p>it's mentioned right in the Socket Programming HOWTO (<a href="http://docs.python.org/2/howto/sockets.html#disconnecting" rel="nofollow">py2</a>/<a href="http://docs.python.org/3/howto/sockets.html#disconnecting" rel="nofollow">py3</a>)</p> <blockquote> <p><strong>Disconnecting</strong></p> <p>Strictly speaking, you’re supposed to use <code>shutdown</code> on a socket before you <code>close</code> it. The <code>shutdown</code> is an advisory to the socket at the other end. Depending on the argument you pass it, it can mean “<em>I’m not going to send anymore, but I’ll still listen</em>”, or “<em>I’m not listening, good riddance!</em>”. Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a <code>close</code> is the same as <code>shutdown(); close()</code>. So in most situations, an explicit shutdown is not needed.</p> <p>...</p> </blockquote>
2
2013-09-25T16:05:00Z
[ "python", "sockets", "asynchronous" ]
How do you embed album art into an MP3 using Python?
409,949
<p>I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.</p>
21
2009-01-03T21:59:30Z
409,988
<p>Looks like you have to add a special type of frame to the MP3. See the site on <a href="http://www.id3.org/id3v2.3.0#head-70a65d30522ef0d37642224c2a40517ae35b7155" rel="nofollow">ID3 tags</a> </p> <p>Also the tutorial for mutagen implies that you can add ID3 tags in mutagen <a href="http://svn.sacredchao.net/svn/quodlibet/trunk/mutagen/TUTORIAL" rel="nofollow">see</a></p>
3
2009-01-03T22:20:00Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
How do you embed album art into an MP3 using Python?
409,949
<p>I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.</p>
21
2009-01-03T21:59:30Z
1,002,814
<p>I've used the <a href="http://eyed3.nicfit.net/">eyeD3</a> module to do this exact thing.</p> <pre><code>def update_id3(mp3_file_name, artwork_file_name, artist, item_title): #edit the ID3 tag to add the title, artist, artwork, date, and genre tag = eyeD3.Tag() tag.link(mp3_file_name) tag.setVersion([2,3,0]) tag.addImage(0x08, artwork_file_name) tag.setArtist(artist) tag.setDate(localtime().tm_year) tag.setTitle(item_title) tag.setGenre("Trance") tag.update() </code></pre>
10
2009-06-16T17:13:44Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
How do you embed album art into an MP3 using Python?
409,949
<p>I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.</p>
21
2009-01-03T21:59:30Z
1,937,425
<p>Here is how to add example.png as album cover into example.mp3 with mutagen:</p> <pre><code>from mutagen.mp3 import MP3 from mutagen.id3 import ID3, APIC, error audio = MP3('example.mp3', ID3=ID3) # add ID3 tag if it doesn't exist try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/png', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=open('example.png').read() ) ) audio.save() </code></pre>
28
2009-12-20T23:02:50Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
How do you embed album art into an MP3 using Python?
409,949
<p>I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.</p>
21
2009-01-03T21:59:30Z
1,961,919
<p>A nice small CLI tool which helped me a lot with checking what I did while developing id3 stuff is mid3v2 which is the mutagen version of id3v2. It comes bundled with the Python mutagen library. The source of this little tool gave me also lots of answers about how to use mutagen.</p>
0
2009-12-25T20:49:06Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
How do you embed album art into an MP3 using Python?
409,949
<p>I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.</p>
21
2009-01-03T21:59:30Z
3,951,901
<p><a href="http://blog.lostpaperclips.com/2010/10/16/embedding-images-in-mp3-files-redux" rel="nofollow">Possible solution</a></p> <p>Are you trying to embed images into a lot of files? If so, I found a script (see the link) that goes through a set of directories, looks for images, and the embeds them into MP3 files. This was useful for me when I wanted to actually have something to look at in CoverFlow on my (now defunct) iPhone.</p>
1
2010-10-17T03:31:38Z
[ "python", "mp3", "metadata", "id3", "albumart" ]
For Python programmers, is there anything equivalent to Perl's CPAN?
410,163
<p>I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules as easy as CPAN. Also, a system that can handle dependencies automatically. I tried to install a module in Python by downloading a zip file from a website, unzipped it, then do:</p> <p><code>sudo python setup.py install</code></p> <p>but it's looking for another module. Now, lazy as I am, I don't like chasing dependencies and such, is there an easy way?</p>
32
2009-01-04T00:30:37Z
410,170
<p>sammy, have a look at <a href="http://pip.openplans.org/">pip</a>, which will let you do "pip install foo", and will download and install its dependencies (as long as they're on <a href="http://pypi.python.org/">PyPI</a>). There's also <a href="http://peak.telecommunity.com/DevCenter/EasyInstall">EasyInstall</a>, but pip is intended to replace that.</p>
32
2009-01-04T00:34:17Z
[ "python", "perl" ]
For Python programmers, is there anything equivalent to Perl's CPAN?
410,163
<p>I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules as easy as CPAN. Also, a system that can handle dependencies automatically. I tried to install a module in Python by downloading a zip file from a website, unzipped it, then do:</p> <p><code>sudo python setup.py install</code></p> <p>but it's looking for another module. Now, lazy as I am, I don't like chasing dependencies and such, is there an easy way?</p>
32
2009-01-04T00:30:37Z
412,211
<p>It might be useful to note that pip and easy_install both use the <a href="http://pypi.python.org/pypi">Python Package Index (PyPI)</a>, sometimes called the "Cheeseshop", to search for packages. Easy_install is currently the most universally supported, as it works with both setuptools and distutils style packaging, completely. See <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">James Bennett's commentary</a> on python packaging for good reasons to use pip, and <a href="http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/">Ian Bicking's reply</a> for some clarifications on the differences.</p>
10
2009-01-05T03:32:27Z
[ "python", "perl" ]
For Python programmers, is there anything equivalent to Perl's CPAN?
410,163
<p>I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules as easy as CPAN. Also, a system that can handle dependencies automatically. I tried to install a module in Python by downloading a zip file from a website, unzipped it, then do:</p> <p><code>sudo python setup.py install</code></p> <p>but it's looking for another module. Now, lazy as I am, I don't like chasing dependencies and such, is there an easy way?</p>
32
2009-01-04T00:30:37Z
653,629
<p>If you do use <code>easy_install</code>, I'd suggest installing packages by doing..</p> <pre><code>easy_install -v -Z package_name | tee date-package.log </code></pre> <p><code>-Z</code> (short for <code>--always-unzip</code>) unzips the <code>.egg</code> files to directories so you can then..</p> <pre><code>less *.egg/EGG-INFO/requires.txt less *.egg/EGG-INFO/PKG-INFO egrep '^(Name|Version|Sum|...)' *.egg/EGG-INFO/PKG-INFO </code></pre> <p>On Sammy's original question, a couple of package indexes other than PyPI are:<br /> <a href="http://www.scipy.org/Topical%5FSoftware" rel="nofollow">Scipy</a> and <a href="http://docs.scipy.org/scipy/docs/scipy" rel="nofollow">Scipy docs</a> for scientific computing<br /> <a href="http://www.ohloh.net/tags/python" rel="nofollow">ohloh</a> with code metrics.</p>
2
2009-03-17T10:09:16Z
[ "python", "perl" ]
Natural/Relative days in Python
410,221
<p>I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.</p> <p>Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.</p> <p>Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. </p>
31
2009-01-04T01:20:55Z
410,328
<p>Are you looking for <a href="http://jehiah.cz/archive/printing-relative-dates-in-python" rel="nofollow">something like this</a> (Printing Relative Dates in Python)?</p>
5
2009-01-04T02:52:41Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
Natural/Relative days in Python
410,221
<p>I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.</p> <p>Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.</p> <p>Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. </p>
31
2009-01-04T01:20:55Z
410,335
<p>Or you could easily adapt <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/timesince.py">timesince.py</a> from Django which only has 2 other dependencies to itself: one for translation (which you might not need) and one for timezones (which can be easily adapted).</p> <p>By the way, <a href="http://code.djangoproject.com/browser/django/trunk/LICENSE">Django has a BSD license</a> which is pretty flexible, you'll be able to use it in whatever project you are currently using.</p>
7
2009-01-04T03:02:03Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
Natural/Relative days in Python
410,221
<p>I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.</p> <p>Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.</p> <p>Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. </p>
31
2009-01-04T01:20:55Z
410,482
<p>While not useful to you at this very moment, it may be so for future searchers: The babel module, which deals with all sorts of locale stuff, has a function for doing more or less what you want. Currently it's only in their trunk though, not in the latest public release (version 0.9.4). Once the functionality lands in a release, you could do something like:</p> <pre><code>from datetime import timedelta from babel.dates import format_timedelta delta = timedelta(days=6) format_timedelta(delta, locale='en_US') u'1 week' </code></pre> <p>This is taken straight from <a href="http://babel.edgewall.org/wiki/Documentation/dates.html#time-delta-formatting">the babel documentation on time delta formatting</a>. This will at least get you parts of the way. It wont do fuzziness down to the level of "moments ago" and such, but it will do "n minutes" etc. correctly pluralized.</p> <p>For what it's worth, the babel module also contains functions for formatting dates and times according to locale, Which might be useful when the time delta is large.</p>
16
2009-01-04T04:52:36Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
Natural/Relative days in Python
410,221
<p>I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.</p> <p>Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.</p> <p>Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. </p>
31
2009-01-04T01:20:55Z
5,164,027
<p>Twitter dates in specific are interesting because they are relative only for the first day. After 24 hours they just show the month and day. After a year they start showing the last two digits of the year. Here's a sample function that does something more akin to Twitter relative dates, though it always shows the year too after 24 hours. It's US locale only, but you can always alter it as needed.</p> <pre><code># tested in Python 2.7 import datetime def prettydate(d): diff = datetime.datetime.utcnow() - d s = diff.seconds if diff.days &gt; 7 or diff.days &lt; 0: return d.strftime('%d %b %y') elif diff.days == 1: return '1 day ago' elif diff.days &gt; 1: return '{} days ago'.format(diff.days) elif s &lt;= 1: return 'just now' elif s &lt; 60: return '{} seconds ago'.format(s) elif s &lt; 120: return '1 minute ago' elif s &lt; 3600: return '{} minutes ago'.format(s/60) elif s &lt; 7200: return '1 hour ago' else: return '{} hours ago'.format(s/3600) </code></pre>
29
2011-03-02T06:09:12Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
Natural/Relative days in Python
410,221
<p>I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.</p> <p>Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.</p> <p>Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. </p>
31
2009-01-04T01:20:55Z
30,048,850
<p>There is <a href="https://pypi.python.org/pypi/humanize/">the humanize package</a>:</p> <pre><code>&gt;&gt;&gt; import humanize &gt;&gt;&gt; import datetime &gt;&gt;&gt; humanize.naturalday(datetime.datetime.now()) 'today' &gt;&gt;&gt; humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1)) 'yesterday' &gt;&gt;&gt; humanize.naturalday(datetime.date(2007, 6, 5)) 'Jun 05' &gt;&gt;&gt; humanize.naturaldate(datetime.date(2007, 6, 5)) 'Jun 05 2007' &gt;&gt;&gt; humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1)) 'a second ago' &gt;&gt;&gt; humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600)) 'an hour ago' </code></pre> <p>Examples for your use case:</p> <pre><code>&gt;&gt;&gt; humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=36000)) '10 hours ago' &gt;&gt;&gt; humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=360000)) '4 days ago' &gt;&gt;&gt; humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600000)) 'a month ago' </code></pre> <p>Further (see link above) it also supports humanization of:</p> <ul> <li>integers</li> <li>file sizes</li> <li>floats (to fractional numbers)</li> </ul>
5
2015-05-05T09:17:37Z
[ "python", "datetime", "human-readable", "datetime-parsing", "humanize" ]
Implementing a buffer-like structure in Python
410,273
<p>I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions? </p>
1
2009-01-04T01:53:27Z
410,284
<p>Examine <a href="https://docs.python.org/library/queue.html" rel="nofollow">https://docs.python.org/library/queue.html</a> to see if it meets your needs.</p>
7
2009-01-04T02:03:01Z
[ "python", "multithreading", "data-structures", "message-queue" ]
Implementing a buffer-like structure in Python
410,273
<p>I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions? </p>
1
2009-01-04T01:53:27Z
410,321
<p>Since you write "thread and/or <em>process</em>", see also <a href="http://docs.python.org/library/multiprocessing.html#pipes-and-queues" rel="nofollow">multiprocessing.Queue and multiprocessing.JoinableQueue</a> from 2.6. Those are interprocess variants of Queue.</p>
2
2009-01-04T02:48:00Z
[ "python", "multithreading", "data-structures", "message-queue" ]
Implementing a buffer-like structure in Python
410,273
<p>I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions? </p>
1
2009-01-04T01:53:27Z
417,538
<p>Use a <a href="http://docs.python.org/3.0/library/io.html#io.BufferedIOBase" rel="nofollow">buffered stream</a> if you are using python 3.0.</p>
1
2009-01-06T18:00:00Z
[ "python", "multithreading", "data-structures", "message-queue" ]
Using AD as authentication for Django
410,392
<p>I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities.</p> <p>Does anyone have a good example of this? </p>
15
2009-01-04T03:37:29Z
410,400
<p>How about that? Did you try that one?</p> <p><a href="http://www.djangosnippets.org/snippets/501/" rel="nofollow">http://www.djangosnippets.org/snippets/501/</a></p>
4
2009-01-04T03:44:56Z
[ "python", "django", "active-directory", "ldap" ]
Using AD as authentication for Django
410,392
<p>I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities.</p> <p>Does anyone have a good example of this? </p>
15
2009-01-04T03:37:29Z
411,080
<p>Here's another more recent snippet (July 2008):</p> <p><a href="http://djangosnippets.org/snippets/901/" rel="nofollow">Authentication Against Active Directory (LDAP) over SSL</a></p>
6
2009-01-04T14:42:18Z
[ "python", "django", "active-directory", "ldap" ]
Using AD as authentication for Django
410,392
<p>I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities.</p> <p>Does anyone have a good example of this? </p>
15
2009-01-04T03:37:29Z
7,914,309
<p>The link provided by Jeff indeed works though it assumes you have a you have a default group where users are added to. I simply replaced:</p> <pre><code>group=Group.objects.get(pk=1) </code></pre> <p>by</p> <pre><code>group,created=Group.objects.get_or_create(name="everyone") </code></pre> <p>If you want tighter integration &amp; more features there is also <a href="http://packages.python.org/django-auth-ldap/" rel="nofollow">django-auth-ldap</a> which gives you you more control over how ldap users/group are mapped onto django users/groups.</p> <p>For debugging the ldap connection I found <a href="http://www.djm.org.uk/using-django-auth-ldap-active-directory-ldaps/" rel="nofollow">this blog post</a> useful, in particular the command for testing the ldap connection with ldap-utils:</p> <pre><code>ldapsearch -H ldaps://ldap-x.companygroup.local:636 -D "CN=Something LDAP,OU=Random Group,DC=companygroup,DC=local" -w "p4ssw0rd" -v -d 1 </code></pre> <p>If you are using ssl there is also the issue of getting hold of a certificate will play nice with. Either you extract it from the server, or you can follow <a href="http://support.microsoft.com/kb/321051" rel="nofollow">these instructions</a> to generate your own.</p>
4
2011-10-27T09:55:43Z
[ "python", "django", "active-directory", "ldap" ]
Using AD as authentication for Django
410,392
<p>I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities.</p> <p>Does anyone have a good example of this? </p>
15
2009-01-04T03:37:29Z
25,569,622
<p>I had the same problem, and noticed that django-auth-ldap does not support SASL at all -> plain text passwords over the connection if TSL is not available.</p> <p>Here is what i did for the problem: <a href="https://github.com/susundberg/django-auth-ldap-ad" rel="nofollow">https://github.com/susundberg/django-auth-ldap-ad</a></p>
0
2014-08-29T13:44:53Z
[ "python", "django", "active-directory", "ldap" ]
TKinter windows do not appear when using multiprocessing on Linux
410,469
<p>I want to spawn another process to display an error message asynchronously while the rest of the application continues. </p> <p>I'm using the <code>multiprocessing</code> module in Python 2.6 to create the process and I'm trying to display the window with <code>TKinter</code>. </p> <p>This code worked okay on Windows, but running it on Linux the <code>TKinter</code> window does not appear if I call <code>'showerror("MyApp Error", "Something bad happened.")'</code>. It <em>does</em> appear if I run it in the same process by calling <code>showerrorprocess</code> directly. Given this, it seems <code>TKinter</code> is working properly. I can print to the console and do other things from processes spawned by <code>multiprocessing</code>, so it seems to be working too. </p> <p>They just don't seem to work together. Do I need to do something special to allow spawned subprocesses to create windows?</p> <pre><code>from multiprocessing import Process from Tkinter import Tk, Text, END, BOTH, DISABLED import sys import traceback def showerrorprocess(title,text): """Pop up a window with the given title and text. The text will be selectable (so you can copy it to the clipboard) but not editable. Returns when the window is closed.""" root = Tk() root.title(title) text_box = Text(root,width=80,height=15) text_box.pack(fill=BOTH) text_box.insert(END,text) text_box.config(state=DISABLED) def quit(): root.destroy() root.quit() root.protocol("WM_DELETE_WINDOW", quit) root.mainloop() def showerror(title,text): """Pop up a window with the given title and text. The text will be selectable (so you can copy it to the clipboard) but not editable. Runs asynchronously in a new child process.""" process = Process(target=showerrorprocess,args=(title,text)) process.start() </code></pre> <hr> <p><strong>Edit</strong></p> <p>The issue seems to be that <code>TKinter</code> was imported by the parent process, and "inherited" into the child process, but somehow its state is inextricably linked to the parent process and it cannot work in the child. So long as you make sure not to import <code>TKinter</code> before you spawn the child process, it will work because then it is the child process that is importing it for the first time.</p>
4
2009-01-04T04:36:34Z
410,587
<p>Maybe calling the shell command <code>xhost +</code> before calling your program from that same shell will work?</p> <p>I am guessing your problem lies with the X-server. </p>
0
2009-01-04T06:54:20Z
[ "python", "linux", "tkinter", "multiprocessing" ]
TKinter windows do not appear when using multiprocessing on Linux
410,469
<p>I want to spawn another process to display an error message asynchronously while the rest of the application continues. </p> <p>I'm using the <code>multiprocessing</code> module in Python 2.6 to create the process and I'm trying to display the window with <code>TKinter</code>. </p> <p>This code worked okay on Windows, but running it on Linux the <code>TKinter</code> window does not appear if I call <code>'showerror("MyApp Error", "Something bad happened.")'</code>. It <em>does</em> appear if I run it in the same process by calling <code>showerrorprocess</code> directly. Given this, it seems <code>TKinter</code> is working properly. I can print to the console and do other things from processes spawned by <code>multiprocessing</code>, so it seems to be working too. </p> <p>They just don't seem to work together. Do I need to do something special to allow spawned subprocesses to create windows?</p> <pre><code>from multiprocessing import Process from Tkinter import Tk, Text, END, BOTH, DISABLED import sys import traceback def showerrorprocess(title,text): """Pop up a window with the given title and text. The text will be selectable (so you can copy it to the clipboard) but not editable. Returns when the window is closed.""" root = Tk() root.title(title) text_box = Text(root,width=80,height=15) text_box.pack(fill=BOTH) text_box.insert(END,text) text_box.config(state=DISABLED) def quit(): root.destroy() root.quit() root.protocol("WM_DELETE_WINDOW", quit) root.mainloop() def showerror(title,text): """Pop up a window with the given title and text. The text will be selectable (so you can copy it to the clipboard) but not editable. Runs asynchronously in a new child process.""" process = Process(target=showerrorprocess,args=(title,text)) process.start() </code></pre> <hr> <p><strong>Edit</strong></p> <p>The issue seems to be that <code>TKinter</code> was imported by the parent process, and "inherited" into the child process, but somehow its state is inextricably linked to the parent process and it cannot work in the child. So long as you make sure not to import <code>TKinter</code> before you spawn the child process, it will work because then it is the child process that is importing it for the first time.</p>
4
2009-01-04T04:36:34Z
434,207
<p>This <a href="http://pyinsci.blogspot.com/2008/09/python-processing.html" rel="nofollow">discussion</a> could be helpful.</p> <blockquote> <p>Here's some sample problems I found: </p> <ol> <li><p>While the multiprocessing module follows threading closely, it's definitely not an exact match. One example: since parameters to a process must be <em>pickleable</em>, I had to go through a lot of code changes to avoid passing <code>Tkinter</code> objects since these aren't <em>pickleable</em>. This doesn't occur with the threading module. </p></li> <li><p><code>process.terminate()</code> doesn't really work after the first attempt. The second or third attempt simply hangs the interpreter, probably because data structures are corrupted (mentioned in the API, but this is little consolation).</p></li> </ol> </blockquote>
4
2009-01-12T01:43:08Z
[ "python", "linux", "tkinter", "multiprocessing" ]
what's the 5 character alphanumeric id in reddit URL?
410,485
<p>Whats the <code>7n5lu</code> in the reddit URL <code>http://www.reddit.com/r/reddit.com/comments/7n5lu/man_can_fly_if_you_watch_one_video_in_2</code></p> <p>how is it generated?</p> <p>update: @Gerald, Thanks for the code. I initially thought this is some obfuscation of the id. But, it is just doing the conversion from integer to a more compact representation. I am thinking, why is this being done? why not use the original integer itself!!</p> <pre><code>&gt;&gt;&gt; to36(4000) '334' &gt;&gt;&gt; to36(4001) '335' </code></pre>
12
2009-01-04T05:00:52Z
410,498
<p>That looks like a unique id for the thread. It's most likely used to find the thread in the database.</p>
0
2009-01-04T05:13:45Z
[ "python", "url", "slug", "reddit" ]
what's the 5 character alphanumeric id in reddit URL?
410,485
<p>Whats the <code>7n5lu</code> in the reddit URL <code>http://www.reddit.com/r/reddit.com/comments/7n5lu/man_can_fly_if_you_watch_one_video_in_2</code></p> <p>how is it generated?</p> <p>update: @Gerald, Thanks for the code. I initially thought this is some obfuscation of the id. But, it is just doing the conversion from integer to a more compact representation. I am thinking, why is this being done? why not use the original integer itself!!</p> <pre><code>&gt;&gt;&gt; to36(4000) '334' &gt;&gt;&gt; to36(4001) '335' </code></pre>
12
2009-01-04T05:00:52Z
410,504
<p>The reddit source code <a href="https://github.com/reddit/reddit">is available</a>! Here is what I found for generating that string:</p> <pre><code>def to_base(q, alphabet): if q &lt; 0: raise ValueError, "must supply a positive integer" l = len(alphabet) converted = [] while q != 0: q, r = divmod(q, l) converted.insert(0, alphabet[r]) return "".join(converted) or '0' def to36(q): return to_base(q, '0123456789abcdefghijklmnopqrstuvwxyz') </code></pre> <p>and elsewhere, under the "Link" class:</p> <pre><code>@property def _id36(self): return to36(self._id) </code></pre>
24
2009-01-04T05:21:43Z
[ "python", "url", "slug", "reddit" ]
what's the 5 character alphanumeric id in reddit URL?
410,485
<p>Whats the <code>7n5lu</code> in the reddit URL <code>http://www.reddit.com/r/reddit.com/comments/7n5lu/man_can_fly_if_you_watch_one_video_in_2</code></p> <p>how is it generated?</p> <p>update: @Gerald, Thanks for the code. I initially thought this is some obfuscation of the id. But, it is just doing the conversion from integer to a more compact representation. I am thinking, why is this being done? why not use the original integer itself!!</p> <pre><code>&gt;&gt;&gt; to36(4000) '334' &gt;&gt;&gt; to36(4001) '335' </code></pre>
12
2009-01-04T05:00:52Z
410,637
<p>Little remark.</p> <p>It is not sufficient for this example but usually appending to lists </p> <pre><code>a = [] for i in range(NNN): a.append(i) a.reverse() </code></pre> <p>really more efficient than inserting at head.</p> <pre><code>a = [] for i in range(NNN): a.insert(0,i) </code></pre> <p>.</p>
-1
2009-01-04T07:56:11Z
[ "python", "url", "slug", "reddit" ]
Best modules to develop a simple windowed 3D modeling application?
410,941
<p>I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport.</p> <p>I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond to the various mouse events. It wouldn't hurt to have some convenience math in place for converting the 2D mouse positions in "camera space" into world space coordinates to make selection tasks easier.</p> <p>I'm looking for recommendations on which modules I should be looking at.</p>
3
2009-01-04T12:52:23Z
411,099
<p>I'm not aware of any boxed up modules which provide that functionality, but you can take some inspiration from <a href="http://www.blender.org/" rel="nofollow">Blender 3D</a>, which has all of the features you described: its a 3D modeling tool, its written in Python, has an OpenGL viewport which responds to mouse events, and its <a href="http://projects.blender.org/" rel="nofollow">open source</a>.</p> <p>You can probably take inspiration from Blender and apply it your own projects.</p>
1
2009-01-04T15:00:04Z
[ "python", "opengl", "3d", "wxpython" ]
Best modules to develop a simple windowed 3D modeling application?
410,941
<p>I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport.</p> <p>I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond to the various mouse events. It wouldn't hurt to have some convenience math in place for converting the 2D mouse positions in "camera space" into world space coordinates to make selection tasks easier.</p> <p>I'm looking for recommendations on which modules I should be looking at.</p>
3
2009-01-04T12:52:23Z
411,163
<p>Any reason you wouldn't use wx's <a href="http://wiki.wxpython.org/GLCanvas" rel="nofollow">GLCanvas</a>? <a href="http://code.activestate.com/recipes/325392/" rel="nofollow">Here's</a> an example that draws a sphere.</p>
3
2009-01-04T15:44:54Z
[ "python", "opengl", "3d", "wxpython" ]
Best modules to develop a simple windowed 3D modeling application?
410,941
<p>I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport.</p> <p>I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respond to the various mouse events. It wouldn't hurt to have some convenience math in place for converting the 2D mouse positions in "camera space" into world space coordinates to make selection tasks easier.</p> <p>I'm looking for recommendations on which modules I should be looking at.</p>
3
2009-01-04T12:52:23Z
411,174
<p>As a very basic 3D modelling tool I'd recommend <a href="http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#50351">VPython</a>.</p>
2
2009-01-04T15:54:16Z
[ "python", "opengl", "3d", "wxpython" ]
How do I parse XML from a Google app engine app?
410,954
<p>How do I parse XML from a Google app engine app? Any examples?</p>
14
2009-01-04T13:05:41Z
410,962
<p>AFAIK Google App Engine provides a fairly complete Python environment for you to use. Since Python comes with "batteries included" you may want to evaluate the different APIs which vanilla Python offers you: <a href="http://docs.python.org/library/markup.html" rel="nofollow">http://docs.python.org/library/markup.html</a></p>
4
2009-01-04T13:14:25Z
[ "python", "xml", "google-app-engine", "parsing" ]
How do I parse XML from a Google app engine app?
410,954
<p>How do I parse XML from a Google app engine app? Any examples?</p>
14
2009-01-04T13:05:41Z
410,971
<p>Take a look at <a href="http://stackoverflow.com/search?q=iterparse">existing answers on XML and Python</a>.</p> <p>Something like this could work:</p> <pre><code>from cStringIO import StringIO from xml.etree import cElementTree as etree xml = "&lt;a&gt;aaa&lt;b&gt;bbb&lt;/b&gt;&lt;/a&gt;" for event, elem in etree.iterparse(StringIO(xml)): print elem.text </code></pre> <p>It prints:</p> <pre><code>bbb aaa </code></pre>
8
2009-01-04T13:27:43Z
[ "python", "xml", "google-app-engine", "parsing" ]
How do I parse XML from a Google app engine app?
410,954
<p>How do I parse XML from a Google app engine app? Any examples?</p>
14
2009-01-04T13:05:41Z
711,167
<p>Since the question was asked, Google has whitelisted pyexpat, which includes minidom, so you can use the following code without having to upload any libraries:</p> <pre><code>from xml.dom import minidom dom = minidom.parseString('&lt;eg&gt;example text&lt;/eg&gt;') </code></pre> <p>More information: <a href="http://docs.python.org/library/xml.dom.minidom.html">http://docs.python.org/library/xml.dom.minidom.html</a></p>
20
2009-04-02T19:09:49Z
[ "python", "xml", "google-app-engine", "parsing" ]
gtk.Builder, container subclass and binding child widgets
411,708
<p>I'm trying to use custom container widgets in gtk.Builder definition files. As far as instantiating those widgets, it works great:</p> <pre><code>#!/usr/bin/env python import sys import gtk class MyDialog(gtk.Dialog): __gtype_name__ = "MyDialog" if __name__ == "__main__": builder = gtk.Builder() builder.add_from_file("mydialog.glade") dialog = builder.get_object("mydialog-instance") dialog.run() </code></pre> <p>Now the question is that say I have a gtk.TreeView widget inside that dialog. I'm trying to figure out how to bind that widget to an MyDialog instance variable. </p> <p>One cheap alternative I can think of is to call additional method after getting the dialog widget like so:</p> <pre><code>dialog = builder.get_object("mydialog-instance") dialog.bind_widgets(builder) </code></pre> <p>But that seems fairly awkward. Has anyone solved this already or has a better idea on how to go about doing it?</p> <p>Thanks,</p>
4
2009-01-04T21:30:01Z
412,097
<p>Alright, I guess I answered my own question.</p> <p>One way to do the above is to override gtk.Buildable's parser_finished(), which gives access to the builder object that created the class instance itself. The method is called after entire .xml file has been loaded, so all of the additional widgets we may want to get hold of are already present and intialized:</p> <pre><code>class MyDialog(gtk.Dialog, gtk.Buildable): __gtype_name__ = "MyDialog" def do_parser_finished(self, builder): self.treeview = builder.get_object("treeview1") # Do any other associated post-initialization </code></pre> <p>One thing to note is that for some reason (at least for me, in pygtk 2.12), if I don't explicitly inherit from gtk.Buildable, the override method doesn't get called, even thought gtk.Dialog already implements the buildable interface.</p>
5
2009-01-05T01:56:06Z
[ "python", "gtk", "bind", "subclass", "gtkbuilder" ]
Variable number of inputs with Django forms possible?
411,761
<p>Is it possible to have a variable number of fields using django forms?</p> <p>The specific application is this:</p> <p>A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.</p> <p>So <strong>how do I get django to generate a form using a variable number of input fields</strong> (which could be passed as an argument if necessary)?</p> <p><strong>edit:</strong> a few things have changed since the <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">article mentioned in jeff bauer's answer</a> was written. </p> <p>Namely this line of code which doesn't seem to work:</p> <pre><code># BAD CODE DO NOT USE!!! return type('ContactForm', [forms.BaseForm], { 'base_fields': fields }) </code></pre> <p>So here is what I came up with...</p> <h1>The Answer I used:</h1> <pre><code> from tagging.forms import TagField from django import forms def make_tagPhotos_form(photoIdList): "Expects a LIST of photo objects (ie. photo_sharing.models.photo)" fields = {} for id in photoIdList: id = str(id) fields[id+'_name'] = forms.CharField() fields[id+'_tags'] = TagField() fields[id+'_description'] = forms.CharField(widget=forms.Textarea) return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields }) </code></pre> <p>note tagging is not part of django, but it is free and very useful. check it out: <a href="http://code.google.com/p/django-tagging/">django-tagging</a></p>
17
2009-01-04T22:00:33Z
411,852
<p>If you run</p> <pre><code>python manage.py shell </code></pre> <p>and type:</p> <pre><code>from app.forms import PictureForm p = PictureForm() p.fields type(p.fields) </code></pre> <p>you'll see that p.fields is a SortedDict. you just have to insert a new field. Something like</p> <pre><code>p.fields.insert(len(p.fields)-2, 'fieldname', Field()) </code></pre> <p>In this case it would insert before the last field, a new field. You should now adapt to your code.</p> <p>Other alternative is to make a for/while loop in your template and do the form in HTML, but django forms rock for some reason, right?</p>
7
2009-01-04T22:57:03Z
[ "python", "django", "django-forms" ]
Variable number of inputs with Django forms possible?
411,761
<p>Is it possible to have a variable number of fields using django forms?</p> <p>The specific application is this:</p> <p>A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.</p> <p>So <strong>how do I get django to generate a form using a variable number of input fields</strong> (which could be passed as an argument if necessary)?</p> <p><strong>edit:</strong> a few things have changed since the <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">article mentioned in jeff bauer's answer</a> was written. </p> <p>Namely this line of code which doesn't seem to work:</p> <pre><code># BAD CODE DO NOT USE!!! return type('ContactForm', [forms.BaseForm], { 'base_fields': fields }) </code></pre> <p>So here is what I came up with...</p> <h1>The Answer I used:</h1> <pre><code> from tagging.forms import TagField from django import forms def make_tagPhotos_form(photoIdList): "Expects a LIST of photo objects (ie. photo_sharing.models.photo)" fields = {} for id in photoIdList: id = str(id) fields[id+'_name'] = forms.CharField() fields[id+'_tags'] = TagField() fields[id+'_description'] = forms.CharField(widget=forms.Textarea) return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields }) </code></pre> <p>note tagging is not part of django, but it is free and very useful. check it out: <a href="http://code.google.com/p/django-tagging/">django-tagging</a></p>
17
2009-01-04T22:00:33Z
411,862
<p>Use either multiple forms (django.forms.Form not the tag)</p> <pre><code>class Foo(forms.Form): field = forms.Charfield() forms = [Foo(prefix=i) for i in xrange(x)] </code></pre> <p>or add multiple fields to the form dynamically using self.fields.</p> <pre><code>class Bar(forms.Form): def __init__(self, fields, *args, **kwargs): super(Bar, self).__init__(*args, **kwargs) for i in xrange(fields): self.fields['my_field_%i' % i] = forms.Charfield() </code></pre>
7
2009-01-04T23:00:48Z
[ "python", "django", "django-forms" ]
Variable number of inputs with Django forms possible?
411,761
<p>Is it possible to have a variable number of fields using django forms?</p> <p>The specific application is this:</p> <p>A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.</p> <p>So <strong>how do I get django to generate a form using a variable number of input fields</strong> (which could be passed as an argument if necessary)?</p> <p><strong>edit:</strong> a few things have changed since the <a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">article mentioned in jeff bauer's answer</a> was written. </p> <p>Namely this line of code which doesn't seem to work:</p> <pre><code># BAD CODE DO NOT USE!!! return type('ContactForm', [forms.BaseForm], { 'base_fields': fields }) </code></pre> <p>So here is what I came up with...</p> <h1>The Answer I used:</h1> <pre><code> from tagging.forms import TagField from django import forms def make_tagPhotos_form(photoIdList): "Expects a LIST of photo objects (ie. photo_sharing.models.photo)" fields = {} for id in photoIdList: id = str(id) fields[id+'_name'] = forms.CharField() fields[id+'_tags'] = TagField() fields[id+'_description'] = forms.CharField(widget=forms.Textarea) return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields }) </code></pre> <p>note tagging is not part of django, but it is free and very useful. check it out: <a href="http://code.google.com/p/django-tagging/">django-tagging</a></p>
17
2009-01-04T22:00:33Z
412,149
<p>Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.</p> <pre><code>class EligibilityForm(forms.Form): def __init__(self, *args, **kwargs): super(EligibilityForm, self).__init__(*args, **kwargs) # dynamic fields here ... self.fields['plan_id'] = CharField() # normal fields here ... date_requested = DateField() </code></pre> <p>For a better elaboration of this technique, see James Bennett's article: <strong>So you want a dynamic form?</strong></p> <p><a href="http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/">http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/</a></p>
13
2009-01-05T02:35:12Z
[ "python", "django", "django-forms" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
411,814
<pre><code>from django.authx.models import User model = User model.objects.all() </code></pre>
3
2009-01-04T22:34:45Z
[ "python", "django", "django-models", "django-queryset" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
411,822
<p>If you have the model name passed as a string I guess one way could be</p> <pre><code>modelname = "User" model = globals()[modelname] </code></pre> <p>But mucking about with globals() might be a bit dangerous in some contexts. So handle with care :)</p>
-2
2009-01-04T22:40:44Z
[ "python", "django", "django-models", "django-queryset" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
411,880
<p>I think you're looking for this:</p> <pre><code>from django.db.models.loading import get_model model = get_model('app_name', 'model_name') </code></pre> <p>There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)</p> <p><strong>Update:</strong> According to Django's <a href="https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9" rel="nofollow">deprecation timeline</a>, <code>django.db.models.loading</code> has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in <a href="http://stackoverflow.com/a/28380435/996114">Alasdair's answer</a>, a new API for dynamically loading models was added to Django 1.7.</p>
32
2009-01-04T23:11:28Z
[ "python", "django", "django-models", "django-queryset" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
411,925
<blockquote> <p>model = django.authx.models.User</p> <p>? Django returns an error, "global name django is not defined."</p> </blockquote> <p>Django does not return the error. Python does.</p> <p>First, you MUST import the model. You must import it with</p> <pre><code>from django.authx.models import User </code></pre> <p>Second, if you get an error that <code>django</code> is not defined, then Django is not installed correctly. You must have Django on your <code>PYTHONPATH</code> or installed in your Python lib/site-packages.</p> <p>To install Django correctly, see <a href="http://docs.djangoproject.com/en/dev/intro/install/#intro-install" rel="nofollow">http://docs.djangoproject.com/en/dev/intro/install/#intro-install</a></p>
1
2009-01-04T23:42:46Z
[ "python", "django", "django-models", "django-queryset" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
411,927
<p>Classes are "first class" objects in Python, meaning they can be passed around and manipulated just like all other objects.</p> <p>Models are classes -- you can tell from the fact that you create new models using class statements:</p> <pre><code>class Person(models.Model): last_name = models.CharField(max_length=64) class AnthropomorphicBear(models.Model): last_name = models.CharField(max_length=64) </code></pre> <p>Both the <code>Person</code> and <code>AnthropomorphicBear</code> identifiers are bound to Django classes, so you can pass them around. This can useful if you want to create helper functions that work at the model level (and share a common interface):</p> <pre><code>def print_obj_by_last_name(model, last_name): model_name = model.__name__ matches = model.objects.filter(last_name=last_name).all() print('{0}: {1!r}'.format(model_name, matches)) </code></pre> <p>So <code>print_obj_by_last_name</code> will work with either the <code>Person</code> or <code>AnthropomorphicBear</code> models. Just pass the model in like so:</p> <pre><code>print_obj_by_last_name(model=Person, last_name='Dole') print_obj_by_last_name(model=AnthropomorphicBear, last_name='Fozzy') </code></pre>
0
2009-01-04T23:43:50Z
[ "python", "django", "django-models", "django-queryset" ]
How do I retrieve a Django model class dynamically?
411,810
<p>Without having the full module path of a Django model, is it possible to do something like:</p> <pre><code>model = 'User' [in Django namespace] model.objects.all() </code></pre> <p>...as opposed to:</p> <pre><code>User.objects.all(). </code></pre> <p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p> <pre><code>model = django.authx.models.User </code></pre> <p>Without Django returning the error:</p> <pre><code>"global name django is not defined." </code></pre>
15
2009-01-04T22:32:50Z
28,380,435
<p>For Django 1.7+, there is an <a href="https://docs.djangoproject.com/en/1.8/ref/applications/#module-django.apps">applications registry</a>. You can use the <a href="https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.apps.get_model"><code>apps.get_model</code></a> method to dynamically get a model.</p> <pre><code>from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') </code></pre>
11
2015-02-07T09:19:49Z
[ "python", "django", "django-models", "django-queryset" ]
Django file upload failing occasionally
411,902
<p>I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. </p> <p>The code for the upload is similar to what described in the Django documentation:</p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) </code></pre> <p>This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error:</p> <pre><code>IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) </code></pre> <p>I tried to run everything using mod_wsgi and no difference.</p> <p>Does anybody know what am I doing wrong?</p> <p>Thanks in advance for your help!</p> <p>ppdo</p> <p>=====</p> <p>Updated:</p> <p>Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before. </p>
8
2009-01-04T23:28:35Z
411,971
<p>How large is the file? It may take long enough to upload that the upload script times out, so try increasing the execution time for that script.</p>
0
2009-01-05T00:21:48Z
[ "python", "django", "apache" ]
Django file upload failing occasionally
411,902
<p>I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. </p> <p>The code for the upload is similar to what described in the Django documentation:</p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) </code></pre> <p>This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error:</p> <pre><code>IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) </code></pre> <p>I tried to run everything using mod_wsgi and no difference.</p> <p>Does anybody know what am I doing wrong?</p> <p>Thanks in advance for your help!</p> <p>ppdo</p> <p>=====</p> <p>Updated:</p> <p>Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before. </p>
8
2009-01-04T23:28:35Z
413,089
<p>I would chase down the exception value </p> <pre><code>Client read error (Timeout?) </code></pre> <p>this seems odd enough. Try reading <a href="http://groups.google.com/group/django-users/browse_thread/thread/03ff1503377a8bfc" rel="nofollow">this thread</a></p>
1
2009-01-05T13:28:23Z
[ "python", "django", "apache" ]
Django file upload failing occasionally
411,902
<p>I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. </p> <p>The code for the upload is similar to what described in the Django documentation:</p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) </code></pre> <p>This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error:</p> <pre><code>IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) </code></pre> <p>I tried to run everything using mod_wsgi and no difference.</p> <p>Does anybody know what am I doing wrong?</p> <p>Thanks in advance for your help!</p> <p>ppdo</p> <p>=====</p> <p>Updated:</p> <p>Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before. </p>
8
2009-01-04T23:28:35Z
416,189
<p>Using mod_wsgi made the problem go away for Firefox. </p> <p>Limiting my research to an interaction problem between Apache and Safari, I stumbled upon this bug report for Apache <a href="https://bugs.webkit.org/show_bug.cgi?id=5760">https://bugs.webkit.org/show_bug.cgi?id=5760</a> that describes something very similar to what is happening and it is apparently still open. Reading this gave me the idea to try and disable the keepalive and, though I need to test it more extensively, it seems the problem is gone.</p> <p>A simple:</p> <p>BrowserMatch "Safari" nokeepalive </p> <p>in the Apache configuration did the trick.</p>
8
2009-01-06T11:33:53Z
[ "python", "django", "apache" ]
Django file upload failing occasionally
411,902
<p>I am trying to port my first Django 1.0.2 application to run on OSX/Leopard with Apache + mod_python 3.3.1 + python 2.6.1 (all running in 64-bit mode) and I am experiencing an occasional error when uploading a file that was not present when testing with the Django development server. </p> <p>The code for the upload is similar to what described in the Django documentation:</p> <pre><code>class UploadFileForm(forms.Form): file = forms.FileField() description = forms.CharField(max_length=100) notifygroup = forms.BooleanField(label='Notify Group?', required=False) def upload_file(request, date, meetingid ): print date, meetingid if request.method == 'POST': print 'before reloading the form...' form = UploadFileForm(request.POST, request.FILES) print 'after reloading the form' if form.is_valid(): try: handle_uploaded_file(request.FILES['file'], request.REQUEST['date'], request.REQUEST['description'], form.cleaned_data['notifygroup'], meetingid ) except: return render_to_response('uploaded.html', { 'message': 'Error! File not uploaded!' }) return HttpResponseRedirect('/myapp/uploaded/') else: form = UploadFileForm() return render_to_response('upload.html', {'form': form, 'date':date, 'meetingid':meetingid}) </code></pre> <p>This code normally works correctly, but sometimes (say, once every 10 uploads) and after a fairly long waiting time, it fails with the following error:</p> <pre><code>IOError at /myapp/upload/2009-01-03/1 Client read error (Timeout?) Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Exception Type: IOError Exception Value: Client read error (Timeout?) Exception Location: /Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py in read, line 406 Python Executable: /usr/sbin/httpd Python Version: 2.6.1 Python Path: ['/djangoapps/myapp/', '/djangoapps/', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python26.zip', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-darwin', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-tk', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-old', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages'] Server time: Sun, 4 Jan 2009 22:42:04 +0100 Environment: Request Method: POST Request URL: http://192.168.0.164/myapp/upload/2009-01-03/1 Django Version: 1.0.2 final Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'myapp.application1'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 86. response = callback(request, *callback_args, **callback_kwargs) File "/djangoapps/myapp/../myapp/application1/views.py" in upload_file 137. form = UploadFileForm(request.POST, request.FILES) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _get_post 113. self._load_post_and_files() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/core/handlers/modpython.py" in _load_post_and_files 87. self._post, self._files = self.parse_file_upload(self.META, self._req) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/__init__.py" in parse_file_upload 124. return parser.parse() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parse 134. for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __iter__ 607. for sub_stream in boundarystream: File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 421. return LazyStream(BoundaryIter(self._stream, self._boundary)) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in __init__ 447. unused_char = self._stream.read(1) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 300. out = ''.join(parts()) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in parts 293. chunk = self.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 315. output = self._producer.next() File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in next 376. data = self.flo.read(self.chunk_size) File "/Library/Frameworks/Python64.framework/Versions/2.6/lib/python2.6/site-packages/django/http/multipartparser.py" in read 406. return self._file.read(num_bytes) Exception Type: IOError at /myapp/upload/2009-01-03/1 Exception Value: Client read error (Timeout?) </code></pre> <p>I tried to run everything using mod_wsgi and no difference.</p> <p>Does anybody know what am I doing wrong?</p> <p>Thanks in advance for your help!</p> <p>ppdo</p> <p>=====</p> <p>Updated:</p> <p>Though I succeeded uploading large files (60+ MB), when it fails it fails with no evident relationship with the size of the upload, i.e. it fails also with 10kB files that have successfully been uploaded before. </p>
8
2009-01-04T23:28:35Z
2,465,744
<p>Long time unanswered here, but having experienced this myself and tried a few things to resolve it. It seems in my case, it happened if someone canceled a download (or lost connection) during an upload.</p> <p>You can try this yourself to see if this is what is causing the "IOError: request data read error" for you: upload a large enough file that you can unplug your ethernet cable from your computer or router. Wait a bit and see if you get the error. I do everytime!</p>
0
2010-03-17T20:43:57Z
[ "python", "django", "apache" ]
How to bring program to front using python
412,214
<p>I would like to force my python app to the front if a condition occurs. I'm using Kubuntu &amp; QT3.1</p> <p>I've tried setActiveWindow(), but it only flashes the task bar in KDE.</p> <p>I think Windows has a function bringwindowtofront() for VB.</p> <p>Is there something similar for KDE?</p>
1
2009-01-05T03:36:21Z
412,294
<p>Have you tried using those 3 (in this order) on your window instead of only <code>setActiveWindow</code>?</p> <pre><code>show() raise() # this might be raiseW() in Python setActiveWindow() </code></pre>
1
2009-01-05T04:46:47Z
[ "python", "qt" ]
How to bring program to front using python
412,214
<p>I would like to force my python app to the front if a condition occurs. I'm using Kubuntu &amp; QT3.1</p> <p>I've tried setActiveWindow(), but it only flashes the task bar in KDE.</p> <p>I think Windows has a function bringwindowtofront() for VB.</p> <p>Is there something similar for KDE?</p>
1
2009-01-05T03:36:21Z
413,073
<p>Check if KWin is configured to prevent focus stealing.</p> <p>There might be nothing wrong with your code -- but we linux people don't like applications bugging us when we work, so stealing focus is kinda frowned upon, and difficult under some window managers.</p>
4
2009-01-05T13:23:31Z
[ "python", "qt" ]
How to bring program to front using python
412,214
<p>I would like to force my python app to the front if a condition occurs. I'm using Kubuntu &amp; QT3.1</p> <p>I've tried setActiveWindow(), but it only flashes the task bar in KDE.</p> <p>I think Windows has a function bringwindowtofront() for VB.</p> <p>Is there something similar for KDE?</p>
1
2009-01-05T03:36:21Z
415,183
<p>It works!</p> <pre><code>show() raiseW() setActiveWindow() #in that sequence </code></pre> <p><em>plus</em> KWin config change to force focus steal prevention.</p> <p>Thanks for the help.</p>
1
2009-01-06T02:13:16Z
[ "python", "qt" ]
How to (simply) connect Python to my web site?
412,368
<p>I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website? After dabbling with Django, I've found it overkill and over my head, but if that's the only option I'll learn to use it.</p> <p>Does anyone know an easy way to output a database of arbitrary format to one or more HTML (or different format) files?</p>
3
2009-01-05T05:57:25Z
412,371
<p>I would generate a page or two of HTML using a template engine (<a href="http://jinja.pocoo.org/2/" rel="nofollow">Jinja</a> is my personal choice) and just stick them in your <code>public_html</code> directory or wherever the webserver's root is.</p>
11
2009-01-05T06:00:41Z
[ "python", "website" ]
How to (simply) connect Python to my web site?
412,368
<p>I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website? After dabbling with Django, I've found it overkill and over my head, but if that's the only option I'll learn to use it.</p> <p>Does anyone know an easy way to output a database of arbitrary format to one or more HTML (or different format) files?</p>
3
2009-01-05T05:57:25Z
415,785
<p>Generating static HTML is great, if that works for you go for it. </p> <p>If you want a dynamic website and the ability to update, <a href="http://webpy.org/" rel="nofollow">web.py</a> might work for you. Simpler than Django and stand-alone (although just about everything I start in web.py eventually gets rewritten as a Django app...)</p>
0
2009-01-06T08:08:27Z
[ "python", "website" ]
Using mocking to test derived classes in Python
412,472
<p>I have code that looks like this:</p> <pre><code>import xmlrpclib class Base(object): def __init__(self, server): self.conn = xmlrpclib.ServerProxy(server) def foo(self): return self.conn.do_something() class Derived(Base): def foo(self): if Base.foo(): return self.conn.do_something_else() </code></pre> <p>How should I use mocking to test the behavior of the <code>Derived</code> class? I don't want to assume that whatever the XML-RPC connection talks to will actually exist, but I feel like mocking the <code>xmlrpclib</code> module requires too much knowledge of the implementation of the <code>Base</code> class (which I have other tests for).</p> <p>Or, I guess, should I even use mocking to test this? If not, how would you test it?</p>
4
2009-01-05T07:16:34Z
412,580
<p>You could create a fake ServerProxy class, and substitute that for testing.</p> <p>Something like this:</p> <pre><code>class FakeServerProxy(object): def __init__(self, server): self.server = server def do_something(self): pass def do_something_else(self): pass def test_derived(): xmlrpclib.ServerProxy = FakeServerProxy derived = Derived(None) derived.foo() </code></pre>
4
2009-01-05T08:33:05Z
[ "python", "mocking" ]
Using mocking to test derived classes in Python
412,472
<p>I have code that looks like this:</p> <pre><code>import xmlrpclib class Base(object): def __init__(self, server): self.conn = xmlrpclib.ServerProxy(server) def foo(self): return self.conn.do_something() class Derived(Base): def foo(self): if Base.foo(): return self.conn.do_something_else() </code></pre> <p>How should I use mocking to test the behavior of the <code>Derived</code> class? I don't want to assume that whatever the XML-RPC connection talks to will actually exist, but I feel like mocking the <code>xmlrpclib</code> module requires too much knowledge of the implementation of the <code>Base</code> class (which I have other tests for).</p> <p>Or, I guess, should I even use mocking to test this? If not, how would you test it?</p>
4
2009-01-05T07:16:34Z
918,439
<p>With some trivial refactoring (call to <code>do_something_else</code> is extracted), you can test <code>Derived.foo</code> logic without needing to "know" about XMLRPC.</p> <pre><code>import xmlrpclib class Base(object): def __init__(self, server): self.conn = xmlrpclib.ServerProxy(server) def foo(self): return self.conn.do_something() class Derived(Base): def foo(self): if Base.foo(self): return self._bar() def _bar(self): # moved to its own method so that you # you can stub it out to avoid any XMLRPCs # actually taking place. return self.conn.do_something_else() import mox d = Derived('http://deep-thought/unanswered/tagged/life+universe+everything') m = mox.Mox() m.StubOutWithMock(Base, 'foo') m.StubOutWithMock(d, '_bar') Base.foo(d).AndReturn(True) d._bar() # Will be called becase Boo.foo returns True. m.ReplayAll() d.foo() m.UnsetStubs() m.VerifyAll() </code></pre> <p>Alternatively or even preferably, you may extract the call to <code>do_something_else</code> into <code>bar</code> method on <code>Base</code>. Which makes sense, if we agree that <code>Base</code> encapsulates all your XMLRPC actions.</p> <p>The example uses <a href="http://code.google.com/p/pymox/" rel="nofollow">pymox</a> mocking library, but the gist of it stays the same regardless of your mocking style.</p>
3
2009-05-27T23:14:50Z
[ "python", "mocking" ]
How to construct notes from a given song file?
412,475
<p>Are there any modules in Python that help us to construct or obtain the musical notes and octaves from a given original song?</p> <p>Thanks for the help</p>
2
2009-01-05T07:17:31Z
412,505
<p>This question has far too few details to give any kind of meaningful answers.</p> <p>Questions:</p> <ul> <li>By song file, do you mean like an MP3?</li> <li>Is it a "song" or a "instrumental"? I would gather trying to decipher notes behind a voice would be harder</li> <li>Is it a simple song, like a single voice played on a simple instrument, like a piano or a flute? Or is it a complex one, like any of the latest hits played on the radio?</li> </ul> <p>I would think that trying to get a good output from such a program would be extremely hard for anything but the simplest of things.</p> <p>Having said that, look at the Fast Fourier Transform, it can give you a frequency spectrum of things played, but it'll be hard trying to determine what is what from that.</p>
2
2009-01-05T07:34:15Z
[ "python" ]
How to construct notes from a given song file?
412,475
<p>Are there any modules in Python that help us to construct or obtain the musical notes and octaves from a given original song?</p> <p>Thanks for the help</p>
2
2009-01-05T07:17:31Z
412,532
<p>As lassevk mentioned, this is a complex topic - a bit like reconstructing C code from assembly, in a way. That being said, a nice framework to play with audio stuff is CLAM:</p> <p><a href="http://clam.iua.upf.edu/" rel="nofollow">http://clam.iua.upf.edu/</a></p> <p>It is an open source C++ framework for music/audio algorithms prototyping, but there are python wrappers, and graphical tools for prototyping.</p>
3
2009-01-05T07:55:53Z
[ "python" ]
How to construct notes from a given song file?
412,475
<p>Are there any modules in Python that help us to construct or obtain the musical notes and octaves from a given original song?</p> <p>Thanks for the help</p>
2
2009-01-05T07:17:31Z
412,555
<p>I think what you are interested in is still topic of research. You won't find any module ready that will do that for you.</p> <p>Besides it is not clear what you mean with "notes and octaves"? What information exaclty would you like to extract?</p>
2
2009-01-05T08:15:43Z
[ "python" ]
How to construct notes from a given song file?
412,475
<p>Are there any modules in Python that help us to construct or obtain the musical notes and octaves from a given original song?</p> <p>Thanks for the help</p>
2
2009-01-05T07:17:31Z
412,803
<p>There are some libraries for Python. Start with this FSF listing for <a href="http://directory.fsf.org/category/audmisc/" rel="nofollow">Audio Misc</a>.</p> <p>There are, however, excellent products: See <a href="http://www.seventhstring.com/xscribe/overview.html" rel="nofollow">Transcribe!</a> and <a href="http://www.nch.com.au/twelvekeys/" rel="nofollow">TwelveKeys</a>. Also see <a href="http://transcribe.qarchive.org/" rel="nofollow">Transcribe Software List</a>.</p>
0
2009-01-05T11:01:33Z
[ "python" ]
How to construct notes from a given song file?
412,475
<p>Are there any modules in Python that help us to construct or obtain the musical notes and octaves from a given original song?</p> <p>Thanks for the help</p>
2
2009-01-05T07:17:31Z
12,613,852
<p>Jordi Bartolomé Guillen's "audioSearch.transcriber" module included in <a href="http://web.mit.edu/music21/" rel="nofollow">music21</a> gives pretty accurate transcriptions from monophonic sound files, so if you're working with a solo piece (or one where the melody is much louder than the accompaniment), it's a useful tool, and you can output the score to Finale, MuseScore, <a href="http://www.lilypond.org/" rel="nofollow">Lilypond</a>, or MIDI in addition to studying the characteristics.</p> <p>For polyphonic transcription, the situation is much less solved, as others have mentioned. The best available work is in the <a href="http://www.celemony.com/cms/index.php?id=products_editor#top" rel="nofollow" title="Melodyne editor">Melodyne editor</a>, but that's a commercial package. We're probably still about 2-4 years away from open source solutions to the problem.</p>
0
2012-09-27T03:56:52Z
[ "python" ]
How to access to the root path in a mod_python directory?
412,498
<p>In my Apache webserver I put this:</p> <pre><code>&lt;Directory /var/www/MYDOMAIN.com/htdocs&gt; SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On &lt;/Directory&gt; </code></pre> <p>Then I have a handler.py file with an index function.</p> <p>When I go to MYDOMAIN.com/handler.py, I see a web page produced by the index function (just a plain vanilla HTML page). Every other page is of this type: MYDOMAIN.com/handler.py/<em>somename</em> where <em>somename</em> corresponds to a funcion in handler.py file.</p> <p>But when I go to MYDOMAIN.com, I get this:</p> <blockquote> <p>Not Found</p> <p>The requested URL / was not found on this server.</p> </blockquote> <p>Is theres a way with mod_python and publisher to just use the root and not a name.py as a starting point?</p> <p>I already tried with this in the apache conf file:</p> <blockquote> <p>DirectoryIndex handler.py</p> </blockquote> <p>To no avail :(</p>
1
2009-01-05T07:30:03Z
412,567
<p>Try creating an empty file called index (or whatever) in the directory and then use</p> <pre><code>DirectoryIndex index </code></pre> <p>Seems like DirectoryIndex checking is done watching the filesystem.</p>
0
2009-01-05T08:24:49Z
[ "python", "mod-python", "publisher" ]
How to access to the root path in a mod_python directory?
412,498
<p>In my Apache webserver I put this:</p> <pre><code>&lt;Directory /var/www/MYDOMAIN.com/htdocs&gt; SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On &lt;/Directory&gt; </code></pre> <p>Then I have a handler.py file with an index function.</p> <p>When I go to MYDOMAIN.com/handler.py, I see a web page produced by the index function (just a plain vanilla HTML page). Every other page is of this type: MYDOMAIN.com/handler.py/<em>somename</em> where <em>somename</em> corresponds to a funcion in handler.py file.</p> <p>But when I go to MYDOMAIN.com, I get this:</p> <blockquote> <p>Not Found</p> <p>The requested URL / was not found on this server.</p> </blockquote> <p>Is theres a way with mod_python and publisher to just use the root and not a name.py as a starting point?</p> <p>I already tried with this in the apache conf file:</p> <blockquote> <p>DirectoryIndex handler.py</p> </blockquote> <p>To no avail :(</p>
1
2009-01-05T07:30:03Z
412,780
<p>Yes, but you need to create your own handler. You currently use publisher, it just checks the URI and loads given python module.</p> <p>To create your own handler you need to create a module like this (just a minimalistic example):</p> <pre><code>from mod_python import apache def requesthandler(req): req.content_type = "text/plain" req.write("Hello World!") return apache.OK </code></pre> <p>Then you just point to it in Apache configuration.</p> <p>You can still use publisher handler inside your own handler, although you can't have pretty URLs with it AFAIK.</p>
2
2009-01-05T10:51:55Z
[ "python", "mod-python", "publisher" ]
Apps Similar to Nodebox?
412,775
<p>I'm looking for apps/environments similar to <a href="http://nodebox.net/code/index.php/Tutorial" rel="nofollow">Nodebox</a>. Nodebox is so cool and I want to know if there were other similar apps out there. </p> <p>They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way.</p>
3
2009-01-05T10:48:05Z
412,778
<p><a href="http://processing.org/">http://processing.org/</a> is a language for creating graphics and animations similar to Nodebox.</p>
5
2009-01-05T10:51:44Z
[ "python", "nodebox" ]
Apps Similar to Nodebox?
412,775
<p>I'm looking for apps/environments similar to <a href="http://nodebox.net/code/index.php/Tutorial" rel="nofollow">Nodebox</a>. Nodebox is so cool and I want to know if there were other similar apps out there. </p> <p>They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way.</p>
3
2009-01-05T10:48:05Z
413,006
<p>it was referenced on @Jonas processing.org, but <a href="http://www.alice.org/" rel="nofollow">alice.org</a> is interesting.</p>
0
2009-01-05T12:47:00Z
[ "python", "nodebox" ]
Algorithm to keep a list of percentages to add up to 100%
412,943
<p>(code examples are python)<br /> Lets assume we have a list of percentages that add up to 100: </p> <pre><code>mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] </code></pre> <p>Some values of mylist may be changed, others must stay fixed.<br /> Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. </p> <pre><code>fix = mylist[:3] vari = mylist[3:] </code></pre> <p>The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari<br /> items keep their relations to each other. For that we need to substract a CERTAIN<br /> PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist.<br /> Using an ugly aproximation loop I found out that i need to substract ca. 5.0634%<br /> of each vari item (CERTAIN PERCENTAGE = 5.0634):</p> <pre><code>adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) </code></pre> <p>adjusted now contains my desired result. </p> <h1>My question is how to calculate CERTAIN PERCENTAGE ;.)</h1>
4
2009-01-05T12:18:09Z
412,966
<p>you're being silly.</p> <p>let's say you want to add 4.0 to the list. You don't need to subtract a certain amount from each one. What you need to do is multiply each item.</p> <p>100 - 4 = 96. therefore, multiply each item by 0.96</p> <p>you want to add 20.0 as an item. so then you multiply each item by 0.8, which is (100-20)*0.01</p> <p>update: Hrmn I didn't read carefuly enough.</p> <p>think of it like this. (fixed)+(vari)= 100; (fixed)+(vari * x) + newitem = 100;</p> <p>so basically like what we did before except with just the vari portion. if vari totals to 50, and the new item you're adding is 3.0, then multiply each item in vari by (47/50)</p>
3
2009-01-05T12:29:19Z
[ "python", "algorithm" ]
Algorithm to keep a list of percentages to add up to 100%
412,943
<p>(code examples are python)<br /> Lets assume we have a list of percentages that add up to 100: </p> <pre><code>mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] </code></pre> <p>Some values of mylist may be changed, others must stay fixed.<br /> Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. </p> <pre><code>fix = mylist[:3] vari = mylist[3:] </code></pre> <p>The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari<br /> items keep their relations to each other. For that we need to substract a CERTAIN<br /> PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist.<br /> Using an ugly aproximation loop I found out that i need to substract ca. 5.0634%<br /> of each vari item (CERTAIN PERCENTAGE = 5.0634):</p> <pre><code>adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) </code></pre> <p>adjusted now contains my desired result. </p> <h1>My question is how to calculate CERTAIN PERCENTAGE ;.)</h1>
4
2009-01-05T12:18:09Z
412,979
<p>How's this?</p> <pre><code>def adjustAppend( v, n ): weight= -n/sum(v) return [ i+i*weight for i in v ] + [n] </code></pre> <p>Given a list of numbers <em>v</em>, append a new number, <em>n</em>. Weight the existing number to keep the sum the same.</p> <pre><code> sum(v) == sum( v + [n] ) </code></pre> <p>Each element of <em>v</em>, <em>i</em>, must be reduced by some function of <em>i</em>, <em>r</em>(<em>i</em>) such that</p> <pre><code>sum(r(i)) == -n </code></pre> <p>or</p> <pre><code>sum( map( r, v ) ) == -n </code></pre> <p>Therefore, the weighting function is <code>-(n*i)/sum(v)</code></p>
9
2009-01-05T12:33:25Z
[ "python", "algorithm" ]
Algorithm to keep a list of percentages to add up to 100%
412,943
<p>(code examples are python)<br /> Lets assume we have a list of percentages that add up to 100: </p> <pre><code>mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] </code></pre> <p>Some values of mylist may be changed, others must stay fixed.<br /> Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. </p> <pre><code>fix = mylist[:3] vari = mylist[3:] </code></pre> <p>The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari<br /> items keep their relations to each other. For that we need to substract a CERTAIN<br /> PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist.<br /> Using an ugly aproximation loop I found out that i need to substract ca. 5.0634%<br /> of each vari item (CERTAIN PERCENTAGE = 5.0634):</p> <pre><code>adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) </code></pre> <p>adjusted now contains my desired result. </p> <h1>My question is how to calculate CERTAIN PERCENTAGE ;.)</h1>
4
2009-01-05T12:18:09Z
412,980
<pre><code>NEW_NUMBER = 4.0 mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] fix = mylist[:3] vari = mylist[3:] weight = (100 - sum(fix) - NEW_NUMBER)/sum(vari) adjusted = [] adjusted.extend( (weight*v for v in vari) ) adjusted.extend(fix) adjusted.append(NEW_NUMBER) print sum(adjusted) # 100.0 </code></pre> <p>Edit: Triptych is right, if you are actually interested in the <em>certain percentage</em>, the following code goes for it:</p> <pre><code>certain_percentage = 100 * NEW_NUMBER / sum(vari) print certain_percentage # 5.06329113924 </code></pre> <p>I think that your constant 5.0634 should actually be 5.0633.</p>
1
2009-01-05T12:34:44Z
[ "python", "algorithm" ]
Algorithm to keep a list of percentages to add up to 100%
412,943
<p>(code examples are python)<br /> Lets assume we have a list of percentages that add up to 100: </p> <pre><code>mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] </code></pre> <p>Some values of mylist may be changed, others must stay fixed.<br /> Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. </p> <pre><code>fix = mylist[:3] vari = mylist[3:] </code></pre> <p>The goal is to add a new item to mylist, while sum(mylist) stays 100.0 and vari<br /> items keep their relations to each other. For that we need to substract a CERTAIN<br /> PERCENTAGE from each vari item. Example: lets assume we want to add 4.0 to mylist.<br /> Using an ugly aproximation loop I found out that i need to substract ca. 5.0634%<br /> of each vari item (CERTAIN PERCENTAGE = 5.0634):</p> <pre><code>adjusted =[] for number in vari: adjusted.append(number-(number*(5.0634/100.0))) adjusted.extend(fix) adjusted.append(4.0) </code></pre> <p>adjusted now contains my desired result. </p> <h1>My question is how to calculate CERTAIN PERCENTAGE ;.)</h1>
4
2009-01-05T12:18:09Z
412,984
<pre><code>new_item = 4.0 CERTAIN_PERCENTAGE = 100 * (float(new_item) / sum(vari)) </code></pre>
2
2009-01-05T12:35:43Z
[ "python", "algorithm" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
412,997
<p>Look at built-in functions <code>getattr</code> and <code>setattr</code>. You'll probably be a lot happier.</p>
10
2009-01-05T12:42:31Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
413,010
<p>Properties are meant to dynamically evaluate attributes or to make them read-only. What you need is customizing attribute access. <code>__getattr__</code> and <code>__setattr__</code> do that really fine, and there's also <code>__getattribute__</code> if <code>__getattr__</code> is not enough.</p> <p>See <a href="http://docs.python.org/reference/datamodel.html#customizing-attribute-access">Python docs on customizing attribute access</a> for details.</p>
5
2009-01-05T12:48:29Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
413,159
<p>Have you looked at the <a href="http://code.enthought.com/projects/traits/" rel="nofollow">traits package</a>? It seems that you are reinventing the wheel here with your parameter classes. Traits also have additional features that might be useful for your type of application (incidently I know a person that happily uses traits in neural simulations).</p>
3
2009-01-05T13:56:58Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
413,192
<p>Now I implemented a solution with set-/getattr:</p> <pre><code>class Collection(object): ... def __setattr__(self, name, value): if 'dict' in self.__dict__: if name in self.dict: self[name].v = value else: self.__dict__[name] = value def __getattr__(self, name): return self[name].v </code></pre> <p>There is one thing I quite don't like that much: The attributes are not in the __dict__. And if I have them there as well I would have a copy of the value - which can be dangerous...</p>
2
2009-01-05T14:10:26Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
439,037
<p>Finally I succeded to implement the classes with property(). Thanks a lot for the advice. It took me quite a bit to work it out - but I can promise you that this exercise helps you to understand better pythons OOP.</p> <p>I implemented it also with __getattr__ and __setattr__ but still don't know the advantages and disadvantages to the property-solution. But this seems to be worth another question. The property-solutions seems to be quit clean.</p> <p>So here is the code:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(*args): self = args[0] print "get(): " print args return self._v def set(*args): print "set(): " print args self = args[0] value = args[-1] self._v = value v = property(fget=get, fset=set, doc='value of parameter') class Collection(dict): # inheriting from dict saves the methods: __getitem__ and __init__ def add(self, par): self[par.name] = par # Now here comes the tricky part. # (Note: this property call the get() and set() methods with one # more argument than the property of SingleParameter) setattr(Collection, par.name, property(fget=par.get, fset=par.set)) # Applying the classes: par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') col = Collection() col.add(par1) col.add(par2) # Setting parameter values: par1.v = 13 col.par1 = 14 # Getting parameter values: par1.v col.par1 # checking identity: par1.v is col.par1 # to access the whole object: col['par1'] </code></pre> <p>As I am new I am not sure how to move on: how to treat follow up questions (like this itself):</p> <ul> <li>get() is seems to be called twice - why?</li> <li>oop-design: property vs. "__getattr__ &amp; __setattr__" - when should I use what?</li> <li>is it rude to check the own answer to the own question as <em>accepted</em>?</li> <li>is it recommended to rename the title in order to put correlated questions or questions elaborated with the same example into the same context?</li> </ul> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" rel="nofollow" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" rel="nofollow" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
0
2009-01-13T14:01:20Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
439,708
<p>Using the same get/set functions for both classes forces you into an ugly hack with the argument list. Very sketchy, this is how I would do it:</p> <p>In class SingleParameter, define get and set as usual:</p> <pre><code>def get(self): return self._s def set(self, value): self._s = value </code></pre> <p>In class Collection, you cannot know the information until you create the property, so you define the metaset/metaget function and particularize them only later with a lambda function:</p> <pre><code>def metaget(self, par): return par.s def metaset(self, value, par): par.s = value def add(self, par): self[par.name] = par setattr(Collection, par.name, property( fget=lambda x : Collection.metaget(x, par), fset=lambda x, y : Collection.metaset(x,y, par)) </code></pre>
7
2009-01-13T16:33:49Z
[ "python", "oop", "parameters", "properties" ]
How to implement property() with dynamic name (in python)
412,951
<p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>class SingleParameter(object): def __init__(self, name, default_value=0, unit='not specified'): self.name = name self.default_value = default_value self.unit = unit self.set(default_value) def get(self): return self._v def set(self, value): self._v = value v = property(fget=get, fset=set, doc='value of parameter') par1 = SingleParameter(name='par1', default_value=10, unit='mV') par2 = SingleParameter(name='par2', default_value=20, unit='mA') # par1 and par2 I can access perfectly via 'p1.v = ...' # or get its value with 'p1.v' class Collection(object): def __init__(self): self.dict = {} def __getitem__(self, name): return self.dict[name] # get the whole object # to get the value instead: # return self.dict[name].v def add(self, parameter): self.dict[parameter.name] = parameter # now comes the part that I don't know how to implement with property(): # It shoule be something like # self.__dict__[parameter.name] = property(...) ? col = Collection() col.add(par1) col.add(par2) col['par1'] # gives the whole object # Now here is what I would like to get: # col.par1 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="http://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="http://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
9
2009-01-05T12:19:45Z
15,555,887
<p>I have a class that does something similar, but I did the following in the collection object:</p> <p>setattr(self, par.name, par.v)</p>
0
2013-03-21T18:57:09Z
[ "python", "oop", "parameters", "properties" ]
Django and units conversion
413,446
<p>I need to store some values in the database, distance, weight etc. In my model, i have field that contains quantity of something and IntegerField whith choices option, that determines what this quantity means(length, time duration etc). Should i create model for units and physical quantity or should i use IntegerField that contains type of unit? </p>
1
2009-01-05T15:27:37Z
413,549
<p>It depends on how you want to use it. Let's say you have length value and two possible units, cm and mm. If you want only to print the value later, you can always print it as <em>value</em>&nbsp;<em>unit</em>.</p> <p>However, if you want to do some calculations with the value, for instance, calculate the area, you need to convert the values to the same units. So you have to define unit conversion table anyway.</p> <p>I would convert the units to the same internal unit <em>before</em> I store them in the database, rather than converting them every time I use them.</p> <p>I would add a model for units and physical quantities only if there are too many of them and conversion is really tricky. Such a model could work as a converter. But for simple cases, like mm⇒cm or inch⇒cm, a static conversion table would suffice.</p>
1
2009-01-05T15:55:33Z
[ "python", "django" ]
Django and units conversion
413,446
<p>I need to store some values in the database, distance, weight etc. In my model, i have field that contains quantity of something and IntegerField whith choices option, that determines what this quantity means(length, time duration etc). Should i create model for units and physical quantity or should i use IntegerField that contains type of unit? </p>
1
2009-01-05T15:27:37Z
413,600
<p>By "field(enum)" do you mean you are using the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#choices" rel="nofollow">choices</a> option on a field? </p> <p>A simple set of choices works out reasonably well for small lists of conversions. It allows you to make simplifying assumptions that helps your users (and you) get something that works.</p> <p>Creating a formal model for units should only be done if you have (a) a LOT of units involved, (b) your need to extend it, AND (c) there's some rational expectation that the DB lookups will be of some value. </p> <p>Units don't change all that often. There seems little reason to use the database for this. It seems a lot simpler to hard-code the list of choices.</p> <p><strong>Choices</strong></p> <p>You can, for example, use a something like this to keep track of conversions.</p> <pre><code>UNIT_CHOICES = ( ('m', 'meters'), ('f', 'feet' ), ('i', 'inches'), ('pt', 'points') ) unit_conversions = { ('m','f'): 3.xyz, ('m','i'): 39.xyz, ('m','pt'): 29.xyz*72, ('f','m'): 1/3.xyz, ('f','i'): 12.0, ('f','pt'): 12.0*72, etc. } </code></pre> <p>Given this mapping, you can get a conversion factor in your conversion method function, do the math, and return the converted unit.</p> <pre><code>class WithUnit( Model ): ... def toUnit( self, someUnit ): if someUnit == self.unit: return self.value elif (someUnit,self.unit) in unit_conversions: return self.value * unit_conversions[(someUnit,self.unit)] else: raise Exception( "Can't convert" ) </code></pre> <p><strong>Model</strong>.</p> <p>If you want to create a formal model for units, you have to carry around the kind of dimension (length, volume, mass, weight/force, pressure, temperature, etc.) and the varous unit conversion factors. This works for everything but temperature, where you have a constant term in addition to a factor. </p> <p>You have to pick a "baseline" set of units (e.g., <a href="http://www.unc.edu/~rowlett/units/cgsmks.html" rel="nofollow">MKS</a>) and carry all the multipliers among the various units.</p> <p>You also have to choose how many of the English units to load into your table (fluid ounces, teaspoons, tablespoons, cups, pints, quarts, etc.)</p>
4
2009-01-05T16:07:26Z
[ "python", "django" ]
Django and units conversion
413,446
<p>I need to store some values in the database, distance, weight etc. In my model, i have field that contains quantity of something and IntegerField whith choices option, that determines what this quantity means(length, time duration etc). Should i create model for units and physical quantity or should i use IntegerField that contains type of unit? </p>
1
2009-01-05T15:27:37Z
413,615
<p>Use a field that indicates the type of measure (weight, length, etc.), and store the value in another field. That should be sufficient. The unit of measure should be implicit. I'm assuming you are using the same unit of measure for each measure type, for example always meters for length.</p> <p>A concrete example: let's say you have two entities, "<strong>Car</strong>" and "<strong>CarMeasures</strong>". I'd write the model this way:</p> <pre><code>class Car(models.Model): type=models.CharField(max_length=256); class CarMeasures(models.Model): carId=models.ForeignKey(Car); measureValue=models.DecimalField(..., max_digits=10, decimal_places=2); measureType=models.CharField(max_length=32); </code></pre>
1
2009-01-05T16:10:17Z
[ "python", "django" ]
Is there a Python library than can simulate network traffic from different addresses
414,025
<p>Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore.</p>
16
2009-01-05T18:20:39Z
414,078
<p>You can spoof an IP address using <a href="http://www.secdev.org/projects/scapy/">Scapy</a> library.</p> <p>Here's an example from <a href="http://web.archive.org/web/20120401161821/http://packetstorm.linuxsecurity.com/papers/general/blackmagic.txt">Packet Wizardry: Ruling the Network with Python</a>:</p> <pre><code>#!/usr/bin/env python import sys from scapy import * conf.verb=0 if len(sys.argv) != 4: print "Usage: ./spoof.py &lt;target&gt; &lt;spoofed_ip&gt; &lt;port&gt;" sys.exit(1) target = sys.argv[1] spoofed_ip = sys.argv[2] port = int(sys.argv[3]) p1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S') send(p1) print "Okay, SYN sent. Enter the sniffed sequence number now: " seq=sys.stdin.readline() print "Okay, using sequence number " + seq seq=int(seq[:-1]) p2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A', ack=seq+1,seq=1) send(p2) print "Okay, final ACK sent. Check netstat on your target :-)" </code></pre>
17
2009-01-05T18:44:27Z
[ "python", "networking" ]
python "'NoneType' object has no attribute 'encode'"
414,230
<p>I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error:</p> <pre><code>&gt; Traceback (most recent call last): &gt; File "/home/vijay/ffour/ffour5.py", &gt; line 20, in &lt;module&gt; &gt; myfeed() File "/home/vijay/ffour/ffour5.py", line &gt; 15, in myfeed &gt; sys.stdout.write(entry["title"]).encode('utf-8') &gt; AttributeError: 'NoneType' object has &gt; no attribute 'encode' </code></pre>
5
2009-01-05T19:35:09Z
414,239
<blockquote> <pre><code>&gt; sys.stdout.write(entry["title"]).encode('utf-8') </code></pre> </blockquote> <p>This is the culprit. You probably mean:</p> <pre><code>sys.stdout.write(entry["title"].encode('utf-8')) </code></pre> <p>(Notice the position of the last closing bracket.)</p>
12
2009-01-05T19:39:27Z
[ "python", "urlencode" ]
python "'NoneType' object has no attribute 'encode'"
414,230
<p>I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error:</p> <pre><code>&gt; Traceback (most recent call last): &gt; File "/home/vijay/ffour/ffour5.py", &gt; line 20, in &lt;module&gt; &gt; myfeed() File "/home/vijay/ffour/ffour5.py", line &gt; 15, in myfeed &gt; sys.stdout.write(entry["title"]).encode('utf-8') &gt; AttributeError: 'NoneType' object has &gt; no attribute 'encode' </code></pre>
5
2009-01-05T19:35:09Z
414,270
<p>Lets try to clear up some of the confusion in the exception message.</p> <p>The function call</p> <pre><code>sys.stdout.write(entry["title"]) </code></pre> <p>Returns None. The ".encode('utf-8')" is a call to the encode function on what is returned by the above function.</p> <p>The problem is that None doesn't have an encode function (or an encode attribute) and so you get an attribute error that names the type you were trying to get an attribute of and the attribute you were trying to get.</p>
5
2009-01-05T19:50:07Z
[ "python", "urlencode" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
414,573
<p>Have a look at serializing inherited models and objects from the Django documentation available at <a href="http://docs.djangoproject.com/en/dev/topics/serialization/?from=olddocs#inherited-models" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/serialization/?from=olddocs#inherited-models</a></p> <p>That should solve your problem.</p>
3
2009-01-05T21:20:21Z
[ "python", "django", "json" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
414,696
<p>Before you do serialization, when retrieving your objects, to preserve the relationships use select_related() to get children, grandchildren, etc </p> <p>see <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/">http://docs.djangoproject.com/en/dev/ref/models/querysets/</a></p>
10
2009-01-05T22:11:28Z
[ "python", "django", "json" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
415,421
<p>It seems to me that the question the poster was asking was to end up with a result like:</p> <p>For instance, starting with these models:</p> <pre><code>class Entity(models.Model): name = models.CharField(...) class Activity(models.Model): name = models.CharField(...) team_entity = models.ForeignKey(Entity) class Event(models.Model): name = models.CharField(...) activity = models.ForeignKey(Activity) </code></pre> <p>Result in JSON:</p> <pre><code>{ "model": "Entity", "name": "Dallas Cowboys", "activities": [ { "model": "Activity", "name": "Practice" }, { "model": "Activity", "name": "Game" "events": [ { "model": "Event", "name": "vs Washington Redskins" }, { "model": "Event", "name": "vs Green Bay Packers" } ] } ] } </code></pre> <p>Thus keeping the parent-child-grandchild (not inheritence, but one-to-many relationship traversal). If this wasn't the initial poster's intention, I apologize...but if so I would like the answer to this as well.</p>
5
2009-01-06T04:07:53Z
[ "python", "django", "json" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
518,167
<p>I believe you can find your answer here: <a href="http://code.djangoproject.com/ticket/4656" rel="nofollow">http://code.djangoproject.com/ticket/4656</a></p> <p>This will become part of django serializers at some stage. Right now it should be able to just replace standard django serializers with this and work away.</p>
3
2009-02-05T22:01:47Z
[ "python", "django", "json" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
918,010
<p>I now use django-piston. This does the trick.</p>
7
2009-05-27T21:05:55Z
[ "python", "django", "json" ]
Django serialize to JSON
414,543
<p>I have a Django model (schedule) with the class of entity, that is the parent of <code>Activity</code>, that is the parent of <code>Event</code>.</p> <pre><code>class Entity(models.Model): &lt;...&gt; class Activity(models.Model): &lt;...&gt; team_entity = models.ForeignKey(Entity) &lt;...&gt; class Event(models.Model): &lt;...&gt; activity = models.ForeignKey(Activity) &lt;...&gt; </code></pre> <p>How do I serialize and get both the child object and grand children as part of the JSON file?</p>
15
2009-01-05T21:10:09Z
13,697,848
<p>you can do this in simple two lines of code :</p> <pre><code>from django.core import serializers data = serializers.serialize("json", SomeModel.objects.all()) </code></pre>
-1
2012-12-04T07:14:35Z
[ "python", "django", "json" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
415,770
<p>A <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags">custom template tag</a> seems to be the solution. A custom filter would also do, although it can be less elegant. But you would need to fall back to custom form rendering in both cases.</p> <p>If this is a task of high importance; I'd create a Mixin that allows me to annotate the form fields with label classes and supplies form rendering methods using those classes. So that the following code works:</p> <pre><code>{{ form.as_table_with_label_classes }} </code></pre> <p>But I'd like to ask; Do you really need a class on the label tag? I mean HTML design-wise. It is absolutely necessary to <em>add</em> a class in there? Couldn't it be solved with some CSS like:</p> <pre><code>encapsulating_selector label { some-attr: some-value; } </code></pre> <p>I sometimes use <a href="http://jquery.com">jQuery</a> for such cases where; <em>it will improve the page if it works, but it won't be a disaster if it doesn't</em>. And keep the HTML source as lean as possible.</p>
8
2009-01-06T08:00:00Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
1,653,548
<p>I am agree with answer number one, with css this could be done, but. What is the reson for this to be in django source?</p> <p>In django.forms.forms.py there's this definition that shows there's code to display attrs in labels:</p> <pre><code>class BoundField(StrAndUnicode): # .... def label_tag(self, contents=None, attrs=None): contents = u'&lt;label for="%s"%s&gt;%s&lt;/label&gt;' % (widget.id_for_label(id_), attrs, unicode(contents)) </code></pre> <p>but <code>_html_output</code> calls this function without attrs:</p> <pre><code>label = bf.label_tag(label) or '' </code></pre> <p>So it seems that django is partially prepared to this but actually it does not used it.</p>
1
2009-10-31T05:47:09Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
1,933,711
<p>How about adding the CSS class to the form field in the forms.py, like:</p> <pre><code>class MyForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'foo'})) </code></pre> <p>then I just do the following in the template:</p> <pre><code>&lt;label for="id_{{form.title.name}}" class="bar"&gt; {{ form.title }} &lt;/label&gt; </code></pre> <p>Of course this can easily be modified to work within a for loop tag in the template.</p>
10
2009-12-19T18:16:02Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
6,192,134
<pre><code>@register.simple_tag def advanced_label_tag(field): """ Return form field label html marked to fill by `*` """ classes = [] attrs = {} contents = force_unicode(escape(field.label)) if field.field.required: classes.append(u'required') contents = force_unicode('%s &lt;span&gt;*&lt;/span&gt;'%escape(field.label)) if classes: attrs['class'] = u' '.join(classes) return field.label_tag(contents=contents, attrs=attrs) </code></pre>
0
2011-05-31T18:52:51Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
11,584,458
<p><strong>Technique 1</strong></p> <p>I take issue with another answer's assertion that a filter would be "less elegant." As you can see, it's very elegant indeed.</p> <pre><code>@register.filter(is_safe=True) def label_with_classes(value, arg): return value.label_tag(attrs={'class': arg}) </code></pre> <p>Using this in a template is just as elegant:</p> <pre><code>{{ form.my_field|label_with_classes:"class1 class2"}} </code></pre> <p><strong>Technique 2</strong></p> <p>Alternatively, one of the more interesting technique I've found is: <a href="http://www.thebitguru.com/blog/view/299-Adding%20%2a%20to%20required%20fields">Adding * to required fields</a>.</p> <p>You create a decorator for BoundField.label_tag that will call it with <em>attrs</em> set appropriately. Then you monkey patch BoundField so that calling BoundField.label_tag calls the decorated function.</p> <pre><code>from django.forms.forms import BoundField def add_control_label(f): def control_label_tag(self, contents=None, attrs=None): if attrs is None: attrs = {} attrs['class'] = 'control-label' return f(self, contents, attrs) return control_label_tag BoundField.label_tag = add_control_label(BoundField.label_tag) </code></pre>
7
2012-07-20T17:49:31Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
18,531,433
<pre><code>class CustomBoundField(BoundField): def label_tag(self, contents=None, attrs=None): if self.field.required: attrs = {'class': 'required'} return super(CustomBoundField, self).label_tag(contents, attrs) class ImportViewerForm(forms.Form): url = fields.URLField(widget=forms.TextInput(attrs={'class': 'vTextField'})) type = fields.ChoiceField(choices=[('o', 'Organisation'), ('p', 'Program')], widget=forms.RadioSelect, help_text='Url contain infornation about this type') source = fields.ChoiceField(choices=[('h', 'hodex'), ('s', 'studyfinder')], initial='h', widget=forms.RadioSelect) def __getitem__(self, name): "Returns a BoundField with the given name." try: field = self.fields[name] except KeyError: raise KeyError('Key %r not found in Form' % name) return CustomBoundField(self, field, name) class Media: css = {'all': [settings.STATIC_URL + 'admin/css/forms.css']} </code></pre> <p>You need change method label_tag in BoundField class, and use it in form</p>
0
2013-08-30T11:08:07Z
[ "python", "django", "forms", "newforms" ]
Add class to Django label_tag() output
414,679
<p>I need some way to add a class attribute to the output of the label_tag() method for a forms field. </p> <p>I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:</p> <pre><code>for field in form: print field.label_tag(attrs{'class':'Foo'}) </code></pre> <p>I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?</p> <p>Is there a way in my form definition to define the class to be displayed in the label?</p> <p>In the form, I can do the following to give the inputs a class</p> <pre><code>self.fields['some_field'].widget.attrs['class'] = 'Foo' </code></pre> <p>I just need to have it output the class for the as well.</p>
16
2009-01-05T22:05:15Z
28,235,472
<p>A bit too late but came across a similar problem. Hope this helps you. </p> <pre><code>class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['myfield1'].widget.attrs.update( {'class': 'form-control'}) self.fields['myfield2'].widget.attrs.update( {'class': 'form-control'}) def as_two_col_layout(self): return self._html_output( normal_row='&lt;div class="form-group"&gt;&lt;span class="col-xs-2"&gt;%(label)s&lt;/span&gt; &lt;div class="col-xs-10"&gt;%(field)s%(help_text)s&lt;/div&gt;&lt;/div&gt;', error_row='%s', row_ender='&lt;/div&gt;', help_text_html=' &lt;span class="helptext"&gt;%s&lt;/span&gt;', errors_on_separate_row=True) class Meta: model = mymodel fields = ['myfield1', 'myfield2'] </code></pre>
0
2015-01-30T11:59:59Z
[ "python", "django", "forms", "newforms" ]