title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Get Root Domain of Link
1,521,592
<p>I have a link such as <a href="http://www.techcrunch.com/">http://www.techcrunch.com/</a> and I would like to get just the techcrunch.com part of the link. How do I go about this in python?</p>
10
2009-10-05T18:16:12Z
3,369,248
<p>This worked for my purposes. I figured I'd share it. </p> <pre><code>".".join("www.sun.google.com".split(".")[-2:]) </code></pre>
-2
2010-07-30T06:53:24Z
[ "python", "regex", "dns", "root" ]
Get Root Domain of Link
1,521,592
<p>I have a link such as <a href="http://www.techcrunch.com/">http://www.techcrunch.com/</a> and I would like to get just the techcrunch.com part of the link. How do I go about this in python?</p>
10
2009-10-05T18:16:12Z
32,146,940
<p>______Using Python 3.3 and not 2.x________</p> <p>I would like to add a small thing to Ben Blank's answer.</p> <pre><code>from urllib.parse import quote,unquote,urlparse u=unquote(u) #u= URL e.g. http://twitter.co.uk/hello/there g=urlparse(u) u=g.netloc </code></pre> <p>By now, I just got the domain name from <a href="https://docs.python.org/3.3/library/urllib.parse.html" rel="nofollow">urlparse</a>.</p> <p>To remove the subdomains you first of all need to know which are Top Level Domains and which are not. E.g. in the above <code>http://twitter.co.uk</code> - <code>co.uk</code> is a TLD while in <code>http://sub.twitter.com</code> we have only <code>.com</code> as TLD and <code>sub</code> is a subdomain.</p> <p>So, we need to get a file/list which has all the <a href="https://en.wikipedia.org/wiki/Top-level_domain#External_links" rel="nofollow">tlds</a>.</p> <p><code>tlds = load_file("tlds.txt") #tlds holds the list of tlds</code></p> <pre><code>hostname = u.split(".") if len(hostname)&gt;2: if hostname[-2].upper() in tlds: hostname=".".join(hostname[-3:]) else: hostname=".".join(hostname[-2:]) else: hostname=".".join(hostname[-2:]) </code></pre>
0
2015-08-21T18:19:11Z
[ "python", "regex", "dns", "root" ]
Using Python's isinstance
1,521,655
<p>The following usage of <code>isinstance</code> doesn't seem to work in Python 2.5.2 or 2.6.2:</p> <pre><code>class BananaCake: def __init__(self): print 'Banana Cake' class ChocolateCake: def __init__(self): print 'Chocolate Cake' class CakeFactory: @staticmethod def create(name): if name == 'banana': return BananaCake elif name == 'chocolate': return ChocolateCake else: return None if __name__ == '__main__': banana_cake = CakeFactory.create('banana') print isinstance(banana_cake, BananaCake) </code></pre> <p>The above <code>isinstance</code> is returning <code>False</code> even though banana_cake is an instance of <code>BananaCake</code>. Does anyone know what I might be missing? I'm performing this check in my test scripts. You should be able to copy and paste the above and run it easily in a Python script.</p>
1
2009-10-05T18:25:57Z
1,521,678
<p>You're returning a class instead of an instance.</p> <pre> >>> banana_cake is BananaCake True </pre> <p>I believe you want this:</p> <pre><code>class CakeFactory: @staticmethod def create(name): if name == 'banana': return BananaCake() # call the constructor elif name == 'chocolate': return ChocolateCake() # call the constructor else: return None </code></pre> <p><hr /></p> <p>To make <code>isinstance()</code>work with classes you need to define them as new-style classes:</p> <pre><code>class ChocolateCake(object): pass </code></pre> <p>You should declare all your classes as new-style classes anyway, there is a lot of extra functionality and old-style classes were dropped in Python 3.</p>
8
2009-10-05T18:32:02Z
[ "python" ]
Using Python's isinstance
1,521,655
<p>The following usage of <code>isinstance</code> doesn't seem to work in Python 2.5.2 or 2.6.2:</p> <pre><code>class BananaCake: def __init__(self): print 'Banana Cake' class ChocolateCake: def __init__(self): print 'Chocolate Cake' class CakeFactory: @staticmethod def create(name): if name == 'banana': return BananaCake elif name == 'chocolate': return ChocolateCake else: return None if __name__ == '__main__': banana_cake = CakeFactory.create('banana') print isinstance(banana_cake, BananaCake) </code></pre> <p>The above <code>isinstance</code> is returning <code>False</code> even though banana_cake is an instance of <code>BananaCake</code>. Does anyone know what I might be missing? I'm performing this check in my test scripts. You should be able to copy and paste the above and run it easily in a Python script.</p>
1
2009-10-05T18:25:57Z
1,521,698
<p>That's because 'banana_cake' is not an instance of BananaCake.</p> <p>The CakeFactory implementation returns the BananaCake CLASS, not an instance of BananaCake.</p> <p>Try modifying CakeFactory to return "BananaCake()". Calling the BananCake constructor will return an instance, rather than the class.</p>
2
2009-10-05T18:35:50Z
[ "python" ]
Close Python when Parent is closed
1,521,670
<p>I have a Python program (PP) that loads another Program(AP) via COM, gets its window handle and sets it to be the PP parent.</p> <p>This works pretty well except that I can't control that AP still has their [X] button available in the top left corner. Since this is a pretty obvious place for the user to close when they are done with the program, I tried this and it left the PP in the Task Manager running, but not visible with no possible way to kill it other than through Task Manager. Any ideas on how to handle this? I expect it to be rather Common that the user closes in this manner.</p> <p>Thanks!</p>
0
2009-10-05T18:28:55Z
1,522,240
<p>How's PP's control flow? If it's event-driven it could get appropriate events upon closure of that parent window or termination of that AP process; otherwise it could "poll" to check if the window or process are still around.</p>
1
2009-10-05T20:33:51Z
[ "python", "com", "wxpython", "parent" ]
Close Python when Parent is closed
1,521,670
<p>I have a Python program (PP) that loads another Program(AP) via COM, gets its window handle and sets it to be the PP parent.</p> <p>This works pretty well except that I can't control that AP still has their [X] button available in the top left corner. Since this is a pretty obvious place for the user to close when they are done with the program, I tried this and it left the PP in the Task Manager running, but not visible with no possible way to kill it other than through Task Manager. Any ideas on how to handle this? I expect it to be rather Common that the user closes in this manner.</p> <p>Thanks!</p>
0
2009-10-05T18:28:55Z
1,530,203
<p>As you said you get AP's handle and pass it to PP, so PP has that handle around, so when AP is closed PP can check if that window handle exists using windows API IsWindow or IsWindowVisible depending on you needs</p> <pre><code>import win32gui win32gui.IsWindow(handle) win32gui.IsWindowVisible(handle) </code></pre>
0
2009-10-07T08:10:11Z
[ "python", "com", "wxpython", "parent" ]
How to prevent log file truncation with python logging module?
1,521,681
<p>I need to use python logging module to print debugging info to a file with statements like:</p> <pre><code>logging.debug(something) </code></pre> <p>The file is truncated (i am assuming - by the logging module) and the messages get deleted before I can see them - how can that be prevented?</p> <p>Here is my logging config:</p> <pre><code>logging.basicConfig( level = logging.DEBUG, format = '%(asctime)s %(levelname)s %(message)s', filename = '/tmp/my-log.txt', filemode = 'w' ) </code></pre> <p>Thanks!</p>
5
2009-10-05T18:32:29Z
1,521,739
<p><a href="http://docs.python.org/library/logging.html#simple-examples" rel="nofollow"><code>logging</code></a></p> <blockquote> <p>If you run the script repeatedly, the additional log messages are appended to the file. <strong>To create a new file each time, you can pass a filemode argument to basicConfig() with a value of 'w'</strong>. Rather than managing the file size yourself, though, it is simpler to use a RotatingFileHandler.</p> </blockquote> <p>To prevent overwriting the file, you should not set <code>filemode</code> to <code>'w'</code>, or <a href="http://docs.python.org/library/logging.html#logging.basicConfig" rel="nofollow">set it to <code>'a'</code></a> (that is the default setting anyway).</p> <p>I believe that you are simply overwriting the file.</p>
11
2009-10-05T18:45:23Z
[ "python", "logging" ]
Cost of list functions in Python
1,521,784
<p>Based on <a href="http://bytes.com/topic/python/answers/101848-list-implementation">this older thread</a>, it looks like the cost of list functions in Python is:</p> <ul> <li>Random access: O(1)</li> <li>Insertion/deletion to front: O(n)</li> <li>Insertion/deletion to back: O(1)</li> </ul> <p>Can anyone confirm whether this is still true in Python 2.6/3.x?</p>
8
2009-10-05T18:58:42Z
1,521,842
<p>That's correct, inserting in front forces a move of all the elements to make place.</p> <p><code>collections.deque</code> offers similar functionality, but is optimized for insertion on both sides.</p>
3
2009-10-05T19:10:59Z
[ "python", "performance", "list" ]
Cost of list functions in Python
1,521,784
<p>Based on <a href="http://bytes.com/topic/python/answers/101848-list-implementation">this older thread</a>, it looks like the cost of list functions in Python is:</p> <ul> <li>Random access: O(1)</li> <li>Insertion/deletion to front: O(n)</li> <li>Insertion/deletion to back: O(1)</li> </ul> <p>Can anyone confirm whether this is still true in Python 2.6/3.x?</p>
8
2009-10-05T18:58:42Z
1,521,843
<p>Take a look <a href="http://www.python.org/dev/peps/pep-3128/#motivation">here</a>. It's a PEP for a different kind of list. The version specified is 2.6/3.0.</p> <p>Append (insertion to back) is <code>O(1)</code>, while insertion (everywhere else) is <code>O(n)</code>. So <strong>yes</strong>, it looks like this is still true.</p> <pre><code>Operation...Complexity Copy........O(n) Append......O(1) Insert......O(n) Get Item....O(1) Set Item....O(1) Del Item....O(n) Iteration...O(n) Get Slice...O(k) Del Slice...O(n) Set Slice...O(n+k) Extend......O(k) Sort........O(n log n) Multiply....O(nk) </code></pre>
15
2009-10-05T19:11:08Z
[ "python", "performance", "list" ]
Cost of list functions in Python
1,521,784
<p>Based on <a href="http://bytes.com/topic/python/answers/101848-list-implementation">this older thread</a>, it looks like the cost of list functions in Python is:</p> <ul> <li>Random access: O(1)</li> <li>Insertion/deletion to front: O(n)</li> <li>Insertion/deletion to back: O(1)</li> </ul> <p>Can anyone confirm whether this is still true in Python 2.6/3.x?</p>
8
2009-10-05T18:58:42Z
1,522,168
<p>Python 3 is mostly an evolutionary change, no big changes in the datastructures and their complexities.</p> <p>The canonical source for Python collections is <a href="http://wiki.python.org/moin/TimeComplexity" rel="nofollow">TimeComplexity</a> on the Wiki.</p>
4
2009-10-05T20:19:51Z
[ "python", "performance", "list" ]
Cost of list functions in Python
1,521,784
<p>Based on <a href="http://bytes.com/topic/python/answers/101848-list-implementation">this older thread</a>, it looks like the cost of list functions in Python is:</p> <ul> <li>Random access: O(1)</li> <li>Insertion/deletion to front: O(n)</li> <li>Insertion/deletion to back: O(1)</li> </ul> <p>Can anyone confirm whether this is still true in Python 2.6/3.x?</p>
8
2009-10-05T18:58:42Z
1,522,519
<p>Fwiw, there is a faster (for some ops... insert is O(log n)) <a href="http://www.python.org/dev/peps/pep-3128/" rel="nofollow">list implementation</a> called BList if you need it. <a href="http://stutzbachenterprises.com/blist/" rel="nofollow">BList</a></p>
2
2009-10-05T21:31:34Z
[ "python", "performance", "list" ]
How to specify date and time in python?
1,521,906
<p>Quite simple newbie question:</p> <p>What is the object used in python to specify date (and time) in Python?</p> <p>For instance, to create an object that holds a given date and time, (let's say <code>'05/10/09 18:00'</code>).</p> <p><strong>EDIT</strong></p> <p>As per S.Lott request, what I have so far is:</p> <pre><code>class Some: date = </code></pre> <p>I stop there, after the "=" sign for I realize I didn't knew what the right object was ;) </p>
2
2009-10-05T19:22:49Z
1,521,922
<p>Look at the <a href="http://docs.python.org/library/datetime.html" rel="nofollow">datetime</a> module; there are datetime, date and timedelta class definitions.</p>
4
2009-10-05T19:26:32Z
[ "python", "datetime" ]
How to specify date and time in python?
1,521,906
<p>Quite simple newbie question:</p> <p>What is the object used in python to specify date (and time) in Python?</p> <p>For instance, to create an object that holds a given date and time, (let's say <code>'05/10/09 18:00'</code>).</p> <p><strong>EDIT</strong></p> <p>As per S.Lott request, what I have so far is:</p> <pre><code>class Some: date = </code></pre> <p>I stop there, after the "=" sign for I realize I didn't knew what the right object was ;) </p>
2
2009-10-05T19:22:49Z
1,522,043
<p>Simple example:</p> <pre><code>&gt;&gt;&gt; import datetime # 05/10/09 18:00 &gt;&gt;&gt; d = datetime.datetime(2009, 10, 5, 18, 00) &gt;&gt;&gt; print d.year, d.month, d.day, d.hour, d.second 2009 10 5 18 0 &gt;&gt;&gt; print d.isoformat(' ') 2009-10-05 18:00:00 &gt;&gt;&gt; </code></pre>
18
2009-10-05T19:51:58Z
[ "python", "datetime" ]
How to specify date and time in python?
1,521,906
<p>Quite simple newbie question:</p> <p>What is the object used in python to specify date (and time) in Python?</p> <p>For instance, to create an object that holds a given date and time, (let's say <code>'05/10/09 18:00'</code>).</p> <p><strong>EDIT</strong></p> <p>As per S.Lott request, what I have so far is:</p> <pre><code>class Some: date = </code></pre> <p>I stop there, after the "=" sign for I realize I didn't knew what the right object was ;) </p>
2
2009-10-05T19:22:49Z
1,522,078
<p>Nick D has the official way of handling your problem. If you want to pass in a string like you did in your question, the dateutil module (<a href="http://labix.org/python-dateutil" rel="nofollow">http://labix.org/python-dateutil</a>) has excellent support for that kind of thing.</p> <p>For examples, I'm going to copy and paste from another answer I gave a while back now:</p> <p>Simple example:</p> <pre><code>&gt;&gt;&gt; parse("Thu Sep 25 2003") datetime.datetime(2003, 9, 25, 0, 0) &gt;&gt;&gt; parse("Sep 25 2003") datetime.datetime(2003, 9, 25, 0, 0) &gt;&gt;&gt; parse("Sep 2003", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) &gt;&gt;&gt; parse("Sep", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) &gt;&gt;&gt; parse("2003", default=DEFAULT) datetime.datetime(2003, 9, 25, 0, 0) </code></pre> <p>To ambigous:</p> <pre><code>&gt;&gt;&gt; parse("10-09-2003") datetime.datetime(2003, 10, 9, 0, 0) &gt;&gt;&gt; parse("10-09-2003", dayfirst=True) datetime.datetime(2003, 9, 10, 0, 0) &gt;&gt;&gt; parse("10-09-03") datetime.datetime(2003, 10, 9, 0, 0) &gt;&gt;&gt; parse("10-09-03", yearfirst=True) datetime.datetime(2010, 9, 3, 0, 0) </code></pre> <p>To all over the board:</p> <pre><code>&gt;&gt;&gt; parse("Wed, July 10, '96") datetime.datetime(1996, 7, 10, 0, 0) &gt;&gt;&gt; parse("1996.07.10 AD at 15:08:56 PDT", ignoretz=True) datetime.datetime(1996, 7, 10, 15, 8, 56) &gt;&gt;&gt; parse("Tuesday, April 12, 1952 AD 3:30:42pm PST", ignoretz=True) datetime.datetime(1952, 4, 12, 15, 30, 42) &gt;&gt;&gt; parse("November 5, 1994, 8:15:30 am EST", ignoretz=True) datetime.datetime(1994, 11, 5, 8, 15, 30) &gt;&gt;&gt; parse("3rd of May 2001") datetime.datetime(2001, 5, 3, 0, 0) &gt;&gt;&gt; parse("5:50 A.M. on June 13, 1990") datetime.datetime(1990, 6, 13, 5, 50) </code></pre> <p>Take a look at the documentation for it here:</p> <p><a href="http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2" rel="nofollow">http://labix.org/python-dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2</a></p>
4
2009-10-05T20:01:29Z
[ "python", "datetime" ]
How to specify date and time in python?
1,521,906
<p>Quite simple newbie question:</p> <p>What is the object used in python to specify date (and time) in Python?</p> <p>For instance, to create an object that holds a given date and time, (let's say <code>'05/10/09 18:00'</code>).</p> <p><strong>EDIT</strong></p> <p>As per S.Lott request, what I have so far is:</p> <pre><code>class Some: date = </code></pre> <p>I stop there, after the "=" sign for I realize I didn't knew what the right object was ;) </p>
2
2009-10-05T19:22:49Z
1,522,102
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.strptime('05/10/09 18:00', '%d/%m/%y %H:%M') datetime.datetime(2009, 10, 5, 18, 0) &gt;&gt;&gt; datetime.datetime.today() datetime.datetime(2009, 10, 5, 21, 3, 55, 827787) </code></pre> <p>So, you can either use format string to convert to <code>datetime.datetime</code> object or if you're particularly looking at today's date could use <code>today()</code> function.</p>
1
2009-10-05T20:05:01Z
[ "python", "datetime" ]
How create jinja2 extension?
1,521,909
<p>I try to make extension for jinja2. I has written such code:</p> <p><a href="http://dumpz.org/12996/" rel="nofollow">http://dumpz.org/12996/</a></p> <p>But I receive exception: <code>'NoneType' object is not iterable</code>. Where is a bug? That should return <code>parse</code>. Also what should accept and return <code>_media</code>?</p>
1
2009-10-05T19:22:56Z
1,796,953
<p>You're using a <code>CallBlock</code>, which indicates that you want your extension to act as a block. E.g.</p> <pre><code>{% mytest arg1 arg2 %} stuff in here {% endmytest %} </code></pre> <p><code>nodes.CallBlock</code> expects that you pass it a list of nodes representing the body (the inner statements) for your extension. Currently this is where you're passing <code>None</code> - hence your error.</p> <p>Once you've parsed your arguments, you need to proceed to parse the body of the block. Fortunately, it's easy. You can simply do:</p> <pre><code>body = parser.parse_statements(['name:endmytest'], drop_needle=True) </code></pre> <p>and then return a new node. The <code>CallBlock</code> receives a method to be called (in this case <code>_mytestfunc</code>) that provides the logic for your extension.</p> <pre><code>body = parser.parse_statements(['name:endmytest'], drop_needle=True) return nodes.CallBlock(self.call_method('_mytestfunc', args),[], [], body).set_lineno(lineno) </code></pre> <p>Alternatively, if you don't want your extension to be a block tag, e.g.</p> <pre><code>{% mytest arg1 arg2 %} </code></pre> <p>you shouldn't use <code>nodes.CallBlock</code>, you should just use <code>nodes.Call</code> instead, which doesn't take a body parameter. So just do: </p> <pre><code>return self.call_method('_mytestfunc', args) </code></pre> <p><code>self.call_method</code> is simply a handy wrapper function that creates a Call node for you.</p> <p>I've spent a few days writing Jinja2 extensions and it's tricky. There's not much documentation (other than the code). The coffin GitHub project has a few examples of extensions <a href="https://github.com/coffin/coffin/blob/master/coffin/common.py" rel="nofollow">here</a>.</p>
10
2009-11-25T13:36:49Z
[ "python", "templates", "jinja2" ]
How to fix such ClientForm bug?
1,522,125
<pre><code>from mechanize import Browser br = Browser() page = br.open('http://wow.interzet.ru/news.php?readmore=23') br.form = br.forms().next() print br.form </code></pre> <p>gives me the following error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\roddik\Desktop\mech.py", line 6, in &lt;module&gt; br.form = br.forms().next() File "build\bdist.win32\egg\mechanize\_mechanize.py", line 426, in forms File "D:\py26\lib\site-package\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 559, in forms File "D:\py26\lib\site-packages\mechanize-0.1.11-py2.6.egg\mechanize\_html.py", line 225, in forms File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 967, in ParseResponseEx File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 1100, in _ParseFileEx File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 870, in feed File "D:\py26\lib\sgmllib.py", line 104, in feed self.goahead(0) File "D:\py26\lib\sgmllib.py", line 138, in goahead k = self.parse_starttag(i) File "D:\py26\lib\sgmllib.py", line 290, in parse_starttag self._convert_ref, attrvalue) File "D:\py26\lib\sgmllib.py", line 302, in _convert_ref return self.convert_charref(match.group(2)) or \ File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 850, in convert_charref File "D:\py26\lib\site-packages\clientform-0.2.10-py2.6.egg\ClientForm.py", line 244, in unescape_charref ValueError: invalid literal for int() with base 10: 'e' </code></pre> <p>How can I fix it?</p> <p>Edit:</p> <p>I've fixed it this way. Is it ok? If not, how instead?</p> <pre><code>import ClientForm from mechanize import Browser def myunescape_charref(data, encoding): if not str(data).isdigit(): return 0 name, base = data, 10 if name.startswith("x"): name, base= name[1:], 16 uc = unichr(int(name, base)) if encoding is None: return uc else: try: repl = uc.encode(encoding) except UnicodeError: repl = "&amp;#%s;" % data return repl ClientForm.unescape_charref = myunescape_charref </code></pre>
1
2009-10-05T20:10:08Z
1,522,392
<p>The problem is caused by urls like this</p> <pre><code>http://wow.zet/forum/index.php?showtopic=1197&amp;pid=30419&amp;st=0&amp;#entry30419 </code></pre> <p>ClientForm is looking for an integer after the &amp;#</p> <p>It is ok to have the # in the url, but it should be escaped in the html as &amp;# means a character encoding</p>
1
2009-10-05T21:06:26Z
[ "python", "mechanize", "clientform" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,453
<p>Simple enough; assuming the lists of verbs is fixed and small, this is easy to do with a dictionary and <code>for</code> loop:</p> <pre><code>VERBS = { "likes": "red" , "dislikes": "blue" , "knows": "black" } def replace_verb (line): for verb, color in VERBS.items(): if verb in line: return "%s %s;" % ( line.replace (verb, "-&gt;") , color ) return line def main (): filename = "my_file.txt" with open (filename, "r") as fp: for line in fp: print replace_verb (line) # Allow the module to be executed directly on the command line if __name__ == "__main__": main () </code></pre>
3
2009-10-05T21:19:22Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,461
<p>Are you sure this isn't a little homeworky :) If so, it's okay to fess up. Without going into too much detail, think about the tasks you're trying to do:</p> <p>For each line:</p> <ol> <li>read it</li> <li>split it into words (on whitespace - .split() )</li> <li>convert the middle word into a color (based on a mapping -> cf: python dict()</li> <li>print the first word, arrow, third word and the color</li> </ol> <p>Code using NetworkX (networkx.lanl.gov/)</p> <pre><code>''' plot relationships in a social network ''' import networkx ## make a fake file 'ex.txt' in this directory ## then write fake relationships to it. example_relationships = file('ex.txt','w') print &gt;&gt; example_relationships, '''\ Jane Doe likes Fred Chris dislikes Joe Nate knows Jill \ ''' example_relationships.close() rel_colors = { 'likes': 'blue', 'dislikes' : 'black', 'knows' : 'green', } def split_on_verb(sentence): ''' we know the verb is the only lower cased word &gt;&gt;&gt; split_on_verb("Jane Doe likes Fred") ('Jane Does','Fred','likes') ''' words = sentence.strip().split() # take off any outside whitespace, then split # on whitespace if not words: return None # if there aren't any words, just return nothing verbs = [x for x in words if x.islower()] verb = verbs[0] # we want the '1st' one (python numbers from 0,1,2...) verb_index = words.index(verb) # where is the verb? subject = ' '.join(words[:verb_index]) obj = ' '.join(words[(verb_index+1):]) # 'object' is already used in python return (subject, obj, verb) def graph_from_relationships(fh,color_dict): ''' fh: a filehandle, i.e., an opened file, from which we can read lines and loop over ''' G = networkx.DiGraph() for line in fh: if not line.strip(): continue # move on to the next line, # if our line is empty-ish (subj,obj,verb) = split_on_verb(line) color = color_dict[verb] # cf: python 'string templates', there are other solutions here # this is the print "'%s' -&gt; '%s' [color='%s'];" % (subj,obj,color) G.add_edge(subj,obj,color) # return G G = graph_from_relationships(file('ex.txt'),rel_colors) print G.edges() # from here you can use the various networkx plotting tools on G, as you're inclined. </code></pre>
1
2009-10-05T21:21:44Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,476
<p>Python 2.5:</p> <pre><code>import sys from collections import defaultdict codes = defaultdict(lambda: ("---", "Missing action!")) codes["likes"] = ("--&gt;", "red") codes["dislikes"] = ("-/&gt;", "green") codes["loves"] = ("==&gt;", "blue") for line in sys.stdin: subject, verb, object_ = line.strip().split(" ") arrow, color = codes[verb] print subject, arrow, object_, color, ";" </code></pre>
0
2009-10-05T21:24:01Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,500
<p>It sounds like you will want to research <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionaries</a> and <a href="http://docs.python.org/library/stdtypes.html#string-formatting-operations" rel="nofollow">string formatting</a>. In general, if you need help programming, just break down any problem you have into extremely small, discrete chunks, search those chunks independently, and then you should be able to formulate it all into a larger answer. Stack Overflow is a great resource for this type of searching.</p> <p>Also, if you have any general curiosities about Python, search or browse the <a href="http://docs.python.org/index.html" rel="nofollow">official Python documentation</a>. If you find yourself constantly not knowing where to begin, read the <a href="http://docs.python.org/tutorial/index.html" rel="nofollow">Python tutorial</a> or find a book to go through. A week or two investment to get a good foundational knowledge of what you are doing will pay off over and over again as you complete work.</p> <pre><code>verb_color_map = { 'likes': 'red', 'dislikes': 'blue', 'knows': 'black', } with open('infile.txt') as infile: # assuming you've stored your data in 'infile.txt' for line in infile: # Python uses the name object, so I use object_ subject, verb, object_ = line.split() print "%s -&gt; %s %s;" % (subject, object_, verb_color_map[verb]) </code></pre>
5
2009-10-05T21:27:41Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,530
<pre><code>verbs = {"dislikes":"blue", "knows":"black", "likes":"red"} for s in open("/tmp/infile"): s = s.strip() for verb in verbs.keys(): if (s.count(verb) &gt; 0): print s.replace(verb,"-&gt;")+" "+verbs[verb]+";" break </code></pre> <p>Edit: Rather use "for s in open"</p>
2
2009-10-05T21:34:23Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,522,868
<p>In addition to the question, Karasu also said (in a comment on one answer): "In the actual input both subjects and objects vary unpredictably between one and two words."</p> <p>Okay, here's how I would solve this.</p> <pre><code>color_map = \ { "likes" : "red", "dislikes" : "blue", "knows" : "black", } def is_verb(word): return word in color_map def make_noun(lst): if not lst: return "--NONE--" elif len(lst) == 1: return lst[0] else: return "_".join(lst) for line in open("filename").readlines(): words = line.split() # subject could be one or two words if is_verb(words[1]): # subject was one word s = words[0] v = words[1] o = make_noun(words[2:]) else: # subject was two words assert is_verb(words[2]) s = make_noun(words[0:2]) v = words[2] o = make_noun(words[3:]) color = color_map[v] print "%s -&gt; %s %s;" % (s, o, color) </code></pre> <p>Some notes:</p> <p>0) We don't really need "with" for this problem, and writing it this way makes the program more portable to older versions of Python. This should work on Python 2.2 and newer, I think (I only tested on Python 2.6).</p> <p>1) You can change make_noun() to have whatever strategy you deem useful for handling multiple words. I showed just chaining them together with underscores, but you could have a dictionary with adjectives and throw those out, have a dictionary of nouns and choose those, or whatever.</p> <p>2) You could also use regular expressions for fuzzier matching. Instead of simply using a dictionary for color_map you could have a list of tuples, with a regular expression paired with the replacement color, and then when the regular expression matches, replace the color.</p>
0
2009-10-05T23:10:31Z
[ "python", "text-processing" ]
Put bar at the end of every line that includes foo
1,522,386
<p>I have a list with a large number of lines, each taking the subject-verb-object form, eg: </p> <pre> Jane likes Fred Chris dislikes Joe Nate knows Jill </pre> <p>To plot a network graph that expresses the different relationships between the nodes in directed color-coded edges, I will need to replace the verb with an arrow and place a color code at the end of each line, thus, somewhat simplified:</p> <pre> Jane -> Fred red; Chris -> Joe blue; Nate -> Jill black; </pre> <p>There's only a small number of verbs, so replacing them with an arrow is just a matter of a few search and replace commands. Before doing that, however, I will need to put a color code at the end of every line that corresponds to the line's verb. I'd like to do this using Python.</p> <p>These are my baby steps in programming, so please be explicit and include the code that reads in the text file.</p> <p>Thanks for your help!</p>
4
2009-10-05T21:04:32Z
1,523,649
<p>Here is an improved version of my previous answer. This one uses regular expression matching to make a fuzzy match on the verb. These all work:</p> <pre><code>Steve loves Denise Bears love honey Maria interested Anders Maria interests Anders </code></pre> <p>The regular expression pattern "loves?" matches "love" plus an optional 's'. The pattern "interest.*" matches "interest" plus anything. Patterns with multiple alternatives separated by vertical bars match if any one of the alternatives matches.</p> <pre><code>import re re_map = \ [ ("likes?|loves?|interest.*", "red"), ("dislikes?|hates?", "blue"), ("knows?|tolerates?|ignores?", "black"), ] # compile the regular expressions one time, then use many times pat_map = [(re.compile(s), color) for s, color in re_map] # We dont use is_verb() in this version, but here it is. # A word is a verb if any of the patterns match. def is_verb(word): return any(pat.match(word) for pat, color in pat_map) # Return color from matched verb, or None if no match. # This detects whether a word is a verb, and looks up the color, at the same time. def color_from_verb(word): for pat, color in pat_map: if pat.match(word): return color return None def make_noun(lst): if not lst: return "--NONE--" elif len(lst) == 1: return lst[0] else: return "_".join(lst) for line in open("filename"): words = line.split() # subject could be one or two words color = color_from_verb(words[1]) if color: # subject was one word s = words[0] o = make_noun(words[2:]) else: # subject was two words color = color_from_verb(words[1]) assert color s = make_noun(words[0:2]) o = make_noun(words[3:]) print "%s -&gt; %s %s;" % (s, o, color) </code></pre> <p>I hope it is clear how to take this answer and extend it. You can easily add more patterns to match more verbs. You could add logic to detect "is" and "in" and discard them, so that "Anders is interested in Maria" would match. And so on.</p> <p>If you have any questions, I'd be happy to explain this further. Good luck.</p>
0
2009-10-06T04:51:14Z
[ "python", "text-processing" ]
(Python) Passing a threading.Thread object through a function?
1,522,409
<p>I have a timer function:</p> <pre><code># This is a class that schedules tasks. It will call it's ring() function # when the timer starts, and call it's running() function when within the # time limit, and call it's over() function when the time is up. # This class uses SYSTEM time. import time, threading import settings from object import Object class Timer(Object, threading.Thread): # INIT ------------------------------------------------------------- # Init vars # # If autotick is True (default) the timer will run in a seperate # process. Other wise it will need to be updated automatically by # calling tick() def __init__(self, autotick=False): # Call inherited __init__ first. threading.Thread.__init__(self) Object.__init__(self) # Now our vars self.startTimeString = "" # The time when the timer starts as a string self.endTimeString = "" # The time when the timer stops as a string self.timeFormat = "" # The string to use as the format for the string self.set = False # The timer starts deactivated self.process = autotick # Wether or not to run in a seperate process. self.rung = False # Has the timer rang yet? # ACTIVATE -------------------------------------------------------------- # Sets the timer def activate(self, startTime, endTime, format): # Set the timer. self.startTimeString = startTime self.endTimeString = endTime self.timeFormat = format # Conver the strings to time using format try: self.startTime = time.strptime(startTime, self.timeFormat) self.endTime = time.strptime(endTime, self.timeFormat) except ValueError: # Error print ("Error: Cannot convert time according to format") return False # Try and convert the time to seconds try: self.startTimeSecs = time.mktime(self.startTime) self.endTimeSecs = time.mktime(self.endTime) except OverflowError, ValueError: # Error print ("Error: Cannot convert time to seconds") return False # The timer is now set self.set = True # If self.process is true, we need to start calling tick in a # seperate process. if self.process: self.deamon = True # We don't want python to hang if a timer # is still running at exit. self.start() # RING ------------------------------------------------------------- # This function is called when the timer starts. def ring(self): pass # RUNNING ---------------------------------------------------------- # Called when the the time is whithin the time limits. def running(self): pass # OVER ------------------------------------------------------------- # Called when the time is up def over(self): pass # TICK ------------------------------------------------------------- # Call this every loop (or in a seperate process) def tick(self): print time.time(), self.startTimeSecs, self.endTimeSecs, time.strftime("%A %H:%M", time.localtime(self.startTimeSecs)) # Check the time if time.mktime(time.localtime()) &gt; self.startTimeSecs and time.mktime(time.localtime()) &lt; self.endTimeSecs and not self.rung: # The time has come =) # Call ring() self.ring() # Now set self.rung to True self.rung = True # If the time is up.. elif time.mktime(time.localtime()) &gt; self.endTimeSecs and self.rung: self.over() # Unset the timer self.set = False self.rung = False # If we are inbetween the starttime and endtime. elif time.mktime(time.localtime()) &gt; self.startTimeSecs and time.mktime(time.localtime()) &lt; self.endTimeSecs and self.rung: self.running() # If any of those aren't true, then the timer hasn't started yet else: # Check if the endTime has already passed if time.mktime(time.localtime()) &gt; self.endTimeSecs: # The time has already passed. self.set = False # THREADING STUFF -------------------------------------------------- # This is run by Threads start() method. def run(self): while self.set == True: # Tick self.tick() # Sleep for a bit to save CPU time.sleep(settings.TIMER_SLEEP) </code></pre> <p>And I am added schedule blocks to a scheduler:</p> <pre><code># LOAD ------------------------------------------------------------- # Loads schedule from a file (schedule_settings.py). def load(self): # Add blocks for block in schedule_settings.BLOCKS: # Calculate the day start_day = str(getDate(block[1].split()[0])) end_day = str(getDate(block[2].split()[0])) self.scheduler.add(start_day + " " + block[1].split()[1], end_day + " " + block[2].split()[1], "%j %H:%M", block[0]) for block in self.scheduler.blocks: block.timer.tick() print len(self.scheduler.blocks) # Start the scheduler (if it isn't already) if not self.scheduler.running: self.scheduler.start() </code></pre> <p>The add function looks like this:</p> <pre><code># ADD -------------------------------------------------------------- # Add a scheduled time # # block should be a Block instance, describing what to do at this time. def add(self, startTime, endTime, format, block): # Add this block newBlock = block # Start a timer for this block newBlock.timer = Timer() # Figure out the time year = time.strftime("%Y") # Add the block timer newBlock.timer.activate(year + " " + startTime, year + " " + endTime, "%Y " + format) # Add this block to the list self.blocks.append(newBlock) return </code></pre> <p>Basically with my program you can make a week's schedule and play your videos as if it were a TV channel. A block is a period of time where the channel will play certain episodes, or certain series. </p> <p>My problem is that the blocks get completley messed up after using the add function. Some get duplicated, they're in the wrong order, etc. However before the add function they are completely fine. If I use a small amount of blocks (2 or 3) it seems to work fine, though.</p> <p>For example if my schedule_settings.py (set's up a weeks schedule) looks like this:</p> <pre><code># -*- coding: utf-8 -*- # This file contains settings for a week's schedule from block import Block from series import Series # MAIN BLOCK (All old episodes) mainBlock = Block() mainBlock.picker = 'random' mainBlock.name = "Main Block" mainBlock.auto(".") mainBlock.old_episodes = True # ONE PIECE onepieceBlock = Block() onepieceBlock.picker = 'latest' onepieceBlock.name = "One Piece" onepieceBlock.series = [ Series(auto="One Piece"), ] # NEWISH STUFF newishBlock = Block() newishBlock.picker = 'random' newishBlock.auto(".") newishBlock.name = "NewishBlock" newishBlock.exclude_series = [ #Series(auto="One Piece"), #Series(auto="Nyan Koi!"), ] # NEW STUFF newBlock = Block() newBlock.picker = 'latest' newBlock.name = "New Stuff" newBlock.series = [ Series(auto="Nyan Koi!"), ] # ACTIVE BLOCKS BLOCKS = ( # MONDAY (mainBlock, "Monday 08:00", "Monday 22:20"), (onepieceBlock, "Monday 22:20", "Monday 22:30"), (newishBlock, "Monday 22:30", "Monday 23:00"), # TUESDAY (mainBlock, "Tuesday 08:00", "Tuesday 18:00"), (newBlock, "Tuesday 18:00", "Tuesday 18:30"), (newishBlock, "Tuesday 18:30", "Tuesday 22:00"), # WEDNESDAY (mainBlock, "Wednesday 08:00", "Wednesday 18:00"), (newBlock, "Wednesday 18:00", "Wednesday 18:30"), (newishBlock, "Wednesday 18:30", "Wednesday 22:00"), # THURSDAY (mainBlock, "Thursday 08:00", "Thursday 18:00"), (newBlock, "Thursday 18:00", "Thursday 18:30"), (newishBlock, "Thursday 18:30", "Thursday 22:00"), # FRIDAY (mainBlock, "Friday 08:00", "Friday 18:00"), (newBlock, "Friday 18:00", "Friday 18:30"), # WEEKEND (newishBlock, "Saturday 08:00", "Saturday 23:00"), (newishBlock, "Sunday 08:00", "Sunday 23:00"), ) </code></pre> <p>Before adding to the scheduler, The list produced looks fine, but after adding, then printing it out, I get:</p> <pre><code>1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1254777600.0 1254778200.0 Monday 22:20 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 </code></pre> <p>I'm assuming this has somthing to do with the subclassing of threading.Thread I have done in my Timer class. Does passing it through a function and adding it to a list mess this up somehow?</p> <p>(Edit) Sorry if that wasn't very concise, I was in rush and forgot to post the most important code =( Using the timer to tick manually was just some debug code, normally I would have auto=True in the timer class.</p> <p>You can find all my code at: <a href="http://github.com/bombpersons/MYOT" rel="nofollow">http://github.com/bombpersons/MYOT</a></p>
0
2009-10-05T21:10:25Z
1,522,753
<p>You show us tons of code but not the key parts -- the Scheduler part (and what's that peculiar upper-case-O Object class...?). Anyway, to answer your question, passing instances of Thread subclasses through functions, adding them to lists, etc etc, is perfectly fine (though other things you're doing may not be -- e.g. you may not realize that, just because <code>tick</code> is a method of a Thread subclass, calling it from another thread does NOT mean it will execute in its own thread... rather, when called, it will execute in the calling thread).</p> <p>May I suggest using the <a href="http://docs.python.org/library/sched.html" rel="nofollow">sched</a> module in Python standard library to implement scheduling functionality, rather than running your own...?</p>
2
2009-10-05T22:34:05Z
[ "python", "class", "inheritance", "multithreading" ]
(Python) Passing a threading.Thread object through a function?
1,522,409
<p>I have a timer function:</p> <pre><code># This is a class that schedules tasks. It will call it's ring() function # when the timer starts, and call it's running() function when within the # time limit, and call it's over() function when the time is up. # This class uses SYSTEM time. import time, threading import settings from object import Object class Timer(Object, threading.Thread): # INIT ------------------------------------------------------------- # Init vars # # If autotick is True (default) the timer will run in a seperate # process. Other wise it will need to be updated automatically by # calling tick() def __init__(self, autotick=False): # Call inherited __init__ first. threading.Thread.__init__(self) Object.__init__(self) # Now our vars self.startTimeString = "" # The time when the timer starts as a string self.endTimeString = "" # The time when the timer stops as a string self.timeFormat = "" # The string to use as the format for the string self.set = False # The timer starts deactivated self.process = autotick # Wether or not to run in a seperate process. self.rung = False # Has the timer rang yet? # ACTIVATE -------------------------------------------------------------- # Sets the timer def activate(self, startTime, endTime, format): # Set the timer. self.startTimeString = startTime self.endTimeString = endTime self.timeFormat = format # Conver the strings to time using format try: self.startTime = time.strptime(startTime, self.timeFormat) self.endTime = time.strptime(endTime, self.timeFormat) except ValueError: # Error print ("Error: Cannot convert time according to format") return False # Try and convert the time to seconds try: self.startTimeSecs = time.mktime(self.startTime) self.endTimeSecs = time.mktime(self.endTime) except OverflowError, ValueError: # Error print ("Error: Cannot convert time to seconds") return False # The timer is now set self.set = True # If self.process is true, we need to start calling tick in a # seperate process. if self.process: self.deamon = True # We don't want python to hang if a timer # is still running at exit. self.start() # RING ------------------------------------------------------------- # This function is called when the timer starts. def ring(self): pass # RUNNING ---------------------------------------------------------- # Called when the the time is whithin the time limits. def running(self): pass # OVER ------------------------------------------------------------- # Called when the time is up def over(self): pass # TICK ------------------------------------------------------------- # Call this every loop (or in a seperate process) def tick(self): print time.time(), self.startTimeSecs, self.endTimeSecs, time.strftime("%A %H:%M", time.localtime(self.startTimeSecs)) # Check the time if time.mktime(time.localtime()) &gt; self.startTimeSecs and time.mktime(time.localtime()) &lt; self.endTimeSecs and not self.rung: # The time has come =) # Call ring() self.ring() # Now set self.rung to True self.rung = True # If the time is up.. elif time.mktime(time.localtime()) &gt; self.endTimeSecs and self.rung: self.over() # Unset the timer self.set = False self.rung = False # If we are inbetween the starttime and endtime. elif time.mktime(time.localtime()) &gt; self.startTimeSecs and time.mktime(time.localtime()) &lt; self.endTimeSecs and self.rung: self.running() # If any of those aren't true, then the timer hasn't started yet else: # Check if the endTime has already passed if time.mktime(time.localtime()) &gt; self.endTimeSecs: # The time has already passed. self.set = False # THREADING STUFF -------------------------------------------------- # This is run by Threads start() method. def run(self): while self.set == True: # Tick self.tick() # Sleep for a bit to save CPU time.sleep(settings.TIMER_SLEEP) </code></pre> <p>And I am added schedule blocks to a scheduler:</p> <pre><code># LOAD ------------------------------------------------------------- # Loads schedule from a file (schedule_settings.py). def load(self): # Add blocks for block in schedule_settings.BLOCKS: # Calculate the day start_day = str(getDate(block[1].split()[0])) end_day = str(getDate(block[2].split()[0])) self.scheduler.add(start_day + " " + block[1].split()[1], end_day + " " + block[2].split()[1], "%j %H:%M", block[0]) for block in self.scheduler.blocks: block.timer.tick() print len(self.scheduler.blocks) # Start the scheduler (if it isn't already) if not self.scheduler.running: self.scheduler.start() </code></pre> <p>The add function looks like this:</p> <pre><code># ADD -------------------------------------------------------------- # Add a scheduled time # # block should be a Block instance, describing what to do at this time. def add(self, startTime, endTime, format, block): # Add this block newBlock = block # Start a timer for this block newBlock.timer = Timer() # Figure out the time year = time.strftime("%Y") # Add the block timer newBlock.timer.activate(year + " " + startTime, year + " " + endTime, "%Y " + format) # Add this block to the list self.blocks.append(newBlock) return </code></pre> <p>Basically with my program you can make a week's schedule and play your videos as if it were a TV channel. A block is a period of time where the channel will play certain episodes, or certain series. </p> <p>My problem is that the blocks get completley messed up after using the add function. Some get duplicated, they're in the wrong order, etc. However before the add function they are completely fine. If I use a small amount of blocks (2 or 3) it seems to work fine, though.</p> <p>For example if my schedule_settings.py (set's up a weeks schedule) looks like this:</p> <pre><code># -*- coding: utf-8 -*- # This file contains settings for a week's schedule from block import Block from series import Series # MAIN BLOCK (All old episodes) mainBlock = Block() mainBlock.picker = 'random' mainBlock.name = "Main Block" mainBlock.auto(".") mainBlock.old_episodes = True # ONE PIECE onepieceBlock = Block() onepieceBlock.picker = 'latest' onepieceBlock.name = "One Piece" onepieceBlock.series = [ Series(auto="One Piece"), ] # NEWISH STUFF newishBlock = Block() newishBlock.picker = 'random' newishBlock.auto(".") newishBlock.name = "NewishBlock" newishBlock.exclude_series = [ #Series(auto="One Piece"), #Series(auto="Nyan Koi!"), ] # NEW STUFF newBlock = Block() newBlock.picker = 'latest' newBlock.name = "New Stuff" newBlock.series = [ Series(auto="Nyan Koi!"), ] # ACTIVE BLOCKS BLOCKS = ( # MONDAY (mainBlock, "Monday 08:00", "Monday 22:20"), (onepieceBlock, "Monday 22:20", "Monday 22:30"), (newishBlock, "Monday 22:30", "Monday 23:00"), # TUESDAY (mainBlock, "Tuesday 08:00", "Tuesday 18:00"), (newBlock, "Tuesday 18:00", "Tuesday 18:30"), (newishBlock, "Tuesday 18:30", "Tuesday 22:00"), # WEDNESDAY (mainBlock, "Wednesday 08:00", "Wednesday 18:00"), (newBlock, "Wednesday 18:00", "Wednesday 18:30"), (newishBlock, "Wednesday 18:30", "Wednesday 22:00"), # THURSDAY (mainBlock, "Thursday 08:00", "Thursday 18:00"), (newBlock, "Thursday 18:00", "Thursday 18:30"), (newishBlock, "Thursday 18:30", "Thursday 22:00"), # FRIDAY (mainBlock, "Friday 08:00", "Friday 18:00"), (newBlock, "Friday 18:00", "Friday 18:30"), # WEEKEND (newishBlock, "Saturday 08:00", "Saturday 23:00"), (newishBlock, "Sunday 08:00", "Sunday 23:00"), ) </code></pre> <p>Before adding to the scheduler, The list produced looks fine, but after adding, then printing it out, I get:</p> <pre><code>1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1254777600.0 1254778200.0 Monday 22:20 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255071600.0 1255107600.0 Friday 08:00 1254810368.0 1255107600.0 1255109400.0 Friday 18:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 1254810368.0 1255244400.0 1255298400.0 Sunday 08:00 </code></pre> <p>I'm assuming this has somthing to do with the subclassing of threading.Thread I have done in my Timer class. Does passing it through a function and adding it to a list mess this up somehow?</p> <p>(Edit) Sorry if that wasn't very concise, I was in rush and forgot to post the most important code =( Using the timer to tick manually was just some debug code, normally I would have auto=True in the timer class.</p> <p>You can find all my code at: <a href="http://github.com/bombpersons/MYOT" rel="nofollow">http://github.com/bombpersons/MYOT</a></p>
0
2009-10-05T21:10:25Z
1,526,084
<p>Ugh.. I feel stupid now. The problem was that, the blocks were being passed by reference to the scheduler, therefore everytime I added a timer to the block, I was overwriting the older timer. </p> <p>I made a schedulerBlock class containing a timer and a block. It now works perfectly =)</p>
0
2009-10-06T14:51:17Z
[ "python", "class", "inheritance", "multithreading" ]
map string position to line number in regex output
1,522,510
<p>I'm working on a "grep-like" utility in Python for searching Oracle source code files. Coding standards have changed over time, so trying to find something like "all deletes from table a.foo" could span multiple lines, or not, depending on the age of that piece of code:</p> <pre><code>s = """-- multiline DDL statement DELETE a.foo f WHERE f.bar = 'XYZ'; DELETE a.foo f WHERE f.bar = 'ABC'; DELETE a.foo WHERE bar = 'PDQ'; """ import re p = re.compile( r'\bDELETE\b.+?a\.foo', re.MULTILINE | re.DOTALL ) for m in re.finditer( p, s ): print s[ m.start() : m.end() ] </code></pre> <p>This outputs:</p> <pre><code>DELETE a.foo DELETE a.foo DELETE a.foo </code></pre> <p>What I want:</p> <pre><code>[2] DELETE [3] a.foo [7] DELETE a.foo [10] DELETE a.foo </code></pre> <p>Is there a quick/simple/builtin way to map string indices to line numbers?</p>
2
2009-10-05T21:30:29Z
1,522,531
<pre><code>lineno = s.count("\n",0,m.start())+1 </code></pre>
5
2009-10-05T21:34:40Z
[ "python", "regex", "grep", "multiline" ]
How do I run a Python program?
1,522,564
<p>So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol</p> <p>I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.</p> <p>I'm also using Komodo Edit to create the actual .py files.</p> <p>My question is, how can I run the .py files to test out the actual program? </p> <p>I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.</p> <p><img src="http://imgur.com/x8DJK.png" alt="alt text" /></p>
36
2009-10-05T21:42:30Z
1,522,567
<p>You can just call</p> <pre><code>python /path/to/filename.py </code></pre>
12
2009-10-05T21:43:01Z
[ "python", "ide", "debugging" ]
How do I run a Python program?
1,522,564
<p>So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol</p> <p>I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.</p> <p>I'm also using Komodo Edit to create the actual .py files.</p> <p>My question is, how can I run the .py files to test out the actual program? </p> <p>I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.</p> <p><img src="http://imgur.com/x8DJK.png" alt="alt text" /></p>
36
2009-10-05T21:42:30Z
1,522,599
<p>In IDLE press F5</p> <p>You can open your .py file with IDLE and press F5 to run it. </p> <p>You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ).</p> <p>If you want to run it directly from Komodo according to this article: <a href="http://community.activestate.com/forum-topic/executing-python-code-within-komodo-edit" rel="nofollow">Executing Python Code Within Komodo Edit</a> you have to:</p> <ol> <li>go to Toolbox -> Add -> New Command...</li> <li>in the top field enter the name 'Run Python file'</li> <li><p>in the 'Command' field enter this text:</p> <p>%(python) %F 3.a optionall click on the 'Key Binding' tab and assign a key command to this command</p></li> <li>click Ok.</li> </ol>
11
2009-10-05T21:52:24Z
[ "python", "ide", "debugging" ]
How do I run a Python program?
1,522,564
<p>So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol</p> <p>I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.</p> <p>I'm also using Komodo Edit to create the actual .py files.</p> <p>My question is, how can I run the .py files to test out the actual program? </p> <p>I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.</p> <p><img src="http://imgur.com/x8DJK.png" alt="alt text" /></p>
36
2009-10-05T21:42:30Z
1,527,012
<p>I'm very glad you asked! I was just working on explaining this very thing <a href="http://en.wikibooks.org/wiki/Choose%5FYour%5FOwn%5FPyventure">in our wikibook</a> (which is obviously incomplete). We're working with Python novices, and had to help a few through exactly what you're asking! </p> <p><strong>Command-line Python in Windows:</strong> </p> <ol> <li><p>Save your python code file somewhere, using "Save" or "Save as" in your editor. Lets call it 'first.py' in some folder, like "pyscripts" that you make on your Desktop.</p></li> <li><p>Open a <strong>prompt</strong> (a Windows 'cmd' shell that is a text interface into the computer): </p> <p>start > run > "cmd" (in the little box). OK. </p></li> <li><p>Navigate to where your python file is, using the commands 'cd' (change directory) and 'dir' (to show files in the directory, to verify your head). For our example something like, </p> <p>> cd C:\Documents and Settings\Gregg\Desktop\pyscripts</p></li> <li><p>try:</p> <p>> python first.py</p></li> </ol> <p>If you get this message: </p> <blockquote> <p>'python' is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <p>then <strong>python</strong> (the <em>interpreter</em> program that can translate Python into 'computer instructions') isn't on your path (see Putting Python in Your Path below). Then try calling it like this (assuming Python2.6, installed in the usual location):</p> <p>> C:\Python26\python.exe first.py</p> <p>(Advanced users: instead of first.py, you could write out first.py's full path of C:\Documents and Settings\Gregg\Desktop\pyscripts\first.py)</p> <p><strong>Putting Python In Your Path</strong></p> <p><em>Windows</em></p> <p>In order to run programs, your operating system looks in various places, and tries to match the name of the program / command you typed with some programs along the way. </p> <p>In windows:</p> <p>control panel > system > advanced > |Environmental Variables| > system variables -> Path</p> <p>this needs to include: C:\Python26; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner.</p> <p>Then restart your prompt, and try typing 'python'. If it all worked, you should get a ">>>" prompt.</p>
45
2009-10-06T17:37:26Z
[ "python", "ide", "debugging" ]
How do I run a Python program?
1,522,564
<p>So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol</p> <p>I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.</p> <p>I'm also using Komodo Edit to create the actual .py files.</p> <p>My question is, how can I run the .py files to test out the actual program? </p> <p>I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.</p> <p><img src="http://imgur.com/x8DJK.png" alt="alt text" /></p>
36
2009-10-05T21:42:30Z
25,067,116
<p>if you dont want call <code>filename.py</code> you can add <code>.PY</code> to the PATHEXT, that way you will just call <code>filename</code></p>
0
2014-07-31T19:13:20Z
[ "python", "ide", "debugging" ]
How do I run a Python program?
1,522,564
<p>So I'm starting like Python a bit, but I'm having trouble erm...running it. Lol</p> <p>I'm using IDLE for now, but its no use whatsoever because you can only run a couple of lines at a time.</p> <p>I'm also using Komodo Edit to create the actual .py files.</p> <p>My question is, how can I run the .py files to test out the actual program? </p> <p>I'm using Windows 7, and Komodo Edit 5 as my IDE. Pressing F5 in Komodo doesn't do anythin at all.</p> <p><img src="http://imgur.com/x8DJK.png" alt="alt text" /></p>
36
2009-10-05T21:42:30Z
34,713,762
<p>Python itself comes with an editor that you can access from the IDLE File > New File menu option.</p> <p>Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.</p> <p>Note: it's just been the easiest and most straightforward way for me so far.</p>
1
2016-01-11T03:26:27Z
[ "python", "ide", "debugging" ]
should I call close() after urllib.urlopen()?
1,522,636
<p>I'm new to Python and reading someone else's code:</p> <p>should <code>urllib.urlopen()</code> be followed by <code>urllib.close()</code>? Otherwise, one would leak connections, correct?</p>
48
2009-10-05T21:59:04Z
1,522,662
<p>Strictly speaking, this is true. But in practice, once (if) <code>urllib</code> goes out of scope, the connection will be closed by the automatic garbage collector.</p>
2
2009-10-05T22:07:57Z
[ "python", "urllib" ]
should I call close() after urllib.urlopen()?
1,522,636
<p>I'm new to Python and reading someone else's code:</p> <p>should <code>urllib.urlopen()</code> be followed by <code>urllib.close()</code>? Otherwise, one would leak connections, correct?</p>
48
2009-10-05T21:59:04Z
1,522,709
<p>The <code>close</code> method must be called on the <em>result</em> of <code>urllib.urlopen</code>, <strong>not</strong> on the <code>urllib</code> module itself as you're thinking about (as you mention <code>urllib.close</code> -- which doesn't exist).</p> <p>The best approach: instead of <code>x = urllib.urlopen(u)</code> etc, use:</p> <pre><code>import contextlib with contextlib.closing(urllib.urlopen(u)) as x: ...use x at will here... </code></pre> <p>The <code>with</code> statement, and the <code>closing</code> context manager, will ensure proper closure even in presence of exceptions.</p>
80
2009-10-05T22:22:17Z
[ "python", "urllib" ]
should I call close() after urllib.urlopen()?
1,522,636
<p>I'm new to Python and reading someone else's code:</p> <p>should <code>urllib.urlopen()</code> be followed by <code>urllib.close()</code>? Otherwise, one would leak connections, correct?</p>
48
2009-10-05T21:59:04Z
1,522,713
<p>Like @Peter says, out-of-scope opened URLs will become eligible for garbage collection.</p> <p>However, also note that <code>urllib.py</code> defines:</p> <pre><code> def __del__(self): self.close() </code></pre> <p>This means that <strong>when the reference count for that instance reaches zero</strong>, its <a href="http://docs.python.org/reference/datamodel.html#object.__del__"><code>__del__</code></a> method will be called, and thus its <code>close</code> method will be called as well. The most "normal" way for the reference count to reach zero is to simply let the instance go out of scope, but there's nothing strictly stopping you from an explicit <code>del x</code> early (however it doesn’t directly call <code>__del__</code> but just decrements the reference count by one).</p> <p>It's certainly good style to explicitly close your resources -- especially when your application runs the risk of using too much of said resources -- but Python <em>will</em> automatically clean up for you if you don't do anything funny like maintaining (circular?) references to instances that you don't need any more.</p>
11
2009-10-05T22:24:08Z
[ "python", "urllib" ]
should I call close() after urllib.urlopen()?
1,522,636
<p>I'm new to Python and reading someone else's code:</p> <p>should <code>urllib.urlopen()</code> be followed by <code>urllib.close()</code>? Otherwise, one would leak connections, correct?</p>
48
2009-10-05T21:59:04Z
35,426,368
<p>If I am not mistaken,I guess even <code>del varname[:]</code> should work to decrement the reference count to zero which should ideally call the <code>__del__(self)</code> automatically</p>
0
2016-02-16T07:30:42Z
[ "python", "urllib" ]
How do I get the module instance for a class in Python?
1,522,651
<p>I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called <code>install_path</code>. I would like to obtain the <code>__path__</code> for the <code>__module__</code> for <code>self</code> (which in this case will be the subclass). Problem is, <code>__module__</code> returns a <code>str</code> rather than the module instance itself. <code>eval()</code> is unreliable and undesirable, so I need a good way of getting my hands on the actual module instance that doesn't involve <code>eval</code>ling the <code>str</code> I get back from <code>__module__</code>.</p>
8
2009-10-05T22:03:21Z
1,522,667
<p>How about <a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow">Importing modules</a></p> <blockquote> <p><code>X = __import__(‘X’)</code> works like <code>import X</code>, with the difference that you 1) pass the module name as a string, and 2) explicitly assign it to a variable in your current namespace.</p> </blockquote> <p>You could pass the module name (instead of 'X') and get the module instance back. Python will ensure that you don't import the same module twice, so you should get back the instance that you imported earlier.</p>
1
2009-10-05T22:09:45Z
[ "python" ]
How do I get the module instance for a class in Python?
1,522,651
<p>I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called <code>install_path</code>. I would like to obtain the <code>__path__</code> for the <code>__module__</code> for <code>self</code> (which in this case will be the subclass). Problem is, <code>__module__</code> returns a <code>str</code> rather than the module instance itself. <code>eval()</code> is unreliable and undesirable, so I need a good way of getting my hands on the actual module instance that doesn't involve <code>eval</code>ling the <code>str</code> I get back from <code>__module__</code>.</p>
8
2009-10-05T22:03:21Z
1,522,687
<p>The <a href="http://docs.python.org/library/sys.html#sys.modules"><code>sys.modules</code></a> dict contains all imported modules, so you can use:</p> <pre><code>mod = sys.modules[__module__] </code></pre>
11
2009-10-05T22:13:24Z
[ "python" ]
How do I get the module instance for a class in Python?
1,522,651
<p>I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called <code>install_path</code>. I would like to obtain the <code>__path__</code> for the <code>__module__</code> for <code>self</code> (which in this case will be the subclass). Problem is, <code>__module__</code> returns a <code>str</code> rather than the module instance itself. <code>eval()</code> is unreliable and undesirable, so I need a good way of getting my hands on the actual module instance that doesn't involve <code>eval</code>ling the <code>str</code> I get back from <code>__module__</code>.</p>
8
2009-10-05T22:03:21Z
1,522,746
<p>Alternatively, you can use the module's global <a href="http://docs.python.org/reference/datamodel.html?highlight=%5F%5Ffile%5F%5F" rel="nofollow"><code>__file__</code> variable</a> if all you want is the module's path.</p>
1
2009-10-05T22:31:26Z
[ "python" ]
Problem running a very simple Python program
1,522,708
<p>Why is my program giving me an error here?</p> <pre><code>import random TheNumber = random.randrange(1,200,1) NotGuessed = True Tries = 0 GuessedNumber = int(input("Take a guess at the magic number!: ")) while NotGuessed == True: if GuessedNumber &lt; TheNumber: print("Your guess is a bit too low.") Tries = Tries + 1 GuessedNumber = int(input("Take another guess at the magic number!: ")) if GuessedNumber &gt; TheNumber: print("Your guess is a bit too high!") Tries = Tries + 1 GuessedNumber = int(input("Take another guess at the magic number!: ")) if GuessedNumber == TheNumber: print("You've guess the number, and it only took you " + string(Tries) + "!") </code></pre> <p>The error is on the last line. What can I do?</p> <p>Edit:</p> <p>Also, why can;t I use Tries++ here in Python? Isn't there an autoincrement code?</p> <p>Edit 2: Error is:</p> <pre><code>Traceback (most recent call last): File "C:/Users/Sergio/Desktop/GuessingGame.py", line 21, in &lt;module&gt; print("You've guess the number, and it only took you " + string(Tries) + "!") NameError: name 'string' is not defined </code></pre>
1
2009-10-05T22:22:08Z
1,522,726
<p>it's <code>str</code>, not <code>string</code>. but your infinite loop is a bigger problem. auto-increment is written like this:</p> <pre><code>Tries += 1 </code></pre> <p>General comment: you could improve your code slightly:</p> <pre><code>the_number = random.randrange(1,200,1) tries = 1 guessed_number = int(input("Take a guess at the magic number!: ")) while True: if guessed_number &lt; the_number: print("Your guess is a bit too low.") if guessed_number &gt; the_number: print("Your guess is a bit too high!") if guessed_number == the_number: break else: guessed_number = int(input("Take another guess at the magic number!: ")) tries += 1 print("You've guessed the number, and it only took you %d tries!" % tries) </code></pre>
2
2009-10-05T22:26:45Z
[ "python", "ide", "python-idle" ]
Problem running a very simple Python program
1,522,708
<p>Why is my program giving me an error here?</p> <pre><code>import random TheNumber = random.randrange(1,200,1) NotGuessed = True Tries = 0 GuessedNumber = int(input("Take a guess at the magic number!: ")) while NotGuessed == True: if GuessedNumber &lt; TheNumber: print("Your guess is a bit too low.") Tries = Tries + 1 GuessedNumber = int(input("Take another guess at the magic number!: ")) if GuessedNumber &gt; TheNumber: print("Your guess is a bit too high!") Tries = Tries + 1 GuessedNumber = int(input("Take another guess at the magic number!: ")) if GuessedNumber == TheNumber: print("You've guess the number, and it only took you " + string(Tries) + "!") </code></pre> <p>The error is on the last line. What can I do?</p> <p>Edit:</p> <p>Also, why can;t I use Tries++ here in Python? Isn't there an autoincrement code?</p> <p>Edit 2: Error is:</p> <pre><code>Traceback (most recent call last): File "C:/Users/Sergio/Desktop/GuessingGame.py", line 21, in &lt;module&gt; print("You've guess the number, and it only took you " + string(Tries) + "!") NameError: name 'string' is not defined </code></pre>
1
2009-10-05T22:22:08Z
1,522,727
<p>In your last line, replace <code>string</code> with <code>str</code> -- that should take care of the error python is complaining about, at least.</p>
3
2009-10-05T22:27:15Z
[ "python", "ide", "python-idle" ]
how to apply "catch-all" exception clause to complex python web-scraping script?
1,522,823
<p>I've got a list of 100 websites in CSV format. All of the sites have the same general format, including a large table with 7 columns. I wrote this script to extract the data from the 7th column of each of the websites and then write this data to file. The script below partially works, however: opening the output file (after running the script) shows that something is being skipped because it only shows 98 writes (clearly the script also registers a number of exceptions). Guidance on how to implement a "catching exception" in this context would be much appreciated. Thank you! </p> <pre><code>import csv, urllib2, re def replace(variab): return variab.replace(",", " ") urls = csv.reader(open('input100.txt', 'rb')) #access list of 100 URLs for url in urls: html = urllib2.urlopen(url[0]).read() #get HTML starting with the first URL col7 = re.findall('td7.*?td', html) #use regex to get data from column 7 string = str(col7) #stringify data neat = re.findall('div3.*?div', string) #use regex to get target text result = map(replace, neat) #apply function to remove','s from elements string2 = ", ".join(result) #separate list elements with ', ' for export to csv output = open('output.csv', 'ab') #open file for writing output.write(string2 + '\n') #append output to file and create new line output.close() </code></pre> <p>Return:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\supertest3.py", line 6, in &lt;module&gt; html = urllib2.urlopen(url[0]).read() File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 383, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 401, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1130, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1103, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 950, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 390, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 354, in _read_status raise BadStatusLine(line) BadStatusLine &gt;&gt;&gt;&gt; </code></pre>
0
2009-10-05T22:53:39Z
1,522,837
<p>I'd recommend reading the <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">Errors and Exceptions</a> Python documentation, especially section 8.3 -- Handling Exceptions.</p>
1
2009-10-05T22:58:21Z
[ "python", "list", "exception-handling", "loops", "urllib2" ]
how to apply "catch-all" exception clause to complex python web-scraping script?
1,522,823
<p>I've got a list of 100 websites in CSV format. All of the sites have the same general format, including a large table with 7 columns. I wrote this script to extract the data from the 7th column of each of the websites and then write this data to file. The script below partially works, however: opening the output file (after running the script) shows that something is being skipped because it only shows 98 writes (clearly the script also registers a number of exceptions). Guidance on how to implement a "catching exception" in this context would be much appreciated. Thank you! </p> <pre><code>import csv, urllib2, re def replace(variab): return variab.replace(",", " ") urls = csv.reader(open('input100.txt', 'rb')) #access list of 100 URLs for url in urls: html = urllib2.urlopen(url[0]).read() #get HTML starting with the first URL col7 = re.findall('td7.*?td', html) #use regex to get data from column 7 string = str(col7) #stringify data neat = re.findall('div3.*?div', string) #use regex to get target text result = map(replace, neat) #apply function to remove','s from elements string2 = ", ".join(result) #separate list elements with ', ' for export to csv output = open('output.csv', 'ab') #open file for writing output.write(string2 + '\n') #append output to file and create new line output.close() </code></pre> <p>Return:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\supertest3.py", line 6, in &lt;module&gt; html = urllib2.urlopen(url[0]).read() File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout) File "C:\Python26\lib\urllib2.py", line 383, in open response = self._open(req, data) File "C:\Python26\lib\urllib2.py", line 401, in _open '_open', req) File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args) File "C:\Python26\lib\urllib2.py", line 1130, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python26\lib\urllib2.py", line 1103, in do_open r = h.getresponse() File "C:\Python26\lib\httplib.py", line 950, in getresponse response.begin() File "C:\Python26\lib\httplib.py", line 390, in begin version, status, reason = self._read_status() File "C:\Python26\lib\httplib.py", line 354, in _read_status raise BadStatusLine(line) BadStatusLine &gt;&gt;&gt;&gt; </code></pre>
0
2009-10-05T22:53:39Z
1,522,890
<p>Make the body of your <code>for</code> loop into:</p> <pre><code>for url in urls: try: ...the body you have now... except Exception, e: print&gt;&gt;sys.stderr, "Url %r not processed: error (%s) % (url, e) </code></pre> <p>(Or, use <code>logging.error</code> instead of the goofy <code>print&gt;&gt;</code>, if you're already using the <code>logging</code> module of the standard library [and you should;-)]).</p>
2
2009-10-05T23:19:37Z
[ "python", "list", "exception-handling", "loops", "urllib2" ]
flup/fastcgi cpu usage under no-load conditions
1,522,844
<p>I'm running Django as threaded fastcgi via flup, served by lighttpd, communicating via sockets.</p> <p>What is the expected CPU usage for each fastcgi thread under no load? On startup, each thread runs at 3-4% cpu usage for a while, and then backs off to around .5% over the course of a couple of hours. It doesn't sink below this level.</p> <p>Is this much CPU usage normal? Do I have some bug in my code that is causing the idle loop to require more processing than it should? I expected the process to use no measurable CPU when it was completely idle.</p> <p>I'm not doing anything ridiculously complicated with Django, definitely nothing that should require extended processing. I realize that this isn't a lot of load, but if it's a bug I introduced, I would like to fix it.</p>
1
2009-10-05T23:02:18Z
1,526,653
<p>Your fast-cgi threads must not consume any (noticeable) CPU if there are no requests to process.</p> <p>You should investigate the load you are describing. I use the same architecture and my threads are completely idle.</p>
0
2009-10-06T16:27:19Z
[ "python", "django", "fastcgi", "lighttpd", "flup" ]
flup/fastcgi cpu usage under no-load conditions
1,522,844
<p>I'm running Django as threaded fastcgi via flup, served by lighttpd, communicating via sockets.</p> <p>What is the expected CPU usage for each fastcgi thread under no load? On startup, each thread runs at 3-4% cpu usage for a while, and then backs off to around .5% over the course of a couple of hours. It doesn't sink below this level.</p> <p>Is this much CPU usage normal? Do I have some bug in my code that is causing the idle loop to require more processing than it should? I expected the process to use no measurable CPU when it was completely idle.</p> <p>I'm not doing anything ridiculously complicated with Django, definitely nothing that should require extended processing. I realize that this isn't a lot of load, but if it's a bug I introduced, I would like to fix it.</p>
1
2009-10-05T23:02:18Z
1,531,138
<p>I've looked at this on django running as fastcgi on both Slicehost (django 1.1, python 2.6) and Dreamhost (django 1.0, python 2.5), and I can say this:</p> <p>Running the <code>top</code> command shows the processes use a large amount of CPU to start up for ~2-3 seconds, then drop down to 0 almost immediately.</p> <p>Running the <code>ps aux</code> command after starting the django app shows something similar to what you describe, <strong>however</strong> this is actually misleading. From the Ubuntu man pages for ps:</p> <blockquote> <p>CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process. This is not ideal, and it does not conform to the standards that ps otherwise conforms to. CPU usage is unlikely to add up to exactly 100%.</p> </blockquote> <p>Basically, the %CPU column shown by <code>ps</code> is actually an <em>average</em> over the time the process has been running. The decay you see is due to the high initial spike followed by inactivity being averaged over time.</p>
2
2009-10-07T11:48:17Z
[ "python", "django", "fastcgi", "lighttpd", "flup" ]
python: how do you setup your workspace on Ubuntu?
1,522,867
<p>Lets say I have my workspace (on Eclipse) where I develop my Python modules and I would like to "link" my working files to system Python paths. I know I can drop .pth files etc. but I would like to get the community's wisdom as to the best practices.</p>
3
2009-10-05T23:10:22Z
1,523,307
<p>One thing you can try is creating a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtual environment</a> and then pointing pydev at the interpreter inside the virtual environment.</p> <pre><code>$ virtualenv --no-site-packages myProject $ cd myProject $ source bin/activate (myproject)$ </code></pre> <p>at that point you have a python interpreter that will reference libraries in ~/myProject/lib/python2.x/site-packages</p> <p>So in pydev in your workspace select ~/myProject/bin/python as your python interpreter. In this way you aren't infecting your system install of python, won't need root permissions to install stuff etc....</p> <p>Speaking of which, virtualenv sets up an "easy_install" bin so you can install whatever libs you need, again without infecting your system python install.</p> <pre><code>(myproject)$easy_install sqlalchemy paste pylons ipython sphinx #...download to win... </code></pre> <p>And if you do install paste, you can create package templates rather than doing it by hand like so...</p> <pre><code>(myproject)$ paster create mynewlib #...do stuff to win... (myproject)$ cd mynewlib (myproject)$ python setup.py develop #...puts links in your virtualenv site-packages but does not move the source (myproject)$ &lt;start hacking&gt; </code></pre> <p>Check out <a href="http://showmedo.com/videos/video?name=2910000&amp;fromSeriesID=291" rel="nofollow">this screencast series</a> on ShowMeDo, it helped me A LOT</p> <p>Hope that helps.</p>
1
2009-10-06T02:16:03Z
[ "python", "eclipse" ]
Update a gallery webpage via Dropbox?
1,522,951
<p>I'd like to know if the following situation and scripts are at all possible: </p> <p>I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?). </p> <p>That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that will check the Dropbox folder and then embed those images onto the webpage via the newest added and the webpage will automatically be updated. </p> <p>Is it at all possible to link to a Dropbox folder via a webpage? If so, how would I best go about using scripts to automate the process of updating the webpage with new content? </p> <p>Any and all help is very appreciated, thanks!</p>
2
2009-10-05T23:43:07Z
1,927,690
<p>You can try this : <a href="http://forums.dropbox.com/topic.php?id=15885" rel="nofollow">http://forums.dropbox.com/topic.php?id=15885</a></p>
1
2009-12-18T11:34:08Z
[ "php", "python", "html", "dropbox" ]
Update a gallery webpage via Dropbox?
1,522,951
<p>I'd like to know if the following situation and scripts are at all possible: </p> <p>I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?). </p> <p>That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that will check the Dropbox folder and then embed those images onto the webpage via the newest added and the webpage will automatically be updated. </p> <p>Is it at all possible to link to a Dropbox folder via a webpage? If so, how would I best go about using scripts to automate the process of updating the webpage with new content? </p> <p>Any and all help is very appreciated, thanks!</p>
2
2009-10-05T23:43:07Z
2,074,899
<p>If you can install the DropBox client on the webserver then it would be simple to let it sync your folder and then iterate over the contents of the folder with a programming language (PHP, Python, .NET etc) and produce the gallery page. This could be done every time the page is requested or as a scheduled job which recreayes a static page. This is all dependent on you having access to install the client on your server.</p>
2
2010-01-15T21:25:28Z
[ "php", "python", "html", "dropbox" ]
Update a gallery webpage via Dropbox?
1,522,951
<p>I'd like to know if the following situation and scripts are at all possible: </p> <p>I'm looking to have a photo-gallery (Javascript) webpage that will display in order of the latest added to the Dropbox folder (PHP or Python?). </p> <p>That is, when someone adds a picture to the Dropbox folder, there is a script on the webpage that will check the Dropbox folder and then embed those images onto the webpage via the newest added and the webpage will automatically be updated. </p> <p>Is it at all possible to link to a Dropbox folder via a webpage? If so, how would I best go about using scripts to automate the process of updating the webpage with new content? </p> <p>Any and all help is very appreciated, thanks!</p>
2
2009-10-05T23:43:07Z
2,950,259
<p>You can use the (alpha) tool <a href="http://github.com/berkes/autodrop" rel="nofollow">autodrop</a>, wich is just that: a simple gallery frontend that uses images in Dropbox.</p> <p>As said: alpha. I am still developing it, rewriting it and making it a little prettier and nicer. Written in Ruby, using dropbox, sinatra and HAML gems. So you will need a host that supports Ruby apps. </p>
0
2010-06-01T13:45:20Z
[ "php", "python", "html", "dropbox" ]
Python: List comprehension to assign different values
1,522,960
<p>I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this:</p> <pre><code>[[x for i in range(3) if j &lt;= 1: x=1 else x=2] for j in range(3)] </code></pre> <p>so it should return something like:</p> <pre><code>[[1,1,1], [1,1,1], [2,2,2]] </code></pre> <p>How might I go about doing this?</p> <p>Thanks for your help.</p>
7
2009-10-05T23:45:02Z
1,522,973
<p>It appears as though you're looking for something like this:</p> <pre><code>[[1 if j &lt;= 1 else 2 for i in range(3)] for j in range(3)] </code></pre> <p>The Python <a href="http://docs.python.org/reference/expressions.html#boolean-operations">conditional expression</a> is a bit different from what you might be used to if you're coming from something like C or Java:</p> <blockquote> <p>The expression <code>x if C else y</code> first evaluates <em>C</em> (<em>not x</em>); if <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is evaluated and its value is returned.</p> </blockquote> <p>A slightly shorter way to do the same thing is:</p> <pre><code>[[1 if j &lt;= 1 else 2]*3 for j in range(3)] </code></pre>
14
2009-10-05T23:49:46Z
[ "python", "list-comprehension" ]
Python: List comprehension to assign different values
1,522,960
<p>I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this:</p> <pre><code>[[x for i in range(3) if j &lt;= 1: x=1 else x=2] for j in range(3)] </code></pre> <p>so it should return something like:</p> <pre><code>[[1,1,1], [1,1,1], [2,2,2]] </code></pre> <p>How might I go about doing this?</p> <p>Thanks for your help.</p>
7
2009-10-05T23:45:02Z
1,522,986
<p>Greg's response is correct, though a much simpler and faster expression to produce your desired result would be</p> <pre><code>[[j] * 3 for j in (1, 1, 2)] </code></pre> <p>i.e., remember that <code>for</code> need not apply to a <code>range</code> only;-), list-multiplication exists, and so on;-).</p>
14
2009-10-05T23:55:08Z
[ "python", "list-comprehension" ]
Python: List comprehension to assign different values
1,522,960
<p>I'm making a 2D list and I would like to initialize it with a list comprehension. I would like it to do something like this:</p> <pre><code>[[x for i in range(3) if j &lt;= 1: x=1 else x=2] for j in range(3)] </code></pre> <p>so it should return something like:</p> <pre><code>[[1,1,1], [1,1,1], [2,2,2]] </code></pre> <p>How might I go about doing this?</p> <p>Thanks for your help.</p>
7
2009-10-05T23:45:02Z
1,522,988
<p>Try that</p> <pre><code>&gt;&gt;&gt; [[(1 if j&lt;1 else 2) for i in range(3)] for j in range(3)] [[1, 1, 1], [2, 2, 2], [2, 2, 2]] </code></pre> <p>The second time j=1 so j&lt;1 fails </p>
1
2009-10-05T23:55:33Z
[ "python", "list-comprehension" ]
python sax: is there a way to halt the parsing from inside a content handler?
1,523,225
<p>Is there a way to halt the parsing from inside a content handler? Or is throwing an exception the only way?</p> <p>Note that I am using <em>xml.sax.parseString</em>.</p>
3
2009-10-06T01:42:41Z
1,523,600
<p>The complete API for Python's SAX content handlers is documented <a href="http://docs.python.org/library/xml.sax.handler.html#contenthandler-objects" rel="nofollow">here</a>: as you can see, the information flow is entirely one-way, parser to handler -- no way for the handler to supply info back to the parser (such as whether the parse should be terminated).</p> <p>Therefore, as you had surmised and the commenters confirmed, "control-flow exceptions" are indeed the only way to achieve such a "premature termination". As the commenters mention, it's not too bad, after all.</p>
4
2009-10-06T04:32:39Z
[ "python", "sax" ]
How do I do this in Python? List to function
1,523,348
<pre><code>def getStuff(x): return 'stuff'+x def getData(x): return 'data'+x thefunctions = [] thefunctions.append("getStuff") thefunctions.append("getData") for i in thefunctions: print i('abc') </code></pre> <p>Is this possible? Thank you.</p>
2
2009-10-06T02:43:50Z
1,523,364
<pre><code>thefunctions = [ getStuff, getData ] for f in thefunctions: print f('shazam') </code></pre> <p>Once you've done a <code>def</code> statement, you've associated a name with a function. Just use that name to refer to the function.</p>
12
2009-10-06T02:50:44Z
[ "python" ]
Elegant way to skip first line when using python fileinput module?
1,523,378
<p>Is there an elegant way of skipping first line of file when using <code>python</code> fileinput module?</p> <p>I have data file with nicely formated data but the first line is header. Using <code>fileinput</code> I would have to include check and discard line if the line does not seem to contain data.</p> <p>The problem is that it would apply the same check for the rest of the file. With <code>read()</code> you can open file, read first line then go to loop over the rest of the file. Is there similar trick with <code>fileinput</code>?</p> <p>Is there an elegant way to skip processing of the first line?</p> <p>Example code:</p> <pre><code>import fileinput # how to skip first line elegantly? for line in fileinput.input(["file.dat"]): data = proces_line(line); output(data) </code></pre>
11
2009-10-06T02:57:43Z
1,523,395
<p>It's right in the docs: <a href="http://docs.python.org/library/fileinput.html#fileinput.isfirstline">http://docs.python.org/library/fileinput.html#fileinput.isfirstline</a></p>
5
2009-10-06T03:05:43Z
[ "python", "file-io" ]
Elegant way to skip first line when using python fileinput module?
1,523,378
<p>Is there an elegant way of skipping first line of file when using <code>python</code> fileinput module?</p> <p>I have data file with nicely formated data but the first line is header. Using <code>fileinput</code> I would have to include check and discard line if the line does not seem to contain data.</p> <p>The problem is that it would apply the same check for the rest of the file. With <code>read()</code> you can open file, read first line then go to loop over the rest of the file. Is there similar trick with <code>fileinput</code>?</p> <p>Is there an elegant way to skip processing of the first line?</p> <p>Example code:</p> <pre><code>import fileinput # how to skip first line elegantly? for line in fileinput.input(["file.dat"]): data = proces_line(line); output(data) </code></pre>
11
2009-10-06T02:57:43Z
1,523,396
<p>The <code>fileinput</code> module contains a bunch of handy functions, one of which seems to do exactly what you're looking for:</p> <pre><code>for line in fileinput.input(["file.dat"]): if not fileinput.isfirstline(): data = proces_line(line); output(data) </code></pre> <p><a href="http://docs.python.org/library/fileinput.html">fileinput module documentation</a></p>
15
2009-10-06T03:05:47Z
[ "python", "file-io" ]
Elegant way to skip first line when using python fileinput module?
1,523,378
<p>Is there an elegant way of skipping first line of file when using <code>python</code> fileinput module?</p> <p>I have data file with nicely formated data but the first line is header. Using <code>fileinput</code> I would have to include check and discard line if the line does not seem to contain data.</p> <p>The problem is that it would apply the same check for the rest of the file. With <code>read()</code> you can open file, read first line then go to loop over the rest of the file. Is there similar trick with <code>fileinput</code>?</p> <p>Is there an elegant way to skip processing of the first line?</p> <p>Example code:</p> <pre><code>import fileinput # how to skip first line elegantly? for line in fileinput.input(["file.dat"]): data = proces_line(line); output(data) </code></pre>
11
2009-10-06T02:57:43Z
1,523,466
<pre><code>lines = iter(fileinput.input(["file.dat"])) next(lines) # extract and discard first line for line in lines: data = proces_line(line) output(data) </code></pre> <p>or use the itertools.islice way if you prefer</p> <pre><code>import itertools finput = fileinput.input(["file.dat"]) lines = itertools.islice(finput, 1, None) # cuts off first line dataset = (process_line(line) for line in lines) results = [output(data) for data in dataset] </code></pre> <p>Since everything used are generators and iterators, no intermediate list will be built.</p>
14
2009-10-06T03:39:03Z
[ "python", "file-io" ]
What is the common header format of Python files?
1,523,427
<p>I came across the following header format for Python source files in a document about Python coding guidelines:</p> <pre><code>#!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" </code></pre> <p>Is this the standard format of headers in the Python world? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)</p>
270
2009-10-06T03:23:14Z
1,523,435
<p>Here's a good place to start: <a href="http://www.python.org/dev/peps/pep-0257/">PEP 257</a>, which talks about Docstrings, and links to several other relevant documents.</p>
15
2009-10-06T03:25:12Z
[ "python", "header", "comments" ]
What is the common header format of Python files?
1,523,427
<p>I came across the following header format for Python source files in a document about Python coding guidelines:</p> <pre><code>#!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" </code></pre> <p>Is this the standard format of headers in the Python world? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)</p>
270
2009-10-06T03:23:14Z
1,523,456
<p>Its all metadata for the <code>Foobar</code> module.</p> <p>The first one is the <code>docstring</code> of the module, that is already explained in <a href="http://stackoverflow.com/questions/1523427/python-what-is-the-common-header-format/1523435#1523435">Peter's answer</a>.</p> <blockquote> <h2><a href="http://web.archive.org/web/20111010053227/http://jaynes.colorado.edu/PythonGuidelines.html#module_formatting">How do I organize my modules (source files)? (Archive)</a></h2> <p><strong>The first line of each file shoud be <code>#!/usr/bin/env python</code>.</strong> This makes it possible to run the file as a script invoking the interpreter implicitly, e.g. in a CGI context.</p> <p><strong><em>Next should be the docstring with a description.</em></strong> If the description is long, the first line should be a short summary that makes sense on its own, separated from the rest by a newline.</p> <p><strong>All code, including import statements, should follow the docstring.</strong> Otherwise, the docstring will not be recognized by the interpreter, and you will not have access to it in interactive sessions (i.e. through <code>obj.__doc__</code>) or when generating documentation with automated tools.</p> <p><strong>Import built-in modules first, followed by third-party modules, followed by any changes to the path and your own modules.</strong> Especially, additions to the path and names of your modules are likely to change rapidly: keeping them in one place makes them easier to find.</p> <p><strong>Next should be authorship information.</strong> This information should follow this format:</p> <pre><code>__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell" __copyright__ = "Copyright 2007, The Cogent Project" __credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley", "Matthew Wakefield"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Rob Knight" __email__ = "rob@spot.colorado.edu" __status__ = "Production" </code></pre> <p>Status should typically be one of "Prototype", "Development", or "Production". <code>__maintainer__</code> should be the person who will fix bugs and make improvements if imported. <code>__credits__</code> differs from <code>__author__</code> in that <code>__credits__</code> includes people who reported bug fixes, made suggestions, etc. but did not actually write the code.</p> </blockquote> <p><a href="http://epydoc.sourceforge.net/manual-fields.html#module-metadata-variables">Here</a> you have more information, listing <code>__author__</code>, <code>__authors__</code>, <code>__contact__</code>, <code>__copyright__</code>, <code>__license__</code>, <code>__deprecated__</code>, <code>__date__</code> and <code>__version__</code> as recognized metadata.</p>
323
2009-10-06T03:34:00Z
[ "python", "header", "comments" ]
What is the common header format of Python files?
1,523,427
<p>I came across the following header format for Python source files in a document about Python coding guidelines:</p> <pre><code>#!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" </code></pre> <p>Is this the standard format of headers in the Python world? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)</p>
270
2009-10-06T03:23:14Z
1,523,621
<p>Also see <a href="http://www.python.org/dev/peps/pep-0263/">PEP 263</a> if you are using a non-ascii characterset</p> <blockquote> <h2>Abstract</h2> <p>This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.</p> <h2>Problem</h2> <p>In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding "unicode-escape". This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the "unicode-escape" encoding for Unicode literals.</p> <h2>Proposed Solution</h2> <p>I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.</p> <p>To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.</p> <h2>Defining the Encoding</h2> <p>Python will default to ASCII as standard encoding if no other encoding hints are given.</p> <p>To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:</p> <pre><code> # coding=&lt;encoding name&gt; </code></pre> <p>or (using formats recognized by popular editors)</p> <pre><code> #!/usr/bin/python # -*- coding: &lt;encoding name&gt; -*- </code></pre> <p>or</p> <pre><code> #!/usr/bin/python # vim: set fileencoding=&lt;encoding name&gt; : </code></pre> <p>...</p> </blockquote>
12
2009-10-06T04:39:28Z
[ "python", "header", "comments" ]
What is the common header format of Python files?
1,523,427
<p>I came across the following header format for Python source files in a document about Python coding guidelines:</p> <pre><code>#!/usr/bin/env python """Foobar.py: Description of what foobar does.""" __author__ = "Barack Obama" __copyright__ = "Copyright 2009, Planet Earth" </code></pre> <p>Is this the standard format of headers in the Python world? What other fields/information can I put in the header? Python gurus share your guidelines for good Python source headers :-)</p>
270
2009-10-06T03:23:14Z
9,225,336
<p>I strongly favour minimal file headers, by which I mean just:</p> <ul> <li>The hashbang (<code>#!</code> line) if this is an executable script</li> <li>Module docstring</li> <li>Imports, grouped as described in <strong>voyager</strong>’s answer.</li> </ul> <p>Everything else is a waste of time, visual space, and is actively misleading.</p> <p>If you have legal disclaimers or licencing info, it goes into a separate file. It does not need to infect every source code file. Your copyright should be part of this. People should be able to find it in your <code>LICENSE</code> file, not random source code.</p> <p>Metadata such as authorship and dates is already maintained by your source control. There is no need to add a less-detailed, erroneous, and out-of-date version of the same info in the file itself.</p> <p>I don't believe there is any other data that everyone needs to put into all their source files. You may have some particular requirement to do so, but such things apply, by definition, only to you. They have no place in “general headers recommended for everyone”.</p>
85
2012-02-10T09:13:33Z
[ "python", "header", "comments" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
1,523,477
<p>Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.</p>
3
2009-10-06T03:44:26Z
[ "python", "binary" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
1,523,478
<p>I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.</p> <p>If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.</p>
9
2009-10-06T03:44:47Z
[ "python", "binary" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
1,523,514
<p>If you're talking about bitwise operators, then you're after:</p> <pre><code>~ Not ^ XOR | Or &amp; And </code></pre> <p>Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.</p>
5
2009-10-06T03:54:33Z
[ "python", "binary" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
1,523,581
<p>You can convert between a string representation of the binary using bin() and int()</p> <pre><code>&gt;&gt;&gt; bin(88) '0b1011000' &gt;&gt;&gt; int('0b1011000', 2) 88 &gt;&gt;&gt; &gt;&gt;&gt; a=int('01100000', 2) &gt;&gt;&gt; b=int('00100110', 2) &gt;&gt;&gt; bin(a &amp; b) '0b100000' &gt;&gt;&gt; bin(a | b) '0b1100110' &gt;&gt;&gt; bin(a ^ b) '0b1000110' </code></pre>
65
2009-10-06T04:19:28Z
[ "python", "binary" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
33,672,372
<p>I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.</p>
-4
2015-11-12T13:19:29Z
[ "python", "binary" ]
Binary numbers in Python
1,523,465
<p>How can I add, subtract, and compare binary numbers in Python without converting to decimal?</p>
34
2009-10-06T03:37:55Z
37,560,399
<p>Not sure if helpful, but I leave my solution here:</p> <pre><code>class Solution: # @param A : string # @param B : string # @return a strings def addBinary(self, A, B): num1 = bin(int(A, 2)) num2 = bin(int(B, 2)) bin_str = bin(int(num1, 2)+int(num2, 2)) b_index = bin_str.index('b') return bin_str[b_index+1:] s = Solution() print(s.addBinary("11", "100")) </code></pre>
0
2016-06-01T05:49:03Z
[ "python", "binary" ]
.vimrc configuration for Python
1,523,482
<p>My current .vimrc configuration is below:</p> <pre><code>set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:&gt;-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on set listchars=tab:&gt;- set listchars+=trail:. set ignorecase set smartcase map &lt;C-t&gt;&lt;up&gt; :tabr&lt;cr&gt; map &lt;C-t&gt;&lt;down&gt; :tabl&lt;cr&gt; map &lt;C-t&gt;&lt;left&gt; :tabp&lt;cr&gt; map &lt;C-t&gt;&lt;right&gt; :tabn&lt;cr&gt; </code></pre> <p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p>
18
2009-10-06T03:45:54Z
1,523,512
<p>The short answer is that your autocmd is missing the BufEnter trigger, so it isn't being fired when you create a new file. Try this instead:</p> <pre><code> au BufEnter,BufRead *.py setlocal smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class </code></pre> <p>Note that I also changed the <code>set</code> to <code>setlocal</code>. This'll prevent these options from stomping on your other buffers' options.</p> <p>The "right" way to do what you're trying to do is to add <code>filetype indent on</code> to your .vimrc. This'll turn on the built-in filetype based indentation. Vim comes with Python indentation support. See <code>:help filetype-indent-on</code> for more info.</p>
12
2009-10-06T03:54:16Z
[ "python", "vim" ]
.vimrc configuration for Python
1,523,482
<p>My current .vimrc configuration is below:</p> <pre><code>set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:&gt;-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on set listchars=tab:&gt;- set listchars+=trail:. set ignorecase set smartcase map &lt;C-t&gt;&lt;up&gt; :tabr&lt;cr&gt; map &lt;C-t&gt;&lt;down&gt; :tabl&lt;cr&gt; map &lt;C-t&gt;&lt;left&gt; :tabp&lt;cr&gt; map &lt;C-t&gt;&lt;right&gt; :tabn&lt;cr&gt; </code></pre> <p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p>
18
2009-10-06T03:45:54Z
1,523,519
<p>Try this:</p> <pre><code>filetype indent on filetype on filetype plugin on </code></pre> <p>I primarily do Python programming and this is the brunt of my vimrc</p> <pre><code>set nobackup set nowritebackup set noswapfile set lines=40 set columns=80 set tabstop=4 set shiftwidth=4 set softtabstop=4 set autoindent set smarttab filetype indent on filetype on filetype plugin on </code></pre>
13
2009-10-06T03:56:30Z
[ "python", "vim" ]
.vimrc configuration for Python
1,523,482
<p>My current .vimrc configuration is below:</p> <pre><code>set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:&gt;-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on set listchars=tab:&gt;- set listchars+=trail:. set ignorecase set smartcase map &lt;C-t&gt;&lt;up&gt; :tabr&lt;cr&gt; map &lt;C-t&gt;&lt;down&gt; :tabl&lt;cr&gt; map &lt;C-t&gt;&lt;left&gt; :tabp&lt;cr&gt; map &lt;C-t&gt;&lt;right&gt; :tabn&lt;cr&gt; </code></pre> <p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p>
18
2009-10-06T03:45:54Z
1,524,853
<p>You shouldn't have to explicitly indent python keywords. The $VIM/indent/python.vim file takes care of that. You just need to turn on filetype indent and autoindent. </p>
4
2009-10-06T10:46:42Z
[ "python", "vim" ]
.vimrc configuration for Python
1,523,482
<p>My current .vimrc configuration is below:</p> <pre><code>set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:&gt;-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on set listchars=tab:&gt;- set listchars+=trail:. set ignorecase set smartcase map &lt;C-t&gt;&lt;up&gt; :tabr&lt;cr&gt; map &lt;C-t&gt;&lt;down&gt; :tabl&lt;cr&gt; map &lt;C-t&gt;&lt;left&gt; :tabp&lt;cr&gt; map &lt;C-t&gt;&lt;right&gt; :tabn&lt;cr&gt; </code></pre> <p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p>
18
2009-10-06T03:45:54Z
9,606,530
<p>Consider having a look at the official .vimrc for following PEP 7 &amp; 8 conventions. Present over here</p> <p><a href="http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc" rel="nofollow">http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc</a></p>
2
2012-03-07T17:44:16Z
[ "python", "vim" ]
.vimrc configuration for Python
1,523,482
<p>My current .vimrc configuration is below:</p> <pre><code>set nohlsearch set ai set bg=dark set showmatch highlight SpecialKey ctermfg=DarkGray set listchars=tab:&gt;-,trail:~ set list autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class set tabstop=4 set shiftwidth=4 set expandtab set autoindent set smartindent syntax on set listchars=tab:&gt;- set listchars+=trail:. set ignorecase set smartcase map &lt;C-t&gt;&lt;up&gt; :tabr&lt;cr&gt; map &lt;C-t&gt;&lt;down&gt; :tabl&lt;cr&gt; map &lt;C-t&gt;&lt;left&gt; :tabp&lt;cr&gt; map &lt;C-t&gt;&lt;right&gt; :tabn&lt;cr&gt; </code></pre> <p>However, when I write python scripts, when I push "ENTER", it will go to the BEGINNING of the next line. What do I add so that it will auto-tab for me?</p>
18
2009-10-06T03:45:54Z
17,102,397
<p>I (simply) use this:</p> <pre><code>set shiftwidth=4 set tabstop=4 set expandtab filetype plugin on filetype indent on syntax on </code></pre>
3
2013-06-14T06:29:46Z
[ "python", "vim" ]
Python module search path problem
1,523,551
<p>I am trying to work on a dev environment but am find problems in that python seems to be using modules from the site-packages directory. I want it to be using the modules from my dev directory.</p> <p>sys.path returns a bunch of dirs, like this</p> <pre><code>['', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/site-packages' etc </code></pre> <p>This is good, it's using the current directory as the first place of lookup (at least this is how I understand it to be).</p> <p>Ok now if I create say a file called command.py in the current directory, things work as I would expect them.</p> <pre><code>&gt;&gt;&gt; import commands &gt;&gt;&gt; commands.__file__ 'commands.pyc' </code></pre> <p>I then exit out of the python shell, and start another one. I then do this.</p> <pre><code>&gt;&gt;&gt; import foo.bar.commands </code></pre> <p>Now, what I'm expecting it to do is go down from the current directory to ./foo/bar/ and get me the commands module from there. What I get though is this</p> <pre><code>&gt;&gt;&gt; foo.bar.commands.__file__ '/usr/lib/python2.6/site-packages/foo/bar/commands.pyc' </code></pre> <p>Even though from my current directory there is a ./foo/bar/commands.py</p> <p>Using imp.find_module() and imp.load_module() I can load the local module properly. Whats actually interesting (although I don't really know what it means) is the last line that is printed out in this sequence</p> <pre><code>&gt;&gt;&gt; import foo.bar.commands &gt;&gt;&gt; foo.bar.commands.__file__ '/usr/lib/python2.6/site-packages/foo/bar/commands.pyc' &gt;&gt;&gt; foo.bar.__file__ '/usr/lib/python2.6/site-packages/foo/bar/__int__.pyc' &gt;&gt;&gt; foo.__file__ './foo/__init__.pyc' </code></pre> <p>So if it can find the foo/<strong>init</strong>.pyc in the local dir why can't it find the other files in the local dir?</p> <p>Cheers</p>
2
2009-10-06T04:06:18Z
1,523,624
<p>You mention that there's a <code>foo</code> directory under your current directory, but you don't tell us whether <code>foo/__init__.py</code> exists (even possibly empty): if it doesn't, this tells Python that <code>foo</code> is <strong>not</strong> a package. Similarly for <code>foo/bar/__init__.py</code> -- if that file doesn't exist, even if <code>foo/__init__.py</code> does, then <code>foo.bar</code> is not a package.</p> <p>You can play around a little by placing <code>.pth</code> files and/or setting <code>__path__</code> explicitly in your packages, but the basic, simple rule is to just place an <code>__init__.py</code> in every directory that you want Python to recognize as a package. The contents of that file are "the body" of the package itself, so if you <code>import foo</code> and <code>foo</code> is a directory with a <code>foo/__init__.py</code> file, then that's what you're importing (in any case, the package's body executes the first time you import anything from the package or any subpackage thereof).</p> <p>If that is not the problem, it looks like some other import (or explicit sys.path manipulation) may be messing you up. Running python with a <code>-v</code> flag makes imports highly visible, which can help. Another good technique is to place an</p> <pre><code>import pdb; pdb.set_trace() </code></pre> <p>just before the import that you think is misbehaving, and examining sys.path, sys.modules (and possibly other advanced structures such as import hooks) at that point - is there a sys.modules['foo'] already defined, for example? Interactively trying the functions from standard library module <code>imp</code> that locate modules on your behalf given a path may also prove instructive.</p>
3
2009-10-06T04:40:06Z
[ "python", "search", "path", "module" ]
Python module search path problem
1,523,551
<p>I am trying to work on a dev environment but am find problems in that python seems to be using modules from the site-packages directory. I want it to be using the modules from my dev directory.</p> <p>sys.path returns a bunch of dirs, like this</p> <pre><code>['', '/usr/lib/python26.zip', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/site-packages' etc </code></pre> <p>This is good, it's using the current directory as the first place of lookup (at least this is how I understand it to be).</p> <p>Ok now if I create say a file called command.py in the current directory, things work as I would expect them.</p> <pre><code>&gt;&gt;&gt; import commands &gt;&gt;&gt; commands.__file__ 'commands.pyc' </code></pre> <p>I then exit out of the python shell, and start another one. I then do this.</p> <pre><code>&gt;&gt;&gt; import foo.bar.commands </code></pre> <p>Now, what I'm expecting it to do is go down from the current directory to ./foo/bar/ and get me the commands module from there. What I get though is this</p> <pre><code>&gt;&gt;&gt; foo.bar.commands.__file__ '/usr/lib/python2.6/site-packages/foo/bar/commands.pyc' </code></pre> <p>Even though from my current directory there is a ./foo/bar/commands.py</p> <p>Using imp.find_module() and imp.load_module() I can load the local module properly. Whats actually interesting (although I don't really know what it means) is the last line that is printed out in this sequence</p> <pre><code>&gt;&gt;&gt; import foo.bar.commands &gt;&gt;&gt; foo.bar.commands.__file__ '/usr/lib/python2.6/site-packages/foo/bar/commands.pyc' &gt;&gt;&gt; foo.bar.__file__ '/usr/lib/python2.6/site-packages/foo/bar/__int__.pyc' &gt;&gt;&gt; foo.__file__ './foo/__init__.pyc' </code></pre> <p>So if it can find the foo/<strong>init</strong>.pyc in the local dir why can't it find the other files in the local dir?</p> <p>Cheers</p>
2
2009-10-06T04:06:18Z
1,524,108
<p>What is foo doing in /usr/lib/python2.6/site-packages? It sounds like you have created foo in your local directory but that is not necessarily the one you are importing.</p> <p>Try getting rid of the foo/bar in site-packages</p> <p>Make sure your directory structure looks like this</p> <pre><code>/foo/__init__.py /bar/__init__.py /commands.py </code></pre> <p>Also, it is a good idea to not reuse python standard library names for your own modules -- can you call your commands.py something else?</p>
0
2009-10-06T07:39:04Z
[ "python", "search", "path", "module" ]
BioPython: Skipping over bad GIDs with Entrez.esummary/Entrez.read
1,523,571
<p>Sorry about the odd title.</p> <p>I am using eSearch &amp; eSummary to go from </p> <p>Accession Number --> gID --> TaxID</p> <p>Assume that 'accessions' is a list of 20 accession numbers (I do 20 at a time because that's the maximum that NCBI will allow).</p> <p>I do:</p> <pre><code>handle = Entrez.esearch(db="nucleotide", rettype="xml", term=accessions) record = Entrez.read(handle) gids = ",".join(record[u'IdList']) </code></pre> <p>This gives me 20 correspoding GIDs from those 20 accession numbers.</p> <p>Followed by:</p> <pre><code>handle = Entrez.esummary(db="nucleotide", id=gids) record = Entrez.read(handle) </code></pre> <p>Which gives me this error because one of the GIDs in gids has been removed from NCBI:</p> <pre><code>File ".../biopython-1.52/build/lib.macosx-10.6-universal-2.6/Bio/Entrez/Parser.py", line 191, in endElement value = IntegerElement(value) ValueError: invalid literal for int() with base 10: '' </code></pre> <p>I could do try:, except: except that would skip the other 19 GIDs which are okay.</p> <p>My question is:</p> <p>How do I read 20 records at a time with Entrez.read and skip over the ones that are missing without sacrificing the other 20? I could do one at a time but that would be incredibly slow (I have 300,000 accession numbers, and NCBI only allows you to do 3 queries per second but in reality it's more like 1 query per second).</p>
3
2009-10-06T04:15:15Z
1,523,590
<p>I'd have a look at Parser.py and see what is being parsed. It looks like you are getting a result from the NCBI ok, but the format of one record is tripping up the parser.</p> <p>It may be possible to subclass/monkeypatch the parser to get it past the exception.</p>
0
2009-10-06T04:24:01Z
[ "python", "bioinformatics", "biopython" ]
BioPython: Skipping over bad GIDs with Entrez.esummary/Entrez.read
1,523,571
<p>Sorry about the odd title.</p> <p>I am using eSearch &amp; eSummary to go from </p> <p>Accession Number --> gID --> TaxID</p> <p>Assume that 'accessions' is a list of 20 accession numbers (I do 20 at a time because that's the maximum that NCBI will allow).</p> <p>I do:</p> <pre><code>handle = Entrez.esearch(db="nucleotide", rettype="xml", term=accessions) record = Entrez.read(handle) gids = ",".join(record[u'IdList']) </code></pre> <p>This gives me 20 correspoding GIDs from those 20 accession numbers.</p> <p>Followed by:</p> <pre><code>handle = Entrez.esummary(db="nucleotide", id=gids) record = Entrez.read(handle) </code></pre> <p>Which gives me this error because one of the GIDs in gids has been removed from NCBI:</p> <pre><code>File ".../biopython-1.52/build/lib.macosx-10.6-universal-2.6/Bio/Entrez/Parser.py", line 191, in endElement value = IntegerElement(value) ValueError: invalid literal for int() with base 10: '' </code></pre> <p>I could do try:, except: except that would skip the other 19 GIDs which are okay.</p> <p>My question is:</p> <p>How do I read 20 records at a time with Entrez.read and skip over the ones that are missing without sacrificing the other 20? I could do one at a time but that would be incredibly slow (I have 300,000 accession numbers, and NCBI only allows you to do 3 queries per second but in reality it's more like 1 query per second).</p>
3
2009-10-06T04:15:15Z
1,531,787
<p>I sent a message out to the BioPython mailing list.Apparently it's a bug &amp; they're working on it.</p>
3
2009-10-07T13:52:55Z
[ "python", "bioinformatics", "biopython" ]
redirect() Not Actually Redirecting (Routes for Pylons)
1,523,613
<p>I am constructing a table of routes in my Pylons app. I can't get redirect() to work the way that it should work. I'm not sure what I'm doing wrong. </p> <p>Here is an example of redirect() usage from the <a href="http://routes.groovie.org/manual.html#redirect-routes" rel="nofollow">Routes documentation</a>:</p> <pre><code>map.redirect("/home/index", "/", _redirect_code="301 Moved Permanently") </code></pre> <p>Here is what appears in my routing.py file:</p> <pre><code>map.redirect("/view", "/", _redirect_code="301 Moved Permanently") </code></pre> <p>Here is a route using redirect() that appears at the end of my routing.py file:</p> <pre><code>map.redirect('/*(url)/', '/{url}', _redirect_code="301 Moved Permanently") </code></pre> <p>This route works just fine, so I know that redirect() is present and functional. Therefore, I am doing something wrong in the /view redirect. I know this because when I point my browser at /view, I get the 404 page instead of getting redirected. Going to / works just fine, so I don't think that the problem is there, either. I think that redirect() in Routes is a great idea and I would like to be able to use it as intended, but I'm not sure what I'm doing wrong here.</p> <p>ETA @jasonjs: I believe that no other route matches. When I try to access /view and then look at Paster's output, here's what I get:</p> <pre><code>21:22:26,276 DEBUG [routes.middleware] No route matched for GET /view </code></pre> <p>which seems pretty conclusive to me. I should mention that there is a route that matches POST requests to /view:</p> <pre><code>map.connect('/view', controller='view', action='search', conditions=dict(method=['POST']) </code></pre> <p>That route also works correctly, and I have it listed earlier in routing.py so that it tries to match that before it tries to match the /view[GET] route. </p>
1
2009-10-06T04:36:54Z
1,526,917
<p>That syntax works, so there must be something else going on.</p> <p>Routes is sensitive to order. Is there another route above the redirect that would match <code>/view</code> to a controller that would return a 404?</p> <p>Routes is also sensitive to trailing slashes. Did you accidentally type a trailing slash in the browser but not in the route, or vice versa?</p> <p>Finally, in <code>development.ini</code>, if you set <code>level = DEBUG</code> under <code>[logger_routes]</code>, you can then check the log messages after visiting <code>/view</code> to see what was matched.</p> <p>ETA: I just tried putting a POST-matching rule before a redirect for the same path, and it worked as expected. Are you on the latest Routes version (1.11)? Otherwise I don't have anything else for you, not being able to see code. It may just be a matter of starting with a barebones test case and building up until it breaks, or taking things away until it works...</p>
1
2009-10-06T17:16:19Z
[ "python", "routes", "pylons" ]
How to disable URL redirection in Python when using M2Crypto SSL?
1,523,654
<p>This is what my code looks like:</p> <pre><code>url_object = urlparse(url) hostname = url_object.hostname port = url_object.port uri = url_object.path if url_object.path else '/' ctx = SSL.Context() if ctx.load_verify_locations(cafile='ca-bundle.crt') != 1: raise Exception("Could not load CA certificates.") ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=5) c = httpslib.HTTPSConnection(hostname, port, ssl_context=ctx) c.request('GET', uri) data = c.getresponse().read() c.close() return data </code></pre> <p>How can I disable url redirection in this code? I am hoping there would be some way of setting this option on connection object 'c' in the above code.</p> <p>Thanks in advance for the help.</p>
0
2009-10-06T04:52:37Z
1,526,647
<p>httpslib.HTTPSConnection does not redirect automatically. Like Lennart says in the comment, it subclasses from httplib.HTTPConnection which does not redirect either. It is easy to test with httplib:</p> <pre><code>import httplib c = httplib.HTTPConnection('www.heikkitoivonen.net', 80) c.request('GET', '/deadwinter/disclaimer.html') data = c.getresponse().read() c.close() print data </code></pre> <p>This prints:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"&gt; &lt;html&gt;&lt;head&gt; &lt;title&gt;301 Moved Permanently&lt;/title&gt; &lt;/head&gt;&lt;body&gt; &lt;h1&gt;Moved Permanently&lt;/h1&gt; &lt;p&gt;The document has moved &lt;a href="http://www.heikkitoivonen.net/deadwinter/copyright.html"&gt;here&lt;/a&gt;.&lt;/p&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>You have to handle redirects yourself with http(s)lib, see for example the request function in <a href="http://svn.osafoundation.org/server/cosmo/trunk/cosmo/src/test/functional/silmut/silmut.py" rel="nofollow">silmut</a> (a simple test framework I wrote a while back).</p>
0
2009-10-06T16:25:22Z
[ "python", "url", "redirect", "m2crypto" ]
How to print a list in Python "nicely"
1,523,660
<p>In PHP, I can do this:</p> <pre><code>echo '&lt;pre&gt;' print_r($array); echo '&lt;/pre&gt;' </code></pre> <p>In Python, I currently just do this:</p> <pre><code>print the_list </code></pre> <p>However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?</p>
20
2009-10-06T04:55:40Z
1,523,664
<pre><code>from pprint import pprint pprint(the_list) </code></pre>
47
2009-10-06T04:57:49Z
[ "python" ]
How to print a list in Python "nicely"
1,523,660
<p>In PHP, I can do this:</p> <pre><code>echo '&lt;pre&gt;' print_r($array); echo '&lt;/pre&gt;' </code></pre> <p>In Python, I currently just do this:</p> <pre><code>print the_list </code></pre> <p>However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?</p>
20
2009-10-06T04:55:40Z
1,523,674
<p>You mean something like...:</p> <pre><code>&gt;&gt;&gt; print L ['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it'] &gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(L) ['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it'] &gt;&gt;&gt; </code></pre> <p>...? From your cursory description, standard library module <a href="http://docs.python.org/library/pprint.html">pprint</a> is the first thing that comes to mind; however, if you can describe example inputs and outputs (so that one doesn't have to learn PHP in order to help you;-), it may be possible for us to offer more specific help!</p>
16
2009-10-06T05:02:42Z
[ "python" ]
How to print a list in Python "nicely"
1,523,660
<p>In PHP, I can do this:</p> <pre><code>echo '&lt;pre&gt;' print_r($array); echo '&lt;/pre&gt;' </code></pre> <p>In Python, I currently just do this:</p> <pre><code>print the_list </code></pre> <p>However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?</p>
20
2009-10-06T04:55:40Z
28,928,248
<p>A quick hack while debugging that works without having to import <code>pprint</code> would be to join the list on <code>'\n'</code>.</p> <pre><code>&gt;&gt;&gt; lst = ['foo', 'bar', 'spam', 'egg'] &gt;&gt;&gt; print '\n'.join(lst) foo bar spam egg </code></pre>
4
2015-03-08T15:35:46Z
[ "python" ]
How to print a list in Python "nicely"
1,523,660
<p>In PHP, I can do this:</p> <pre><code>echo '&lt;pre&gt;' print_r($array); echo '&lt;/pre&gt;' </code></pre> <p>In Python, I currently just do this:</p> <pre><code>print the_list </code></pre> <p>However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?</p>
20
2009-10-06T04:55:40Z
34,240,753
<p><a href="https://docs.python.org/3/library/pprint.html" rel="nofollow">https://docs.python.org/3/library/pprint.html</a></p> <p>If you need the text (for using with curses for example):</p> <pre><code>import pprint myObject = [] myText = pprint.pformat(myObject) </code></pre> <p>Then <code>myText</code> variable will something alike php <code>var_dump</code> or <code>print_r</code>. Check the documentation for more options, arguments.</p>
1
2015-12-12T14:08:13Z
[ "python" ]
How to print a list in Python "nicely"
1,523,660
<p>In PHP, I can do this:</p> <pre><code>echo '&lt;pre&gt;' print_r($array); echo '&lt;/pre&gt;' </code></pre> <p>In Python, I currently just do this:</p> <pre><code>print the_list </code></pre> <p>However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?</p>
20
2009-10-06T04:55:40Z
35,211,376
<p>Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator.</p> <p><strong>print(*lst, sep='\n')</strong></p> <pre><code>lst = ['foo', 'bar', 'spam', 'egg'] print(*lst, sep='\n') foo bar spam egg </code></pre>
0
2016-02-04T20:51:11Z
[ "python" ]
An ALGORITHM to create one list from "X" nested lists in Python
1,523,675
<p>What is the simplest way to create this list in Python?</p> <p>First, suppose I have this nested list:</p> <pre><code>oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] </code></pre> <p>I want a function to spit out:</p> <pre><code>newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] </code></pre> <p>Well, this could be done manually. However, what if there are <strong>three nested</strong>? ...<strong>X nested</strong></p> <p>Tricky? :)</p>
0
2009-10-06T05:03:39Z
1,523,693
<p><a href="http://www.daniel-lemire.com/blog/archives/2006/05/10/flattening-lists-in-python/" rel="nofollow">http://www.daniel-lemire.com/blog/archives/2006/05/10/flattening-lists-in-python/</a></p> <p>from that link (with a couple minor changes:</p> <pre><code>def flatten(l): if isinstance(l, list): return sum(map(flatten,l),[]) else: return [l] </code></pre>
2
2009-10-06T05:07:30Z
[ "python" ]
An ALGORITHM to create one list from "X" nested lists in Python
1,523,675
<p>What is the simplest way to create this list in Python?</p> <p>First, suppose I have this nested list:</p> <pre><code>oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] </code></pre> <p>I want a function to spit out:</p> <pre><code>newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] </code></pre> <p>Well, this could be done manually. However, what if there are <strong>three nested</strong>? ...<strong>X nested</strong></p> <p>Tricky? :)</p>
0
2009-10-06T05:03:39Z
1,523,711
<p>The <a href="http://oreilly.com/catalog/9780596007973" rel="nofollow"><strong>Python Cookbook</strong></a> Martelli, Ravenscroft and Asher 2005 O'Reilley also offers a solution to this flattening problem.<br> See <em>4.6 Flattening a nested sequence.</em><br> This solution uses generators which can be a good thing if the lists are long.<br> Also, this solution deals equaly well with lists or tuples.</p> <p>Note: Oops... I rushed a bit. I'm unsure of the legality of reproducing this snippet here... let me look for policy / precedents in this area.</p> <p><strong>Edit:</strong> later found reference as a Google Books preview.</p> <p>Here's a link to this section of the book in <a href="http://books.google.com/books?id=Q0s6Vgb98CQC&amp;pg=PA157&amp;dq=%22flattening+a+Nested+Sequence%22+%2Bproblem&amp;lr=#v=onepage&amp;q=%22flattening%20a%20Nested%20Sequence%22%20%2Bproblem&amp;f=false" rel="nofollow">Google books</a></p>
0
2009-10-06T05:15:57Z
[ "python" ]
An ALGORITHM to create one list from "X" nested lists in Python
1,523,675
<p>What is the simplest way to create this list in Python?</p> <p>First, suppose I have this nested list:</p> <pre><code>oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] </code></pre> <p>I want a function to spit out:</p> <pre><code>newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] </code></pre> <p>Well, this could be done manually. However, what if there are <strong>three nested</strong>? ...<strong>X nested</strong></p> <p>Tricky? :)</p>
0
2009-10-06T05:03:39Z
1,523,726
<p>Recursive solutions are simplest, but limited to at most a few thousand levels of nesting before you get an exception about too-deep recursion. For real generality, you can eliminate recursion by keeping your own stack; iterators are good things to keep on said stack, and the whole function's best written as a generator (just call <code>list(flatten(thelist))</code> if you really want a huge list result).</p> <pre><code>def flatten(alist): stack = [iter(alist)] while stack: current = stack.pop() for item in current: if isinstance(item, list): stack.append(current) stack.append(iter(item)) break yield item </code></pre> <p>Now <em>this</em> should let you handle as many levels of nesting as you have virtual memory for;-).</p>
4
2009-10-06T05:20:18Z
[ "python" ]
An ALGORITHM to create one list from "X" nested lists in Python
1,523,675
<p>What is the simplest way to create this list in Python?</p> <p>First, suppose I have this nested list:</p> <pre><code>oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] </code></pre> <p>I want a function to spit out:</p> <pre><code>newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] </code></pre> <p>Well, this could be done manually. However, what if there are <strong>three nested</strong>? ...<strong>X nested</strong></p> <p>Tricky? :)</p>
0
2009-10-06T05:03:39Z
1,523,978
<p>I prefer Alex Martelli's post as usual. Just want to add a not recommended trick: </p> <pre><code>from Tkinter import _flatten print _flatten(oldList) </code></pre>
0
2009-10-06T06:51:19Z
[ "python" ]
An ALGORITHM to create one list from "X" nested lists in Python
1,523,675
<p>What is the simplest way to create this list in Python?</p> <p>First, suppose I have this nested list:</p> <pre><code>oldList = [ [{'letter':'a'}], [{'letter':'b'}], [{'letter':'c'}] ] </code></pre> <p>I want a function to spit out:</p> <pre><code>newList = [ {'letter':a}, {'letter':'b'}, {'letter':'c'} ] </code></pre> <p>Well, this could be done manually. However, what if there are <strong>three nested</strong>? ...<strong>X nested</strong></p> <p>Tricky? :)</p>
0
2009-10-06T05:03:39Z
1,524,950
<p>The simplest answer is this</p> <p><strong>Only you can prevent nested lists</strong></p> <p>Do not create a list of lists using <code>append</code>. Create a flat list using <code>extend</code>. </p>
1
2009-10-06T11:06:42Z
[ "python" ]
Werkzeug in General, and in Python 3.1
1,523,706
<p>I've been looking really hard at all of the way**(s)** one can develop web applications using Python. For reference, we are using RHEL 64bit, apache, mod_wsgi.</p> <p><strong>History:</strong></p> <ol> <li>PHP + MySQL <sup>years ago</sup></li> <li>PHP + Python 2.x + MySQL <sup>recently and current</sup></li> <li>Python + PostgreSQL <sup>working on it</sup></li> </ol> <p>We use a great library for communicating between PHP and Python (interface in PHP, backend in Python)... However, with a larger upcoming project starting, using 100% python may be very advantagous.</p> <p>We typically prefer not to have a monolithic framework dictating how things are done. A collection of useful helpers and utilities are much preferred (be it PHP or Python).</p> <p><strong>Question 1:</strong></p> <p>In reading a number of answers from experienced Python users, I've seen <strong>Werkzeug</strong> recommended a number of times. I would love it if several people with direct experience using Werkzeug to develop professional web applications could comment (in as much detail as their fingers feel like) why they use it, why they like it, and anything to watch out for.</p> <p><strong>Question 2:</strong></p> <p>Is there a version of Werkzeug that supports Python 3.1.1. I've succefully installed <strong>mod_wsgi</strong> on Apache 2.2 with Python 3.1.1.</p> <p>If there is not a version, what would it take to upgrade it to work on Python 3.1?</p> <p>Note: I've run <code>2to3</code> on the Werkzeug source code, and it does python-compile without </p> <h2>Edit:</h2> <p>The project that we are starting is not slated to be finished until nearly a year from now. At which point, I'm guessing Python 3.X will be a lot more mainstream. Furthermore, considering that we are running the App (not distributing it), can anyone comment on the viability of bashing through some of the Python 3 issues now, so that when a year from now arrives, we are more-or-less already there?</p> <p>Thoughts appreciated!</p>
2
2009-10-06T05:13:48Z
1,523,934
<p>I haven't used Werkzeug, so I can only answer question 2:</p> <p>No, Werkzeug does not work on Python 3. In fact, very little works on Python 3 as of today. Porting is not difficult, but you can't port until all your third-party libraries have been ported, so progress is slow.</p> <p>One big stopper has been setuptools, which is a very popular package to use. Setuptools is unmaintained, but there is a maintained fork called Distribute. Distribute was released with Python 3 support just a week or two ago. I hope package support for Python 3 will pick up now. But it will still be a long time, at least months probably a year or so, before any major project like Werkzeug will be ported to Python 3.</p>
1
2009-10-06T06:36:32Z
[ "python", "python-3.x", "werkzeug" ]
Werkzeug in General, and in Python 3.1
1,523,706
<p>I've been looking really hard at all of the way**(s)** one can develop web applications using Python. For reference, we are using RHEL 64bit, apache, mod_wsgi.</p> <p><strong>History:</strong></p> <ol> <li>PHP + MySQL <sup>years ago</sup></li> <li>PHP + Python 2.x + MySQL <sup>recently and current</sup></li> <li>Python + PostgreSQL <sup>working on it</sup></li> </ol> <p>We use a great library for communicating between PHP and Python (interface in PHP, backend in Python)... However, with a larger upcoming project starting, using 100% python may be very advantagous.</p> <p>We typically prefer not to have a monolithic framework dictating how things are done. A collection of useful helpers and utilities are much preferred (be it PHP or Python).</p> <p><strong>Question 1:</strong></p> <p>In reading a number of answers from experienced Python users, I've seen <strong>Werkzeug</strong> recommended a number of times. I would love it if several people with direct experience using Werkzeug to develop professional web applications could comment (in as much detail as their fingers feel like) why they use it, why they like it, and anything to watch out for.</p> <p><strong>Question 2:</strong></p> <p>Is there a version of Werkzeug that supports Python 3.1.1. I've succefully installed <strong>mod_wsgi</strong> on Apache 2.2 with Python 3.1.1.</p> <p>If there is not a version, what would it take to upgrade it to work on Python 3.1?</p> <p>Note: I've run <code>2to3</code> on the Werkzeug source code, and it does python-compile without </p> <h2>Edit:</h2> <p>The project that we are starting is not slated to be finished until nearly a year from now. At which point, I'm guessing Python 3.X will be a lot more mainstream. Furthermore, considering that we are running the App (not distributing it), can anyone comment on the viability of bashing through some of the Python 3 issues now, so that when a year from now arrives, we are more-or-less already there?</p> <p>Thoughts appreciated!</p>
2
2009-10-06T05:13:48Z
1,525,943
<p>mod_wsgi for Python 3.x is also not ready. There is no satisfactory definition of WSGI for Python 3.x yet; the WEB-SIG are still bashing out the issues. mod_wsgi targets a guess at what might be in it, but there are very likely to be changes to both the spec and to standard libraries. Any web application you write today in Python 3.1 is likely to break in the future.</p> <p>It's a bit of a shambles. Today, for webapps you can only realistically use Python 2.x.</p>
3
2009-10-06T14:29:19Z
[ "python", "python-3.x", "werkzeug" ]
Werkzeug in General, and in Python 3.1
1,523,706
<p>I've been looking really hard at all of the way**(s)** one can develop web applications using Python. For reference, we are using RHEL 64bit, apache, mod_wsgi.</p> <p><strong>History:</strong></p> <ol> <li>PHP + MySQL <sup>years ago</sup></li> <li>PHP + Python 2.x + MySQL <sup>recently and current</sup></li> <li>Python + PostgreSQL <sup>working on it</sup></li> </ol> <p>We use a great library for communicating between PHP and Python (interface in PHP, backend in Python)... However, with a larger upcoming project starting, using 100% python may be very advantagous.</p> <p>We typically prefer not to have a monolithic framework dictating how things are done. A collection of useful helpers and utilities are much preferred (be it PHP or Python).</p> <p><strong>Question 1:</strong></p> <p>In reading a number of answers from experienced Python users, I've seen <strong>Werkzeug</strong> recommended a number of times. I would love it if several people with direct experience using Werkzeug to develop professional web applications could comment (in as much detail as their fingers feel like) why they use it, why they like it, and anything to watch out for.</p> <p><strong>Question 2:</strong></p> <p>Is there a version of Werkzeug that supports Python 3.1.1. I've succefully installed <strong>mod_wsgi</strong> on Apache 2.2 with Python 3.1.1.</p> <p>If there is not a version, what would it take to upgrade it to work on Python 3.1?</p> <p>Note: I've run <code>2to3</code> on the Werkzeug source code, and it does python-compile without </p> <h2>Edit:</h2> <p>The project that we are starting is not slated to be finished until nearly a year from now. At which point, I'm guessing Python 3.X will be a lot more mainstream. Furthermore, considering that we are running the App (not distributing it), can anyone comment on the viability of bashing through some of the Python 3 issues now, so that when a year from now arrives, we are more-or-less already there?</p> <p>Thoughts appreciated!</p>
2
2009-10-06T05:13:48Z
1,622,505
<p>I can only answer question one:</p> <p>I started using it for some small webstuff but now moved on to rework larger apps with it. Why Werkzeug? The modular concept is really helpful. You can hook in modules as you like, make stuff easily context aware and you get good request file handling for free which is able to cope with 300mb+ files by not storing it in memory.</p> <p>Disadvantages... Well sometimes modularity needs some upfront thought (django f.ex. gives you everything all at once, stripping stuff out is hard to do there though) but for me it works fine.</p>
1
2009-10-25T23:45:30Z
[ "python", "python-3.x", "werkzeug" ]
Reasons to use distutils when packaging C/Python project
1,523,874
<p>I have an open source project containing both Python and C code. I'm wondering that is there any use for distutils for me, because I'm planning to do a ubuntu/debian package. The C code is not something that I could or want to use as Python extension. C and Python programs communicate with TCP/IP through localhost.</p> <p>So the bottom line here is that while I'm learning packaging, does the usage of distutils specific files only make me more confused since I can't use my C-code as Python extensions? Or should I divide my C and Python functionality to separate projects to be able to understand packaging concepts better?</p>
0
2009-10-06T06:17:53Z
1,523,993
<p>distutils can be used to install end user programs, but it's most useful when using it for Python libraries, as it can create source packages and also install them in the correct place. For that I would say it's more or less required.</p> <p>But for an end user Python program you can also use make or whatever you like and are used to, as you don't need to install any code in the Python site-packages directory, and you don't need to put your code onto PyPI and it doesn't need to be accessible from other Python-code.</p> <p>I don't think distutils will be neither more or less complicated to use in installing an end-user program compared to other tools. All such install/packaging tools are hella-complex, as Cartman would have said.</p>
1
2009-10-06T06:56:02Z
[ "python", "c", "packaging", "distutils" ]
Reasons to use distutils when packaging C/Python project
1,523,874
<p>I have an open source project containing both Python and C code. I'm wondering that is there any use for distutils for me, because I'm planning to do a ubuntu/debian package. The C code is not something that I could or want to use as Python extension. C and Python programs communicate with TCP/IP through localhost.</p> <p>So the bottom line here is that while I'm learning packaging, does the usage of distutils specific files only make me more confused since I can't use my C-code as Python extensions? Or should I divide my C and Python functionality to separate projects to be able to understand packaging concepts better?</p>
0
2009-10-06T06:17:53Z
1,525,194
<p>Because it uses an unified <code>python setup.py install</code> command? distutils, or setuptools? Whatever, just use one of those.</p> <p>For development, it's also really useful because you don't have to care where to find such and such dependency. As long as it's standard Python/basic system library stuff, <code>setup.py</code> should find it for you. With <code>setup.py</code>, you don't require anymore <code>./configure</code> stuff or ugly autotools to create huge Makefiles. <em>It just works</em> (tm)</p>
1
2009-10-06T12:07:21Z
[ "python", "c", "packaging", "distutils" ]
Convert a decimal matrix to a binary matrix in SciPy
1,524,023
<p>Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples.</p> <p>My question: is there a fast, convenient way to reduce the decimal matrix to a binary matrix. </p> <p>Such that:</p> <pre><code>26, 3, 0 3, 195, 1 0, 1, 17 </code></pre> <p>Becomes:</p> <pre><code>1, 1, 0 1, 1, 1 0, 1, 1 </code></pre>
1
2009-10-06T07:03:42Z
1,524,039
<p>Apply the <code>scipy.sign</code> function to every cell in the matrix.</p> <p>[EDIT] Cudos to <a href="http://stackoverflow.com/users/39584/speciousfool">speciousfool</a>:</p> <p>If <code>x</code> is your matrix then <code>scipy.sign(x)</code> gives you the binary matrix.</p>
2
2009-10-06T07:14:19Z
[ "python", "scipy" ]
Convert a decimal matrix to a binary matrix in SciPy
1,524,023
<p>Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples.</p> <p>My question: is there a fast, convenient way to reduce the decimal matrix to a binary matrix. </p> <p>Such that:</p> <pre><code>26, 3, 0 3, 195, 1 0, 1, 17 </code></pre> <p>Becomes:</p> <pre><code>1, 1, 0 1, 1, 1 0, 1, 1 </code></pre>
1
2009-10-06T07:03:42Z
1,524,261
<p>You can do the following:</p> <pre><code>&gt;&gt;&gt; import scipy &gt;&gt;&gt; a = scipy.array((12, 0, -1, 23, 0)) array([12, 0, -1, 23, 0]) &gt;&gt;&gt; (a != 0).astype(int) array([1, 0, 1, 1, 0]) </code></pre> <p>The magic is in the <code>a != 0</code> part. You can apply boolean expressions to arrays and it will return an array of booleans. Then it is converted to ints.</p>
2
2009-10-06T08:20:03Z
[ "python", "scipy" ]
Convert a decimal matrix to a binary matrix in SciPy
1,524,023
<p>Suppose I have a integer matrix which represents who has emailed whom and how many times. For social network analysis I'd like to make a simple undirected graph. So I need to convert the matrix to binary matrix and later into a list of tuples.</p> <p>My question: is there a fast, convenient way to reduce the decimal matrix to a binary matrix. </p> <p>Such that:</p> <pre><code>26, 3, 0 3, 195, 1 0, 1, 17 </code></pre> <p>Becomes:</p> <pre><code>1, 1, 0 1, 1, 1 0, 1, 1 </code></pre>
1
2009-10-06T07:03:42Z
8,470,103
<p>You can also try this:</p> <pre><code>&gt;&gt;&gt;x,y = scipy.where(yourMatrix&gt;0) &gt;&gt;&gt;yourMatrix[:,:] = 0 &gt;&gt;&gt;yourMatrix[x,y] = 1 </code></pre> <p>i guess this will also be faster.</p>
0
2011-12-12T04:55:14Z
[ "python", "scipy" ]
How to print a list more nicely?
1,524,126
<p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python “nicely”</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p> <pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] evenNicerPrint(foolist) </code></pre> <p>Desired result:</p> <pre><code>exiv2-devel msvcrt mingw-libs gdal-grass tcltk-demos iconv fcgi qgis-devel netcdf qgis1.1 pdcurses-devel php_mapscript </code></pre> <p>thanks!</p>
6
2009-10-06T07:43:58Z
1,524,132
<p>Simple:</p> <pre><code>l = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] if len(l) % 2 != 0: l.append(" ") split = len(l)/2 l1 = l[0:split] l2 = l[split:] for key, value in zip(l1,l2): print '%-20s %s' % (key, value) #python &lt;2.6 print "{0:&lt;20s} {1}".format(key, value) #python 2.6+ </code></pre>
8
2009-10-06T07:45:33Z
[ "python", "printing" ]
How to print a list more nicely?
1,524,126
<p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python “nicely”</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p> <pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] evenNicerPrint(foolist) </code></pre> <p>Desired result:</p> <pre><code>exiv2-devel msvcrt mingw-libs gdal-grass tcltk-demos iconv fcgi qgis-devel netcdf qgis1.1 pdcurses-devel php_mapscript </code></pre> <p>thanks!</p>
6
2009-10-06T07:43:58Z
1,524,225
<p>If the data is in the format you have provided, it is a little more work</p> <pre><code> >>> d = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', ... 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', ... 'qgis1.1', 'php_mapscript'] >>> print "\n".join("%-20s %s"%(d[i],d[i+len(d)/2]) for i in range(len(d)/2)) exiv2-devel msvcrt mingw-libs gdal-grass tcltk-demos iconv fcgi qgis-devel netcdf qgis1.1 pdcurses-devel php_mapscript </code></pre>
2
2009-10-06T08:10:07Z
[ "python", "printing" ]
How to print a list more nicely?
1,524,126
<p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python “nicely”</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p> <pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] evenNicerPrint(foolist) </code></pre> <p>Desired result:</p> <pre><code>exiv2-devel msvcrt mingw-libs gdal-grass tcltk-demos iconv fcgi qgis-devel netcdf qgis1.1 pdcurses-devel php_mapscript </code></pre> <p>thanks!</p>
6
2009-10-06T07:43:58Z
1,524,333
<p>See <a href="http://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns">formatting-a-list-of-text-into-columns</a>, </p> <p>A general solution, handles any number of columns and odd lists. Tab characters separate columns, using generator expressions to save space.</p> <pre><code>def fmtcols(mylist, cols): lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols)) return '\n'.join(lines) </code></pre>
4
2009-10-06T08:40:54Z
[ "python", "printing" ]
How to print a list more nicely?
1,524,126
<p>This is similar to <a href="http://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely">How to print a list in Python “nicely”</a>, but I would like to print the list even more nicely -- without the brackets and apostrophes and commas, and even better in columns.</p> <pre><code>foolist = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', 'qgis1.1', 'php_mapscript'] evenNicerPrint(foolist) </code></pre> <p>Desired result:</p> <pre><code>exiv2-devel msvcrt mingw-libs gdal-grass tcltk-demos iconv fcgi qgis-devel netcdf qgis1.1 pdcurses-devel php_mapscript </code></pre> <p>thanks!</p>
6
2009-10-06T07:43:58Z
1,524,335
<p>The way Aaron has done it can work with more than two colums</p> <pre><code> >>> l = ['exiv2-devel', 'mingw-libs', 'tcltk-demos', 'fcgi', 'netcdf', ... 'pdcurses-devel', 'msvcrt', 'gdal-grass', 'iconv', 'qgis-devel', ... 'qgis1.1', 'php_mapscript'] >>> cols = 4 >>> split=[l[i:i+len(l)/cols] for i in range(0,len(l),len(l)/cols)] >>> for row in zip(*split): ... print "".join(str.ljust(i,20) for i in row) ... exiv2-devel fcgi msvcrt qgis-devel mingw-libs netcdf gdal-grass qgis1.1 tcltk-demos pdcurses-devel iconv php_mapscript </code></pre>
5
2009-10-06T08:41:10Z
[ "python", "printing" ]