title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Accessing mp3 Meta-Data with Python
8,948
<p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
81
2008-08-12T15:16:00Z
6,621,839
<p>Just additional information to you guys:</p> <p>take a look at the section "MP3 stuff and Metadata editors" in the page of <a href="http://wiki.python.org/moin/PythonInMusic" rel="nofollow">PythonInMusic</a>.</p>
3
2011-07-08T08:24:29Z
[ "python", "mp3", "metadata" ]
Accessing mp3 Meta-Data with Python
8,948
<p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
81
2008-08-12T15:16:00Z
31,373,513
<p>After some initial research I thought songdetails might fit my use case, but it doesn't handle .m4b files. Mutagen does. Note that while some have (reasonably) taken issue with Mutagen's surfacing of format-native keys, that vary from format to format (TIT2 for mp3, title for ogg, \xa9nam for mp4, Title for WMA et...
0
2015-07-12T23:17:59Z
[ "python", "mp3", "metadata" ]
Accessing mp3 Meta-Data with Python
8,948
<p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
81
2008-08-12T15:16:00Z
34,970,600
<p>A problem with <code>eyed3</code> is that it will throw <code>NotImplementedError("Unable to write ID3 v2.2")</code> for common MP3 files.</p> <p>In my experience, the <code>mutagen</code> class <code>EasyID3</code> works more reliably. Example:</p> <pre><code>from mutagen.easyid3 import EasyID3 audio = EasyID3("...
4
2016-01-24T00:07:24Z
[ "python", "mp3", "metadata" ]
Accessing mp3 Meta-Data with Python
8,948
<p>What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?</p>
81
2008-08-12T15:16:00Z
38,891,913
<p>easiest method is <a href="https://github.com/Ciantic/songdetails" rel="nofollow">songdetails</a>..</p> <p>for read data</p> <pre><code>import songdetails song = songdetails.scan("blah.mp3") if song is not None: print song.artist </code></pre> <p>similarly for edit</p> <pre><code>import songdetails song = so...
0
2016-08-11T09:05:38Z
[ "python", "mp3", "metadata" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
10,129
<p>This will do what you want:</p> <pre><code>signum = status &amp; 0xff exitstatus = (status &amp; 0xff00) &gt;&gt; 8 </code></pre>
10
2008-08-13T17:56:34Z
[ "python" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
10,132
<p>You can unpack the status using <a href="http://docs.python.org/ref/shifting.html" rel="nofollow">bit-shifting</a> and <a href="http://docs.python.org/ref/bitwise.html" rel="nofollow">masking</a> operators.</p> <pre><code>low = status &amp; 0x00FF high = (status &amp; 0xFF00) &gt;&gt; 8 </code></pre> <p>I'm not a ...
1
2008-08-13T17:58:27Z
[ "python" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
10,148
<p>The folks before me've nailed it, but if you really want it on one line, you can do this:</p> <pre><code>(signum, exitstatus) = (status &amp; 0xFF, (status &gt;&gt; 8) &amp; 0xFF) </code></pre> <p>EDIT: Had it backwards.</p>
0
2008-08-13T18:14:10Z
[ "python" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
10,213
<p>To answer your general question, you can use <a href="http://en.wikipedia.org/wiki/Bit_twiddling" rel="nofollow">bit manipulation</a> techniques:</p> <pre><code>pid, status = os.wait() exitstatus, signum = status &amp; 0xFF, (status &amp; 0xFF00) &gt;&gt; 8 </code></pre> <p>However, there are also <a href="http://...
10
2008-08-13T18:52:36Z
[ "python" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
686,128
<p>You can get break your int into a string of unsigned bytes with the <a href="http://docs.python.org/library/struct.html" rel="nofollow">struct</a> module:</p> <pre><code>import struct i = 3235830701 # 0xC0DEDBAD s = struct.pack("&gt;L", i) # "&gt;" = Big-endian, "&lt;" = Little-endian print s # '\xc0\xde\...
2
2009-03-26T14:52:42Z
[ "python" ]
How do I treat an integer as an array of bytes in Python?
10,123
<p>I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:</p> <blockquote> <p>a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the sign...
8
2008-08-13T17:46:41Z
687,977
<pre><code>exitstatus, signum= divmod(status, 256) </code></pre>
2
2009-03-26T23:48:20Z
[ "python" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
11,074
<p>I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look.</p> <p>Problem is, this is hard to test, the generated code might not ...
8
2008-08-14T14:04:25Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
11,128
<p>Yes, results are the ONLY thing that matters. The real chore is writing a framework that allows your generated code to run independently... spend your time there.</p>
0
2008-08-14T14:38:19Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
11,235
<p>If you are running on *nux you might consider dumping the unittest framework in favor of a bash script or makefile. on windows you might consider building a shell app/function that runs the generator and then uses the code (as another process) and unittest that.</p> <p>A third option would be to generate the code a...
0
2008-08-14T15:46:01Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
11,443
<p>Recall that "unit testing" is only one kind of testing. You should be able to unit test the <strong>internal</strong> pieces of your code generator. What you're really looking at here is system level testing (a.k.a. regression testing). It's not just semantics... there are different mindsets, approaches, expectat...
4
2008-08-14T18:15:42Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
70,778
<p>Just wanted to point out that you can still achieve fine-grained testing while verifying the results: you can test individual chunks of code by nesting them inside some setup and verification code:</p> <pre><code>int x = 0; GENERATED_CODE assert(x == 100); </code></pre> <p>Provided you have your generated code ass...
0
2008-09-16T09:41:03Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
2,870,088
<p>Unit testing is just that testing a specific unit. So if you are writing a specification for class A, it is ideal if class A does not have the real concrete versions of class B and C.</p> <p>Ok I noticed afterwards the tag for this question includes C++ / Python, but the principles are the same:</p> <pre><code> ...
0
2010-05-19T23:17:11Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
3,331,503
<p>My recommendation would be to figure out a set of known input-output results, such as some simpler cases that you already have in place, and <em>unit test the code that is produced</em>. It's entirely possible that as you change the generator that the exact string that is produced may be slightly different... but wh...
0
2010-07-25T23:56:06Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
How should I unit test a code-generator?
11,060
<p>This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions.</p> <p>I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When ...
18
2008-08-14T13:59:21Z
31,508,737
<p>I find that you need to test what you're generating more than how you generate it.</p> <p>In my case, the program generates many types of code (C#, HTML, SCSS, JS, etc.) that compile into a web application. The best way I've found to reduce regression bugs overall is to test the web application itself, not by testi...
0
2015-07-20T04:10:25Z
[ "c++", "python", "unit-testing", "code-generation", "swig" ]
Using an XML catalog with Python's lxml?
12,591
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
6
2008-08-15T18:42:20Z
13,040
<p>Can you give an example? According to the <a href="http://codespeak.net/lxml/validation.html" rel="nofollow">lxml validation docs</a>, lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs, which covers most cases I can think of.</p> <pre><code>f = StringIO("&lt;!ELEMEN...
1
2008-08-16T07:57:53Z
[ "python", "xml", "lxml" ]
Using an XML catalog with Python's lxml?
12,591
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
6
2008-08-15T18:42:20Z
36,219
<p>It seems that lxml does not expose this libxml2 feature, grepping the source only turns up some #defines for the error handling:</p> <pre><code>C:\Dev&gt;grep -ir --include=*.px[id] catalog lxml-2.1.1/src | sed -r "s/\s+/ /g" lxml-2.1.1/src/lxml/dtd.pxi: catalog. lxml-2.1.1/src/lxml/xmlerror.pxd: XML_FROM_CATALOG =...
0
2008-08-30T18:10:33Z
[ "python", "xml", "lxml" ]
Using an XML catalog with Python's lxml?
12,591
<p>Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file? I need to be able to work the fixed attributes defined in a document’s DTD.</p>
6
2008-08-15T18:42:20Z
8,391,738
<p>You can add the catalog to the <code>XML_CATALOG_FILES</code> environment variable:</p> <pre><code>os.environ['XML_CATALOG_FILES'] = 'file:///to/my/catalog.xml' </code></pre> <p>See <a href="http://thread.gmane.org/gmane.comp.python.lxml.devel/5907" rel="nofollow">this thread</a>. Note that entries in <code>XML_CA...
5
2011-12-05T20:54:36Z
[ "python", "xml", "lxml" ]
Can you check that an exception is thrown with doctest in Python?
12,592
<p>Is it possible to write a doctest unit test that will check that an exception is raised?<br> For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x&lt;0</code>, how would I write the doctest for that? </p>
28
2008-08-15T18:43:17Z
12,609
<p>Yes. You can do it. The <a href="https://docs.python.org/3/library/doctest.html">doctest module documentation</a> and Wikipedia has an <a href="http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file">example</a> of it.</p> <pre><code> &gt;&gt;&gt; x Traceback (most recent call...
45
2008-08-15T19:04:13Z
[ "python", "doctest" ]
Can you check that an exception is thrown with doctest in Python?
12,592
<p>Is it possible to write a doctest unit test that will check that an exception is raised?<br> For example, if I have a function <code>foo(x)</code> that is supposed to raise an exception if <code>x&lt;0</code>, how would I write the doctest for that? </p>
28
2008-08-15T18:43:17Z
33,787,471
<pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.log(-2) Traceback (most recent call last): ... ValueError: math domain error </code></pre> <p>ellipsis flag <em># doctest: +ELLIPSIS</em> is not required to use ... in Traceback doctest </p>
0
2015-11-18T18:22:25Z
[ "python", "doctest" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
13,399
<p>Depends on the language and what you need to do, a "map" as it's called in many languages could be what you're looking for. I don't know C#, but according to <a href="http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx" rel="nofollow">this</a> page, .NET 2.0 calls map "ConvertAll".</p> <p>The meaning of "ma...
0
2008-08-16T22:37:06Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
13,403
<p>in Ruby:</p> <pre><code>intArray.select { |x| x &gt; 3 }.each do |x| # do other processing end </code></pre> <p>or if "other processing" is a short one-liner:</p> <pre><code>intArray.select { |x| x &gt; 3 }.each { |x| something_that_uses x } </code></pre> <p>lastly, if you want to return a new array containing...
1
2008-08-16T22:47:53Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
13,405
<p>In Python, you have <a href="http://docs.python.org/tut/node7.html#SECTION007130000000000000000" rel="nofollow" title="Human Interface Guidelines">filter and map</a>, which can so what you want:</p> <pre><code>map(lambda x: foo(x + 1) filter(lambda x: x &gt; 3, intArray)) </code></pre> <p>There's also <a href="htt...
2
2008-08-16T22:56:30Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
13,406
<p>In C# you can apply selective processing on anything that lives inside an IEnumerable like this: </p> <pre><code>intArray.Where(i =&gt; i &gt; 3).ConvertAll(); DoStuff(intArray.Where(i =&gt; i 3)); </code></pre> <p>Etc..</p>
3
2008-08-16T23:06:52Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
13,435
<p>The increment in the original <code>foreach</code> loop will not affect the contents of the array, the only way to do this remains a <code>for</code> loop:</p> <pre><code>for(int i = 0; i &lt; intArray.Length; ++i) { if(intArray[i] &gt; 3) ++intArray[i]; } </code></pre> <p>Linq is not intended to modify existi...
4
2008-08-17T00:44:57Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Replacement for for... if array iteration
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processin...
5
2008-08-16T22:28:39Z
6,477,444
<pre><code>map(lambda x: test(x + 1) filter(lambda x: x &gt; 3, arr)) </code></pre>
1
2011-06-25T11:28:54Z
[ ".net", "python", "arrays", "loops", "iteration" ]
Python version of PHP's stripslashes
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
9
2008-08-17T01:23:50Z
13,456
<p>You can obviously concatenate everything together:</p> <pre><code>cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","") </code></pre> <p>Is that what you were after? Or were you hoping for something more terse?</p>
0
2008-08-17T01:26:52Z
[ "python", "string", "escaping" ]
Python version of PHP's stripslashes
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
9
2008-08-17T01:23:50Z
13,579
<p>Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.</p> <p>Regular expressions to the rescue (code not tested):</p> <pre><code>p = re.compile( '\\(\\\S)') p.sub('\1',escapedstring) </code></pre> <p>In theory that...
-4
2008-08-17T10:28:00Z
[ "python", "string", "escaping" ]
Python version of PHP's stripslashes
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
9
2008-08-17T01:23:50Z
13,598
<p>Not totally sure this is what you want, but..</p> <pre><code>cleaned = stringwithslashes.decode('string_escape') </code></pre>
10
2008-08-17T12:15:13Z
[ "python", "string", "escaping" ]
Python version of PHP's stripslashes
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
9
2008-08-17T01:23:50Z
13,608
<p>It sounds like what you want could be reasonably efficiently handled through regular expressions:</p> <pre><code>import re def stripslashes(s): r = re.sub(r"\\(n|r)", "\n", s) r = re.sub(r"\\", "", r) return r cleaned = stripslashes(stringwithslashes) </code></pre>
2
2008-08-17T12:55:25Z
[ "python", "string", "escaping" ]
Python version of PHP's stripslashes
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
9
2008-08-17T01:23:50Z
21,862,975
<p>use <code>decode('string_escape')</code></p> <pre><code>cleaned = stringwithslashes.decode('string_escape') </code></pre> <p>Using </p> <blockquote> <p><strong>string_escape</strong> : Produce a string that is suitable as string literal in Python source code</p> </blockquote> <p>or concatenate the replace() li...
0
2014-02-18T19:02:19Z
[ "python", "string", "escaping" ]
Python Regular Expressions to implement string unescaping
13,791
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\...
10
2008-08-17T18:20:21Z
13,844
<p>Well, I think you might have missed the r or miscounted the backslashes...</p> <pre><code>"\\n" == r"\n" &gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \\n a test \\r" &gt;&gt;&gt; p = re.compile( r"[\\][\\](.)" ) &gt;&gt;&gt; print p.sub( r"\\\1", mystring ) This is \n a test \r &gt;&gt;&gt; </code></pr...
3
2008-08-17T19:01:02Z
[ "python", "regex", "backreference" ]
Python Regular Expressions to implement string unescaping
13,791
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\...
10
2008-08-17T18:20:21Z
13,869
<p>You are being tricked by Python's representation of the result string. The Python expression:</p> <pre><code>'This is \\n a test \\r' </code></pre> <p>represents the string</p> <pre><code>This is \n a test \r </code></pre> <p>which is I think what you wanted. Try adding 'print' in front of each of your p.sub() c...
0
2008-08-17T19:26:33Z
[ "python", "regex", "backreference" ]
Python Regular Expressions to implement string unescaping
13,791
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\...
10
2008-08-17T18:20:21Z
13,882
<p>The idea is that I'll read in an escaped string, and unescape it (a feature notably lacking from Python, which you shouldn't need to resort to regular expressions for in the first place). Unfortunately I'm not being tricked by the backslashes...</p> <p>Another illustrative example:</p> <pre><code>&gt;&gt;&gt; myst...
0
2008-08-17T19:40:49Z
[ "python", "regex", "backreference" ]
Python Regular Expressions to implement string unescaping
13,791
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\...
10
2008-08-17T18:20:21Z
13,943
<p>Isn't that what <a href="#13844">Anders' second example</a> does?</p> <p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p> <pre><code>&gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; mystring.decode('string-escape') 'This is \n a test \r' &gt;&gt;&gt; print mystring.decode('s...
7
2008-08-17T21:36:32Z
[ "python", "regex", "backreference" ]
Python Regular Expressions to implement string unescaping
13,791
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\...
10
2008-08-17T18:20:21Z
13,958
<p>Mark; his second example requires every escaped character thrown into an array initially, which generates a KeyError if the escape sequence happens not to be in the array. It will die on anything but the three characters provided (give \v a try), and enumerating every possible escape sequence every time you want to ...
0
2008-08-17T21:55:54Z
[ "python", "regex", "backreference" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
13,875
<p>It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:</p> <pre><code>&gt;&gt;&gt; def makeConstantAdder(x): ... constant = x ... def adder(y): ... return y + constant ... return adder ... &...
37
2008-08-17T19:32:33Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
13,902
<p>I've never heard of transactions being used in the same context as explaining what a closure is and there really aren't any transaction semantics here.</p> <p>It's called a closure because it "closes over" the outside variable (constant)--i.e., it's not just a function but an enclosure of the environment where the ...
6
2008-08-17T20:20:20Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
13,906
<p>I like <a href="http://effbot.org/zone/closure.htm">this rough, succinct definition</a>:</p> <blockquote> <p>A function that can refer to environments that are no longer active.</p> </blockquote> <p>I'd add</p> <blockquote> <p>A closure allows you to bind variables into a function <em>without passing them as ...
13
2008-08-17T20:25:18Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
24,061
<p>To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the "closure" and what's so "closure" about it. I recommend you give up looking for any logic behind the choice of term.</p> <p>Anyway, here's my explanation:</p> <pre><code>def foo(): x = 3 ...
11
2008-08-23T07:43:18Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
94,543
<p>The best explanation I ever saw of a closure was to explain the mechanism. It went something like this:</p> <p>Imagine your program stack as a degenerate tree where each node has only one child and the single leaf node is the context of your currently executing procedure.</p> <p>Now relax the constraint that each...
-3
2008-09-18T17:10:42Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
141,426
<p><a href="http://mrevelle.blogspot.com/2006/10/closure-on-closures.html">Closure on closures</a></p> <blockquote> <p>Objects are data with methods attached, closures are functions with data attached.</p> </blockquote> <pre><code>def make_counter(): i = 0 def counter(): # counter() is a closure ...
60
2008-09-26T19:28:32Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
473,491
<p>Here's a typical use case for closures - callbacks for GUI elements (this would be an alternative to subclassing the button class). For example, you can construct a function that will be called in response to a button press, and "close" over the relevant variables in the parent scope that are necessary for processin...
2
2009-01-23T16:13:53Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
18,918,261
<p>For me, "closures" are functions which are capable to remember the environment they were created. This functionality, allows you to use variables or methods within the closure wich, in other way,you wouldn't be able to use either because they don't exist anymore or they are out of reach due to scope. Let's look at ...
0
2013-09-20T13:39:53Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
24,816,814
<p>In Python, a closure is an instance of a function that has variables bound to it immutably.</p> <p>In fact, the <a href="https://docs.python.org/3.3/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow">data model explains this</a> in its description of functions' <code>__closure__</code> attribute: ...
1
2014-07-18T03:33:13Z
[ "python", "functional-programming", "closures" ]
Can you explain closures (as they relate to Python)?
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>...
56
2008-08-17T19:14:30Z
32,726,068
<p>Here is an example of Python3 closures </p> <pre><code>def closure(x): def counter(): nonlocal x x += 1 return x return counter; counter1 = closure(100); counter2 = closure(200); print("i from closure 1 " + str(counter1())) print("i from closure 1 " + str(counter1())) print("i from...
1
2015-09-22T20:16:22Z
[ "python", "functional-programming", "closures" ]
Python Sound ("Bell")
13,941
<p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete." I much rather it be a simple "bell."</p> <p>I know that there's a function that can be used in Cocoa apps...
34
2008-08-17T21:33:39Z
13,949
<p>Have you tried :</p> <pre><code>import sys sys.stdout.write('\a') sys.stdout.flush() </code></pre> <p>That works for me here on Mac OS 10.5</p> <p>Actually, I think your original attempt works also with a little modification:</p> <pre><code>print('\a') </code></pre> <p>(You just need the single quotes around th...
47
2008-08-17T21:46:02Z
[ "python", "osx", "audio", "terminal" ]
Python Sound ("Bell")
13,941
<p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete." I much rather it be a simple "bell."</p> <p>I know that there's a function that can be used in Cocoa apps...
34
2008-08-17T21:33:39Z
13,959
<p>I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for <code>print('\a')</code> to work. It seemed to work fine by default in Terminal.</p> <p>You can also use the Mac module <code>Carbon.Snd</code> to play the system beep:</p> <pre><code>&gt;&gt;&gt; import Carbon.Snd &gt;...
4
2008-08-17T21:56:10Z
[ "python", "osx", "audio", "terminal" ]
Python Sound ("Bell")
13,941
<p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete." I much rather it be a simple "bell."</p> <p>I know that there's a function that can be used in Cocoa apps...
34
2008-08-17T21:33:39Z
34,482
<p>If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do</p> <pre><code>from AppKit import NSBeep NSBeep() </code></pre> <p>to play the system alert.</p>
9
2008-08-29T15:47:05Z
[ "python", "osx", "audio", "terminal" ]
Python Sound ("Bell")
13,941
<p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete." I much rather it be a simple "bell."</p> <p>I know that there's a function that can be used in Cocoa apps...
34
2008-08-17T21:33:39Z
6,110,229
<p>I tried the mixer from the pygame module, and it works fine. First install the module:</p> <pre><code>$ sudo apt-get install python-pygame </code></pre> <p>Then in the program, write this:</p> <pre><code>from pygame import mixer mixer.init() #you must initialize the mixer alert=mixer.Sound('bell.wav') alert.play(...
6
2011-05-24T12:14:54Z
[ "python", "osx", "audio", "terminal" ]
Is there a python module for regex matching in zip files
14,281
<p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p> <p>Is there any python module which can do a regex match on the files without unzipping it. Is there a...
3
2008-08-18T07:41:09Z
14,304
<p>You could loop through the zip files, reading individual files using the zipfile module and running your regex on those, eliminating to unzip all the files at once. </p> <p>I'm fairly certain that you can't run a regex over the zipped data, at least not meaningfully.</p>
0
2008-08-18T08:06:30Z
[ "python", "regex", "zip", "text-processing" ]
Is there a python module for regex matching in zip files
14,281
<p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p> <p>Is there any python module which can do a regex match on the files without unzipping it. Is there a...
3
2008-08-18T07:41:09Z
14,314
<p>To access the contents of a zip file you have to unzip it, although the zipfile package makes this fairly easy, as you can unzip each file within an archive individually.</p> <p><a href="http://docs.python.org/lib/module-zipfile.html" rel="nofollow">Python zipfile module</a></p>
0
2008-08-18T08:10:57Z
[ "python", "regex", "zip", "text-processing" ]
Is there a python module for regex matching in zip files
14,281
<p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p> <p>Is there any python module which can do a regex match on the files without unzipping it. Is there a...
3
2008-08-18T07:41:09Z
14,320
<p>There's nothing that will automatically do what you want.</p> <p>However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.</p> <pre><code>#!/usr/bin/python import zipfile f = zipfile.ZipFile('myfile.zip') for subfile in f.namelist(): print su...
8
2008-08-18T08:19:06Z
[ "python", "regex", "zip", "text-processing" ]
Is there a python module for regex matching in zip files
14,281
<p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p> <p>Is there any python module which can do a regex match on the files without unzipping it. Is there a...
3
2008-08-18T07:41:09Z
41,822
<p>Isn't it (at least theoretically) possible, to read in the ZIP's Huffman coding and then translate the regexp into the Huffman code? Might this be more efficient than first de-compressing the data, then running the regexp?</p> <p>(Note: I know it wouldn't be quite that simple: you'd also have to deal with other asp...
0
2008-09-03T14:42:10Z
[ "python", "regex", "zip", "text-processing" ]
Regex and unicode
14,389
<p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p> <p>The script works fine, that is until you try and use it on files that have Unicode s...
21
2008-08-18T09:41:14Z
14,391
<p>Use a subrange of [\u0000-\uFFFF] for what you want.</p> <p>You can also use the re.UNICODE compile flag. <a href="http://docs.python.org/lib/re-syntax.html">The docs</a> say that if UNICODE is set, \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties d...
14
2008-08-18T09:43:10Z
[ "python", "regex", "unicode", "character-properties" ]
Regex and unicode
14,389
<p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p> <p>The script works fine, that is until you try and use it on files that have Unicode s...
21
2008-08-18T09:41:14Z
14,399
<p>\X seems to be available as a generic word-character in some languages, it allows you to match a single character disregarding of how many bytes it takes up. Might be useful.</p>
0
2008-08-18T09:53:13Z
[ "python", "regex", "unicode", "character-properties" ]
Regex and unicode
14,389
<p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p> <p>The script works fine, that is until you try and use it on files that have Unicode s...
21
2008-08-18T09:41:14Z
14,420
<p>In Mastering Regular Expressions from Jeffrey Friedl (great book) it is mentioned that you could use \p{Letter} which will match unicode stuff that is considered a letter.</p>
4
2008-08-18T10:17:35Z
[ "python", "regex", "unicode", "character-properties" ]
Regex and unicode
14,389
<p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p> <p>The script works fine, that is until you try and use it on files that have Unicode s...
21
2008-08-18T09:41:14Z
5,519,872
<p>Python's re module doesn't support \p{Letter} or \X. However, the <a href="http://pypi.python.org/pypi/regex" rel="nofollow">new regex implementation on PyPI</a> does.</p>
4
2011-04-01T23:19:55Z
[ "python", "regex", "unicode", "character-properties" ]
How do I validate xml against a DTD file in Python
15,798
<p>I need to validate an XML string (and not a file) against a DTD description file. </p> <p>How can that be done in <code>python</code>?</p>
27
2008-08-19T06:24:54Z
15,931
<p>Another good option is <a href="http://lxml.de/validation.html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use.</p> <p>A simple example taken from the lxml site:</p> <pre><code>from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""&lt;!ELEMENT foo EMPTY&gt;""")...
28
2008-08-19T09:39:56Z
[ "python", "xml", "validation", "dtd" ]
How do I validate xml against a DTD file in Python
15,798
<p>I need to validate an XML string (and not a file) against a DTD description file. </p> <p>How can that be done in <code>python</code>?</p>
27
2008-08-19T06:24:54Z
270,538
<p>from the examples directory in the libxml2 python bindings:</p> <pre><code>#!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) dtd="""&lt;!ELEMENT foo EMPTY&gt;""" instance="""&lt;?xml version="1.0"?&gt; &lt;foo&gt;&lt;/foo&gt;""" dtd = libxml2.parseDTD(None, 'test.dtd')...
7
2008-11-06T22:17:48Z
[ "python", "xml", "validation", "dtd" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
16,191
<p>In my experience, there are two easy ways to call into C code from Python code. There are other approaches, all of which are more annoying and/or verbose.</p> <p>The first and easiest is to compile a bunch of C code as a separate shared library and then call functions in that library using ctypes. Unfortunately, ...
1
2008-08-19T13:52:23Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
17,300
<p>The best way to plan for an eventual transition to compiled code is to write the performance sensitive portions as a module of simple functions in a <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="nofollow">functional style</a> (stateless and without side effects), which accept and return basic da...
6
2008-08-20T01:45:05Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
28,467
<p>I haven't used SWIG or SIP, but I find writing Python wrappers with <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html" rel="nofollow">boost.python</a> to be very powerful and relatively easy to use.</p> <p>I'm not clear on what your requirements are for passing types between C/C++ and python,...
10
2008-08-26T15:58:08Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
151,006
<p><a href="http://cens.ioc.ee/projects/f2py2e/usersguide/index.html#the-quick-and-smart-way" rel="nofollow">f2py</a> (part of <code>numpy</code>) is a simpler alternative to SWIG and boost.python for wrapping C/Fortran number-crunching code.</p>
4
2008-09-29T22:30:59Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
151,084
<blockquote> <p>Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p> </blockquote> <p>In C you cannot pass a function as an argument to a function but you can pass a function pointer which is just as g...
0
2008-09-29T22:52:19Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
872,600
<p>In addition to the tools above, I can recommend using <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow" title="Pyrex">Pyrex</a> (for creating Python extension modules) or <a href="http://psyco.sourceforge.net/" rel="nofollow" title="Psyco">Psyco</a> (as JIT compiler for Python).</p>...
0
2009-05-16T15:08:53Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Prototyping with Python code before compiling
16,067
<p>I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyp...
18
2008-08-19T12:32:38Z
1,661,276
<p>Finally a question that I can really put a value answer to :). </p> <p>I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:</p> <p><strong>...
33
2009-11-02T13:16:20Z
[ "python", "swig", "ctypes", "prototyping", "python-sip" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
16,875
<p>If you are using a framework like <a href="http://www.djangoproject.com/" rel="nofollow">django</a>, the framework can easily do this for you using standard filters. In fact, I'm pretty sure django automatically does it unless you tell it not to.</p> <p>Otherwise, I would recommend using some sort of regex validat...
0
2008-08-19T20:24:18Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
16,929
<p>Jeff Atwood himself described how StackOverflow.com sanitizes user input (in non-language-specific terms) on the Stack Overflow blog: <a href="http://blog.stackoverflow.com/2008/06/safe-html-and-xss/" rel="nofollow">http://blog.stackoverflow.com/2008/06/safe-html-and-xss/</a></p> <p>However, as Justin points out, i...
6
2008-08-19T20:51:39Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
25,136
<p>Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use <code>onclick</code>).</p> <p>It is a modified version of <a href="http://www.djangosnippets.org/snippets/205/">http://www.djangosnippets.org/snippets/205/</a>, with the regex o...
23
2008-08-24T16:08:37Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
25,151
<p>I don't do web development much any longer, but when I did, I did something like so:</p> <p>When no parsing is supposed to happen, I usually just escape the data to not interfere with the database when I store it, and escape everything I read up from the database to not interfere with html when I display it (cgi.es...
4
2008-08-24T16:23:13Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
93,857
<p>The best way to prevent XSS is not to try and filter everything, but rather to simply do HTML Entity encoding. For example, automatically turn &lt; into &amp;lt;. This is the ideal solution assuming you don't need to accept any html input (outside of forum/comment areas where it is used as markup, it should be pre...
12
2008-09-18T15:56:09Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
248,933
<p><strong>Edit</strong>: <a href="https://github.com/jsocol/bleach">bleach</a> is a wrapper around html5lib which makes it even easier to use as a whitelist-based sanitiser.</p> <p><a href="http://code.google.com/p/html5lib/"><code>html5lib</code></a> comes with a whitelist-based HTML sanitiser - it's easy to subclas...
18
2008-10-30T00:41:40Z
[ "python", "xss" ]
Sanitising user input using Python
16,861
<p>What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="nofollow">XSS</a> or SQL injection attack?</p>
46
2008-08-19T20:18:31Z
1,503,641
<p>To sanitize a string input which you want to store to the database (for example a customer name) you need either to escape it or plainly remove any quotes (', ") from it. This effectively prevents classical SQL injection which can happen if you are assembling an SQL query from strings passed by the user.</p> <p>For...
2
2009-10-01T12:21:45Z
[ "python", "xss" ]
Create an encrypted ZIP file in Python
17,250
<p>I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:</p> <pre><code>import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() </code></pre> <p>but I couldn't find how to encrypt the files in the Z...
24
2008-08-20T00:16:40Z
17,287
<p>You can use the <a href="http://www.chilkatsoft.com/python.asp" rel="nofollow">Chilkat</a> library. It's commercial, but has a free evaluation and seems pretty nice.</p> <p>Here's an example I got from <a href="http://www.example-code.com/python/zip.asp" rel="nofollow">here</a>:</p> <pre><code>import chilkat # D...
0
2008-08-20T01:20:48Z
[ "python", "zip" ]
Create an encrypted ZIP file in Python
17,250
<p>I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:</p> <pre><code>import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() </code></pre> <p>but I couldn't find how to encrypt the files in the Z...
24
2008-08-20T00:16:40Z
16,050,005
<p>I created a simple library to create a password encrypted zip file in python. - <a href="https://github.com/smihica/pyminizip"><strong>here</strong></a></p> <pre><code>import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) </code></pre> <p><strong>The ...
13
2013-04-17T01:39:00Z
[ "python", "zip" ]
Create an encrypted ZIP file in Python
17,250
<p>I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far:</p> <pre><code>import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() </code></pre> <p>but I couldn't find how to encrypt the files in the Z...
24
2008-08-20T00:16:40Z
27,443,681
<p>The duplicate question <a href="http://stackoverflow.com/a/2366917/874188">http://stackoverflow.com/a/2366917/874188</a> recommends using <code>7z</code> instead of <code>zip</code>. My experience bears this out.</p> <p>Copy/pasting the answer by @JFSebastian here too for completeness:</p> <p>To create encrypted ...
3
2014-12-12T12:27:59Z
[ "python", "zip" ]
What's the best way to distribute python command-line tools?
17,893
<p>My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar..</p> <p>Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?</p>
36
2008-08-20T13:07:25Z
17,933
<p>Try the <code>entry_points.console_scripts</code> parameter in the setup() call. As described in the <a href="http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation">setuptools docs</a>, this should do what I think you want.</p> <p>To reproduce here:</p> <pre><code>from setuptools import setu...
33
2008-08-20T13:25:23Z
[ "python", "command-line", "packaging" ]
How to check set of files conform to a naming scheme
19,030
<p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p> <p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p> <p>Then, I loop though each valid-...
2
2008-08-20T22:50:55Z
19,389
<p>maybe you should take the approach of defaulting to: "the filename is correct" and work from there to disprove that statement:</p> <p>with the fact that you only allow filenames with: 'show name', 'season number x episode number' and 'episode name', you know for certain that these items should be separated by a "-"...
0
2008-08-21T05:59:00Z
[ "python", "validation", "naming" ]
How to check set of files conform to a naming scheme
19,030
<p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p> <p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p> <p>Then, I loop though each valid-...
2
2008-08-20T22:50:55Z
21,302
<blockquote> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state..</p> </blockquote> <p>This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good ...
2
2008-08-21T22:02:01Z
[ "python", "validation", "naming" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
19,152
<p>First of all the <a href="https://docs.python.org/3/library/itertools.html">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:</p> <blockquote> <p>yield</p> </blockquote> <p>Isn't that cool? Yield can b...
90
2008-08-21T00:36:33Z
[ "python", "object", "iterator" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
24,377
<p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>next()</code>. The <code>__iter__</code> returns the iterator object and is implicitly called at the start of loops. The <code>next()</code> method returns the next value...
374
2008-08-23T16:57:28Z
[ "python", "object", "iterator" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
7,542,261
<p>There are four ways to build an iterative function:</p> <ul> <li>create a generator (uses the <a href="http://docs.python.org/py3k/reference/expressions.html#yield-expressions">yield keyword</a>)</li> <li>use a generator expression (<a href="http://docs.python.org/py3k/reference/expressions.html#generator-expressio...
202
2011-09-24T22:13:44Z
[ "python", "object", "iterator" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
11,690,539
<p>I see some of you doing <code>return self</code> in <code>__iter__</code>. I just wanted to note that <code>__iter__</code> itself can be a generator (thus removing the need for <code>__next__</code> and raising <code>StopIteration</code> exceptions)</p> <pre><code>class range: def __init__(self,a,b): self.a ...
52
2012-07-27T15:05:12Z
[ "python", "object", "iterator" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
35,779,493
<p>This is an iterable function without <code>yield</code>. It make use of the <code>iter</code> function and a closure which keeps it's state in a mutable (<code>list</code>) in the enclosing scope for python 2. </p> <pre><code>def count(low, high): counter = [0] def tmp(): val = low + counter[0] ...
-1
2016-03-03T17:55:26Z
[ "python", "object", "iterator" ]
Build a Basic Python Iterator
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
321
2008-08-21T00:36:11Z
36,138,037
<p>This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it <code>__getitem__</code> and <code>__len__</code> methods. I have tested this on Python 2 and 3.</p> <pre><code>class CustomRan...
0
2016-03-21T17:39:14Z
[ "python", "object", "iterator" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
19,343
<p><a href="http://docs.python.org/library/functions.html#zip"><code>zip</code></a> is its own inverse! Provided you use the special * operator.</p> <pre><code>&gt;&gt;&gt; zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] </code></pre> <p>The way this works is by calling <code>zip</...
397
2008-08-21T04:36:29Z
[ "python", "list", "matrix", "unzip", "transpose" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
25,193
<p>You could also do</p> <pre><code>result = ([ a for a,b in original ], [ b for a,b in original ]) </code></pre> <p>It <em>should</em> scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.</p> <p>(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of...
17
2008-08-24T17:07:57Z
[ "python", "list", "matrix", "unzip", "transpose" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
4,578,299
<p>If you have lists that are not the same length, you may not want to use zip as per Patricks answer. This works:</p> <pre><code>&gt;&gt;&gt; zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] </code></pre> <p>But with different length lists, zip truncates each item to the length of ...
14
2011-01-02T12:14:17Z
[ "python", "list", "matrix", "unzip", "transpose" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
22,115,957
<p>I like to use <code>zip(*iterable)</code> (which is the piece of code you're looking for) in my programs as so:</p> <pre><code>def unzip(iterable): return zip(*iterable) </code></pre> <p>I find <code>unzip</code> more readable.</p>
7
2014-03-01T15:00:15Z
[ "python", "list", "matrix", "unzip", "transpose" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
35,012,020
<p>It's only another way to do it but it helped me a lot so I write it here:</p> <p>Having this data structure:</p> <pre><code>X=[1,2,3,4] Y=['a','b','c','d'] XY=zip(X,Y) </code></pre> <p>Resulting in:</p> <pre><code>In: XY Out: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] </code></pre> <p>The more pythonic way to unz...
0
2016-01-26T10:45:23Z
[ "python", "list", "matrix", "unzip", "transpose" ]
A Transpose/Unzip Function in Python (inverse of zip)
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', '...
241
2008-08-21T04:29:07Z
35,813,331
<pre><code>&gt;&gt;&gt; original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] &gt;&gt;&gt; tuple([list(tup) for tup in zip(*original)]) (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) </code></pre> <p>Gives a tuple of lists as in the question.</p> <pre><code>list1, list2 = [list(tup) for tup in zip(*original)] </code></pre> <p>U...
2
2016-03-05T11:08:28Z
[ "python", "list", "matrix", "unzip", "transpose" ]
Introducing Python
19,654
<p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p> <p>But, currently, one of the developers has seen the light of Django (the company has only developed ...
5
2008-08-21T11:48:03Z
19,665
<p>Well, python is a high level language.. its not hard to learn and if the guys already have programming knowledge it should be much easier to learn.. i like django.. i think it should be a nice try to use django .. </p>
0
2008-08-21T11:53:38Z
[ "php", "python" ]
Introducing Python
19,654
<p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p> <p>But, currently, one of the developers has seen the light of Django (the company has only developed ...
5
2008-08-21T11:48:03Z
19,668
<p>If the mandate of the new lead is to put the house in order, the current situation should likely be simplified as much as possible prior. If I had to bring things to order, I wouldn't want to have to manage an ongoing language conversion project on top of everything else, or at least I'd like some choice when initi...
4
2008-08-21T11:56:00Z
[ "php", "python" ]
Introducing Python
19,654
<p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p> <p>But, currently, one of the developers has seen the light of Django (the company has only developed ...
5
2008-08-21T11:48:03Z
19,685
<p>I don't think it's a matter of a programming language as such. </p> <p>What is the proficiency level of PHP in the team you're talking about? Are they doing spaghetti code or using some structured framework like Zend? If this is the first case then I absolutely understand the guy's interest in Python and Django. It...
0
2008-08-21T12:03:43Z
[ "php", "python" ]
Introducing Python
19,654
<p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p> <p>But, currently, one of the developers has seen the light of Django (the company has only developed ...
5
2008-08-21T11:48:03Z
19,692
<p>@darkdog:</p> <p>Using a new language in production code is about more than easy syntax and high-level capability. You want to be familiar with core APIs and feel like you can fix something through logic instead of having to comb through the documentation.</p> <p>I'm not saying transitioning to Python would be a b...
2
2008-08-21T12:09:46Z
[ "php", "python" ]
Introducing Python
19,654
<p>The company I used to work with has two developers working fulltime, and a handful of freelancers. They're in the process of hiring a new lead developer to try to bring order and management to the development.</p> <p>But, currently, one of the developers has seen the light of Django (the company has only developed ...
5
2008-08-21T11:48:03Z
19,700
<p>I think the language itself is not an issue here, as python is really nice high level language with good and easy to find, thorough documentation.</p> <p>From what I've seen, the Django framework is also a great tooklit for web development, giving much the same developer performance boost Rails is touted to give.</...
1
2008-08-21T12:13:51Z
[ "php", "python" ]