title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to unescape apostrophes and such in Python?
816,272
<p>I have a string with symbols like this:</p> <pre><code>&amp;#39; </code></pre> <p>That's an apostrophe apparently.</p> <p>I tried saxutils.unescape() without any luck and tried urllib.unquote()</p> <p>How can I decode this? Thanks!</p>
7
2009-05-03T03:37:49Z
816,612
<p>The most robust solution seems to be <a href="http://effbot.org/zone/re-sub.htm#unescape-html" rel="nofollow">this function</a> by Python luminary Fredrik Lundh. It is not the shortest solution, but it handles named entities as well as hex and decimal codes.</p>
1
2009-05-03T08:53:22Z
[ "python", "html", "django", "html-entities" ]
How to unescape apostrophes and such in Python?
816,272
<p>I have a string with symbols like this:</p> <pre><code>&amp;#39; </code></pre> <p>That's an apostrophe apparently.</p> <p>I tried saxutils.unescape() without any luck and tried urllib.unquote()</p> <p>How can I decode this? Thanks!</p>
7
2009-05-03T03:37:49Z
816,805
<p>Try this: (found it <a href="http://github.com/sku/python-twitter-ircbot/blob/321d94e0e40d0acc92f5bf57d126b57369da70de/html%5Fdecode.py" rel="nofollow">here</a>)</p> <pre><code>from htmlentitydefs import name2codepoint as n2cp import re def decode_htmlentities(string): """ Decode HTML entities–hex, decimal, or named–in a string @see http://snippets.dzone.com/posts/show/4569 &gt;&gt;&gt; u = u'E tu vivrai nel terrore - L&amp;#x27;aldil&amp;#xE0; (1981)' &gt;&gt;&gt; print decode_htmlentities(u).encode('UTF-8') E tu vivrai nel terrore - L'aldilà (1981) &gt;&gt;&gt; print decode_htmlentities("l&amp;#39;eau") l'eau &gt;&gt;&gt; print decode_htmlentities("foo &amp;lt; bar") foo &lt; bar """ def substitute_entity(match): ent = match.group(3) if match.group(1) == "#": # decoding by number if match.group(2) == '': # number is in decimal return unichr(int(ent)) elif match.group(2) == 'x': # number is in hex return unichr(int('0x'+ent, 16)) else: # they were using a name cp = n2cp.get(ent) if cp: return unichr(cp) else: return match.group() entity_re = re.compile(r'&amp;(#?)(x?)(\w+);') return entity_re.subn(substitute_entity, string)[0] </code></pre>
2
2009-05-03T11:12:42Z
[ "python", "html", "django", "html-entities" ]
Where is Python's "best ASCII for this Unicode" database?
816,285
<p>I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?</p>
66
2009-05-03T03:46:17Z
816,318
<p>Interesting question. </p> <p>Google helped me find <a href="http://www.peterbe.com/plog/unicode-to-ascii">this page</a> which descibes using the <a href="http://effbot.org/librarybook/unicodedata.htm">unicodedata module</a> as the following:</p> <pre><code>import unicodedata unicodedata.normalize('NFKD', title).encode('ascii','ignore') </code></pre>
16
2009-05-03T04:15:43Z
[ "python", "unicode", "ascii" ]
Where is Python's "best ASCII for this Unicode" database?
816,285
<p>I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?</p>
66
2009-05-03T03:46:17Z
816,319
<p>In my original answer, I also suggested <code>unicodedata.normalize</code>. However, I decided to test it out and it turns out it doesn't work with Unicode quotation marks. It does a good job translating accented Unicode characters, so I'm guessing <code>unicodedata.normalize</code> is implemented using the <code>unicode.decomposition</code> function, which leads me to believe it probably can only handle Unicode characters that are combinations of a letter and a diacritical mark, but I'm not really an expert on the Unicode specification, so I could just be full of hot air... </p> <p>In any event, you can use <code>unicode.translate</code> to deal with punctuation characters instead. The <code>translate</code> method takes a dictionary of Unicode ordinals to Unicode ordinals, thus you can create a mapping that translates Unicode-only punctuation to ASCII-compatible punctuation:</p> <pre><code>'Maps left and right single and double quotation marks' 'into ASCII single and double quotation marks' &gt;&gt;&gt; punctuation = { 0x2018:0x27, 0x2019:0x27, 0x201C:0x22, 0x201D:0x22 } &gt;&gt;&gt; teststring = u'\u201Chello, world!\u201D' &gt;&gt;&gt; teststring.translate(punctuation).encode('ascii', 'ignore') '"hello, world!"' </code></pre> <p>You can add more punctuation mappings if needed, but I don't think you necessarily need to worry about handling every single Unicode punctuation character. If you <em>do</em> need to handle accents and other diacritical marks, you can still use <code>unicodedata.normalize</code> to deal with those characters.</p>
24
2009-05-03T04:16:58Z
[ "python", "unicode", "ascii" ]
Where is Python's "best ASCII for this Unicode" database?
816,285
<p>I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?</p>
66
2009-05-03T03:46:17Z
1,360,215
<p>There's additional discussion about this at <a href="http://code.activestate.com/recipes/251871/" rel="nofollow">http://code.activestate.com/recipes/251871/</a> which has the NFKD solution and some ways of doing a conversion table, for things like ± => +/- and other non-letter characters.</p>
3
2009-09-01T02:03:07Z
[ "python", "unicode", "ascii" ]
Where is Python's "best ASCII for this Unicode" database?
816,285
<p>I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?</p>
66
2009-05-03T03:46:17Z
1,701,378
<p><a href="http://pypi.python.org/pypi/Unidecode">Unidecode</a> looks like a complete solution. It converts fancy quotes to ascii quotes, accented latin characters to unaccented and even attempts transliteration to deal with characters that don't have ASCII equivalents. That way your users don't have to see a bunch of ? when you had to pass their text through a legacy 7-bit ascii system.</p> <pre><code>&gt;&gt;&gt; from unidecode import unidecode &gt;&gt;&gt; print unidecode(u"\u5317\u4EB0") Bei Jing </code></pre> <p><a href="http://www.tablix.org/~avian/blog/archives/2009/01/unicode%5Ftransliteration%5Fin%5Fpython/">http://www.tablix.org/~avian/blog/archives/2009/01/unicode%5Ftransliteration%5Fin%5Fpython/</a></p>
73
2009-11-09T14:37:23Z
[ "python", "unicode", "ascii" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,394
<p>Simplify or break apart the function so that it doesn't require nine arguments (or ignore pylint, but dodges like the ones you're proposing defeat the purpose of a lint tool).</p> <p>EDIT: if it's a temporary measure, disable the warning for the particular function in question using a comment as described here: <a href="http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html" rel="nofollow">http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html</a></p> <p>Later, you can grep for all of the disabled warnings.</p>
4
2009-05-03T05:16:17Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,396
<p>You could try using <a href="http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists">Python's variable arguments</a> feature:</p> <pre><code>def myfunction(*args): for x in args: # Do stuff with specific argument here </code></pre>
9
2009-05-03T05:17:42Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,399
<p>Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me. </p>
5
2009-05-03T05:18:05Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,402
<p>Python has some nice functional programming tools that are likely to fit your needs well. Check out <a href="http://www.secnetix.de/olli/Python/lambda%5Ffunctions.hawk" rel="nofollow">lambda functions</a> and <a href="http://docs.python.org/library/functions.html" rel="nofollow">map</a>. Also, you're using dicts when it seems like you'd be much better served with lists. For the simple example you provided, try this idiom. Note that map would be better and faster but may not fit your needs:</p> <pre><code>def mysum(d): s = 0 for x in d: s += x return s def mybigfunction(): d = (x1, x2, x3, x4, x5, x6, x7, x8, x9) return mysum(d) </code></pre> <p>You mentioned having a lot of local variables, but frankly if you're dealing with lists (or tuples), you should use lists and factor out all those local variables in the long run.</p>
0
2009-05-03T05:19:36Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,517
<p>First, one of <a href="http://www.cs.yale.edu/quotes.html">Perlis's epigrams</a>:</p> <blockquote> <p>"If you have a procedure with 10 parameters, you probably missed some."</p> </blockquote> <p>Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.</p> <p>Making an example up, because there's not enough information in the question to answer directly:</p> <pre><code>class PersonInfo(object): def __init__(self, name, age, iq): self.name = name self.age = age self.iq = iq </code></pre> <p>Then your 10 argument function:</p> <pre><code>def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7): ... </code></pre> <p>becomes:</p> <pre><code>def f(personinfo, x1, x2, x3, x4, x5, x6, x7): ... </code></pre> <p>and the caller changes to:</p> <pre><code>personinfo = PersonInfo(name, age, iq) result = f(personinfo, x1, x2, x3, x4, x5, x6, x7) </code></pre>
35
2009-05-03T07:22:58Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,549
<p>Do you want a better way to pass the arguments or just a way to stop <code>pylint</code> from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting <code>pylint</code>-controlling comments in your code along the lines of:</p> <pre><code>#pylint: disable-msg=R0913 </code></pre> <p>or:</p> <pre><code>#pylint: disable-msg=too-many-arguments </code></pre> <p>remembering to turn them back on as soon as practicable.</p> <p>In my opinion, there's nothing <em>inherently</em> wrong with passing a lot of arguments and solutions advocating wrapping them all up in some container argument don't really solve any problems, other than stopping <code>pylint</code> from nagging you :-).</p> <p>If you need to pass twenty arguments, then pass them. It may be that this is required because your function is doing too much and a re-factoring could assist there, and that's something you should look at. But it's not a decision <em>we</em> can really make unless we see what the 'real' code is.</p>
18
2009-05-03T07:59:40Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
816,789
<p>You can easily change the maximum allowed number of arguments in pylint. Just open your pylintrc file (generate it if you don't already have one) and change:</p> <p>max-args=5</p> <p>to:</p> <p>max-args = 6 # or any value that suits you </p> <p>From pylint's <a href="http://www.logilab.org/card/pylint%5Fmanual">manual</a></p> <blockquote> <p>Specifying all the options suitable for your setup and coding standards can be tedious, so it is possible to use a rc file to specify the default values. Pylint looks for /etc/pylintrc and ~/.pylintrc. The --generate-rcfile option will generate a commented configuration file according to the current configuration on standard output and exit. You can put other options before this one to use them in the configuration, or start with the default values and hand tune the configuration.</p> </blockquote>
11
2009-05-03T10:58:03Z
[ "python", "refactoring", "pylint" ]
Python: avoiding pylint warnings about too many arguments
816,391
<p>I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:</p> <pre><code>x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 </code></pre> <p>Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:</p> <pre><code>def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x </code></pre> <p>The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:</p> <pre><code>def mysum(d): x1 = d['x1'] x2 = d['x2'] ... x9 = d['x9'] x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x def mybigfunction(): ... d = {} d['x1'] = x1 ... d['x9'] = x9 x = mysum(d) </code></pre> <p>but this approach loos ugly to me, it requires writing a lot of code that is even redundant.</p> <p>Is there a better way to do it?</p>
16
2009-05-03T05:13:02Z
26,778,409
<p>Comment about paxdiablo's reply - as I do not have enough reputation to comment there directly :-/</p> <p>I do not like referring to the number, the sybolic name is much more expressive and avoid having to add a comment that could become obsolete over time.</p> <p>So I'd rather do:</p> <pre><code>#pylint: disable-msg=too-many-arguments </code></pre> <p>And I would also recommend to not leave it dangling there: it will stay active until the file ends or it is disabled, whichever comes first.</p> <p>So better doing:</p> <pre><code>#pylint: disable-msg=too-many-arguments code_which_would_trigger_the_msg #pylint: enable-msg=too-many-arguments </code></pre> <p>I would also recommend enabling/disabling one single warning/error per line.</p>
3
2014-11-06T11:31:02Z
[ "python", "refactoring", "pylint" ]
how to get the url of the current page in a GAE template
816,683
<p>In Google App Engine, is there a tag or other mechanism to get the URL of the current page in a template or is it necessary to pass the url as a variable to the template from the python code?</p>
2
2009-05-03T09:36:30Z
816,728
<p>It depends how you are populating the templates. If you are using them outside of Django, then you have to populate them with the URL yourself. If you are using them in Django with the default configuration, you would have to populate them with the URL yourself. An alternative that would avoid you having to populate them yourself is to configure the DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST context processor as described on <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/" rel="nofollow">this page</a> and then access the appropriate part of the request object directly (e.g. request.path).</p>
3
2009-05-03T10:13:19Z
[ "python", "google-app-engine", "templates", "django-templates", "web-applications" ]
save an image with selenium & firefox
816,704
<p>i'm trying to save an image from a website using selenium server &amp; python client. i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.</p> <p>the workaround i found so far is to save the page's screenshot (there are 2 selenium methods for doing just that), but i want the original image.</p> <p>i don't mind fiddling with the clicking menu options etc. but i couldn't found how.</p> <p>thanks</p>
8
2009-05-03T09:51:07Z
816,777
<p>How about going to the image URL and then taking a screenshot of the page? Firefox displays the image in full screen. Hope this helps..</p>
-1
2009-05-03T10:48:43Z
[ "python", "selenium" ]
save an image with selenium & firefox
816,704
<p>i'm trying to save an image from a website using selenium server &amp; python client. i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.</p> <p>the workaround i found so far is to save the page's screenshot (there are 2 selenium methods for doing just that), but i want the original image.</p> <p>i don't mind fiddling with the clicking menu options etc. but i couldn't found how.</p> <p>thanks</p>
8
2009-05-03T09:51:07Z
816,814
<p>I haven't used selenium, but if you know the image's URL, why not just do:</p> <pre><code>from urllib import urlretrieve urlretrieve(url, filename) </code></pre> <p>which will save the url to the filename. more info <a href="http://docs.python.org/library/urllib.html#urllib.urlretrieve" rel="nofollow">here</a></p>
-1
2009-05-03T11:21:02Z
[ "python", "selenium" ]
save an image with selenium & firefox
816,704
<p>i'm trying to save an image from a website using selenium server &amp; python client. i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.</p> <p>the workaround i found so far is to save the page's screenshot (there are 2 selenium methods for doing just that), but i want the original image.</p> <p>i don't mind fiddling with the clicking menu options etc. but i couldn't found how.</p> <p>thanks</p>
8
2009-05-03T09:51:07Z
827,891
<p>To do this the way you want (to actually capture the content sent down to the browser) you'd need to modify Selenium RC's proxy code (see ProxyHandler.java) and store the files locally on the disk in parallel to sending the response back to the browser.</p>
2
2009-05-06T03:18:48Z
[ "python", "selenium" ]
save an image with selenium & firefox
816,704
<p>i'm trying to save an image from a website using selenium server &amp; python client. i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.</p> <p>the workaround i found so far is to save the page's screenshot (there are 2 selenium methods for doing just that), but i want the original image.</p> <p>i don't mind fiddling with the clicking menu options etc. but i couldn't found how.</p> <p>thanks</p>
8
2009-05-03T09:51:07Z
2,699,314
<p>I was trying to accomplish the same task, but the images I wanted to grab were the size of my monitor (wallpaper) -- so the capture screenshot workaround didn't work for me. I figured out a way to do it...</p> <p>I've got selenium set up to go to the page I want (which induces all the session goodies) Then I used a program called "Workspace Macro" to loop through the selenium tasks.</p> <p>Grab it from here <a href="http://www.tethyssolutions.com/product.htm" rel="nofollow">http://www.tethyssolutions.com/product.htm</a> -- they have a trial version, which I think works for 30 runs or something.</p> <p>So here's the progression:</p> <ul> <li>start firefox</li> <li>open selenium and load test case</li> <li>start it, but quickly pause it.</li> <li>record a macro, which pushes "step" on selenium, then goes over to the firefox window and clicks file->save page as, saves, then stop recording</li> <li>run the macro x times... </li> <li>profit??</li> </ul> <p>Cheers</p>
2
2010-04-23T14:25:26Z
[ "python", "selenium" ]
save an image with selenium & firefox
816,704
<p>i'm trying to save an image from a website using selenium server &amp; python client. i know the image's URL, but i can't find the code to save it, either when it's the the document itself, or when it's embedded in the current browser session.</p> <p>the workaround i found so far is to save the page's screenshot (there are 2 selenium methods for doing just that), but i want the original image.</p> <p>i don't mind fiddling with the clicking menu options etc. but i couldn't found how.</p> <p>thanks</p>
8
2009-05-03T09:51:07Z
4,686,774
<p>I found code that puts an image in to a canvas, then converts it to data - which could then be base64 encoded for example. My thought was to call this using the eval command in selenium, however in my testing the toDataURL is throwing a security error 1000. Seems like it is so close to a solution if not for that error.</p> <pre><code>var data, canvas, ctx; var img = new Image(); img = document.getElementById("yourimageID"); canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); // everything works up to here data = canvas.toDataURL(); // this fails *** var base64Img = data.replace(/^data:image\/(png|jpg);base64,/, ""); </code></pre> <p>Doing some research I found references that it is not allowed to use toDataURL when the image is from a different domain. However, I even tried this code by saving the page, stripping everything out except the image itself and this script.</p> <p>For example (index.html) :</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; &lt;img src="local/hard/disk/img.jpg" id="yourimageID"&gt; &lt;script&gt; // script from above &lt;/script&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>The img.jpg and index.html are stored locally, opening the page in firefox locally, still get a security error 1000!</p>
4
2011-01-14T00:10:28Z
[ "python", "selenium" ]
Dynamically change range in Python?
816,712
<p>So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.</p> <p>The pagination looks like</p> <pre><code> 1 2 3 4 5 6 7 Next </code></pre> <p>If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like</p> <pre><code> 1 2 3 7 8 9 10 Next </code></pre> <p>So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get_num_pages returns 7</p> <p>What I am doing is iterating over items on each page so I have something like</p> <pre><code>for page in range(1,num_pages + 1): # do some stuff here </code></pre> <p>Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this. </p>
1
2009-05-03T09:59:57Z
816,721
<p>You could probably çreate a generator that has mutable state that determines when it terminates... but what about something simple like this?</p> <pre><code>page = 1 while page &lt; num_pages + 1: # do stuff that possibly updates num_pages here page += 1 </code></pre>
6
2009-05-03T10:07:23Z
[ "python", "beautifulsoup" ]
Dynamically change range in Python?
816,712
<p>So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.</p> <p>The pagination looks like</p> <pre><code> 1 2 3 4 5 6 7 Next </code></pre> <p>If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like</p> <pre><code> 1 2 3 7 8 9 10 Next </code></pre> <p>So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get_num_pages returns 7</p> <p>What I am doing is iterating over items on each page so I have something like</p> <pre><code>for page in range(1,num_pages + 1): # do some stuff here </code></pre> <p>Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this. </p>
1
2009-05-03T09:59:57Z
816,800
<p>Here's a code free answer, but I think it's simple if you take advantage of what beautiful soup lets you do:</p> <p>To start with, on the first page you have somewhere the page numbers &amp; links; from your question they look like this:</p> <pre><code>1 2 3 4 5 6 7 [next] </code></pre> <p>Different sites handle paging differently, some give a link to jump to beginning/end, but on yours you say it looks like this after the first 7 pages:</p> <pre><code>1 2 3 ... 7 8 9 10 [next] </code></pre> <p>Now, at some point, you will get to the end, it's going to look like this:</p> <pre><code>1 2 3 ... 20 21 22 23 </code></pre> <p>Notice there's no [next] link.</p> <p>So forget about generators and ranges and keeping track of intermediate ranges, etc. Just do this:</p> <ol> <li>use beautiful soup to identify the page # links on a given page, along with the next button.</li> <li>Every time you see a [next] link, follow it and reparse with beautiful soup</li> <li>When you hit a page where there is no next link, the last # page link is the total number of pages.</li> </ol>
2
2009-05-03T11:05:47Z
[ "python", "beautifulsoup" ]
Dynamically change range in Python?
816,712
<p>So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.</p> <p>The pagination looks like</p> <pre><code> 1 2 3 4 5 6 7 Next </code></pre> <p>If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like</p> <pre><code> 1 2 3 7 8 9 10 Next </code></pre> <p>So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get_num_pages returns 7</p> <p>What I am doing is iterating over items on each page so I have something like</p> <pre><code>for page in range(1,num_pages + 1): # do some stuff here </code></pre> <p>Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this. </p>
1
2009-05-03T09:59:57Z
817,795
<p>I like John's <code>while</code>-based solution, but to use a <code>for</code> you could do something like:</p> <pre><code>pages = range(1, num_pages+1) for p in pages: ...possibly pages.extend(range(something, something)) here... </code></pre> <p>that is, you have to give a name to the range you're looping on, so you can extend it when needed. Changing the container you're iterating on is normally frowned upon, but in this specific and highly-constrained case it can actually be a useful idiom.</p>
1
2009-05-03T19:27:35Z
[ "python", "beautifulsoup" ]
wxPython: A foldable panel widget
816,887
<p>I have my main program window, and I would like to make a foldable panel. What I mean is, a panel which is aligned to one of the sides of the window, with a fold/unfold button. It's important that when the panel gets folded/unfolded, the other widgets change their size accordingly to take advantage of the space they have.</p> <p>How do I do this?</p>
2
2009-05-03T12:04:04Z
817,004
<p>The layout managers for wxPython (and Swing and others) should be able to do this for you if you create the hierarchy properly. Let's assume it's bound to the right hand side, thus:</p> <pre><code>+-----------------------------+ |+----------------+ +--------+| || | | This is|| || | | your || || Other stuff | | panel || || | +--------+| || | +--------+| || | | Another|| || | | panel || |+----------------+ +--------+| +-----------------------------+ </code></pre> <p>If your layout is done right, you will have a top-level layout with two columns, one for the other stuff and one for the right-side container.</p> <p><em>That</em> container will have it's own layout manager with two rows, one for the top panel, one for the bottom.</p> <p>That way, when you resize the top panel (your foldable one) to be shorter (fold) or taller (unfold), the layout manager should expand or contract the bottom panel to fit.</p> <p>Obviously you can use more complicated layout managers, I've chosen the simplest ones to illustrate how to do it without cluttering the discussion with column/row spans and anchors and so on. You can also change the direction of folding by reversing the window managers (horizontal &lt;-> vertical).</p>
1
2009-05-03T12:57:31Z
[ "python", "user-interface", "wxpython", "widget" ]
wxPython: A foldable panel widget
816,887
<p>I have my main program window, and I would like to make a foldable panel. What I mean is, a panel which is aligned to one of the sides of the window, with a fold/unfold button. It's important that when the panel gets folded/unfolded, the other widgets change their size accordingly to take advantage of the space they have.</p> <p>How do I do this?</p>
2
2009-05-03T12:04:04Z
817,095
<p>Here is one way using wx.SplitterWindow</p> <pre><code>import wx, wx.calendar class FoldableWindowContainer(wx.Panel): def __init__(self, parent, left, right): wx.Panel.__init__(self, parent) sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(sizer) self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE) left.Reparent(self.splitter) right.Reparent(self.splitter) self.left = left self.right = right self.splitter.SplitVertically(self.left, self.right) self.splitter.SetMinimumPaneSize(50) self.sash_pos = self.splitter.SashPosition sizer.Add(self.splitter, 1, wx.EXPAND) fold_button = wx.Button(self, size=(10, -1)) fold_button.Bind(wx.EVT_BUTTON, self.On_FoldToggle) sizer.Add(fold_button, 0, wx.EXPAND) def On_FoldToggle(self, event): if self.splitter.IsSplit(): self.sash_pos = self.splitter.SashPosition self.splitter.Unsplit() else: self.splitter.SplitVertically(self.left, self.right, self.sash_pos) class FoldTest(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) left = wx.Panel(self, style=wx.BORDER_SUNKEN) right = wx.Panel(self, style=wx.BORDER_SUNKEN) left_sizer = wx.BoxSizer(wx.VERTICAL) left.SetSizer(left_sizer) left_sizer.Add(wx.calendar.CalendarCtrl(left), 1, wx.EXPAND | wx.ALL, 5) left_sizer.Add(wx.Button(left, label="Act"), 0, wx.EXPAND | wx.ALL, 5) right_sizer = wx.BoxSizer(wx.VERTICAL) right.SetSizer(right_sizer) right_sizer.Add( wx.StaticText(right, label="Fold panel", style=wx.BORDER_RAISED), 1, wx.EXPAND | wx.ALL, 5 ) FoldableWindowContainer(self, left, right) app = wx.PySimpleApp() app.TopWindow = FoldTest() app.TopWindow.Show() app.MainLoop() </code></pre> <p>Also, check out wx.CollapsiblePane in the wxPython demos.</p>
3
2009-05-03T13:47:19Z
[ "python", "user-interface", "wxpython", "widget" ]
Call a function with argument list in python
817,087
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p> <pre><code>def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) </code></pre> <p>In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.</p>
104
2009-05-03T13:43:33Z
817,093
<p>You can use *args and **kwargs syntax for variable length arguments.</p> <p><a href="http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean">http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean</a></p> <p>And from the official python tutorial </p> <p><a href="http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions">http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions</a></p>
10
2009-05-03T13:47:05Z
[ "python", "function" ]
Call a function with argument list in python
817,087
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p> <pre><code>def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) </code></pre> <p>In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.</p>
104
2009-05-03T13:43:33Z
817,111
<p>You need to use arguments unpacking..</p> <pre><code>def wrapper(func, *args): func(*args) def func1(x): print(x) def func2(x, y, z): print x+y+z wrapper(func1, 1) wrapper(func2, 1, 2, 3) </code></pre>
8
2009-05-03T13:53:57Z
[ "python", "function" ]
Call a function with argument list in python
817,087
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p> <pre><code>def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) </code></pre> <p>In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.</p>
104
2009-05-03T13:43:33Z
817,296
<p>To expand a little on the other answers:</p> <p>In the line:</p> <pre><code>def wrapper(func, *args): </code></pre> <p>The * next to <code>args</code> means "take the rest of the parameters given and put them in a list called <code>args</code>". </p> <p>In the line:</p> <pre><code> func(*args) </code></pre> <p>The * next to <code>args</code> here means "take this list called args and 'unwrap' it into the rest of the parameters.</p> <p>So you can do the following:</p> <pre><code>def wrapper1(func, *args): # with star func(*args) def wrapper2(func, args): # without star func(*args) def func2(x, y, z): print x+y+z wrapper1(func2, 1, 2, 3) wrapper2(func2, [1, 2, 3]) </code></pre> <p>In <code>wrapper2</code>, the list is passed explicitly, but in both wrappers <code>args</code> contains the list <code>[1,2,3]</code>.</p>
187
2009-05-03T15:17:44Z
[ "python", "function" ]
Call a function with argument list in python
817,087
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p> <pre><code>def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) </code></pre> <p>In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.</p>
104
2009-05-03T13:43:33Z
817,834
<p>The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line</p> <pre><code>func(args) </code></pre> <p>to read </p> <pre><code>func(*args) </code></pre> <p>This tells Python to take the list given (in this case, <code>args</code>) and pass its contents to the function as positional arguments.</p> <p>This trick works on both "sides" of the function call, so a function defined like this:</p> <pre><code>def func2(*args): return sum(args) </code></pre> <p>would be able to accept as many positional arguments as you throw at it, and place them all into a list called <code>args</code>.</p> <p>I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using <code>**</code> instead of <code>*</code>.</p>
7
2009-05-03T19:48:20Z
[ "python", "function" ]
Call a function with argument list in python
817,087
<p>I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this:</p> <pre><code>def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) </code></pre> <p>In this case first call will work, and second won't. What I want to modify is the wrapper function and not the called functions.</p>
104
2009-05-03T13:43:33Z
817,968
<p>The simpliest way to wrap a function </p> <pre><code> func(*args, **kwargs) </code></pre> <p>... is to manually write a wrapper that would call <em>func()</em> inside itself:</p> <pre><code> def wrapper(*args, **kwargs): # do something before try: return func(*a, **kwargs) finally: # do something after </code></pre> <p>In Python function is an object, so you can pass it's name as an argument of another function and return it. You can also write a wraper generator for any function <em>anyFunc()</em>:</p> <pre><code> def wrapperGenerator(anyFunc, *args, **kwargs): def wrapper(*args, **kwargs): try: # do something before return anyFunc(*args, **kwargs) finally: #do something after return wrapper </code></pre> <p>Please also note that in Python when you don't know or don't want to name all the arguments of a function you can refer to a tuple of arguments, which is denoted by its name preceded by an asterisk in the parentheses after the function name:</p> <pre><code> *args </code></pre> <p>For example you can define a function that would take any number of arguments:</p> <pre><code> def testFunc(*args): print args # prints the tuple of arguments </code></pre> <p>Python provides for even funther manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses arter the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:</p> <pre><code> **kwargs </code></pre> <p>A similar example that prints the keyword arguments dictionary:</p> <pre><code> def testFunc(**kwargs): print kwargs # prints the dictionary of keyword arguments </code></pre>
13
2009-05-03T20:50:24Z
[ "python", "function" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,140
<p>Add a space before the \d+.</p> <pre><code>&gt;&gt;&gt; s = "This must not b3 delet3d, but the number at the end yes 134411" &gt;&gt;&gt; s = re.sub(" \d+", " ", s) &gt;&gt;&gt; s 'This must not b3 delet3d, but the number at the end yes ' </code></pre> <p>Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.</p> <pre><code>s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s) </code></pre>
7
2009-05-03T14:04:05Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,148
<p>If your number is allways at the end of your strings try : re.sub("\d+$", "", s)</p> <p>otherwise, you may try re.sub("(\s)\d+(\s)", "\1\2", s)</p> <p>You can adjust the back-references to keep only one or two of the spaces (\s match any white separator)</p>
1
2009-05-03T14:06:05Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,164
<p>Try this:</p> <pre><code>"\b\d+\b" </code></pre> <p>That'll match only those digits that are not part of another word.</p>
11
2009-05-03T14:12:44Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,189
<p>To handle digit strings at the beginning of a line as well:</p> <pre><code>s = re.sub(r"(^|\W)\d+", "", s) </code></pre>
2
2009-05-03T14:23:58Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,271
<p>Using <code>\s</code> isn't very good, since it doesn't handle tabs, et al. A first cut at a better solution is:</p> <pre><code>re.sub(r"\b\d+\b", "", s) </code></pre> <p>Note that the pattern is a raw string because <code>\b</code> is normally the backspace escape for strings, and we want the special word boundary regex escape instead. A slightly fancier version is:</p> <pre><code>re.sub(r"$\d+\W+|\b\d+\b|\W+\d+$", "", s) </code></pre> <p>That tries to remove leading/trailing whitespace when there are digits at the beginning/end of the string. I say "tries" because if there are multiple numbers at the end then you still have some spaces.</p>
4
2009-05-03T15:05:28Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,304
<p>Non-regex solution:</p> <pre><code>&gt;&gt;&gt; s = "This must not b3 delet3d, but the number at the end yes 134411" &gt;&gt;&gt; " ".join([x for x in s.split(" ") if not x.isdigit()]) 'This must not b3 delet3d, but the number at the end yes' </code></pre> <p>Splits by <code>" "</code>, and checks if the chunk is a number by doing <a href="http://docs.python.org/library/stdtypes.html#str.isdigit" rel="nofollow"><code>str().isdigit()</code></a>, then joins them back together. More verbosely (not using a list comprehension):</p> <pre><code>words = s.split(" ") non_digits = [] for word in words: if not word.isdigit(): non_digits.append(word) " ".join(non_digits) </code></pre>
0
2009-05-03T15:21:27Z
[ "python", "regex", "digits" ]
Delete digits in Python (Regex)
817,122
<p>I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.</p> <p>Thanks!</p> <p><hr /></p> <pre><code>s = "This must not b3 delet3d, but the number at the end yes 134411" s = re.sub("\d+", "", s) print s </code></pre> <p>Result:</p> <blockquote> <p>This must not b deletd, but the number at the end yes</p> </blockquote>
6
2009-05-03T13:59:17Z
817,328
<p>I don't know what your real situation looks like, but most of the answers look like they won't handle negative numbers or decimals,</p> <p><code>re.sub(r"(\b|\s+\-?|^\-?)(\d+|\d*\.\d+)\b","")</code></p> <p>The above should also handle things like,</p> <p>"This must not b3 delet3d, but the number at the end yes -134.411"</p> <p>But this is still incomplete - you probably need a more complete definition of what you can expect to find in the files you need to parse.</p> <p>Edit: it's also worth noting that '\b' changes depending on the locale/character set you are using so you need to be a little careful with that.</p>
1
2009-05-03T15:37:32Z
[ "python", "regex", "digits" ]
Overriding the save method in Django ModelForm
817,284
<p>I'm having trouble overriding a <code>ModelForm</code> save method. This is the error I'm receiving:</p> <pre><code>Exception Type: TypeError Exception Value: save() got an unexpected keyword argument 'commit' </code></pre> <p>My intentions are to have a form submit many values for 3 fields, to then create an object for each combination of those fields, and to save each of those objects. Helpful nudge in the right direction would be ace.</p> <h3>File <code>models.py</code></h3> <pre><code>class CallResultType(models.Model): id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True) callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id') campaign = models.ForeignKey('Campaign', db_column='icampaign_id') callType = models.ForeignKey('CallType', db_column='icall_type_id') agent = models.BooleanField(db_column='bagent', default=True) teamLeader = models.BooleanField(db_column='bTeamLeader', default=True) active = models.BooleanField(db_column='bactive', default=True) </code></pre> <h3>File <code>forms.py</code></h3> <pre><code>from django.forms import ModelForm, ModelMultipleChoiceField from callresults.models import * class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, force_insert=False, force_update=False): for cr in self.callResult: for c in self.campain: for ct in self.callType: m = CallResultType(self) # this line is probably wrong m.callResult = cr m.campaign = c m.calltype = ct m.save() class Meta: model = CallResultType </code></pre> <h3>File <code>admin.py</code></h3> <pre><code>class CallResultTypeAdmin(admin.ModelAdmin): form = CallResultTypeForm </code></pre>
48
2009-05-03T15:12:00Z
817,364
<p>In your <code>save</code> you have to have the argument <code>commit</code>. If anything overrides your form, or wants to modify what it's saving, it will do <code>save(commit=False)</code>, modify the output, and then save it itself.</p> <p>Also, your ModelForm should return the model it's saving. Usually a ModelForm's <code>save</code> will look something like:</p> <pre><code>def save(self, commit=True): m = super(CallResultTypeForm, self).save(commit=False) # do custom stuff if commit: m.save() return m </code></pre> <p>Read up on <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method" rel="nofollow">the <code>save</code> method</a>.</p> <p>Finally, a lot of this ModelForm won't work just because of the way you are accessing things. Instead of <code>self.callResult</code>, you need to use <code>self.fields['callResult']</code>.</p> <p><em>UPDATE</em>: In response to your answer:</p> <p><em>Aside:</em> Why not just use <code>ManyToManyField</code>s in the Model so you don't have to do this? Seems like you're storing redundant data and making more work for yourself (and me <code>:P</code>).</p> <pre><code>from django.db.models import AutoField def copy_model_instance(obj): """ Create a copy of a model instance. M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case) See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/ """ initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()]) return obj.__class__(**initial) class CallResultTypeForm(ModelForm): callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all()) campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all()) callType = ModelMultipleChoiceField(queryset=CallType.objects.all()) def save(self, commit=True, *args, **kwargs): m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs) results = [] for cr in self.callResult: for c in self.campain: for ct in self.callType: m_new = copy_model_instance(m) m_new.callResult = cr m_new.campaign = c m_new.calltype = ct if commit: m_new.save() results.append(m_new) return results </code></pre> <p>This allows for inheritance of <code>CallResultTypeForm</code>, just in case that's ever necessary.</p>
115
2009-05-03T15:54:10Z
[ "python", "django", "django-forms", "django-admin" ]
NetBeans debugging of Python (GAE)
817,407
<p>dev_appserver works normal when run it. But if i try o debug, i found an error caused by</p> <pre><code> __file__ </code></pre> <p>that is changed on jpydaemon.py. Has anyone successfully debugged apps on NetBeans?</p>
2
2009-05-03T16:13:11Z
1,202,861
<p>Nope but I'm interested in setting this up. You have to attach the netbeans debugger to the port somehow. This may help you: here's an example I was reading about for java: <a href="http://blogs.oracle.com/leonfan/entry/netbeans_development_series_for_google" rel="nofollow">http://blogs.oracle.com/leonfan/entry/netbeans_development_series_for_google</a> </p> <p>Quoted what I found pertinent to your question dynback "How to debug application for Google App Engine</p> <p>Since we already map 'test' action to 'debug', we should right click on project and choose 'test' to do debug'. When system is running and listenning on Java remote debug port 5005, attach debugger under menu 'Debug':"</p>
1
2009-07-29T20:33:21Z
[ "python", "debugging", "google-app-engine", "netbeans" ]
NetBeans debugging of Python (GAE)
817,407
<p>dev_appserver works normal when run it. But if i try o debug, i found an error caused by</p> <pre><code> __file__ </code></pre> <p>that is changed on jpydaemon.py. Has anyone successfully debugged apps on NetBeans?</p>
2
2009-05-03T16:13:11Z
35,345,329
<p>You need to make sure the port in your debug settings is not in use.</p> <p>I am assuming you have the python plugin in stalled for Netbeans.</p> <p>Go to your settings and select python and then the Debugger tab. The debugger port is set there.</p> <p>Check your in use ports (In Windows open a command prompt and run the NetStat command)</p> <p>If the port configured in the debugger tab is in use then select a port that is not in use and try again. </p> <p>The default port appears to be 29100 but when I first installed the python plugin that was not the setting I saw there. When I changed it back to the default which was not in use it worked. I hope that helps.</p>
1
2016-02-11T16:52:31Z
[ "python", "debugging", "google-app-engine", "netbeans" ]
Update Facebooks Status using Python
817,431
<p>Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?</p>
3
2009-05-03T16:25:43Z
817,437
<p>The Facebook Developers site for Python is a great place to start. You should be able to accomplish this with a REST call.</p> <p><a href="http://wiki.developers.facebook.com/index.php/Python" rel="nofollow">http://wiki.developers.facebook.com/index.php/Python</a></p>
3
2009-05-03T16:29:45Z
[ "python", "facebook" ]
Update Facebooks Status using Python
817,431
<p>Is there an easy way to update my Facebook status ("What's on your mind?" box) using Python code ?</p>
3
2009-05-03T16:25:43Z
817,443
<p>Check out <a href="http://github.com/sciyoshi/pyfacebook/tree/master" rel="nofollow">PyFacebook</a> which has a <a href="http://wiki.developers.facebook.com/index.php/PyFacebook%5FTutorial" rel="nofollow">tutorial</a>, from... Facebook!</p> <p>Blatantly ripped from the documentation on that page and untested, you'd probably do something like this:</p> <pre><code>import facebook fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY') fb.auth.createToken() fb.login() fb.auth.getSession() fb.set_status('Checking out StackOverFlow.com') </code></pre>
12
2009-05-03T16:31:21Z
[ "python", "facebook" ]
Python's random: What happens if I don't use seed(someValue)?
817,705
<p>a)In this case does the random number generator uses the system's clock (making the seed change) on each run? </p> <p>b)Is the seed used to generate the pseudo-random values of expovariate(lambda)? </p>
17
2009-05-03T18:44:19Z
817,716
<p>a) It typically uses the system clock, the clock on some systems may only have ms precision and so seed twice very quickly may result in the same value.</p> <blockquote> <p>seed(self, a=None) Initialize internal state from hashable object.</p> <pre><code>None or no argument seeds from current time or from an operating system specific randomness source if available. </code></pre> <p><a href="http://pydoc.org/2.5.1/random.html#Random-seed">http://pydoc.org/2.5.1/random.html#Random-seed</a></p> </blockquote> <p>b) I would imagine expovariate does, but I can't find any proof. It would be silly if it didn't.</p>
6
2009-05-03T18:51:43Z
[ "python", "random", "seed" ]
Python's random: What happens if I don't use seed(someValue)?
817,705
<p>a)In this case does the random number generator uses the system's clock (making the seed change) on each run? </p> <p>b)Is the seed used to generate the pseudo-random values of expovariate(lambda)? </p>
17
2009-05-03T18:44:19Z
817,717
<blockquote> <p>current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).</p> </blockquote> <p><a href="http://docs.python.org/library/random.html" rel="nofollow">Random Docs</a></p>
2
2009-05-03T18:52:06Z
[ "python", "random", "seed" ]
Python's random: What happens if I don't use seed(someValue)?
817,705
<p>a)In this case does the random number generator uses the system's clock (making the seed change) on each run? </p> <p>b)Is the seed used to generate the pseudo-random values of expovariate(lambda)? </p>
17
2009-05-03T18:44:19Z
817,742
<p>"Use the Source, Luke!"...;-). Studying <a href="http://svn.python.org/view/python/trunk/Lib/random.py?revision=68378&amp;view=markup">http://svn.python.org/view/python/trunk/Lib/random.py?revision=68378&amp;view=markup</a> will rapidly reassure you;-).</p> <p>What happens when seed isn't set (that's the "i is None" case):</p> <pre><code>if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds </code></pre> <p>and the expovariate:</p> <pre><code>random = self.random u = random() while u &lt;= 1e-7: u = random() return -_log(u)/lambd </code></pre> <p>obviously uses the same underlying random generator as every other method, and so is identically affected by the seeding or lack thereof (really, how else would it have been done?-)</p>
17
2009-05-03T19:04:15Z
[ "python", "random", "seed" ]
Unique session id in python
817,882
<p>How do I generate a unique session id in Python?</p>
33
2009-05-03T20:11:02Z
817,892
<p>You can use the <a href="http://docs.python.org/library/uuid.html">uuid library</a> like so:</p> <pre> import uuid my_id = uuid.uuid1() # or uuid.uuid4() </pre>
21
2009-05-03T20:14:37Z
[ "python", "session" ]
Unique session id in python
817,882
<p>How do I generate a unique session id in Python?</p>
33
2009-05-03T20:11:02Z
817,940
<p>It can be as simple as creating a random number. Of course, you'd have to store your session IDs in a database or something and check each one you generate to make sure it's not a duplicate, but odds are it never will be if the numbers are large enough.</p>
1
2009-05-03T20:32:03Z
[ "python", "session" ]
Unique session id in python
817,882
<p>How do I generate a unique session id in Python?</p>
33
2009-05-03T20:11:02Z
818,040
<pre><code>import os, base64 def generate_session(): return base64.b64encode(os.urandom(16)) </code></pre>
18
2009-05-03T21:19:46Z
[ "python", "session" ]
Unique session id in python
817,882
<p>How do I generate a unique session id in Python?</p>
33
2009-05-03T20:11:02Z
820,198
<p>What's the session for? A web app? You might wanna look at <a href="http://beaker.groovie.org/" rel="nofollow">the beaker module</a>. It is the default module for handling sessions in Pylons.</p>
1
2009-05-04T13:53:34Z
[ "python", "session" ]
Unique session id in python
817,882
<p>How do I generate a unique session id in Python?</p>
33
2009-05-03T20:11:02Z
6,092,448
<p>I hate to say this, but none of the other solutions posted here are correct with regards to being a "secure session ID." </p> <pre><code># pip install M2Crypto import base64, M2Crypto def generate_session_id(num_bytes = 16): return base64.b64encode(M2Crypto.m2.rand_bytes(num_bytes)) </code></pre> <p>Neither <code>uuid()</code> or <code>os.urandom()</code> are good choices for generating session IDs. Both may generate <strong>random</strong> results, but random does not mean it is <strong>secure</strong> due to poor <strong>entropy</strong>. See "<a href="http://www.reteam.org/papers/e59.pdf">How to Crack a Linear Congruential Generator</a>" by Haldir or <a href="http://csrc.nist.gov/groups/ST/toolkit/rng/index.html">NIST's resources on Random Number Generation</a>. If you still want to use a UUID, then use a UUID that was generated with a good initial random number:</p> <pre><code>import uuid, M2Crypto uuid.UUID(bytes = M2Crypto.m2.rand_bytes(num_bytes))) # UUID('5e85edc4-7078-d214-e773-f8caae16fe6c') </code></pre> <p>or:</p> <pre><code># pip install pyOpenSSL import uuid, OpenSSL uuid.UUID(bytes = OpenSSL.rand.bytes(16)) # UUID('c9bf635f-b0cc-d278-a2c5-01eaae654461') </code></pre> <p>M2Crypto is best OpenSSL API in Python atm as pyOpenSSL appears to be maintained only to support legacy applications.</p>
70
2011-05-23T03:07:22Z
[ "python", "session" ]
Creating dictionaries with pre-defined keys
817,884
<p>In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?</p>
3
2009-05-03T20:12:18Z
817,893
<p>You can easily extend any built in type. This is how you'd do it with a dict:</p> <pre><code>&gt;&gt;&gt; class MyClass(dict): ... def __init__(self, *args, **kwargs): ... self['mykey'] = 'myvalue' ... self['mykey2'] = 'myvalue2' ... &gt;&gt;&gt; x = MyClass() &gt;&gt;&gt; x['mykey'] 'myvalue' &gt;&gt;&gt; x {'mykey2': 'myvalue2', 'mykey': 'myvalue'} </code></pre> <p>I wasn't able to find the Python documentation that talks about this, but the very popular book <a href="http://diveintopython.net/index.html" rel="nofollow">Dive Into Python</a> (available for free online) <a href="http://diveintopython.net/object_oriented_framework/userdict.html" rel="nofollow">has a few examples</a> on doing this.</p>
7
2009-05-03T20:14:56Z
[ "python", "dictionary" ]
Creating dictionaries with pre-defined keys
817,884
<p>In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?</p>
3
2009-05-03T20:12:18Z
817,902
<p>Just create a subclass of dict and add the keys in the <strong>init</strong> method.</p> <pre> class MyClass(dict) def __init__(self): """Creates a new dict with default values"""" self['key1'] = 'value1' </pre> <p>Remember though, that in python any class that 'acts like a dict' is usually treated like one, so you don't have to worry too much about it being a subclass, you could instead implement the dict methods, although the above approach is probably more useful to you :).</p>
0
2009-05-03T20:17:28Z
[ "python", "dictionary" ]
Creating dictionaries with pre-defined keys
817,884
<p>In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?</p>
3
2009-05-03T20:12:18Z
818,019
<p>Yes, in Python <code>dict</code> is a class , so you can subclass it:</p> <pre><code> class SubDict(dict): def __init__(self): dict.__init__(self) self.update({ 'foo': 'bar', 'baz': 'spam',}) </code></pre> <p>Here you override dict's <code>__init__()</code> method (a method which is called when an instance of the class is created). Inside <code>__init__</code> you first call supercalss's <code>__init__()</code> method, which is a common practice when you whant to expand on the functionality of the base class. Then you update the new instance of <code>SubDictionary</code> with your initial data.</p> <pre><code> subDict = SubDict() print subDict # prints {'foo': 'bar', 'baz': 'spam'} </code></pre>
3
2009-05-03T21:13:03Z
[ "python", "dictionary" ]
Creating dictionaries with pre-defined keys
817,884
<p>In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?</p>
3
2009-05-03T20:12:18Z
818,116
<p>You can also have the dict subclass restrict the keys to a predefined list, by overriding <code>__setitem__()</code></p> <pre><code>&gt;&gt;&gt; class LimitedDict(dict): _keys = "a b c".split() def __init__(self, valtype=int): for key in LimitedDict._keys: self[key] = valtype() def __setitem__(self, key, val): if key not in LimitedDict._keys: raise KeyError dict.__setitem__(self, key, val) &gt;&gt;&gt; limited = LimitedDict() &gt;&gt;&gt; limited['a'] 0 &gt;&gt;&gt; limited['a'] = 3 &gt;&gt;&gt; limited['a'] 3 &gt;&gt;&gt; limited['z'] = 0 Traceback (most recent call last): File "&lt;pyshell#61&gt;", line 1, in &lt;module&gt; limited['z'] = 0 File "&lt;pyshell#56&gt;", line 8, in __setitem__ raise KeyError KeyError &gt;&gt;&gt; len(limited) 3 </code></pre>
5
2009-05-03T22:00:11Z
[ "python", "dictionary" ]
Creating dictionaries with pre-defined keys
817,884
<p>In python, is there a way to create a class that is treated like a dictionary but have the keys pre-defined when a new instance is created?</p>
3
2009-05-03T20:12:18Z
819,017
<p>I'm not sure this is what you're looking for, but when I read your post I immediately thought you were looking to dynamically generate keys for counting exercises.</p> <p>Unlike perl, which will do this for you by default,</p> <pre><code> grep{$_{$_}++} qw/ a a b c c c /; print map{$_."\t".$_{$_}."\n"} sort {$_{$b}$_{$a}} keys %_; c 3 a 2 b 1 </code></pre> <p>Python won't give you this for free:</p> <pre><code> l = ["a","a","b","c","c","c"] d = {} for item in l: d[item] += 1 Traceback (most recent call last): File "./y.py", line 6, in d[item] += 1 KeyError: 'a' </code></pre> <p>however, defaultdict will do this for you,</p> <pre><code> from collections import defaultdict from operator import itemgetter l = ["a","a","b","c","c","c"] d = defaultdict(int) for item in l: d[item] += 1 dl = sorted(d.items(),key=itemgetter(1), reverse=True) for item in dl: print item ('c', 3) ('a', 2) ('b', 1) </code></pre>
0
2009-05-04T06:44:26Z
[ "python", "dictionary" ]
C55: More Info?
818,016
<p>I saw a PyCon09 keynote presentation (slides: <a href="http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55" rel="nofollow">http://www.slideshare.net/kn0thing/ride-the-snake-reddit-keynote-pycon-09?c55</a>) given by the reddit guys, and in it they mention a CSS compiler called C55. They said it would be open sourced soon. It looks cool - does anyone have more information about how it works, why they created it (aside from the fact that CSS is a pain), etc...?</p>
3
2009-05-03T21:11:43Z
818,146
<p>Just from the talk, the main advantage over simply generating CSS from templates is that it allows nesting, which is conceptually a lot nicer to work with.</p> <p>So you could do something like this in C55 (obviously I'm kind of making up the syntax):</p> <pre><code>div.content { color: $content_color ; .left { float: left; }; .right { float: right; }; }; </code></pre>
3
2009-05-03T22:14:50Z
[ "python", "css", "reddit" ]
MPI4Py Scatter sendbuf Argument Type?
818,362
<p>I'm having trouble with the Scatter function in the MPI4Py Python module. My assumption is that I should be able to pass it a single list for the sendbuffer. However, I'm getting a consistent error message when I do that, or indeed add the other two arguments, recvbuf and root:</p> <pre><code> File "code/step3.py", line 682, in subbox_grid i = mpi_communicator.Scatter(station_range, station_data) File "Comm.pyx", line 427, in mpi4py.MPI.Comm.Scatter (src/ mpi4py_MPI.c:44993) File "message.pxi", line 321, in mpi4py.MPI._p_msg_cco.for_scatter (src/mpi4py_MPI.c:14497) File "message.pxi", line 232, in mpi4py.MPI._p_msg_cco.for_cco_send (src/mpi4py_MPI.c:13630) File "message.pxi", line 36, in mpi4py.MPI.message_simple (src/ mpi4py_MPI.c:11904) ValueError: message: expecting 2 or 3 items </code></pre> <p>Here is the relevant code snipped, starting a few lines above 682 mentioned above.</p> <pre><code>for station in stations #snip--do some stuff with station station_data = [] station_range = range(1,len(station)) mpi_communicator = MPI.COMM_WORLD i = mpi_communicator.Scatter(station_range, nsm) #snip--do some stuff with station[i] nsm = combine(avg, wt, dnew, nf1, nl1, wti[i], wtm, station[i].id) station_data = mpi_communicator.Gather(station_range, nsm) </code></pre> <p>I've tried a number of combinations initializing station_range, but I must not be understanding the Scatter argument types properly. </p> <p>Does a Python/MPI guru have a clarification this?</p>
2
2009-05-03T23:47:51Z
3,712,648
<p>If you want to move raw buffers (as with <code>Gather</code>), you provide a triplet <code>[buffer, size, type]</code>. Look at the demos for examples of this. If you want to send Python objects, you should use the higher level interface and call <code>gather</code> (note the lowercase) which uses <code>pickle</code> internally.</p>
6
2010-09-14T20:29:17Z
[ "python", "parallel-processing", "mpi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
818,405
<p>Yes.</p> <p>Allow them to script their client, not your server.</p>
3
2009-05-04T00:25:46Z
[ "python", "cgi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
818,417
<p>I am in no way associated with this site and I'm only linking it because it tries to achieve what you are getting after: jailing of python. The site is <a href="http://codepad.org/about">code pad</a>.</p> <p>According to the about page it is ran under <a href="http://www.xs4all.nl/~weegen/eelis/geordi/">geordi</a> and traps all sys calls with ptrace. In addition to be chroot'ed they are on a virtual machine with firewalls in place to disallow outbound connections.</p> <p>Consider it a starting point but I do have to chime in on the whole danger thing. Gotta CYA myself. :)</p>
8
2009-05-04T00:34:51Z
[ "python", "cgi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
818,430
<p>Using PyPy you can create a python sandbox. The sandbox is a separate and supposedly secure python environment where you can execute their scripts. More info here</p> <p><a href="http://codespeak.net/pypy/dist/pypy/doc/sandbox.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/sandbox.html</a></p> <p>"In theory it's impossible to do anything bad or read a random file on the machine from this prompt."</p> <p>"This is safe to do even if script.py comes from some random untrusted source, e.g. if it is done by an HTTP server."</p>
8
2009-05-04T00:44:33Z
[ "python", "cgi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
818,558
<p>Along with other safeguards, you can also incorporate human review of the code. Assuming part of the experience is reviewing other members' solutions, and everyone is a python developer, don't allow new code to be activated until a certain number of members vote for it. Your users aren't going to approve malicious code. </p>
4
2009-05-04T01:58:12Z
[ "python", "cgi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
819,227
<p>PyPy is probably a decent bet on the server side as suggested, but I'd look into having your python backend provide well defined APIs and data formats and have the users implement the AI and logic in Javascript so it can run in their browser. So the interaction would look like: For each match/turn/etc, pass data to the browser in a well defined format, provide a javascript template that receives the data and can implement logic, and provide web APIs that can be invoked by the client (browser) to take the desired actions. That way you don't have to worry about security or server power.</p>
1
2009-05-04T08:11:25Z
[ "python", "cgi" ]
Letting users upload Python scripts for execution
818,402
<p>I understand that letting any anonymous user upload any sort of file in general can be dangerous, especially if it's code. However, I have an idea to let users upload custom AI scripts to my website. I would provide the template so that the user could compete with other AI's in an online web game I wrote in Python. I either need a solution to ensure a user couldn't compromise any other files or inject malicious code via their uploaded script or a solution for client-side execution of the game. Any suggestions? (I'm looking for a solution that will work with my Python scripts)</p>
12
2009-05-04T00:20:54Z
878,455
<p>Have an extensive API for the users and strip all other calls upon upload (such as import statements). Also, strip everything that has anything to do with file i/o.</p> <p>(You might want to do multiple passes to ensure that you didn't miss anything.)</p>
0
2009-05-18T15:59:40Z
[ "python", "cgi" ]
Shouldn't __metaclass__ force the use of a metaclass in Python?
818,483
<p>I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting <code>__metaclass__</code> to M at the global or class level. To test this out, I wrote the following program:</p> <pre><code>p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta: __metaclass__ = M p(2) __metaclass__ = M class GlobalMeta: pass p(3) M('NotMeta2', (), {}) p(4) </code></pre> <p>However, when I run it, I get the following output:</p> <pre> C:\Documents and Settings\Daniel Wong\Desktop>python --version Python 3.0.1 C:\Documents and Settings\Daniel Wong\Desktop>python meta.py 1 2 3 The rain in Spain 4 </pre> <p>Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here?</p>
6
2009-05-04T01:18:10Z
818,502
<p>In Python 3 (which you are using) metaclasses are specified by a keyword parameter in the class definition:</p> <pre><code>class ClassMeta(metaclass=M): pass </code></pre> <p>Specifying a <code>__metaclass__</code> class property or global variable is old syntax from Python 2.x and not longer supported. See also <a href="http://docs.python.org/3.0/whatsnew/3.0.html#changed-syntax" rel="nofollow">"What's new in Python 3"</a> and <a href="http://www.python.org/dev/peps/pep-3115/" rel="nofollow">PEP 2115</a>.</p>
13
2009-05-04T01:29:25Z
[ "python", "oop", "python-3.x", "metaclass" ]
Shouldn't __metaclass__ force the use of a metaclass in Python?
818,483
<p>I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting <code>__metaclass__</code> to M at the global or class level. To test this out, I wrote the following program:</p> <pre><code>p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta: __metaclass__ = M p(2) __metaclass__ = M class GlobalMeta: pass p(3) M('NotMeta2', (), {}) p(4) </code></pre> <p>However, when I run it, I get the following output:</p> <pre> C:\Documents and Settings\Daniel Wong\Desktop>python --version Python 3.0.1 C:\Documents and Settings\Daniel Wong\Desktop>python meta.py 1 2 3 The rain in Spain 4 </pre> <p>Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here?</p>
6
2009-05-04T01:18:10Z
818,508
<p>This works as you expect in Python 2.6 (and earlier), but in 3.0 metaclasses are specified differently:</p> <pre><code>class ArgMeta(metaclass=M): ... </code></pre>
2
2009-05-04T01:33:34Z
[ "python", "oop", "python-3.x", "metaclass" ]
Shouldn't __metaclass__ force the use of a metaclass in Python?
818,483
<p>I've been trying to learn about metaclasses in Python. I get the main idea, but I can't seem to activate the mechanism. As I understand it, you can specify M to be as the metaclass when constructing a class K by setting <code>__metaclass__</code> to M at the global or class level. To test this out, I wrote the following program:</p> <pre><code>p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta: __metaclass__ = M p(2) __metaclass__ = M class GlobalMeta: pass p(3) M('NotMeta2', (), {}) p(4) </code></pre> <p>However, when I run it, I get the following output:</p> <pre> C:\Documents and Settings\Daniel Wong\Desktop>python --version Python 3.0.1 C:\Documents and Settings\Daniel Wong\Desktop>python meta.py 1 2 3 The rain in Spain 4 </pre> <p>Shouldn't I see "The rain in Spain" after 1 and 2? What's going on here?</p>
6
2009-05-04T01:18:10Z
818,514
<p>The syntax of metaclasses has <a href="http://docs.python.org/3.0/whatsnew/3.0.html" rel="nofollow">changed</a> in Python 3.0. The <code>__metaclass__</code> attribute is no longer special at either the class nor the module level. To do what you're trying to do, you need to specify <code>metaclass</code> as a keyword argument to the <code>class</code> statement:</p> <pre><code>p = print class M(type): def __init__(*args): type.__init__(*args) print("The rain in Spain") p(1) class ClassMeta(metaclass=M): pass </code></pre> <p>Yields:</p> <pre><code>1 The rain in Spain </code></pre> <p>As you'd expect.</p>
2
2009-05-04T01:37:32Z
[ "python", "oop", "python-3.x", "metaclass" ]
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
818,691
<p>So what I'm trying to do is replace a string "keyword" with <code>"&lt;b&gt;keyword&lt;/b&gt;"</code> in a larger string.</p> <p>Example:</p> <p>myString = "HI there. You should higher that person for the job. Hi hi."</p> <p>keyword = "hi"</p> <p>result I would want would be:</p> <p><code>result = "&lt;b&gt;HI&lt;/b&gt; there. You should higher that person for the job. </code> <code>&lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;."</code></p> <p>I will not know what the keyword until the user types the keyword and won't know the corpus (myString) until the query is run. </p> <p>I found a solution that works most of the time, but has some false positives, <code>namely it would return "&lt;b&gt;hi&lt;b/&gt;gher" </code>which is not what I want. Also note that I am trying to preserve the case of the original text, and the matching should take place irrespective of case. so if the keyword is "hi" it should replace <code>HI with &lt;b&gt;HI&lt;/b&gt; and hi with &lt;b&gt;hi&lt;/b&gt;.</code></p> <p>The closest I have come is using a slightly derived version of this: <a href="http://code.activestate.com/recipes/576715/" rel="nofollow">http://code.activestate.com/recipes/576715/</a> but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above. </p> <p>Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation) but I'm not sure how I would put the sentences back together given it does not have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7". </p> <p>Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought. </p>
2
2009-05-04T03:26:39Z
818,737
<p>This ok?</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; myString = "HI there. You should higher that person for the job. Hi hi." &gt;&gt;&gt; keyword = "hi" &gt;&gt;&gt; search = re.compile(r'\b(%s)\b' % keyword, re.I) &gt;&gt;&gt; search.sub('&lt;b&gt;\\1&lt;/b&gt;', myString) '&lt;b&gt;HI&lt;/b&gt; there. You should higher that person for the job. &lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;.' </code></pre> <p>The key to the whole thing is using <a href="http://docs.python.org/library/re.html" rel="nofollow">word boundaries</a>, <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow">groups</a> and the <a href="http://docs.python.org/library/re.html#re.I" rel="nofollow">re.I flag</a>.</p>
3
2009-05-04T04:01:01Z
[ "python", "regex", "search", "replace", "nltk" ]
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
818,691
<p>So what I'm trying to do is replace a string "keyword" with <code>"&lt;b&gt;keyword&lt;/b&gt;"</code> in a larger string.</p> <p>Example:</p> <p>myString = "HI there. You should higher that person for the job. Hi hi."</p> <p>keyword = "hi"</p> <p>result I would want would be:</p> <p><code>result = "&lt;b&gt;HI&lt;/b&gt; there. You should higher that person for the job. </code> <code>&lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;."</code></p> <p>I will not know what the keyword until the user types the keyword and won't know the corpus (myString) until the query is run. </p> <p>I found a solution that works most of the time, but has some false positives, <code>namely it would return "&lt;b&gt;hi&lt;b/&gt;gher" </code>which is not what I want. Also note that I am trying to preserve the case of the original text, and the matching should take place irrespective of case. so if the keyword is "hi" it should replace <code>HI with &lt;b&gt;HI&lt;/b&gt; and hi with &lt;b&gt;hi&lt;/b&gt;.</code></p> <p>The closest I have come is using a slightly derived version of this: <a href="http://code.activestate.com/recipes/576715/" rel="nofollow">http://code.activestate.com/recipes/576715/</a> but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above. </p> <p>Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation) but I'm not sure how I would put the sentences back together given it does not have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7". </p> <p>Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought. </p>
2
2009-05-04T03:26:39Z
818,740
<p>You should be able to do this very easily with <code>re.sub</code> using the word boundary assertion <code>\b</code>, which only matches at a word boundary:</p> <pre><code>import re def SurroundWith(text, keyword, before, after): regex = re.compile(r'\b%s\b' % keyword, re.IGNORECASE) return regex.sub(r'%s\0%s' % (before, after), text) </code></pre> <p>Then you get:</p> <pre><code>&gt;&gt;&gt; SurroundWith('HI there. You should hire that person for the job. ' ... 'Hi hi.', 'hi', '&lt;b&gt;', '&lt;/b&gt;') '&lt;b&gt;HI&lt;/b&gt; there. You should hire that person for the job. &lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;.' </code></pre> <p>If you have more complicated criteria for what constitutes a "word boundary," you'll have to do something like:</p> <pre><code>def SurroundWith2(text, keyword, before, after): regex = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % keyword, re.IGNORECASE) return regex.sub(r'\1%s\2%s\3' % (before, after), text) </code></pre> <p>You can modify the <code>[^a-zA-Z0-9]</code> groups to match anything you consider a "non-word."</p>
0
2009-05-04T04:01:59Z
[ "python", "regex", "search", "replace", "nltk" ]
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
818,691
<p>So what I'm trying to do is replace a string "keyword" with <code>"&lt;b&gt;keyword&lt;/b&gt;"</code> in a larger string.</p> <p>Example:</p> <p>myString = "HI there. You should higher that person for the job. Hi hi."</p> <p>keyword = "hi"</p> <p>result I would want would be:</p> <p><code>result = "&lt;b&gt;HI&lt;/b&gt; there. You should higher that person for the job. </code> <code>&lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;."</code></p> <p>I will not know what the keyword until the user types the keyword and won't know the corpus (myString) until the query is run. </p> <p>I found a solution that works most of the time, but has some false positives, <code>namely it would return "&lt;b&gt;hi&lt;b/&gt;gher" </code>which is not what I want. Also note that I am trying to preserve the case of the original text, and the matching should take place irrespective of case. so if the keyword is "hi" it should replace <code>HI with &lt;b&gt;HI&lt;/b&gt; and hi with &lt;b&gt;hi&lt;/b&gt;.</code></p> <p>The closest I have come is using a slightly derived version of this: <a href="http://code.activestate.com/recipes/576715/" rel="nofollow">http://code.activestate.com/recipes/576715/</a> but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above. </p> <p>Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation) but I'm not sure how I would put the sentences back together given it does not have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7". </p> <p>Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought. </p>
2
2009-05-04T03:26:39Z
818,748
<p>I think the best solution would be regular expression...</p> <pre><code>import re def reg(keyword, myString) : regx = re.compile(r'\b(' + keyword + r')\b', re.IGNORECASE) return regx.sub(r'&lt;b&gt;\1&lt;/b&gt;', myString) </code></pre> <p>of course, you must first make your keyword "regular expression safe" (quote any regex special characters).</p>
0
2009-05-04T04:06:50Z
[ "python", "regex", "search", "replace", "nltk" ]
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
818,691
<p>So what I'm trying to do is replace a string "keyword" with <code>"&lt;b&gt;keyword&lt;/b&gt;"</code> in a larger string.</p> <p>Example:</p> <p>myString = "HI there. You should higher that person for the job. Hi hi."</p> <p>keyword = "hi"</p> <p>result I would want would be:</p> <p><code>result = "&lt;b&gt;HI&lt;/b&gt; there. You should higher that person for the job. </code> <code>&lt;b&gt;Hi&lt;/b&gt; &lt;b&gt;hi&lt;/b&gt;."</code></p> <p>I will not know what the keyword until the user types the keyword and won't know the corpus (myString) until the query is run. </p> <p>I found a solution that works most of the time, but has some false positives, <code>namely it would return "&lt;b&gt;hi&lt;b/&gt;gher" </code>which is not what I want. Also note that I am trying to preserve the case of the original text, and the matching should take place irrespective of case. so if the keyword is "hi" it should replace <code>HI with &lt;b&gt;HI&lt;/b&gt; and hi with &lt;b&gt;hi&lt;/b&gt;.</code></p> <p>The closest I have come is using a slightly derived version of this: <a href="http://code.activestate.com/recipes/576715/" rel="nofollow">http://code.activestate.com/recipes/576715/</a> but I still could not figure out how to do a second pass of the string to fix all of the false positives mentioned above. </p> <p>Or using the NLTK's WordPunctTokenizer (which simplifies some things like punctuation) but I'm not sure how I would put the sentences back together given it does not have a reverse function and I want to keep the original punctuation of myString. Essential, doing a concatenation of all the tokens does not return the original string. For example I would not want to replace "7 - 7" with "7-7" when regrouping the tokens into its original text if the original text had "7 - 7". </p> <p>Hope that was clear enough. Seems like a simple problem, but its a turned out a little more difficult then I thought. </p>
2
2009-05-04T03:26:39Z
1,155,326
<p>Here's one suggestion, from the nitpicking committee. :-)</p> <pre><code>myString = "HI there. You should higher that person for the job. Hi hi." myString.replace('higher','hire') </code></pre>
0
2009-07-20T19:08:31Z
[ "python", "regex", "search", "replace", "nltk" ]
Spliting a file into lines in Python using re.split
818,705
<p>I'm trying to split a file with a list comprehension using code similar to:</p> <pre><code>lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] </code></pre> <p>However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?</p>
1
2009-05-04T03:36:47Z
818,712
<p>lines = file.readlines()</p> <p><strong>edit:</strong> or if you didnt want blank lines in there, you can do</p> <p>lines = filter(lambda a:(a!='\n'), file.readlines()) </p> <p><strong>edit^2:</strong> to remove trailing newines, you can do </p> <p>lines = [re.sub('\n','',line) for line in filter(lambda a:(a!='\n'), file.readlines())]</p>
3
2009-05-04T03:40:00Z
[ "python", "regex", "list-comprehension" ]
Spliting a file into lines in Python using re.split
818,705
<p>I'm trying to split a file with a list comprehension using code similar to:</p> <pre><code>lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] </code></pre> <p>However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?</p>
1
2009-05-04T03:36:47Z
818,757
<p>Put the regular expression hammer away :-)</p> <ol> <li>You can iterate over a file directly; <code>readlines()</code> is almost obsolete these days.</li> <li>Read about <a href="http://docs.python.org/library/stdtypes.html#str.strip"><code>str.strip()</code></a> (and its friends, <code>lstrip()</code> and <code>rstrip()</code>).</li> <li>Don't use <code>file</code> as a variable name. It's bad form, because <code>file</code> is a <a href="http://docs.python.org/library/functions.html#file">built-in function</a>.</li> </ol> <p>You can write your code as:</p> <pre><code>lines = [] f = open(filename) for line in f: if not line.startswith('com'): lines.append(line.strip()) </code></pre> <p>If you are still getting blank lines in there, you can add in a test:</p> <pre><code>lines = [] f = open(filename) for line in f: if line.strip() and not line.startswith('com'): lines.append(line.strip()) </code></pre> <p>If you really want it in one line:</p> <pre><code>lines = [line.strip() for line in open(filename) if line.strip() and not line.startswith('com')] </code></pre> <p>Finally, if you're on python 2.6, look at the <a href="http://effbot.org/zone/python-with-statement.htm">with statement</a> to improve things a little more.</p>
8
2009-05-04T04:14:20Z
[ "python", "regex", "list-comprehension" ]
Spliting a file into lines in Python using re.split
818,705
<p>I'm trying to split a file with a list comprehension using code similar to:</p> <pre><code>lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] </code></pre> <p>However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?</p>
1
2009-05-04T03:36:47Z
818,851
<p>This should work, and eliminate the regular expressions as well:</p> <pre><code>all_lines = (line.rstrip() for line in open(filename) if "com" not in line) # filter out the empty lines lines = filter(lambda x : x, all_lines) </code></pre> <p>Since you're using a list comprehension and not a generator expression (so the whole file gets loaded into memory anyway), here's a shortcut that avoids code to filter out empty lines:</p> <pre><code>lines = [line for line in open(filename).read().splitlines() if "com" not in line] </code></pre>
0
2009-05-04T05:21:06Z
[ "python", "regex", "list-comprehension" ]
Spliting a file into lines in Python using re.split
818,705
<p>I'm trying to split a file with a list comprehension using code similar to:</p> <pre><code>lines = [x for x in re.split(r"\n+", file.read()) if not re.match(r"com", x)] </code></pre> <p>However, the lines list always has an empty string as the last element. Does anyone know a way to avoid this (excluding the cludge of putting a pop() afterwards)?</p>
1
2009-05-04T03:36:47Z
818,985
<p>another handy trick, especially when you need the line number, is to use enumerate:</p> <p><pre><code> fp = open("myfile.txt", "r") for n, line in enumerate(fp.readlines()): dosomethingwith(n, line) </pre></code></p> <p>i only found out about enumerate quite recently but it has come in handy quite a few times since then.</p>
1
2009-05-04T06:26:10Z
[ "python", "regex", "list-comprehension" ]
Web-Based Music Library (programming concept)
818,752
<p>So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows:</p> <ol> <li>Does this sound like a good project to begin building databases from scratch with?</li> <li>What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language.</li> <li>If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see?</li> </ol> <p>My idea for building up the indexing script would be as follows:</p> <ul> <li>Get it to populate the database with only the filenames</li> <li>From the extension of the filename, determine format</li> <li>Get file size</li> <li>Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc)</li> <li>Check if all files still exist on disk, and if not, flag the file as unavailable</li> </ul> <p>Another script would go in later and check if the files are back, if they are not, the will remove the row from the database.</p>
2
2009-05-04T04:10:38Z
818,758
<p>I think this is a fine project to learn programming with. By using your own "product" you can really get after things that are missing and are much more motivated to learn and better your program - this is known as <a href="http://www.codinghorror.com/blog/archives/000287.html" rel="nofollow">dogfooding</a>. Curiously enough, the book <a href="http://www.diveintopython.net/" rel="nofollow">Dive Into Python</a>, although a little old, covers in some detail how to extract the ID3 information of music files using Python. Since that's the book most often recommended for beginners, I bet that'd be as good a place to start as any.</p>
3
2009-05-04T04:14:24Z
[ "php", "python", "mysql" ]
Web-Based Music Library (programming concept)
818,752
<p>So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows:</p> <ol> <li>Does this sound like a good project to begin building databases from scratch with?</li> <li>What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language.</li> <li>If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see?</li> </ol> <p>My idea for building up the indexing script would be as follows:</p> <ul> <li>Get it to populate the database with only the filenames</li> <li>From the extension of the filename, determine format</li> <li>Get file size</li> <li>Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc)</li> <li>Check if all files still exist on disk, and if not, flag the file as unavailable</li> </ul> <p>Another script would go in later and check if the files are back, if they are not, the will remove the row from the database.</p>
2
2009-05-04T04:10:38Z
818,763
<p>Working on something you care about is the best way to learn programming, so I think this is a great idea.</p> <p>I also recommend Python as a place to start. Have fun!</p>
1
2009-05-04T04:18:10Z
[ "php", "python", "mysql" ]
Web-Based Music Library (programming concept)
818,752
<p>So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows:</p> <ol> <li>Does this sound like a good project to begin building databases from scratch with?</li> <li>What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language.</li> <li>If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see?</li> </ol> <p>My idea for building up the indexing script would be as follows:</p> <ul> <li>Get it to populate the database with only the filenames</li> <li>From the extension of the filename, determine format</li> <li>Get file size</li> <li>Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc)</li> <li>Check if all files still exist on disk, and if not, flag the file as unavailable</li> </ul> <p>Another script would go in later and check if the files are back, if they are not, the will remove the row from the database.</p>
2
2009-05-04T04:10:38Z
818,779
<p>If you use Python, you could build it with the <a href="http://code.google.com/appengine/" rel="nofollow">Google App Engine</a>. It gives you a very nice database interface, and the tutorial will take you from 'Hello world!' to a functioning web app.</p> <p>You don't even need to upload the result to Google; you can just run it in the dev environment and it will be accessible within your home network.</p>
1
2009-05-04T04:29:32Z
[ "php", "python", "mysql" ]
Web-Based Music Library (programming concept)
818,752
<p>So, I've been tossing this idea around in my head for a while now. At its core, it's mostly a project for me to learn programming. The idea is that, I have a large set of data, my music collection. There are quite a few datasets that my music has. Format, artist, title, album, genre, length, year of release, filename, directory, just to name a few. Ideally, I'd like to create a database that has all of this data stored in it, and in the future, create a web interface on top of it that I can manage my music collection with. So, my questions are as follows:</p> <ol> <li>Does this sound like a good project to begin building databases from scratch with?</li> <li>What language would you recommend I start with? I know tidbits of PHP, but I would imagine it would be awful to index data in a filesystem with. Python was the other language I was thinking of, considering it's the language most people consider as a beginner language.</li> <li>If you were going to implement this kind of system (the web interface) in your home (if you had PCs connected to a couple of stereos in your home and this was the software connected), what kind of features would you want to see?</li> </ol> <p>My idea for building up the indexing script would be as follows:</p> <ul> <li>Get it to populate the database with only the filenames</li> <li>From the extension of the filename, determine format</li> <li>Get file size</li> <li>Using the filenames in the database as a reference, pull ID3 or other applicable metadata (artist, track name, album, etc)</li> <li>Check if all files still exist on disk, and if not, flag the file as unavailable</li> </ul> <p>Another script would go in later and check if the files are back, if they are not, the will remove the row from the database.</p>
2
2009-05-04T04:10:38Z
818,866
<p>I think python would be excellent choice as </p> <ol> <li>easy to learn but have advanced features too</li> <li>good web frameworks available e.g. django which you can run on your machine</li> <li>Word class Free python hosting available i.e. google app engine</li> <li>Libraries available for almost anything imaginable e.g. for reading your mp3 tags you can use <a href="http://id3-py.sourceforge.net/" rel="nofollow">http://id3-py.sourceforge.net/</a></li> <li>for searching you can use pylucene <a href="http://lucene.apache.org/pylucene/" rel="nofollow">http://lucene.apache.org/pylucene/</a> the best search engine available.</li> </ol>
1
2009-05-04T05:28:08Z
[ "php", "python", "mysql" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
818,836
<p>Off the top of my head, no.</p> <p>I think the best you could do is something like this:</p> <pre><code>def loop(f,n): for i in xrange(n): f() loop(lambda: &lt;insert expression here&gt;, 5) </code></pre> <p>But I think you can just live with the extra <code>i</code> variable.</p> <p>Here is the option to use the <code>_</code> variable, which in reality, is just another variable.</p> <pre><code>for _ in range(n): do_something() </code></pre> <p>Note that <code>_</code> is assigned the last result that returned in an interactive python session:</p> <pre><code>&gt;&gt;&gt; 1+2 3 &gt;&gt;&gt; _ 3 </code></pre> <p>For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.</p> <pre><code>&gt;&gt;&gt; for _ in xrange(10): pass ... &gt;&gt;&gt; _ 9 &gt;&gt;&gt; 1+2 3 &gt;&gt;&gt; _ 9 </code></pre> <p>And according to <a href="http://www.python.org/doc/2.4.3/ref/grammar.txt">python grammar</a>, it is an acceptable variable name:</p> <blockquote> <p>identifier ::= (letter|"_") (letter | digit | "_")*</p> </blockquote>
58
2009-05-04T05:14:35Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
818,849
<p>The general idiom for assigning to a value that isn't used is to name it <code>_</code>.</p> <pre><code>for _ in range(times): do_stuff() </code></pre>
36
2009-05-04T05:20:11Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
818,852
<p>May be answer would depend on what problem you have with using iterator? may be use</p> <pre><code>i = 100 while i: print i i-=1 </code></pre> <p>or </p> <pre><code>def loop(N, doSomething): if not N: return print doSomething(N) loop(N-1, doSomething) loop(100, lambda a:a) </code></pre> <p>but frankly i see no point in using such approaches</p>
2
2009-05-04T05:21:23Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
818,888
<p>You may be looking for</p> <pre><code>for _ in itertools.repeat(None, times): ... </code></pre> <p>this is THE fastest way to iterate <code>times</code> times in Python.</p>
46
2009-05-04T05:39:39Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
818,903
<p>What everyone suggesting you to use _ isn't saying is that _ is frequently used as a shortcut to one of the <a href="http://docs.python.org/library/gettext.html">gettext</a> functions, so if you want your software to be available in more than one language then you're best off avoiding using it for other purposes.</p> <pre><code>import gettext gettext.bindtextdomain('myapplication', '/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # ... print _('This is a translatable string.') </code></pre>
17
2009-05-04T05:44:00Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
829,729
<p>Here's a random idea that utilizes (abuses?) the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fnonzero%5F%5F">data model</a>.</p> <pre><code>class Counter(object): def __init__(self, val): self.val = val def __nonzero__(self): self.val -= 1 return self.val &gt;= 0 x = Counter(5) while x: # Do something pass </code></pre> <p>I wonder if there is something like this in the standard libraries?</p>
9
2009-05-06T14:00:39Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
1,356,365
<pre><code>t=0 for _ in range (0, 10): print t t = t+1 </code></pre> <p>OUTPUT:<br /> 0 1 2 3 4 5 6 7 9</p>
1
2009-08-31T08:10:29Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
8,754,535
<p>I generally agree with solutions given above. Namely with: </p> <ol> <li>Using underscore in <code>for</code>-loop (2 and more lines)</li> <li>Defining a normal <code>while</code> counter (3 and more lines)</li> <li>Declaring a custom class with <code>__nonzero__</code> implementation (many more lines) </li> </ol> <p>If one is to define an object as in <strong>#3</strong> I would recommend implementing protocol for <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow"><em>with</em> keyword</a> or apply <a href="http://docs.python.org/library/contextlib.html" rel="nofollow">contextlib</a>.</p> <p>Further I propose yet another solution. It is a 3 liner and is not of supreme elegance, but it uses <strong>itertools</strong> package and thus might be of an interest.</p> <pre><code>from itertools import (chain, repeat) times = chain(repeat(True, 2), repeat(False)) while next(times): print 'do stuff!' </code></pre> <p>In these example <em>2</em> is the number of times to iterate the loop. <strong>chain</strong> is wrapping two <strong>repeat</strong> iterators, the first being limited but the second is infinite. Remember that these are true iterator objects, hence they do not require infinite memory. Obviously this is much slower then solution <strong>#1</strong>. Unless written as a part of a function it might require a clean up for <strong>times</strong> variable.</p>
0
2012-01-06T07:07:47Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
9,920,109
<p>You can use _11 (or any number or another invalid identifier) to prevent name-colision with gettext. Any time you use underscore + invalid identifier you get a dummy name that can be used in for loop.</p>
5
2012-03-29T06:24:20Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
12,837,610
<p>What about:</p> <pre><code>while range(some_number): #do something </code></pre>
-7
2012-10-11T10:34:01Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
15,392,368
<p>Instead of an unneeded counter, now you have an unneeded list. Best solution is to use a variable that starts with "_", that tells syntax checkers that you are aware you are not using the variable.</p> <pre><code>x = range(5) while len(x) &gt; 0: x.pop() print "Work!" </code></pre>
0
2013-03-13T17:30:37Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
15,482,560
<pre><code>#Return first n items of the iterable as a list list(itertools.islice(iterable, n)) </code></pre> <p>Taken from <a href="http://docs.python.org/2/library/itertools.html" rel="nofollow">http://docs.python.org/2/library/itertools.html</a></p>
-1
2013-03-18T17:01:12Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
20,464,059
<p>We have had some fun with the following, interesting to share so: </p> <pre><code>class RepeatFunction: def __init__(self,n=1): self.n = n def __call__(self,Func): for i in xrange(self.n): Func() return Func #----usage k = 0 @RepeatFunction(7) #decorator for repeating function def Job(): global k print k k += 1 print '---------' Job() </code></pre> <p><strong>Results:</strong> </p> <pre><code>0 1 2 3 4 5 6 --------- 7 </code></pre>
0
2013-12-09T05:55:27Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
29,060,307
<p>If you <strong>really</strong> want to avoid putting something with a name (either an iteration variable as in the OP, or unwanted list or unwanted generator returning true the wanted amount of time) you could do it if you really wanted:</p> <pre><code>for type('', (), {}).x in range(somenumber): dosomething() </code></pre> <p>The trick that's used is to create an anonymous class <code>type('', (), {})</code> which results in a class with empty name, but NB that it is not inserted in the local or global namespace (even if a nonempty name was supplied). Then you use a member of that class as iteration variable which is unreachable since the class it's a member of is unreachable.</p>
0
2015-03-15T11:55:38Z
[ "python", "loops", "for-loop", "range" ]
Is it possible to implement a Python for range loop without an iterator variable?
818,828
<p>Is is possible to do this;</p> <pre><code>for i in range(some_number): #do something </code></pre> <p>without the i? If you just want to do something x amount of times and don't need the iterator.</p>
115
2009-05-04T05:06:46Z
32,925,357
<p>According to what Alex Martelli said. It is not true that <code>itertools.repeat()</code> is faster than <code>range</code>. </p> <p>I've run several times a generation of random numbers in for loop using both methods of iteration. Basically in repeats up to 100 000 times <code>range</code> is faster than <code>itertools.repeat()</code>. But when it comes to repeat over 100 000 times it is <code>itertools.repeat()</code> which is faster than <code>range</code>.</p> <pre><code>10000 times Itertools: 0.015010 Range: 0.008006` 100000 times Itertools: 0.091061 Range: 0.087057 1000000 Itertools: 0.846565 Range: 0.911609 </code></pre> <p>I have been generating tuples of random integers in a list. Regards Marek</p>
-1
2015-10-03T17:21:28Z
[ "python", "loops", "for-loop", "range" ]
Parse a .txt file
818,936
<p>I have a .txt file like:</p> <pre><code>Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text </code></pre> <p>How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ?</p> <p>How can i get them by column wise parsing or else how.</p> <p>I need an immediate help...Waiting for an appropriate solution as usual</p>
1
2009-05-04T06:01:35Z
818,944
<p>Here is a basic approach. What do you think?</p> <pre><code># Suppose you have filename "thefile.txt" import re obj = '' for line in file('thefile.txt'): # Checking for the .o file match = re.search('Symbols from (.*):', line) if match: obj = match.groups()[0] # Checking for the symbols. if re.search('|', line): columns = [x.strip() for x in a.split('|')] if columns[3] == 'FUNC': print 'File %s has a FUNC named %s' % (obj, columns[0]) </code></pre>
2
2009-05-04T06:06:42Z
[ "python", "parsing", "text-files" ]
Parse a .txt file
818,936
<p>I have a .txt file like:</p> <pre><code>Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text </code></pre> <p>How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ?</p> <p>How can i get them by column wise parsing or else how.</p> <p>I need an immediate help...Waiting for an appropriate solution as usual</p>
1
2009-05-04T06:01:35Z
818,946
<pre><code>for line in open('thefile.txt'): fields = line.split('|') if len(fields) &lt; 4: continue if fields[3].trim() != 'FUNC': continue dowhateveryouwishwith(line, fields) </code></pre>
8
2009-05-04T06:07:10Z
[ "python", "parsing", "text-files" ]
Parse a .txt file
818,936
<p>I have a .txt file like:</p> <pre><code>Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT |00000004| |.data __ctype_tab |00000000| r | OBJECT |00000101| |.rodata Symbols from _ashldi3.o: Name Value Class Type Size Line Section __ashldi3 |00000000| T | FUNC |00000050| |.text </code></pre> <p>How can i parsr this file and get the functions with type FUNC ? Also,from this txt how can i parse and extract .o name ?</p> <p>How can i get them by column wise parsing or else how.</p> <p>I need an immediate help...Waiting for an appropriate solution as usual</p>
1
2009-05-04T06:01:35Z
822,462
<p>I think this might cost less than the use of regexes though i am not totally clear on what you are trying to accomplish</p> <pre><code>symbolList=[] for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] pass if 'FUNC' not in line: pass else: symbolList.append((tempname,line.split('|')[0])) </code></pre> <p>I have learned from other posts it is cheaper and better to wrap up all of the data when you are reading through a file the first time. Thus if you wanted to wrap up the whole datafile in one pass then you could do the following instead</p> <pre><code>fullDict={} for line in open('datafile.txt','r'): if '.o' in line: tempname=line.split()[-1][0:-2] if '|' not in line: pass else: tempDict={} dataList=[dataItem.strip() for dataItem in line.strip().split('|')] name=dataList[0].strip() tempDict['Value']=dataList[1] tempDict['Class']=dataList[2] tempDict['Type']=dataList[3] tempDict['Size']=dataList[4] tempDict['Line']=dataList[5] tempDict['Section']=dataList[6] tempDict['o.name']=tempname fullDict[name]=tempDict tempDict={} </code></pre> <p>Then if you want the Func type you would use the following:</p> <pre><code>funcDict={} for record in fullDict: if fullDict[record]['Type']=='FUNC': funcDict[record]=fullDict[record] </code></pre> <p>Sorry for being so obsessive but I am trying to get a better handle on creating list comprehensions and I decided that this was worthy of a shot</p>
4
2009-05-04T22:42:35Z
[ "python", "parsing", "text-files" ]
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
818,942
<p>I'm learning wxPython so most of the libraries and classes are new to me.</p> <p>I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform.</p> <p>Does wxPython provide functionality that prevents me from doing a <code>if platform.system() == 'Linux'</code> kind of hack?</p>
2
2009-05-04T06:04:52Z
819,026
<p>The appearance of a dialog can change only if you use stock dialogs (like wx.FileDialog), if you make your own the layout will stay the same on every platform.</p> <p>wx.Dialog has a CreateStdDialogButtonSizer method that creates a wx.StdDialogButtonSizer with standard buttons where you might see differences in layout on different platforms but you don't have to use that.</p>
4
2009-05-04T06:48:22Z
[ "python", "user-interface", "cross-platform", "wxpython" ]
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
818,942
<p>I'm learning wxPython so most of the libraries and classes are new to me.</p> <p>I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform.</p> <p>Does wxPython provide functionality that prevents me from doing a <code>if platform.system() == 'Linux'</code> kind of hack?</p>
2
2009-05-04T06:04:52Z
819,110
<p>If you're going to use wx (or any other x-platform toolkit) you'd better trust that it does the right thing, mon!-)</p>
0
2009-05-04T07:20:45Z
[ "python", "user-interface", "cross-platform", "wxpython" ]
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
818,942
<p>I'm learning wxPython so most of the libraries and classes are new to me.</p> <p>I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform.</p> <p>Does wxPython provide functionality that prevents me from doing a <code>if platform.system() == 'Linux'</code> kind of hack?</p>
2
2009-05-04T06:04:52Z
819,330
<p>There's the GenericMessageDialog widget that should do the right thing depending on the platform (but I've never used it so I'm not sure it does). See the wxPython demo. </p> <p>You can also use the SizedControls addon library (it's part of wxPython). The SizedDialog class helps to create dialogs that conform to the Human Interface Guidelines of each platform. See the wxPython demo.</p>
0
2009-05-04T08:52:47Z
[ "python", "user-interface", "cross-platform", "wxpython" ]
WxPython: Cross-Platform Way to Conform Ok/Cancel Button Order
818,942
<p>I'm learning wxPython so most of the libraries and classes are new to me.</p> <p>I'm creating a Preferences dialog class but don't know the best way to make sure the OK/Cancel (or Save/Close) buttons are in the correct order for the platform. This program is intended to run both on GNOME and Windows, so I want to make sure that the buttons are in the correct order for each platform.</p> <p>Does wxPython provide functionality that prevents me from doing a <code>if platform.system() == 'Linux'</code> kind of hack?</p>
2
2009-05-04T06:04:52Z
822,790
<p>You can use a StdDialogButtonSizer</p> <p><a href="http://www.wxpython.org/docs/api/wx.StdDialogButtonSizer-class.html" rel="nofollow">http://www.wxpython.org/docs/api/wx.StdDialogButtonSizer-class.html</a></p> <p>So long as your buttons have the standard IDs they will be put in the correct order.</p> <p>Just to add a wrinkle though, on a Mac for instance, a preferences dialog would not have OK / Cancel buttons. It would automatically apply the preferences as they were entered (or at least on dialog close). So you'd still have to do some platform sniffing in that case.</p>
2
2009-05-05T00:38:45Z
[ "python", "user-interface", "cross-platform", "wxpython" ]