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
Time complexity of accessing a Python dict
1,963,507
<p>I am writing a simple Python program. </p> <p>My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.<br> I use a dictionary to memoize values. That seems to be a bottleneck. </p> <p>The values I'm hashing are tuples of points. Each...
7
2009-12-26T14:32:01Z
1,963,529
<p>It would be easier to make suggestions if you provided example code and data. </p> <p>Accessing the dictionary is unlikely to be a problem as that operation is <a href="http://wiki.python.org/moin/TimeComplexity" rel="nofollow">O(1) on average, and O(N) amortized worst case</a>. It's possible that the built-in hash...
3
2009-12-26T14:44:07Z
[ "python", "hash", "dictionary", "complexity-theory" ]
Time complexity of accessing a Python dict
1,963,507
<p>I am writing a simple Python program. </p> <p>My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.<br> I use a dictionary to memoize values. That seems to be a bottleneck. </p> <p>The values I'm hashing are tuples of points. Each...
7
2009-12-26T14:32:01Z
1,963,597
<p>As others have pointed out, accessing dicts in Python is fast. They are probably the best-oiled data structure in the language, given their central role. The problem lies elsewhere.</p> <p>How many tuples are you memoizing? Have you considered the memory footprint? Perhaps you are spending all your time in the ...
1
2009-12-26T15:20:01Z
[ "python", "hash", "dictionary", "complexity-theory" ]
Time complexity of accessing a Python dict
1,963,507
<p>I am writing a simple Python program. </p> <p>My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.<br> I use a dictionary to memoize values. That seems to be a bottleneck. </p> <p>The values I'm hashing are tuples of points. Each...
7
2009-12-26T14:32:01Z
1,964,061
<blockquote> <p>My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.</p> <p>I use a dictionary to memoize values. That seems to be a bottleneck.</p> </blockquote> <p>This is evidence of a bug in your memoization method.</p>
1
2009-12-26T19:00:44Z
[ "python", "hash", "dictionary", "complexity-theory" ]
Time complexity of accessing a Python dict
1,963,507
<p>I am writing a simple Python program. </p> <p>My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.<br> I use a dictionary to memoize values. That seems to be a bottleneck. </p> <p>The values I'm hashing are tuples of points. Each...
7
2009-12-26T14:32:01Z
1,964,422
<p>To answer your specific questions:</p> <p>Q1: """Am I correct that python dicts suffer from linear access times with such inputs?"""</p> <p>A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python comm...
1
2009-12-26T21:26:59Z
[ "python", "hash", "dictionary", "complexity-theory" ]
Formatted Input in Python
1,963,546
<p>I have a peculiar problem. I need to read (from a txt file) using python only those substrings that are present at predefined range of offsets. Let's say 5-8 and 12-16.</p> <p>For example, if a line in the file is something like:</p> <pre><code>abcdefghi akdhflskdhfhglskdjfhghsldk </code></pre> <p>then I would li...
0
2009-12-26T14:51:13Z
1,963,553
<p>To extract pieces from offsets simply read each line into a string and then access a substring with a slice ([from:to]). </p> <p>It's unclear what you're saying about the inconsistent whitespace. If whitespace adds to the offset, it must be consistent to be meaningful. If the whitespace amount can change but actual...
1
2009-12-26T14:56:39Z
[ "python", "file-io", "textinput" ]
Formatted Input in Python
1,963,546
<p>I have a peculiar problem. I need to read (from a txt file) using python only those substrings that are present at predefined range of offsets. Let's say 5-8 and 12-16.</p> <p>For example, if a line in the file is something like:</p> <pre><code>abcdefghi akdhflskdhfhglskdjfhghsldk </code></pre> <p>then I would li...
0
2009-12-26T14:51:13Z
1,963,555
<p>What's to stop you from using a regular expression? Besides the whitespace do the offsets vary?</p> <pre><code>/.{4}(.{4}).{4}(.{4})/ </code></pre>
-1
2009-12-26T14:58:05Z
[ "python", "file-io", "textinput" ]
Formatted Input in Python
1,963,546
<p>I have a peculiar problem. I need to read (from a txt file) using python only those substrings that are present at predefined range of offsets. Let's say 5-8 and 12-16.</p> <p>For example, if a line in the file is something like:</p> <pre><code>abcdefghi akdhflskdhfhglskdjfhghsldk </code></pre> <p>then I would li...
0
2009-12-26T14:51:13Z
1,963,593
<p>assuming its a file,</p> <pre><code>for line in open("file"): print line[4:8] , line[11:16] </code></pre>
5
2009-12-26T15:17:26Z
[ "python", "file-io", "textinput" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,561
<p>Here's some good advice on Python idioms from <a href="http://jaynes.colorado.edu/PythonIdioms.html" rel="nofollow">this page</a>:</p> <p><hr></p> <p>Catch errors rather than avoiding them to avoid cluttering your code with special cases. This idiom is called EAFP ('easier to ask forgiveness than permission'), as ...
11
2009-12-26T15:01:41Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,573
<p>"Is my python coding style too paranoid? Or is there a way to improve readability while keeping it fool-proof?"</p> <p>Who's the fool you're protecting yourself from?</p> <p>You? Are you worried that you didn't remember the API you wrote?</p> <p>A peer? Are you worried that someone in the next cubicle will acti...
9
2009-12-26T15:08:03Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,575
<p>It's unusual in Python to use a private instance attribute, and then expose it through a property as you have. Just use <code>self.text_values</code>.</p>
3
2009-12-26T15:08:16Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,614
<p>Your code is too <em>paranoid</em> (especially when you want to protect only against yourself).</p> <p>In Python circles, LBYL is generally (but not always) frowned upon. <strong>But</strong> there's also the (often unstated) assumption that one has (good) unit tests.</p> <p>Me personally? I think readability is ...
3
2009-12-26T15:29:01Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,628
<p>If you try to make your code totally foolproof, someone will invent a better fool. Seriously, a good rule of thumb is to guard against <strong>likely</strong> errors, but don't clutter your code trying to think of every conceivable way a caller could break you.</p>
2
2009-12-26T15:35:57Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,963,720
<p>instead of spending time in <code>assert</code> and private variable i prefer spend time in documentation and test cases. i prefer read documentation and when i have to read code i prefer read tests. this is more true the more code grow up. in the same time tests give you a fool-proof code and useful use cases.</p>
2
2009-12-26T16:30:21Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
1,964,045
<p>I base the need for error checking code on the consequences of the errors that it's checking for. If crap data gets into my system, how long will it be before I discover it, how hard will it be to determine that the problem was crap data, and how difficult will it be to fix? For cases like the one you've posted, t...
2
2009-12-26T18:55:54Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
6,254,562
<p>I don't think this is specific to python. I'm a firm believer in Design by Contract: Ideally all functions should have clear pre- and post-conditions; unfortunately most languages (Eiffel being the canonical exception) don't provide particularly convenient ways to achieve this which contributes to the apparent confl...
0
2011-06-06T15:46:24Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
6,271,941
<p>Take all the energy you're putting into argument checking and channel it instead into writing clear, concise doc-strings.</p> <p>Unless you're writing code for nuclear reactors; in which case I would appreciate you doing both.</p>
0
2011-06-07T21:39:30Z
[ "python", "coding-style", "readability" ]
Should I make my python code less fool-proof to improve readability?
1,963,556
<p>I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code.</p> <p>Instead of:</p> <pre><code>class TextServer(object): def __init__(self, text_values): self.text_values = text_values # &lt;more code&gt; # &lt;mo...
5
2009-12-26T14:58:19Z
15,775,828
<p>Another way to think is: you only need to catch errors that you can correct. If you're checking the input just for aborting with an <code>AssertionError</code>, you're better off just allowing the code to raise the appropriate exception later so you can debug correctly.</p> <p>This line in particular is pretty bad ...
0
2013-04-02T22:49:21Z
[ "python", "coding-style", "readability" ]
Django 1.1 FormWizard, Dynamically extend form
1,963,568
<p>I am trying to create a multipage form, where the number of field elements on the second page is defined by the answers given on the first.</p> <p>I have a formWizard set up and my understanding is that I need to use process_step() to alter the setup for the next page. I can either extend an existing form definiti...
2
2009-12-26T15:05:16Z
1,963,904
<p>Spender,</p> <p>At least at the moment I don't know a way of merging multiple forms onto one page in a FormWizard. In django 1.2 you will be able to include FormSets as steps in FormWizards (as per <a href="http://code.djangoproject.com/ticket/11112" rel="nofollow">this ticket</a>) but those only deal with multipl...
1
2009-12-26T17:49:05Z
[ "python", "django", "forms", "wizard" ]
Django 1.1 FormWizard, Dynamically extend form
1,963,568
<p>I am trying to create a multipage form, where the number of field elements on the second page is defined by the answers given on the first.</p> <p>I have a formWizard set up and my understanding is that I need to use process_step() to alter the setup for the next page. I can either extend an existing form definiti...
2
2009-12-26T15:05:16Z
4,810,225
<p>I don't think the </p> <pre><code>self.form_list[1] = RelatedQForm(chosen_subs) </code></pre> <p>part works. I always get the error message: </p> <pre><code>object is not callable </code></pre> <p>It seems to be like form_list only accepts RelatedQForm (the name of the form), not an instance of it.</p>
0
2011-01-26T21:26:11Z
[ "python", "django", "forms", "wizard" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
1,963,644
<p>You can learn Erlang pretty quickly, you should be able to use things like gen_server, gen_event and that sort of thing from OTP. The quickest way to learn Erlang should be to work your way through the documentation and examples at: <a href="http://www.erlang.org/doc/index.html" rel="nofollow">http://www.erlang.org/...
2
2009-12-26T15:44:51Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
1,963,748
<p>Apache+php is indeed a bad technology for comet style applications. You can use a lot of other technologies that are closer to php though: <a href="http://rubyeventmachine.com/" rel="nofollow">Ruby</a>, <a href="http://twistedmatrix.com/trac/wiki/TwistedWeb" rel="nofollow">Python</a> and Perl should all be usable. I...
2
2009-12-26T16:39:22Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
1,964,010
<p>It's definitely possible to do this with Erlang. One possibility would be to use long polling, which you can do with mochiweb. <a href="http://code.google.com/p/mochiweb/" rel="nofollow">http://code.google.com/p/mochiweb/</a></p> <p>Another idea is to use sockets. Until web sockets are supported by a reasonable num...
3
2009-12-26T18:41:06Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
1,964,239
<p>If you are considering Python and Twisted you can take a look at Orbited. They have very mature Comet implementation. You can make Orbited to communicate with your PHP application through STOMP protocol.</p> <p>This article has a decent tutorial which will get you started with Orbited <a href="http://thingsilearned...
1
2009-12-26T20:11:37Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
1,983,097
<p>An addtional option is to use Nginx and it's push module (http://pushmodule.slact.net/)</p> <p>This will allow you to use Comet from PHP without the need to learn a new language.</p>
1
2009-12-30T23:36:15Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
10,874,970
<p>Try Chicago Boss framework <a href="http://www.chicagoboss.org" rel="nofollow">here</a> ... using that you don't have to know the nuts and bolts of the thing called OTP (which actually very easy, powerful and battle proved), because the designer of Chicago Boss, managed to encapsulate it nicely... according to the t...
0
2012-06-04T00:04:35Z
[ "php", "python", "erlang", "comet", "twisted" ]
implement Comet with erlang and use it for PHP application
1,963,578
<p>I'm building a PHP web application and I've reached a point that I need to build a Comet server because I need to update my users' whenever a new data is available (pretty much like FB). I've spent so much time searching the web and I've come to a conclusion that the best way to build Comet server is to build it wit...
3
2009-12-26T15:09:09Z
10,875,574
<p>You should look into <a href="http://yaws.hyber.org/" rel="nofollow">Yaws</a>. It's an Erlang web server that's been around for over a decade, is extremely stable and still under active development and maintenance, and supports long-polling, PHP applications, WebSockets, and much much more &mdash; pretty much everyt...
1
2012-06-04T02:04:55Z
[ "php", "python", "erlang", "comet", "twisted" ]
Django sending email
1,963,650
<p>In PHP I can send an email simply by calling <code>mail()</code>. In Django, I need to specify SMTP backends and other things. </p> <p>Is there a simpler way to send email from Django?</p>
4
2009-12-26T15:50:31Z
1,963,656
<p>There are several good mail-sending functions in the <code>django.core.mail</code> module.</p> <p>For a tutorial please see <a href="http://docs.djangoproject.com/en/dev/topics/email/" rel="nofollow">Sending e-mail</a>:</p> <blockquote> <p>Although Python makes sending e-mail relatively easy via the smtplib ...
3
2009-12-26T15:52:27Z
[ "python", "django", "email" ]
Django sending email
1,963,650
<p>In PHP I can send an email simply by calling <code>mail()</code>. In Django, I need to specify SMTP backends and other things. </p> <p>Is there a simpler way to send email from Django?</p>
4
2009-12-26T15:50:31Z
1,963,740
<p>In PHP you can only send mail with a simple mail() command on non-Windows systems. These will expect a local MTA like Postfix to be installed and correctly configured, as should be the case for most web servers. If you want to depend on third-party or decentralized mail service depends on how critical email is for y...
2
2009-12-26T16:37:53Z
[ "python", "django", "email" ]
Django sending email
1,963,650
<p>In PHP I can send an email simply by calling <code>mail()</code>. In Django, I need to specify SMTP backends and other things. </p> <p>Is there a simpler way to send email from Django?</p>
4
2009-12-26T15:50:31Z
4,291,944
<p>Either way, you need some backend (read MTA). Of the top of my head I can think of two things:</p> <ol> <li>As already pointed out, you can for example use sendmail <a href="http://djangosnippets.org/snippets/1864/" rel="nofollow">http://djangosnippets.org/snippets/1864/</a></li> <li>Even better, use a Python MTA. ...
0
2010-11-27T13:51:09Z
[ "python", "django", "email" ]
Inserting multiple types into an SQLite database with Python
1,963,790
<p>I'm trying to create an <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand ...
0
2009-12-26T16:55:44Z
1,963,822
<p>Something like this:</p> <pre><code>db = sqlite3.connect("test.db") cursor = db.cursor() cursor.execute("insert into foo values (?,?,?,?)", (val1, val2, val3, val4)) db.commit() # Autocommit is off by default (and rightfully so)! </code></pre> <p>Please note, that I am <em>not</em> using string formatting to injec...
0
2009-12-26T17:06:42Z
[ "python", "sqlite", "insert" ]
Inserting multiple types into an SQLite database with Python
1,963,790
<p>I'm trying to create an <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand ...
0
2009-12-26T16:55:44Z
1,964,012
<p>The type <code>real(4)</code> does not mean an array/list/tuple of 4 reals; the 4 alters the 'real' type. However, SQLite mostly ignores column types due to its manifest typing, but they can still affect <a href="http://sqlite.org/datatype3.html#affinity" rel="nofollow">column affinity</a>.</p> <p>You have a few o...
1
2009-12-26T18:41:32Z
[ "python", "sqlite", "insert" ]
Inserting multiple types into an SQLite database with Python
1,963,790
<p>I'm trying to create an <a href="http://en.wikipedia.org/wiki/SQLite" rel="nofollow">SQLite</a> 3 database from Python. I have a few types I'd like to insert into each record: A float, and then 3 groups of n floats, currently a tuple but could be an array or list.. I'm not well-enough versed in Python to understand ...
0
2009-12-26T16:55:44Z
2,178,191
<p>(A month later), two steps:<br> 1. flatten e.g. DAS lats lons times to one long list, say 18 long<br> 2. generate "Insert into tablename xx (?,?,... 18 question marks )" and execute that.</p> <pre><code>Test = 1 def flatten( *args ): """ 1, (2,3), [4,5] -&gt; [1 2 3 4 5] """ # 1 level only -- SO [python] [...
0
2010-02-01T16:22:36Z
[ "python", "sqlite", "insert" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,131
<p>I would make a specific one. You can catch it and deal with that specific exception since it is a special circumstance that you created :)</p>
3
2009-12-26T19:25:34Z
[ "python", "exception" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,169
<p>If (as you say in one of the comments) that this is a programmer error, then you can raise AssertionError:</p> <pre><code>def two(**kwargs): assert len(kwargs) == 2, "Please only provide two args" </code></pre> <p>BTW, if you only have three named arguments, **kwargs seems like an odd way to do it. More natur...
4
2009-12-26T19:39:49Z
[ "python", "exception" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,172
<p>I would use a ValueError, or a subclass thereof: "Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError."</p> <p>Passing 3 or 1 values when exactly 2 are required would t...
0
2009-12-26T19:41:37Z
[ "python", "exception" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,227
<p>Why not just do what python does?</p> <pre><code>&gt;&gt;&gt; abs(1, 2, 3) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: abs() takes exactly one argument (3 given) </code></pre>
9
2009-12-26T20:05:29Z
[ "python", "exception" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,235
<p>I recommend a custom exception. Like so:</p> <pre><code>class NeedExactlyTwo(ValueError): pass </code></pre> <p>Then you can <code>raise NeedExactlyTwo</code> in your code.</p> <p>Be sure to document this in the docstring for your function.</p>
0
2009-12-26T20:09:26Z
[ "python", "exception" ]
What exception to raise if wrong number of arguments passed in to **args?
1,964,126
<p>Suppose in python you have a routine that accepts three named parameters (as **args), but any two out of these three must be filled in. If only one is filled in, it's an error. If all three are, it's an error. What kind of error would you raise ? RuntimeError, a specifically created exception, or other ?</p>
9
2009-12-26T19:23:38Z
1,964,247
<p>Remember that you can subclass Python's built-in exception classes (and <code>TypeError</code> would surely be the right built-in exception class to raise here -- that's what Python raises if the number of arguments does not match the signature, in normal cases without <code>*a</code> or <code>**k</code> forms in th...
13
2009-12-26T20:13:25Z
[ "python", "exception" ]
Crash reporting in Python
1,964,336
<p>Is there a <a href="http://en.wikipedia.org/wiki/Crash_reporter" rel="nofollow">crash reporting</a> framework that can be used for <a href="http://tkdocs.com/tutorial" rel="nofollow">pure Python Tkinter applications</a>? Ideally, it should work cross-platform.</p> <p>Practically speaking, this is more of 'exception...
6
2009-12-26T20:57:03Z
1,968,226
<p>Stick try excepts everywhere your application can crash (I/O, networking etc.). Whenever an except is called, call a function that will kill the old window, spawn a new tkinter notification window, or a <a href="http://stackoverflow.com/questions/1918752/make-a-tkinter-window-appear-over-all-other-windows">custom on...
2
2009-12-28T06:25:25Z
[ "python", "tkinter", "crash-reports" ]
Crash reporting in Python
1,964,336
<p>Is there a <a href="http://en.wikipedia.org/wiki/Crash_reporter" rel="nofollow">crash reporting</a> framework that can be used for <a href="http://tkdocs.com/tutorial" rel="nofollow">pure Python Tkinter applications</a>? Ideally, it should work cross-platform.</p> <p>Practically speaking, this is more of 'exception...
6
2009-12-26T20:57:03Z
1,971,394
<p>Rather than polluting your code with <code>try..except</code> everywhere, you should just implement your own except hook by setting <code>sys.excepthook</code>. Here is an example:</p> <pre><code>import sys import traceback def install_excepthook(): def my_excepthook(exctype, value, tb): s = ''.join(tr...
7
2009-12-28T20:27:30Z
[ "python", "tkinter", "crash-reports" ]
Random selection ideas
1,964,366
<p>I am thinking of giving one or more set of introductory lectures to introduce people in my department with Python and related scientific tools as I did once in the last summer <a href="http://atmoswiki.aero.und.edu/atmos/py4science" rel="nofollow">py4science @ UND</a>. </p> <p>To make the meetings more interesting ...
2
2009-12-26T21:06:11Z
1,964,430
<p>Cards are also a source of popular (and familiar!) games of chance. Perhaps you could show how easy it is to generate, shuffle and sample cards:</p> <pre><code>#!/usr/bin/env python import random import itertools numname={1:'Ace',11:'Jack',12:'Queen',13:'King'} suits=['Clubs','Diamonds','Hearts','Spades'] numbers=...
3
2009-12-26T21:32:43Z
[ "python", "random" ]
Random selection ideas
1,964,366
<p>I am thinking of giving one or more set of introductory lectures to introduce people in my department with Python and related scientific tools as I did once in the last summer <a href="http://atmoswiki.aero.und.edu/atmos/py4science" rel="nofollow">py4science @ UND</a>. </p> <p>To make the meetings more interesting ...
2
2009-12-26T21:06:11Z
1,964,510
<p>Computing Pi is always fun ;-) </p> <pre><code>import random def approx_pi( n ): # n random (x,y) pairs (as a generator) data = ( (random.random(),random.random()) for _ in range(n) ) return 4.0*sum( 1 for x,y in data if x**2 + y**2 &lt; 1 )/n print approx_pi(100000) </code></pre>
0
2009-12-26T22:12:26Z
[ "python", "random" ]
Random selection ideas
1,964,366
<p>I am thinking of giving one or more set of introductory lectures to introduce people in my department with Python and related scientific tools as I did once in the last summer <a href="http://atmoswiki.aero.und.edu/atmos/py4science" rel="nofollow">py4science @ UND</a>. </p> <p>To make the meetings more interesting ...
2
2009-12-26T21:06:11Z
1,964,953
<p>One of the cutest uses of random numbers for mid-sized crowds is finding cycles. I will describe the physical method, and then some explorations. The Python code is fairly trivial.</p> <p>Start with your group of about 100 people with their names on pieces of paper in a bowl. Everyone descends on the bowl and ta...
1
2009-12-27T02:08:24Z
[ "python", "random" ]
How to use a certain Firefox profile in Python Selenium binding?
1,964,406
<p>I'm looking for a solution similar to presented in this <a href="http://stackoverflow.com/questions/1138953/open-firefox-window-in-selenium-with-firefox-addons-loaded">question</a>, except it has to deal with python. </p>
0
2009-12-26T21:20:07Z
1,984,740
<p>the answer that was accepted is language agnostic. You will need to setup a firefox profile then when starting up selenium rc tell it to use that profile. </p> <p>You just need to run your tests to use <code>*firefox</code> against the rc that has your profile and when the browser loads it will be the one you are a...
1
2009-12-31T09:54:38Z
[ "python", "firefox", "selenium" ]
Python with MySQL on Windows: installation errors
1,964,448
<p>I tried to run the following command, in the folder of my Django project:</p> <pre><code>$ python manage.py dbshell </code></pre> <p>It shows me this error:</p> <pre><code>$python manage.py dbshell Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) Fi...
0
2009-12-26T21:39:32Z
1,964,477
<p>Did you try looking here: <a href="http://sourceforge.net/projects/mysql-python/files/" rel="nofollow">http://sourceforge.net/projects/mysql-python/files/</a></p> <p>That is the download area of MySQLdb project, it has nothing to do with django, so your question is incorrect - django does not make switching databas...
4
2009-12-26T21:55:44Z
[ "python", "mysql" ]
Python with MySQL on Windows: installation errors
1,964,448
<p>I tried to run the following command, in the folder of my Django project:</p> <pre><code>$ python manage.py dbshell </code></pre> <p>It shows me this error:</p> <pre><code>$python manage.py dbshell Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) Fi...
0
2009-12-26T21:39:32Z
1,964,485
<p>Uh, this isn't Django, this is you downloading some unspecified Python environment and expecting it to magically do everything exactly the way you wanted it to. Find a good tutorial on this and follow the instructions.</p> <p>BTW, this is a very helpful forum, but giving no specifics and then delivering a non-quest...
0
2009-12-26T21:58:52Z
[ "python", "mysql" ]
Python with MySQL on Windows: installation errors
1,964,448
<p>I tried to run the following command, in the folder of my Django project:</p> <pre><code>$ python manage.py dbshell </code></pre> <p>It shows me this error:</p> <pre><code>$python manage.py dbshell Traceback (most recent call last): File "manage.py", line 11, in &lt;module&gt; execute_manager(settings) Fi...
0
2009-12-26T21:39:32Z
1,968,983
<p>I once had the same problem running Python and MySQL on the same computer. Like the guys/gals said above, Python does not come with built-in support for MySQL, so you will need to download the connectors. </p> <p>The link given above by @kibitzer will most likely not work on Windows successfully, so go <a href="htt...
0
2009-12-28T11:10:53Z
[ "python", "mysql" ]
When is the formfield() method called in Django?
1,964,545
<p>This is a question on making custom fields in Django. I'm making a field called <code>EditAreaField</code>, which inherits from <code>TextField</code>. Here's what my code looks like:</p> <pre><code>class EditAreaField(models.TextField): description = "A field for editing the HTML of a page" def formfield(s...
0
2009-12-26T22:42:44Z
1,966,424
<p>It looks like the <code>formfield</code> method is called by the <code>ModelForm</code> helper. According to the docs, the <code>formfield</code> method should include only a <code>form_class</code> attribute to point to the formfield class for this custom model field. This is a custom (or default) form field class,...
1
2009-12-27T17:07:33Z
[ "python", "django", "widget", "custom-field-type" ]
edit in place using xpath
1,964,583
<p>Is it possible to do in place edit of XML document using xpath ? I'd prefer any python solution but Java would be fine too.</p>
2
2009-12-26T23:08:18Z
1,964,611
<p><a href="http://en.wikipedia.org/wiki/XPath" rel="nofollow">XPath</a> is not intended to edit document in place, as far as I know. It is intended to only select nodes of the document. <a href="http://en.wikipedia.org/wiki/XSLT" rel="nofollow">XSLT</a> relies on XPath and can transform documents.</p> <p>Regarding Py...
3
2009-12-26T23:22:22Z
[ "python", "xpath" ]
edit in place using xpath
1,964,583
<p>Is it possible to do in place edit of XML document using xpath ? I'd prefer any python solution but Java would be fine too.</p>
2
2009-12-26T23:08:18Z
1,964,631
<p>Using XML to store data is probably not optimal, as you experience here. Editing XML is extremely costly.</p> <p>One way of doing the editing is parsing the xml into a tree, and then inserting stuff into that three, and then rebuilding the xml file. </p> <p>Editing an xml file in place is also possible, but then y...
0
2009-12-26T23:32:52Z
[ "python", "xpath" ]
what is the next code mean, the 'lambda request' and the '**kwargs: {}',i have never see this
1,964,750
<pre><code>def validate(request, *args, **kwargs): form_class = kwargs.pop('form_class') extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {}) </code></pre> <p>thanks</p> <p><hr></p> <pre><code>a={'a':'aaa','b':'bbb'} b=a.pop('a',lambda x,y:x) print a </code></pre> <p>i know dict.pop...
0
2009-12-27T00:23:16Z
1,964,756
<p>That is a "<a href="http://docs.python.org/tutorial/controlflow.html#lambda-forms" rel="nofollow">lambda function</a>". It's a short way of expressing a function that's declared inline. It looks like this:</p> <pre><code>lambda arg1,arg2,...: expression </code></pre> <p>and is the equivalent of a nameless function...
0
2009-12-27T00:24:45Z
[ "python" ]
what is the next code mean, the 'lambda request' and the '**kwargs: {}',i have never see this
1,964,750
<pre><code>def validate(request, *args, **kwargs): form_class = kwargs.pop('form_class') extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {}) </code></pre> <p>thanks</p> <p><hr></p> <pre><code>a={'a':'aaa','b':'bbb'} b=a.pop('a',lambda x,y:x) print a </code></pre> <p>i know dict.pop...
0
2009-12-27T00:23:16Z
1,964,764
<p>What it's doing is pop off a callback function from the kwargs dict, or if that isn't set, it creates a lambda function that does nothing (returns an empty dict). The <code>request, *args, **kwargs</code> part is presumably the "signature" of the callback function.</p>
0
2009-12-27T00:28:15Z
[ "python" ]
what is the next code mean, the 'lambda request' and the '**kwargs: {}',i have never see this
1,964,750
<pre><code>def validate(request, *args, **kwargs): form_class = kwargs.pop('form_class') extra_args_func = kwargs.pop('callback', lambda request, *args, **kwargs: {}) </code></pre> <p>thanks</p> <p><hr></p> <pre><code>a={'a':'aaa','b':'bbb'} b=a.pop('a',lambda x,y:x) print a </code></pre> <p>i know dict.pop...
0
2009-12-27T00:23:16Z
1,964,831
<p>The expression:</p> <pre><code>lambda request, *args, **kwargs: {} </code></pre> <p>builds an anonymous function which must be called with at least one argument (which, if named, must be named <code>request</code>) and can be called with any number of positional and named arguments: when called, it ignores all the...
2
2009-12-27T01:06:21Z
[ "python" ]
What does __contains__ do, what can call __contains__ function
1,964,934
<p>Here is my code:</p> <pre><code>class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error </code></pre>
8
2009-12-27T01:49:02Z
1,964,936
<p>to get your code to do something (although nothing useful):</p> <pre><code>class a(object): d='ddd' def __contains__(self, m): if self.d: return True b=a() &gt;&gt;&gt; 'd' in b True </code></pre> <p>The <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fcontains%5F%5F">docs</a>...
8
2009-12-27T01:51:40Z
[ "python" ]
What does __contains__ do, what can call __contains__ function
1,964,934
<p>Here is my code:</p> <pre><code>class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error </code></pre>
8
2009-12-27T01:49:02Z
1,964,941
<pre><code>if self.d:return true </code></pre> <p><code>self.d</code> is the string <code>'ddd'</code>. Non-empty strings are always truthy: when you use <code>if</code> on <code>'ddd'</code> it will always act as if you'd said <code>if True:</code>.</p> <p>I think what you probably meant is:</p> <pre><code>def __co...
5
2009-12-27T01:56:15Z
[ "python" ]
What does __contains__ do, what can call __contains__ function
1,964,934
<p>Here is my code:</p> <pre><code>class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error </code></pre>
8
2009-12-27T01:49:02Z
1,964,949
<p>Like all special methods (with "magic names" that begin and end in <code>__</code>), <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__"><code>__contains__</code></a> is <strong>not</strong> meant to be called directly (except in very specific cases, such as up=calls to the superclass): ...
17
2009-12-27T02:04:40Z
[ "python" ]
What does __contains__ do, what can call __contains__ function
1,964,934
<p>Here is my code:</p> <pre><code>class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error </code></pre>
8
2009-12-27T01:49:02Z
14,109,333
<p><strong>contains</strong> method defines how instances of class behave when they appear at right side of in and not in operator.</p> <pre><code>class Person(object): def __init__(self,name,age): self.name = name self.age = age def __contains__(self,param1): return True if p...
3
2013-01-01T09:33:54Z
[ "python" ]
What does __contains__ do, what can call __contains__ function
1,964,934
<p>Here is my code:</p> <pre><code>class a(object): d='ddd' def __contains__(self): if self.d:return True b=a() print b.contains('d') # error print contains(b,'d') # error </code></pre>
8
2009-12-27T01:49:02Z
38,655,934
<p>Lets see a very simple example of magic method <strong>__contains__</strong> . Suppose I have class Player and my <strong>__init__</strong> method takes one argument - <strong>name</strong>. In main I have created an object (<strong>obj1</strong>) of class Player. Now I want to know --if my <strong>obj1</strong> c...
1
2016-07-29T10:00:25Z
[ "python" ]
Why is getattr() not working like I think it should? I think this code should print 'sss'
1,964,980
<p>the next is my code:</p> <pre><code>class foo: def __init__(self): self.a = "a" def __getattr__(self,x,defalut): if x in self: return x else:return defalut a=foo() print getattr(a,'b','sss') </code></pre> <p>i know the <code>__getattr__</code> must be 2 argument,but i w...
1
2009-12-27T02:36:09Z
1,964,995
<p>You are confusing the <code>getattr</code> built-in function, which retrieves some attribute binding of an object dynamically (by name), at runtime, and the <code>__getattr__</code> method, which is invoked when you access some missing attribute of an object.</p> <p>You can't ask </p> <pre><code>if x in self: </co...
3
2009-12-27T02:46:14Z
[ "python" ]
Why is getattr() not working like I think it should? I think this code should print 'sss'
1,964,980
<p>the next is my code:</p> <pre><code>class foo: def __init__(self): self.a = "a" def __getattr__(self,x,defalut): if x in self: return x else:return defalut a=foo() print getattr(a,'b','sss') </code></pre> <p>i know the <code>__getattr__</code> must be 2 argument,but i w...
1
2009-12-27T02:36:09Z
1,965,160
<p>Your problem number one: you're defining an old-style class (we know you're on Python 2.something, even though you don't tell us, because you're using <code>print</code> as a keyword;-). In Python 2:</p> <pre><code>class foo: </code></pre> <p>means you're defining an old-style, aka legacy, class, whose behavior c...
3
2009-12-27T04:27:26Z
[ "python" ]
Specify input() type in Python?
1,964,996
<p>I'm still learning so please forgive if this sounds like a dumb question. Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:</p> <pre><code>morning = input('Enter morning Time:') evening = input('Enter evening Time:') </code></pre> <p>.. I need (o...
0
2009-12-27T02:46:30Z
1,964,998
<p><a href="http://docs.python.org/library/functions.html#input" rel="nofollow"><code>input</code></a> (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use <a href="http://docs.python.org/library/functions.html#raw%5Finput" rel="nofollow"><code>raw_input</...
7
2009-12-27T02:48:16Z
[ "python", "input", "types", "condition" ]
Specify input() type in Python?
1,964,996
<p>I'm still learning so please forgive if this sounds like a dumb question. Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:</p> <pre><code>morning = input('Enter morning Time:') evening = input('Enter evening Time:') </code></pre> <p>.. I need (o...
0
2009-12-27T02:46:30Z
1,966,535
<p>You can't really force the <code>input</code> function to return a certain type. It's best you write some kind of a wrapper that reads some input from the user and then converts it to an appropriate type for your application (or throw an exception in case of an error). </p> <p>Also, as Alex said, it's better to use...
0
2009-12-27T17:48:55Z
[ "python", "input", "types", "condition" ]
Specify input() type in Python?
1,964,996
<p>I'm still learning so please forgive if this sounds like a dumb question. Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:</p> <pre><code>morning = input('Enter morning Time:') evening = input('Enter evening Time:') </code></pre> <p>.. I need (o...
0
2009-12-27T02:46:30Z
37,765,593
<pre><code>morning = str(input('Enter morning Time:')) evening = str(input('Enter evening Time:')) </code></pre>
-1
2016-06-11T15:45:25Z
[ "python", "input", "types", "condition" ]
Split a large string into multiple substrings containing 'n' number of words via python
1,964,999
<p>Source text: <a href="http://en.wikisource.org/wiki/United%5FStates%5FDeclaration%5Fof%5FIndependence" rel="nofollow">United States Declaration of Independence</a></p> <p>How can one split the above source text into a number of sub-strings, containing an 'n' number of words?</p> <p>I use split(' ') to extract each...
3
2009-12-27T02:48:46Z
1,965,007
<p>You're trying to create n-grams? Here's how I do it, using the <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>.</p> <pre><code>punct = re.compile(r'^[^A-Za-z0-9]+|[^a-zA-Z0-9]+$') is_word=re.compile(r'[a-z]', re.IGNORECASE) sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle') word_tokenizer...
3
2009-12-27T02:54:19Z
[ "python", "string", "split", "words", "substrings" ]
Split a large string into multiple substrings containing 'n' number of words via python
1,964,999
<p>Source text: <a href="http://en.wikisource.org/wiki/United%5FStates%5FDeclaration%5Fof%5FIndependence" rel="nofollow">United States Declaration of Independence</a></p> <p>How can one split the above source text into a number of sub-strings, containing an 'n' number of words?</p> <p>I use split(' ') to extract each...
3
2009-12-27T02:48:46Z
1,965,012
<pre><code>text = """ When in the course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature?s God entitle them, a decent Respect...
5
2009-12-27T02:59:34Z
[ "python", "string", "split", "words", "substrings" ]
Split a large string into multiple substrings containing 'n' number of words via python
1,964,999
<p>Source text: <a href="http://en.wikisource.org/wiki/United%5FStates%5FDeclaration%5Fof%5FIndependence" rel="nofollow">United States Declaration of Independence</a></p> <p>How can one split the above source text into a number of sub-strings, containing an 'n' number of words?</p> <p>I use split(' ') to extract each...
3
2009-12-27T02:48:46Z
1,965,385
<p>For large string, iterator is recommended for speed and low memory footprint.</p> <pre><code>import re, itertools # Original text text = "When in the course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of...
2
2009-12-27T06:58:55Z
[ "python", "string", "split", "words", "substrings" ]
Error when compiling simple python program
1,965,031
<p>This script won't compile. I wanted to made a simple 21-style game for practice but I get an error: </p> <pre><code>X@X:~/Desktop$ python 21.py File "21.py", line 18 int(ptotal) = ptotal + newcard SyntaxError: can't assign to function call </code></pre> <p><a href="http://pastebin.com/mfc64c2d" rel="nofollow">H...
0
2009-12-27T03:12:26Z
1,965,034
<p>Not sure where you got this syntax:</p> <pre><code>int(cone) == random.randrange(1, 11) </code></pre> <p>I think you mean this:</p> <pre><code>cone = random.randrange(1, 11) </code></pre> <p>This is also an (interesting) invention:</p> <pre><code>while hit is not "No" or "no" or "n": </code></pre> <p>You'll ne...
1
2009-12-27T03:13:50Z
[ "python" ]
encode Netbios name python
1,965,065
<p>I would like to encode "ITSATEST" to it's netbios name value in python; The occurence table and explication are here: <a href="http://support.microsoft.com/kb/194203" rel="nofollow">http://support.microsoft.com/kb/194203</a></p> <p>I dont know how this could be done easily in python, someone can give me a hand ?</p...
1
2009-12-27T03:32:07Z
1,965,129
<p>You can map each nibble of the original string, taking its numerical value and offsetting from 'A':</p> <pre><code>encoded_name = ''.join([chr((ord(c)&gt;&gt;4) + ord('A')) + chr((ord(c)&amp;0xF) + ord('A')) for c in original_name]) </code></pre>
1
2009-12-27T03:59:44Z
[ "python", "netbios" ]
encode Netbios name python
1,965,065
<p>I would like to encode "ITSATEST" to it's netbios name value in python; The occurence table and explication are here: <a href="http://support.microsoft.com/kb/194203" rel="nofollow">http://support.microsoft.com/kb/194203</a></p> <p>I dont know how this could be done easily in python, someone can give me a hand ?</p...
1
2009-12-27T03:32:07Z
1,965,140
<p>Take a look at <a href="http://www.faqs.org/rfcs/rfc1001.html" rel="nofollow">RFC 1001</a>, which defines the encoding. In section 14.1 "FIRST LEVEL ENCODING" is the algorithm for the encoding, which you could implement directly in Python.</p>
0
2009-12-27T04:07:59Z
[ "python", "netbios" ]
Python epoll.register threadsafe?
1,965,092
<p>Does anyone know if I can call epoll.register from another thread safely?</p> <p>Here is what I am imagining:</p> <ul> <li>Thread 1: epoll.poll()</li> <li>Thread 2: adding some fd to the same epoll object with epoll.register</li> </ul> <p><a href="http://docs.python.org/library/select.html" rel="nofollow">http://...
2
2009-12-27T03:48:31Z
1,965,112
<p><em>I changed my answer after you changed the question.</em></p> <p>This will <em>not</em> be "thread safe" in that each thread will impact the same epoll object. Registering a new fd to the epoll object will still do it to that object. </p> <p>There's no reason for that particular object to have different states ...
1
2009-12-27T03:55:32Z
[ "python", "multithreading", "epoll" ]
why my code run wrong ,it is about '@property'
1,965,117
<p>I used python 2.5, I want to know how can change the next code when the Platform is python2.5 or python2.6</p> <pre><code>class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): ...
0
2009-12-27T03:57:06Z
1,965,127
<p>Python 2.5 does not support the <code>.setter</code> and <code>.deleter</code> sub-decorators of <code>property</code>; they were introduced in Python 2.6.</p> <p>To work on both releases, you can, instead, code something like:</p> <pre><code>class C(object): def __init__(self): self._x = None def...
4
2009-12-27T03:59:41Z
[ "python" ]
Change sound output
1,965,155
<p>Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.</p> <p>I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).</p> <p>I have no idea w...
0
2009-12-27T04:25:38Z
1,981,067
<p>The device selected for output in the Control Panel is just a default, each application can choose to output through that device or select a new one. You can get a handle to the device you want to output through, and subsequently use it for playback, by using the Win32 API for multimedia (winmm.dll). Some of those f...
0
2009-12-30T16:30:58Z
[ ".net", "python", "audio" ]
Change sound output
1,965,155
<p>Is there a way in windows by which I can toggle the audio output between a built-in speaker and the headphone jack using a python library.</p> <p>I am thinking someone with .NET experience would be able to give me some pointers (I could use IronPython if there is a .NET library to do that).</p> <p>I have no idea w...
0
2009-12-27T04:25:38Z
2,408,157
<p>Please read <a href="http://alvasnet.blogspot.com/2010/01/communicate-with-aliens-on-ironpython.html" rel="nofollow">http://alvasnet.blogspot.com/2010/01/communicate-with-aliens-on-ironpython.html</a> article</p>
-1
2010-03-09T10:11:05Z
[ ".net", "python", "audio" ]
Calculate time between time-1 to time-2?
1,965,201
<pre><code>enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 </code></pre> <p>How can it be done in Python. I'm a beginner so I really have no clue where to start. </p> <p>Edited to add: I don't want a timer. Both time-1 and time-2 ar...
6
2009-12-27T04:50:24Z
1,965,208
<p>Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.</p> <pre><code>from time import time t0 = time() # do stuff that takes time print time() - t0 </code></pre>
4
2009-12-27T04:55:15Z
[ "python" ]
Calculate time between time-1 to time-2?
1,965,201
<pre><code>enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 </code></pre> <p>How can it be done in Python. I'm a beginner so I really have no clue where to start. </p> <p>Edited to add: I don't want a timer. Both time-1 and time-2 ar...
6
2009-12-27T04:50:24Z
1,965,225
<p>Assuming that the user is entering strings like <code>"01:12"</code>, you need to convert (as well as validate) those strings into the number of minutes since <code>00:00</code> (e.g., <code>"01:12"</code> is <code>1*60+12</code>, or 72 minutes), then subtract one from the other. You can then convert the difference ...
0
2009-12-27T05:05:02Z
[ "python" ]
Calculate time between time-1 to time-2?
1,965,201
<pre><code>enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 </code></pre> <p>How can it be done in Python. I'm a beginner so I really have no clue where to start. </p> <p>Edited to add: I don't want a timer. Both time-1 and time-2 ar...
6
2009-12-27T04:50:24Z
1,965,229
<p>The <code>datetime</code> and <code>timedelta</code> class from the built-in <code>datetime</code> module is what you need.</p> <pre><code>from datetime import datetime # Parse the time strings t1 = datetime.strptime('01:12','%H:%M') t2 = datetime.strptime('18:59','%H:%M') # Do the math, the result is a timedelta...
12
2009-12-27T05:06:59Z
[ "python" ]
Calculate time between time-1 to time-2?
1,965,201
<pre><code>enter time-1 // eg 01:12 enter time-2 // eg 18:59 calculate: time-1 to time-2 / 12 // i.e time between 01:12 to 18:59 divided by 12 </code></pre> <p>How can it be done in Python. I'm a beginner so I really have no clue where to start. </p> <p>Edited to add: I don't want a timer. Both time-1 and time-2 ar...
6
2009-12-27T04:50:24Z
1,965,230
<p>Simplest and most direct may be something like:</p> <pre><code>def getime(prom): """Prompt for input, return minutes since midnight""" s = raw_input('Enter time-%s (hh:mm): ' % prom) sh, sm = s.split(':') return int(sm) + 60 * int(sh) time1 = getime('1') time2 = getime('2') diff = time2 - time1 print "Di...
6
2009-12-27T05:07:29Z
[ "python" ]
File downloading using python with threads
1,965,213
<p>I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file.</p> <p>How do I manage it so that the order in which the threads where generated w...
0
2009-12-27T04:56:47Z
1,965,219
<p>You need to fetch completely separate parts of the file on each thread. Calculate the chunk start and end positions based on the number of threads. Each chunk must have no overlap obviously.</p> <p>For example, if target file was 3000 bytes long and you want to fetch using three thread:</p> <ul> <li>Thread 1: fetc...
1
2009-12-27T05:00:33Z
[ "python", "multithreading" ]
File downloading using python with threads
1,965,213
<p>I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file.</p> <p>How do I manage it so that the order in which the threads where generated w...
0
2009-12-27T04:56:47Z
1,965,227
<p>You can use a thread safe "semaphore", like this:</p> <pre><code>class Counter: counter = 0 @classmethod def inc(cls): n = cls.counter = cls.counter + 1 # atomic increment and assignment return n </code></pre> <p>Using Counter.inc() returns an incremented number across threads, which you can use to k...
0
2009-12-27T05:06:24Z
[ "python", "multithreading" ]
File downloading using python with threads
1,965,213
<p>I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file.</p> <p>How do I manage it so that the order in which the threads where generated w...
0
2009-12-27T04:56:47Z
1,965,250
<p>You could coordinate the works with locks &amp;c, but I recommend instead using <a href="http://docs.python.org/library/queue.html?highlight=queue#Queue.Queue">Queue</a> -- usually the best way to coordinate multi-threading (and multi-processing) in Python.</p> <p>I would have the main thread spawn as many worker t...
9
2009-12-27T05:20:49Z
[ "python", "multithreading" ]
File downloading using python with threads
1,965,213
<p>I'm creating a python script which accepts a path to a remote file and an n number of threads. The file's size will be divided by the number of threads, when each thread completes I want them to append the fetch data to a local file.</p> <p>How do I manage it so that the order in which the threads where generated w...
0
2009-12-27T04:56:47Z
1,965,302
<p>for "download several files simultaneously", I recommond this article: <a href="http://www.ibm.com/developerworks/aix/library/au-threadingpython/" rel="nofollow">Practical threaded programming with Python</a> . It provides a simultaneously download related example by combining threads with Queues, I thought it's wor...
0
2009-12-27T05:52:51Z
[ "python", "multithreading" ]
Implementing a popularity algorithm in Django
1,965,341
<p>I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:</p> <pre> Y Combinator's Hacke...
7
2009-12-27T06:13:47Z
1,965,457
<p>On Hacker News, only the 210 newest stories and 210 most popular stories are paginated (7 pages worth * 30 stories each). My guess is that the reason for the limit (at least in part) is this problem.</p> <p>Why not drop all the fancy SQL for the most popular stories and just keep a running list instead? Once you've...
9
2009-12-27T07:45:45Z
[ "python", "django", "algorithm", "postgresql" ]
Implementing a popularity algorithm in Django
1,965,341
<p>I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:</p> <pre> Y Combinator's Hacke...
7
2009-12-27T06:13:47Z
1,965,527
<pre><code>popular_links = Link.objects.select_related() popular_links = popular_links.extra( select = { 'karma_total': 'SUM(vote.karma_delta)', 'popularity': '(karma_total - 1) / POW(2, 1.5)' }, order_by = ['-popularity'] ) </code></pre> <p>Or select some sane number, sort the selection us...
4
2009-12-27T08:41:45Z
[ "python", "django", "algorithm", "postgresql" ]
Implementing a popularity algorithm in Django
1,965,341
<p>I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:</p> <pre> Y Combinator's Hacke...
7
2009-12-27T06:13:47Z
1,966,672
<p>Seems like you could overload the <code>save</code> of the <code>Vote</code> class and have it update the corresponding <code>Link</code> object. Something like this should work well:</p> <pre><code>from datetime import datetime, timedelta class Link(models.Model): category = models.ForeignKey(Category) user = ...
3
2009-12-27T18:37:29Z
[ "python", "django", "algorithm", "postgresql" ]
Implementing a popularity algorithm in Django
1,965,341
<p>I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple:</p> <pre> Y Combinator's Hacke...
7
2009-12-27T06:13:47Z
2,807,393
<p>Here was the final answer to my question although many months late and not exactly what I had in mind. Hopefully it will be useful to some.</p> <pre><code>def hot(request): links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created')[:150] for link in links: delta_in_hou...
1
2010-05-11T00:46:22Z
[ "python", "django", "algorithm", "postgresql" ]
2to3 not working
1,965,387
<p>I'm converting a single module using 2to3.</p> <p>test_lib2to3.py is in <code>/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/test/test_lib2to3.py</code></p> <p>File to be converted is in <code>/Users/Nimbuz/Documents/python31/Excercise 1/time3.py</code></p> <p>Terminal Session:</p> <pre><code>lo...
0
2009-12-27T07:00:04Z
1,965,816
<p>Maybe there's something wrong with path. Try</p> <pre><code>2to3 "/Users/Nimbuz/Documents/python31/Excercise 1/time3.py" </code></pre> <p>Instead of</p> <pre><code>2to3 /Users/Nimbuz/Documents/python31/Excercise\ 1/time3.py </code></pre> <p>or just cd to that folder and </p> <pre><code>2to3 time3.py </code></pr...
0
2009-12-27T12:04:46Z
[ "python", "path", "2to3" ]
ImageFont's getsize() does not get correct text size?
1,965,466
<p>I use the following two methods to to generate text preview image for a .ttf font file</p> <p><strong>PIL method:</strong></p> <pre><code>def make_preview(text, fontfile, imagefile, fontsize=30): try: font = ImageFont.truetype(fontfile, fontsize) text_width, text_height = font.getsize(text) ...
5
2009-12-27T07:51:31Z
1,965,473
<p>I had a similar issue once in PHP and ImageMagick. </p> <p>In the end, I solved this by drawing the text on a very large canvas, and then trimming it using the <a href="http://www.imagemagick.org/Usage/crop/#trim" rel="nofollow">trim/auto-crop</a> functions that shave extra space off the image. </p> <p>If I unders...
2
2009-12-27T07:57:56Z
[ "python", "fonts", "imagemagick", "python-imaging-library" ]
ImageFont's getsize() does not get correct text size?
1,965,466
<p>I use the following two methods to to generate text preview image for a .ttf font file</p> <p><strong>PIL method:</strong></p> <pre><code>def make_preview(text, fontfile, imagefile, fontsize=30): try: font = ImageFont.truetype(fontfile, fontsize) text_width, text_height = font.getsize(text) ...
5
2009-12-27T07:51:31Z
1,984,517
<p>In this case, just specify ImageMagick to use a larger canvas size with a fixed font size and it will draw text at specified point size while keeping its integrity.</p> <pre><code>def make_preview(text, fontfile, imagefile, fontsize=30): p = subprocess.call(['convert', '-font', fontfile, '-background', ...
1
2009-12-31T08:27:08Z
[ "python", "fonts", "imagemagick", "python-imaging-library" ]
ImageFont's getsize() does not get correct text size?
1,965,466
<p>I use the following two methods to to generate text preview image for a .ttf font file</p> <p><strong>PIL method:</strong></p> <pre><code>def make_preview(text, fontfile, imagefile, fontsize=30): try: font = ImageFont.truetype(fontfile, fontsize) text_width, text_height = font.getsize(text) ...
5
2009-12-27T07:51:31Z
2,003,873
<p><img src="http://img9.imageshack.us/img9/2419/fontfix.jpg" alt="alt text"></p> <p>Not a programming solution, but when I regenerate your problem, its only happens on your fonts (other fonts like Arial is no problem at all), so I have fixed your font files (by changing ascent/decent metrics). you can download <a hre...
5
2010-01-05T02:50:09Z
[ "python", "fonts", "imagemagick", "python-imaging-library" ]
Remove all nested blocks, whilst leaving non-nested blocks alone via python
1,965,486
<p>Source:</p> <pre><code>[This] is some text with [some [blocks that are nested [in a [variety] of ways]]] </code></pre> <p>Resultant text:</p> <pre><code>[This] is some text with </code></pre> <p>I don't think you can do a regex for this, from looking at the <a href="http://stackoverflow.com/questions/133601/can-...
3
2009-12-27T08:01:21Z
1,965,493
<p>Here's an easy way that doesn't require any dependencies: scan the text and keep a counter for the braces that you pass over. Increment the counter each time you see a "["; decrement it each time you see a "]".</p> <ul> <li>As long as the counter is at zero or one, put the text you see onto the output string.</li> ...
5
2009-12-27T08:07:57Z
[ "python", "regex", "recursion", "nested", "brackets" ]
Remove all nested blocks, whilst leaving non-nested blocks alone via python
1,965,486
<p>Source:</p> <pre><code>[This] is some text with [some [blocks that are nested [in a [variety] of ways]]] </code></pre> <p>Resultant text:</p> <pre><code>[This] is some text with </code></pre> <p>I don't think you can do a regex for this, from looking at the <a href="http://stackoverflow.com/questions/133601/can-...
3
2009-12-27T08:01:21Z
1,965,494
<p>You will be better off writing a parser, especially if you use a parser generator like <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a>. It will be more maintainable and extendable.</p> <p>In fact pyparsing already implements the <a href="http://pyparsing.wikispaces.com/file/view/nested.py" ...
3
2009-12-27T08:08:14Z
[ "python", "regex", "recursion", "nested", "brackets" ]
Remove all nested blocks, whilst leaving non-nested blocks alone via python
1,965,486
<p>Source:</p> <pre><code>[This] is some text with [some [blocks that are nested [in a [variety] of ways]]] </code></pre> <p>Resultant text:</p> <pre><code>[This] is some text with </code></pre> <p>I don't think you can do a regex for this, from looking at the <a href="http://stackoverflow.com/questions/133601/can-...
3
2009-12-27T08:01:21Z
1,965,737
<p>I took a couple of passes at writing a single parser expression that could be used with expression.transformString(), but I had difficulty distinguish between nested and unnested []'s at parse time. In the end I had to open up the loop in transformString and iterate over the scanString generator explicitly.</p> <p...
3
2009-12-27T11:00:02Z
[ "python", "regex", "recursion", "nested", "brackets" ]
Remove all nested blocks, whilst leaving non-nested blocks alone via python
1,965,486
<p>Source:</p> <pre><code>[This] is some text with [some [blocks that are nested [in a [variety] of ways]]] </code></pre> <p>Resultant text:</p> <pre><code>[This] is some text with </code></pre> <p>I don't think you can do a regex for this, from looking at the <a href="http://stackoverflow.com/questions/133601/can-...
3
2009-12-27T08:01:21Z
1,966,260
<p>Taking the OP's example as normative (any block including further nested blocks must be removed), what about...:</p> <pre><code>import itertools x = '''[This] is some text with [some [blocks that are nested [in a [variety] of ways]]] and some [which are not], and [any [with nesting] must go] away.''' def nonest(t...
4
2009-12-27T16:02:37Z
[ "python", "regex", "recursion", "nested", "brackets" ]
How can I pass a variable in a decorator to function's argument in a decorated function?
1,965,607
<p>I am in progress to learn Python. Hopefully someone points me to correct way.<br> This is what I'd like to do below:</p> <pre><code>def decorate(function): def wrap_function(*args, **kwargs): str = 'Hello!' # This is what I want return function(*args, **kwargs) return wrap_function @decora...
10
2009-12-27T09:42:33Z
1,965,615
<p>You can't pass it as its own name, but you can add it to the keywords.</p> <pre><code>def decorate(function): def wrap_function(*args, **kwargs): kwargs['str'] = 'Hello!' return function(*args, **kwargs) return wrap_function @decorate def print_message(*args, **kwargs): print(kwargs['st...
20
2009-12-27T09:50:57Z
[ "python", "decorator" ]
How can I pass a variable in a decorator to function's argument in a decorated function?
1,965,607
<p>I am in progress to learn Python. Hopefully someone points me to correct way.<br> This is what I'd like to do below:</p> <pre><code>def decorate(function): def wrap_function(*args, **kwargs): str = 'Hello!' # This is what I want return function(*args, **kwargs) return wrap_function @decora...
10
2009-12-27T09:42:33Z
28,914,097
<p>If you want the argument to be "optionally-injected", only in case the function actually takes it, use something like this:</p> <pre><code>import inspect def decorate(func): def wrap_and_call(*args, **kwargs): if 'str' in inspect.getargspec(func).args: kwargs['str'] = 'Hello!' retur...
4
2015-03-07T10:52:43Z
[ "python", "decorator" ]
how to make a python array of particular objects
1,965,725
<p>in java, the following code defines an array of the predefined class (<code>myCls</code>):</p> <pre><code>myCls arr[] = new myCls </code></pre> <p>how can I do that in python? I want to have an array of type (<code>myCls</code>)?</p> <p>thanks in advance </p>
2
2009-12-27T10:51:53Z
1,965,731
<p>Python is dynamically typed. You do not need to (and in fact CAN'T) create a list that only contains a single type:</p> <pre><code>arr = list() arr = [] </code></pre> <p>If you require it to only contain a single type then you'll have to create your own list-alike, reimplementing the list methods and <code>__setit...
5
2009-12-27T10:54:56Z
[ "python", "arrays", "types" ]
how to make a python array of particular objects
1,965,725
<p>in java, the following code defines an array of the predefined class (<code>myCls</code>):</p> <pre><code>myCls arr[] = new myCls </code></pre> <p>how can I do that in python? I want to have an array of type (<code>myCls</code>)?</p> <p>thanks in advance </p>
2
2009-12-27T10:51:53Z
1,965,736
<p>You can only create arrays of only a single type using the <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a> package, but it is not designed to store user-defined classes.</p> <p>The python way would be to just create a list of objects:</p> <pre><code>a = [myCls() for _ in xrange(10)] </...
4
2009-12-27T10:59:13Z
[ "python", "arrays", "types" ]
Python: error while checking IE state
1,965,911
<p>Please, help me with Python 2.6 and win32com.</p> <p>I'm a newbie to Python and I got error when I start the next program:</p> <pre><code>import pywintypes from win32com.client import Dispatch from time import sleep ie = Dispatch("InternetExplorer.Application") ie.visible=1 url='hotfile.com' ie.navigate(url) wh...
2
2009-12-27T13:05:48Z
1,966,084
<p>The sleep trick won't work with IE. You actually need to pump messages while you wait. I don't think a thread will work, by the way, because IE hates to not be in the GUI thread.</p> <p>Here's a <a href="http://docs.python.org/library/ctypes.htmlhotfile" rel="nofollow">ctypes</a>-based message pump, with which I wa...
1
2009-12-27T14:36:52Z
[ "python", "win32com" ]
How do I send attachments using SMTP?
1,966,073
<p>I want to write a program that sends email using Python's <a href="http://docs.python.org/library/smtplib.html">smtplib</a>. I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in ...
16
2009-12-27T14:31:19Z
1,966,097
<p>What you want to check out is the <code>email</code> module. It lets you build <a href="http://en.wikipedia.org/wiki/MIME">MIME</a>-compliant messages that you then send with smtplib.</p>
10
2009-12-27T14:39:32Z
[ "python", "email", "smtp", "attachment", "smtplib" ]
How do I send attachments using SMTP?
1,966,073
<p>I want to write a program that sends email using Python's <a href="http://docs.python.org/library/smtplib.html">smtplib</a>. I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in ...
16
2009-12-27T14:31:19Z
1,966,119
<p>Well, attachments are not treated in any special ways, they are "just" leaves of the Message-object tree. You can find the answers to any questions regarding MIME-compliant mesasges in <a href="http://docs.python.org/library/email.message.html" rel="nofollow">this</a> section of the documentation on the <a href="htt...
3
2009-12-27T14:50:15Z
[ "python", "email", "smtp", "attachment", "smtplib" ]