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
How to include external Python code to use in other files?
714,881
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p> <p>So if I have:</p> <pre><code>[Math.py] def Calculate ( num ) </code></pre> <p>How do I call it like this:</p> <pre><code>[Tool.py] using Math.py for i...
86
2009-04-03T17:21:58Z
714,890
<p>You will need to import the other file as a module like this:</p> <pre><code>import Math </code></pre> <p>If you don't want to prefix your <code>Calculate</code> function with the module name then do this:</p> <pre><code>from Math import Calculate </code></pre> <p>If you want to import all members of a module th...
129
2009-04-03T17:24:28Z
[ "python" ]
How to include external Python code to use in other files?
714,881
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p> <p>So if I have:</p> <pre><code>[Math.py] def Calculate ( num ) </code></pre> <p>How do I call it like this:</p> <pre><code>[Tool.py] using Math.py for i...
86
2009-04-03T17:21:58Z
16,604,453
<p>Just write the "include" command : </p> <pre><code>import os def include(filename): if os.path.exists(filename): execfile(filename) include('myfile.py') </code></pre> <p>@Deleet :</p> <p>@bfieck remark is correct, for python 2 and 3 compatibility, you need either :</p> <p>Python 2 and 3: alterna...
32
2013-05-17T08:15:42Z
[ "python" ]
How to include external Python code to use in other files?
714,881
<p>If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?</p> <p>So if I have:</p> <pre><code>[Math.py] def Calculate ( num ) </code></pre> <p>How do I call it like this:</p> <pre><code>[Tool.py] using Math.py for i...
86
2009-04-03T17:21:58Z
19,918,123
<p>I've found the python inspect module to be very useful</p> <p>For example with teststuff.py</p> <pre><code>import inspect def dostuff(): return __name__ DOSTUFF_SOURCE = inspect.getsource(dostuff) if __name__ == "__main__": dostuff() </code></pre> <p>And from the another script or the python console</...
0
2013-11-11T23:34:50Z
[ "python" ]
WeakValueDictionary for holding any type
715,125
<p>Is there any way to work around the limitations of WeakValueDictionary to allow it to hold weak references to built-in types like dict or list? Can something be done at the C level in an extension module? I really need a weakref container that can hold (nearly) any type of object.</p>
1
2009-04-03T18:34:46Z
715,212
<p>According to the <a href="http://docs.python.org/library/weakref.html" rel="nofollow">Python documentation</a> you can create weak references to subclasses of <code>dict</code> and <code>list</code>... it's not a perfect solution, but if you're able to create a custom subclass of <code>dict</code> and use that inste...
1
2009-04-03T19:01:08Z
[ "python" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
715,267
<p>Not built in, but you could iterate on the keys of the dict and do comparisons. Could be slow though.</p> <p>Better solution is probably to build a more complex datastructure and use a dictionary as the underlying representation.</p>
0
2009-04-03T19:13:30Z
[ "python", "diff", "dictionary" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
715,268
<p>No, it doesn't. But it's not hard to write a dictionary diff function:</p> <pre><code>def diff(a, b): diff = {} for key in b.keys(): if (not a.has_key(key)) or (a.has_key(key) and a[key] != b[key]): diff[key] = b[key] return diff </code></pre>
2
2009-04-03T19:13:35Z
[ "python", "diff", "dictionary" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
715,314
<p>No, but you can subclass dict to provide notification on change. </p> <pre><code>class ObservableDict( dict ): def __init__( self, *args, **kw ): self.observers= [] super( ObservableDict, self ).__init__( *args, **kw ) def observe( self, observer ): self.observers.append( observer )...
10
2009-04-03T19:23:17Z
[ "python", "diff", "dictionary" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
715,364
<pre><code>def diff_update(dict_to_update, updater): changes=dict((k,updater[k]) for k in filter(lambda k:(k not in dict_to_update or updater[k] != dict_to_update[k]), updater.iterkeys())) dict_to_update.update(updater) return changes a = {'a':'hamburger', 'b':'fries', 'c':'coke'} b = {'b':'fries', 'c':'pe...
1
2009-04-03T19:33:08Z
[ "python", "diff", "dictionary" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
715,366
<p>A simple diffing function is easy to write. Depending on how often you need it, it may be faster than the more elegant ObservableDict by S.Lott.</p> <pre><code>def dict_diff(a, b): """Return differences from dictionaries a to b. Return a tuple of three dicts: (removed, added, changed). 'removed' has al...
2
2009-04-03T19:33:22Z
[ "python", "diff", "dictionary" ]
python dict update diff
715,234
<p>Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? For example I am looking for some functionality like this:</p> <pre><code>&gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'} &gt;...
5
2009-04-03T19:04:34Z
2,904,335
<h2>one year later</h2> <p>I like the following solution:</p> <pre><code>&gt;&gt;&gt; def dictdiff(d1, d2): return dict(set(d2.iteritems()) - set(d1.iteritems())) ... &gt;&gt;&gt; a = {'a':'hamburger', 'b':'fries', 'c':'coke'} &gt;&gt;&gt; b = {'b':'fries', 'c':'...
7
2010-05-25T12:02:03Z
[ "python", "diff", "dictionary" ]
How do I iterate over all lines of files passed on the command line?
715,277
<p>I usually do this in Perl:</p> <p>whatever.pl</p> <pre><code>while(&lt;&gt;) { #do whatever; } </code></pre> <p>then <code>cat foo.txt | whatever.pl</code></p> <p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p...
16
2009-04-03T19:15:37Z
715,282
<p>Try this:</p> <pre><code>import fileinput for line in fileinput.input(): process(line) </code></pre>
35
2009-04-03T19:17:06Z
[ "python", "stdin" ]
How do I iterate over all lines of files passed on the command line?
715,277
<p>I usually do this in Perl:</p> <p>whatever.pl</p> <pre><code>while(&lt;&gt;) { #do whatever; } </code></pre> <p>then <code>cat foo.txt | whatever.pl</code></p> <p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p...
16
2009-04-03T19:15:37Z
715,300
<pre><code>import sys def main(): for line in sys.stdin: print line if __name__=='__main__': sys.exit(main()) </code></pre>
10
2009-04-03T19:19:50Z
[ "python", "stdin" ]
How do I iterate over all lines of files passed on the command line?
715,277
<p>I usually do this in Perl:</p> <p>whatever.pl</p> <pre><code>while(&lt;&gt;) { #do whatever; } </code></pre> <p>then <code>cat foo.txt | whatever.pl</code></p> <p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p...
16
2009-04-03T19:15:37Z
715,301
<p>Something like this:</p> <pre><code>import sys for line in sys.stdin: # whatever </code></pre>
5
2009-04-03T19:20:25Z
[ "python", "stdin" ]
How do I iterate over all lines of files passed on the command line?
715,277
<p>I usually do this in Perl:</p> <p>whatever.pl</p> <pre><code>while(&lt;&gt;) { #do whatever; } </code></pre> <p>then <code>cat foo.txt | whatever.pl</code></p> <p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p...
16
2009-04-03T19:15:37Z
715,305
<pre><code>import sys for line in sys.stdin: # do stuff w/line </code></pre>
3
2009-04-03T19:20:46Z
[ "python", "stdin" ]
How do I iterate over all lines of files passed on the command line?
715,277
<p>I usually do this in Perl:</p> <p>whatever.pl</p> <pre><code>while(&lt;&gt;) { #do whatever; } </code></pre> <p>then <code>cat foo.txt | whatever.pl</code></p> <p>Now, I want to do this in Python. I tried <code>sys.stdin</code> but I have no idea how to do as I have done in Perl. How can I read the input?</p...
16
2009-04-03T19:15:37Z
715,327
<p>You may find a <a href="http://en.wikipedia.org/wiki/Rosetta%5Fstone" rel="nofollow">Rosetta Stone</a> helpful. I tend to use <a href="http://www.lurklurk.org/rosetta.html" rel="nofollow">http://www.lurklurk.org/rosetta.html</a>.</p>
2
2009-04-03T19:25:45Z
[ "python", "stdin" ]
How can I print entity numbers in my xml document instead of entity names using python's lxml?
715,304
<p>I'm using lxml and python to generate xml documents (just using etree.tostring(root) ) but at the moment the resulting xml displays html entities as with named entities ( &amp;lt ; ) rather than their numeric values ( &amp;#60 ; ). How exactly do I go about changing this so that the result uses the numeric values i...
4
2009-04-03T19:20:45Z
715,859
<p>Ultimately, it looks like the python code will call <a href="http://www.opensource.apple.com/darwinsource/WWDC2003/libxml2-3/libxml2/doc/html/libxml-tree.html#XMLNODEDUMPOUTPUT" rel="nofollow">xmlNodeDumpOutput</a> in the libxml2 library.</p> <p>Unfortunately, it doesn't look like there is any way to configure this...
2
2009-04-03T21:50:14Z
[ "python", "xml", "lxml" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
715,455
<p>Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:</p> <pre><code>s == 'True' </code></pre> <p>Or to checks against a whole bunch of values:</p> <pre><code>s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh'] </code></pre> <p>Be cau...
361
2009-04-03T19:52:56Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
715,458
<p>you could always do something like </p> <pre><code>myString = "false" val = (myString == "true") </code></pre> <p>the bit in parens would evaluate to False. This is just another way to do it without having to do an actual function call.</p>
6
2009-04-03T19:53:23Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
715,468
<pre><code>def str2bool(v): return v.lower() in ("yes", "true", "t", "1") </code></pre> <p>Then call it like so:</p> <pre><code>str2bool("yes") </code></pre> <p><code>&gt; True</code></p> <pre><code>str2bool("no") </code></pre> <p><code>&gt; False</code></p> <pre><code>str2bool("stuff") </code></pre> <p><code>...
152
2009-04-03T19:56:44Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
922,374
<p>Starting with Python 2.6, there is now <code>ast.literal_eval</code>:</p> <pre> >>> import ast >>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may...
77
2009-05-28T18:06:39Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
1,114,606
<p>The usual rule for casting to a bool is that a few special literals (<code>False</code>, <code>0</code>, <code>0.0</code>, <code>()</code>, <code>[]</code>, <code>{}</code>) are false and then everything else is true, so I recommend the following:</p> <pre><code>def boolify(val): if (isinstance(val, basestring)...
3
2009-07-11T20:45:35Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
1,114,688
<p>here's a hairy, built in way to get many of the same answers. Note that although python considers <code>""</code> to be false and all other strings to be true, TCL has a very different idea about things. </p> <pre><code>&gt;&gt;&gt; import Tkinter &gt;&gt;&gt; tk = Tkinter.Tk() &gt;&gt;&gt; var = Tkinter.BooleanV...
0
2009-07-11T21:31:45Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
2,073,768
<p>You probably already have a solution but for others who are looking for a method to convert a value to a boolean value using "standard" false values including None, [], {}, and "" in addition to false, no , and 0.</p> <pre><code>def toBoolean( val ): """ Get the boolean value of the provided input. ...
4
2010-01-15T18:13:01Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
2,736,717
<pre><code>def str2bool(str): if isinstance(str, basestring) and str.lower() in ['0','false','no']: return False else: return bool(str) </code></pre> <p>idea: check if you want the string to be evaluated to False; otherwise bool() returns True for any non-empty string.</p>
0
2010-04-29T11:01:15Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
9,051,825
<p>Here's something I threw together to evaluate the truthiness of a string:</p> <pre><code>def as_bool(val): if val: try: if not int(val): val=False except: pass try: if val.lower()=="false": val=False except: pass return bool(val) </code></pre> <p>more-or-less same results as using <code>eval</code>...
0
2012-01-29T08:09:54Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
9,333,816
<p>Here's is my version. It checks against both positive and negative values lists, raising an exception for unknown values. And it does not receive a string, but any type should do.</p> <pre><code>def to_bool(value): """ Converts 'something' to boolean. Raises exception for invalid formats Possi...
11
2012-02-17T18:57:43Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
9,742,086
<p>A dict (really, a defaultdict) gives you a pretty easy way to do this trick:</p> <pre><code>from collections import defaultdict bool_mapping = defaultdict(bool) # Will give you False for non-found values for val in ['True', 'yes', ...]: bool_mapping[val] = True print(bool_mapping['True']) # True print(bool_map...
5
2012-03-16T17:47:14Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
10,587,945
<p>This is the version I wrote. Combines several of the other solutions into one.</p> <pre><code>def to_bool(value): """ Converts 'something' to boolean. Raises exception if it gets a string it doesn't handle. Case is ignored for strings. These string values are handled: True: 'True', "1", "TRue", "y...
3
2012-05-14T17:07:45Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
11,759,968
<p>I like to use the ternary operator for this, since it's a bit more succinct for something that feels like it shouldn't be more than 1 line.</p> <pre><code>True if myString=="True" else False </code></pre>
2
2012-08-01T13:07:39Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
13,562,496
<p>I don't agree with any solution here, as they are too permissive. This is not normally what you want when parsing a string.</p> <p>So here the solution I'm using:</p> <pre><code>def to_bool(bool_str): """Parse the string and return the boolean value encoded or raise an exception""" if isinstance(bool_str, ...
6
2012-11-26T10:04:22Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
13,706,457
<p>The JSON parser is also useful for in general converting strings to reasonable python types.</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.loads("false") False &gt;&gt;&gt; json.loads("true") True </code></pre>
35
2012-12-04T15:38:14Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
14,946,382
<p>A cool, simple trick (based on what @Alan Marchiori posted), but using yaml:</p> <pre><code>import yaml parsed = yaml.load("true") print bool(parsed) </code></pre> <p>If this is too wide, it can be refined by testing the type result. If the yaml-returned type is a str, then it can't be cast to any other type (tha...
2
2013-02-18T22:21:51Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
18,156,046
<p>I realize this is an old post, but some of the solutions require quite a bit of code, here's what I ended up using:</p> <pre><code>def str2bool(value): return {"True": True, "true": True}.get(value, False) </code></pre>
2
2013-08-09T21:37:50Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
18,472,142
<p>Just use:</p> <pre><code>distutils.util.strtobool(some_string) </code></pre> <p><a href="http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool">http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool</a></p> <blockquote> <p>True...
81
2013-08-27T17:42:22Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
19,015,368
<p>This version keeps the semantics of constructors like int(value) and provides an easy way to define acceptable string values.</p> <pre><code>def to_bool(value): valid = {'true': True, 't': True, '1': True, 'false': False, 'f': False, '0': False, } if isinstance(value, bool): ...
9
2013-09-25T21:16:55Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
25,242,187
<p>You can simply use the built-in function <a href="https://docs.python.org/2/library/functions.html#eval">eval()</a>:</p> <pre><code>a='True' if a is True: print 'a is True, a type is', type(a) else: print "a isn't True, a type is", type(a) b = eval(a) if b is True: print 'b is True, b type is', type(b) ...
8
2014-08-11T11:27:49Z
[ "python", "string" ]
Converting from a string to boolean in Python?
715,417
<p>Does anyone know how to do convert from a string to a boolean in Python? I found <a href="http://codecomments.wordpress.com/2008/04/08/converting-a-string-to-a-boolean-value-in-python/">this link</a>. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.</p> <p>EDIT: The reason ...
258
2009-04-03T19:44:20Z
36,185,083
<p>If you know that your input will be either "True" or "False" then why not use:</p> <pre><code>def bool_convert(s): return s == "True" if s else False </code></pre>
0
2016-03-23T17:39:39Z
[ "python", "string" ]
How can I talk to UniProt over HTTP in Python?
715,538
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p> <p>In <a href="http://www.uniprot.org/faq/28" rel="no...
4
2009-04-03T20:11:22Z
715,610
<p><strong>question #1:</strong></p> <p>This can be done using python's urllibs:</p> <pre><code>import urllib, urllib2 import time import sys query = ' '.join(sys.argv) # encode params as a list of 2-tuples params = ( ('from','ACC'), ('to', 'P_REFSEQ_AC'), ('format','tab'), ('query', query)) # url encode them da...
6
2009-04-03T20:28:44Z
[ "python", "http", "user-agent", "bioinformatics" ]
How can I talk to UniProt over HTTP in Python?
715,538
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p> <p>In <a href="http://www.uniprot.org/faq/28" rel="no...
4
2009-04-03T20:11:22Z
715,683
<p>Let's assume that you are using Python 2.5. We can use <a href="http://docs.python.org/library/httplib.html?highlight=httplib#module-httplib" rel="nofollow">httplib</a> to directly call the web site:</p> <pre><code>import httplib, urllib querystring = {} #Build the query string here from the following keys (query, ...
1
2009-04-03T20:49:38Z
[ "python", "http", "user-agent", "bioinformatics" ]
How can I talk to UniProt over HTTP in Python?
715,538
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p> <p>In <a href="http://www.uniprot.org/faq/28" rel="no...
4
2009-04-03T20:11:22Z
1,393,345
<p>You're probably better off using the Protein Identifier Cross Reference service from the EBI to convert one set of IDs to another. It has a very good REST interface.</p> <p><a href="http://www.ebi.ac.uk/Tools/picr/" rel="nofollow">http://www.ebi.ac.uk/Tools/picr/</a></p> <p>I should also mention that UniProt has v...
1
2009-09-08T11:00:26Z
[ "python", "http", "user-agent", "bioinformatics" ]
How can I talk to UniProt over HTTP in Python?
715,538
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p> <p>In <a href="http://www.uniprot.org/faq/28" rel="no...
4
2009-04-03T20:11:22Z
22,295,870
<p>There is a python package in pip which does exactly what you want</p> <pre><code>pip install uniprot-mapper </code></pre>
0
2014-03-10T09:04:08Z
[ "python", "http", "user-agent", "bioinformatics" ]
How can I talk to UniProt over HTTP in Python?
715,538
<p>I'm trying to get some results from UniProt, which is a protein database (details are not important). I'm trying to use some script that translates from one kind of ID to another. I was able to do this manually on the browser, but could not do it in Python. </p> <p>In <a href="http://www.uniprot.org/faq/28" rel="no...
4
2009-04-03T20:11:22Z
38,795,612
<p>check this out <code>bioservices</code>. they interface a lot of databases through Python. <a href="https://pythonhosted.org/bioservices/_modules/bioservices/uniprot.html" rel="nofollow">https://pythonhosted.org/bioservices/_modules/bioservices/uniprot.html</a></p> <pre><code>conda install bioservices --yes </cod...
0
2016-08-05T18:22:05Z
[ "python", "http", "user-agent", "bioinformatics" ]
Best way to encode tuples with json
715,550
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p> <p><code>{(1,2): [(2,3),(1,7)]}</code></p> <p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p> <p>Is the best way to handle t...
21
2009-04-03T20:14:25Z
715,569
<p>Could it simply be a two dimensional array? Then you may use integers as keys</p>
0
2009-04-03T20:17:25Z
[ "python", "json" ]
Best way to encode tuples with json
715,550
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p> <p><code>{(1,2): [(2,3),(1,7)]}</code></p> <p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p> <p>Is the best way to handle t...
21
2009-04-03T20:14:25Z
715,581
<p>My recommendation would be:</p> <pre><code>{ "1": [ { "2": [[2,3],[1,7]] } ] } </code></pre> <p>It's still parsing, but depending on how you use it, it may be easier in this form.</p>
2
2009-04-03T20:20:06Z
[ "python", "json" ]
Best way to encode tuples with json
715,550
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p> <p><code>{(1,2): [(2,3),(1,7)]}</code></p> <p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p> <p>Is the best way to handle t...
21
2009-04-03T20:14:25Z
715,584
<p>You can't use an array as a key in JSON. The best you can do is encode it. Sorry, but there's really no other sane way to do it.</p>
1
2009-04-03T20:20:25Z
[ "python", "json" ]
Best way to encode tuples with json
715,550
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p> <p><code>{(1,2): [(2,3),(1,7)]}</code></p> <p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p> <p>Is the best way to handle t...
21
2009-04-03T20:14:25Z
715,601
<p>You might consider saying</p> <pre><code>{"[1,2]": [(2,3),(1,7)]} </code></pre> <p>and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in <code>JSON.parse</code> method (I'm using <code>jQuery.each</code> to iterate he...
16
2009-04-03T20:25:57Z
[ "python", "json" ]
Best way to encode tuples with json
715,550
<p>In python I have a dictionary that maps tuples to a list of tuples. e.g. </p> <p><code>{(1,2): [(2,3),(1,7)]}</code></p> <p>I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.</p> <p>Is the best way to handle t...
21
2009-04-03T20:14:25Z
715,614
<p>If your key tuples are truly integer pairs, then the easiest and probably most straightforward approach would be as you suggest.... encode them to a string. You can do this in a one-liner:</p> <pre><code>&gt;&gt;&gt; simplejson.dumps(dict([("%d,%d" % k, v) for k, v in d.items()])) '{"1,2": [[2, 3], [1, 7]]}' </cod...
6
2009-04-03T20:29:27Z
[ "python", "json" ]
Launching a .py python script from within a cgi script
715,791
<p>I'm trying to launch a .py script from within a cgi script while running a local cgi server. The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the end of the cgi script.</p> <p>The script runs to completio...
0
2009-04-03T21:26:00Z
715,825
<p>You say you're launching a python script from a CGI script, but you don't specify what language the CGI script is written in. Because CGI is simply an interface, it's not clear what language the CGI script is written in. I'm going to assume python, since that makes the most sense. </p> <p>What would work best wo...
1
2009-04-03T21:36:57Z
[ "python", "cgi", "scripting" ]
Launching a .py python script from within a cgi script
715,791
<p>I'm trying to launch a .py script from within a cgi script while running a local cgi server. The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the end of the cgi script.</p> <p>The script runs to completio...
0
2009-04-03T21:26:00Z
715,834
<p>Use <a href="http://docs.python.org/library/popen2.html" rel="nofollow">popen2</a> or <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> to launch a console while redirecting your output stream to that console.</p>
0
2009-04-03T21:41:12Z
[ "python", "cgi", "scripting" ]
Populating form field based on query/slug factor
715,889
<p>I've seen some similar questions, but nothing that quite pointed me in the direction I was hoping for. I have a situation where I have a standard django form built off of a model. This form has a drop down box where you select an item you want to post a comment on. Now I'd like people to be able to browse by items, ...
0
2009-04-03T21:58:47Z
716,031
<p>If I'm reading your question right, this is a fairly common use-case and well support by django forms. You can use the same form for both scenarios you describe.</p> <p>Let's say the item to be commented has the primary key 5. You would build a link for the user to click with a URL that looks like this:</p> <pre><...
1
2009-04-03T23:02:06Z
[ "python", "django-forms" ]
A wxPython timeline widget
715,950
<p>I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:</p> <p>Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, ...
1
2009-04-03T22:24:24Z
716,196
<p>A quick web search doesn't yield anything but others hoping for the same thing. My guess is you won't find any nice wx widgets for timelines. The closest you're likely to get is a <a href="http://zetcode.com/wxpython/widgets/#slider" rel="nofollow">wxSlider</a>. This is far from ideal, but it'll get you up and ru...
1
2009-04-04T00:46:01Z
[ "python", "controls", "wxpython", "widget", "timeline" ]
A wxPython timeline widget
715,950
<p>I am looking for a certain wxPython widget to use in my program. I hope that something like this exists and that you might know where to find. I will try to describe the functionality I'm looking for:</p> <p>Imagine something like the widget that Audacity uses to display an audio track. It's a horizontal timeline, ...
1
2009-04-03T22:24:24Z
819,462
<p>I have been working on a timeline widget for use in Task Coach (<a href="http://www.taskcoach.org" rel="nofollow">http://www.taskcoach.org</a>). I haven't released it separately yet, but it is fully isolated from the rest of the Task Coach source code so you should be able to rip it out quite easily. See <a href="ht...
1
2009-05-04T09:35:26Z
[ "python", "controls", "wxpython", "widget", "timeline" ]
OptionParser - supporting any option at the end of the command line
716,006
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p> <p>I want to execute it as such:</p> <pre>./floep [command] </pre> <p>However, I need to pass certain command lines from time to time:</p> <p...
5
2009-04-03T22:52:46Z
716,032
<p>You can use a bash script like this:</p> <pre><code>#!/bin/bash while [ "-" == "${1:0:1}" ] ; do if [ "-v" == "${1}" ] ; then # do something echo "-v" elif [ "-s" == "${1}" ] ; then # do something echo "-s" fi shift done ${@} </code></pre> <p>The ${@} gives you the rest of the command line ...
-1
2009-04-03T23:03:02Z
[ "python", "optparse" ]
OptionParser - supporting any option at the end of the command line
716,006
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p> <p>I want to execute it as such:</p> <pre>./floep [command] </pre> <p>However, I need to pass certain command lines from time to time:</p> <p...
5
2009-04-03T22:52:46Z
716,081
<p>OptionParser instances can actually be manipulated during the parsing operation for complex cases. In this case, however, I believe the scenario you describe is supported out-of-the-box (which would be good news if true! how often does that happen??). See this section in the docs: <a href="http://docs.python.org/lib...
1
2009-04-03T23:29:02Z
[ "python", "optparse" ]
OptionParser - supporting any option at the end of the command line
716,006
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p> <p>I want to execute it as such:</p> <pre>./floep [command] </pre> <p>However, I need to pass certain command lines from time to time:</p> <p...
5
2009-04-03T22:52:46Z
716,090
<p>Try using <a href="http://docs.python.org/library/optparse.html#other-methods"><code>disable_interspersed_args()</code></a></p> <pre><code>#!/usr/bin/env python from optparse import OptionParser parser = OptionParser() parser.disable_interspersed_args() parser.add_option("-v", action="store_true", dest="verbose") ...
13
2009-04-03T23:33:45Z
[ "python", "optparse" ]
OptionParser - supporting any option at the end of the command line
716,006
<p>I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around <code>ssh [hostname] [command]</code>).</p> <p>I want to execute it as such:</p> <pre>./floep [command] </pre> <p>However, I need to pass certain command lines from time to time:</p> <p...
5
2009-04-03T22:52:46Z
716,108
<pre><code>from optparse import OptionParser import subprocess import os import sys parser = OptionParser() parser.add_option("-q", "--quiet", action="store_true", dest="quiet", default=False, help="don't print output") parser.add_option("-s", "--signal", action="s...
1
2009-04-03T23:43:06Z
[ "python", "optparse" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
716,018
<p>It's not generally possible. The new process created for python cannot affect its parent process' environment. Neither can the parent affect the child, but the parent gets to setup the child's environment as part of new process creation.</p> <p>Perhaps you can set them in <code>.bashrc</code>, <code>.profile</cod...
1
2009-04-03T22:59:09Z
[ "python", "persistence", "environment-variables" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
716,026
<p>If you set environment variables within a python script (or any other script or program), it won't affect the parent shell.</p> <p>Edit clarification: So the answer to your question is yes, it is true. You can however export from within a shell script and source it by using the dot invocation</p> <p>in fooexport.s...
2
2009-04-03T23:00:56Z
[ "python", "persistence", "environment-variables" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
716,046
<p>You can't do it from python, but some clever bash tricks can do something similar. The basic reasoning is this: environment variables exist in a per-process memory space. When a new process is created with fork() it inherits its parent's environment variables. When you set an environment variable in your shell (...
26
2009-04-03T23:08:47Z
[ "python", "persistence", "environment-variables" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
716,069
<p>What I like to do is use /usr/bin/env in a shell script to "wrap" my command line when I find myself in similar situations:</p> <pre><code>#!/bin/bash /usr/bin/env NAME1="VALUE1" NAME2="VALUE2" ${*} </code></pre> <p>So let's call this script "myappenv". I put it in my $HOME/bin directory which I have in my $PATH...
2
2009-04-03T23:22:30Z
[ "python", "persistence", "environment-variables" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
716,188
<p>One workaround is to output <code>export</code> commands, and have the parent shell evaluate this..</p> <p><code>thescript.py</code>:</p> <pre><code>import pipes import random r = random.randint(1,100) print("export BLAHBLAH=%s" % (pipes.quote(str(r)))) </code></pre> <p>..and the bash alias (the same can be done ...
16
2009-04-04T00:38:24Z
[ "python", "persistence", "environment-variables" ]
Why can't environmental variables set in python persist?
716,011
<p>I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:</p> <p>Is this true?</p> <p>an...
25
2009-04-03T22:55:29Z
32,547,868
<p>As answered by Benson, but the best hack-around is to create a simple bash function to preserve arguments:</p> <pre><code>upsert-env-var (){ eval $(python upsert_env_var.py $*); } </code></pre> <p>Your can do whatever you want in your python script with the arguments. To simply add a variable use something like:<...
0
2015-09-13T08:39:56Z
[ "python", "persistence", "environment-variables" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
716,277
<p>I'm curious why you want this functionality; as I understand it, the reason for having matrices (in numpy), is primarily for doing linear math (matrix transformations and so on).</p> <p>I'm not sure what the mathematical definition would be for the product of a decimal and a String.</p> <p>Internally, you'll proba...
5
2009-04-04T01:27:36Z
[ "python", "matrix" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
716,292
<p>You can have inhomogeneous types if your <code>dtype</code> is <code>object</code>:</p> <pre><code>In [1]: m = numpy.matrix([[1, 2, 3], [4, '5', 6]], dtype=numpy.object) In [2]: m Out[2]: matrix([[1, 2, 3], [4, 5, 6]], dtype=object) In [3]: m[1, 1] Out[3]: '5' In [4]: m[1, 2] Out[4]: 6 </code></pre> <p>I ...
10
2009-04-04T01:38:21Z
[ "python", "matrix" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
716,389
<p>Have you looked at the numpy.recarray capabilities?</p> <p>For instance here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.html</p> <p>It's designed to allow arrays with mixed datatypes.</p> <p>I don't know if an array will suit your purposes, or if you really need a matrix - I haven't worke...
3
2009-04-04T02:37:53Z
[ "python", "matrix" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
716,931
<p>Have you considered the csv module for working with csv files?</p> <p><a href="http://docs.python.org/library/csv.html" rel="nofollow">Python docs for csv module</a></p>
0
2009-04-04T11:32:13Z
[ "python", "matrix" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
5,371,300
<p>Check out sympy -- it does quite a good job at polymorphism in its matrices and you you have operations on sympy.matrices.Matrix objects like col_swap, col_insert, col_del, etc...</p> <pre> In [2]: import sympy as s In [6]: import numpy as np In [11]: npM = np.array([[1,2,3.0], [4,4,"abc"]], dtype=object) In [12]...
1
2011-03-20T20:28:20Z
[ "python", "matrix" ]
Matrices in Python
716,259
<p>Yesterday I had the need for a matrix type in Python.</p> <p>Apparently, a trivial answer to this need would be to use <code>numpy.matrix()</code>, but the additional issue I have is that I would like a matrix to store arbitrary values with mixed types, similarly to a list. <code>numpy.matrix</code> does not perfor...
4
2009-04-04T01:21:36Z
19,811,361
<p>Maybe it's a late answer, but, why not use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>?</p>
1
2013-11-06T11:49:11Z
[ "python", "matrix" ]
My first python program: can you tell me what I'm doing wrong?
716,278
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p> <p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p> <p>This is just for personal educational purposes. The...
6
2009-04-04T01:27:46Z
716,309
<p>Usually is preferred that what follows after the end of sentence <code>:</code> is in a separate line (also don't add a space before it)</p> <pre><code>if options.verbose: print "" </code></pre> <p>instead of</p> <pre><code>if options.verbose : print "" </code></pre> <p>You don't need to check the len of a lis...
10
2009-04-04T01:46:23Z
[ "python" ]
My first python program: can you tell me what I'm doing wrong?
716,278
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p> <p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p> <p>This is just for personal educational purposes. The...
6
2009-04-04T01:27:46Z
716,367
<p>String exceptions are deprecated in Python, so this line:</p> <pre><code>if not config.has_section(sectionname): raise 'Server or group ' + sectionname + ' not found in ' + configfile </code></pre> <p>should be reworked into something like this:</p> <pre><code>if not config.has_section(sectionname): rais...
5
2009-04-04T02:22:43Z
[ "python" ]
My first python program: can you tell me what I'm doing wrong?
716,278
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p> <p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p> <p>This is just for personal educational purposes. The...
6
2009-04-04T01:27:46Z
716,388
<p>Before unloading any criticism, first let me say congratulations on getting your first Python program working. Moving from one language to another can be a chore, constantly fumbling around with syntax issues and hunting through unfamiliar libraries.</p> <p>The most quoted style guideline is <a href="http://www.py...
7
2009-04-04T02:37:51Z
[ "python" ]
My first python program: can you tell me what I'm doing wrong?
716,278
<p>I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.</p> <p>I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.</p> <p>This is just for personal educational purposes. The...
6
2009-04-04T01:27:46Z
716,954
<p>Often, for reuse purposes, we do the following, starting at about line 48 in your program</p> <pre><code>def main(): config = ConfigParser.RawConfigParser() etc. if __name__ == "__main__": main() </code></pre> <p>This is just a starting point. </p> <p>Once you've done this, you realize that main() i...
3
2009-04-04T11:58:15Z
[ "python" ]
Why is my PyObjc Cocoa view class forgetting its fields?
716,386
<p>I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:</p> <pre><code>from objc ...
1
2009-04-04T02:33:10Z
716,917
<p>Depending on what's happening elsewhere in your app, your instance might actually be getting copied. </p> <p>In this case, implement the <code>copyWithZone</code> method to ensure that the new copy gets the renderer as well. (Caveat, while I am a Python developer, and an Objective-C cocoa developer, I haven't used ...
3
2009-04-04T11:14:01Z
[ "python", "xcode", "osx", "pyobjc" ]
Why is my PyObjc Cocoa view class forgetting its fields?
716,386
<p>I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:</p> <pre><code>from objc ...
1
2009-04-04T02:33:10Z
717,655
<p>Even if they weren't serialized, the __init__-constructor of python isn't supported by the ObjectiveC-bridge. So one needs to overload e.g. initWithFrame: for self-created Views.</p>
2
2009-04-04T19:28:33Z
[ "python", "xcode", "osx", "pyobjc" ]
Packaging Ruby or Python applications for distribution?
716,524
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a co...
4
2009-04-04T04:52:53Z
716,538
<p>For Python, there's <a href="http://docs.python.org/library/distutils.html" rel="nofollow">distutils</a>, and Ars Technica had a <a href="http://arstechnica.com/open-source/guides/2009/03/how-to-deploying-pyqt-applications-on-windows-and-mac-os-x.ars" rel="nofollow">pretty good article</a> on packaging cross-platfor...
4
2009-04-04T05:08:36Z
[ "python", "ruby", "deployment" ]
Packaging Ruby or Python applications for distribution?
716,524
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a co...
4
2009-04-04T04:52:53Z
717,159
<p>I'm not sure I understand you here. You want to create a web-based application that you want to ship to end-users? I'm not sure how to interpret that:</p> <ul> <li>You want to create an app with a custom GUI that uses a network connection to grab data and stores some information locally in a database?</li> <li>Yo...
2
2009-04-04T14:10:28Z
[ "python", "ruby", "deployment" ]
Packaging Ruby or Python applications for distribution?
716,524
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a co...
4
2009-04-04T04:52:53Z
718,216
<p>You can't strictly do this (creating a single installer/executable) in a general cross-platform way, because different platforms use different executable formats. The JVM thing is relying on having a platform-specific JVM already installed on the destination computer; if there is <em>not</em> one installed, then yo...
1
2009-04-05T02:22:44Z
[ "python", "ruby", "deployment" ]
Packaging Ruby or Python applications for distribution?
716,524
<p>Are there any good options <em>other</em> than the JVM for packaging Python or Ruby applications for distribution to end-users? Specifically, I'm looking for ways to be able to write and test a web-based application written in either Ruby or Python, complete with a back-end database, that I can then wrap up in a co...
4
2009-04-04T04:52:53Z
7,002,189
<p>You can either distribute the app as a virtual machine or create an installer that includes all dependencies, like the GitHub guys did for their on-premise version.</p>
1
2011-08-09T20:00:27Z
[ "python", "ruby", "deployment" ]
Locating (file/line) the invocation of a constructor in python
716,795
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p> <p>So my question is: Is there an effici...
1
2009-04-04T08:58:33Z
716,803
<p>It may be worthwhile to attach a hash of the stack trace to the constructor of your event and to store the actual contents in memcache with the hash as the key.</p>
0
2009-04-04T09:06:57Z
[ "python", "exception", "event-handling", "stack-trace" ]
Locating (file/line) the invocation of a constructor in python
716,795
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p> <p>So my question is: Is there an effici...
1
2009-04-04T08:58:33Z
716,829
<pre><code>import sys def get_caller(ext=False): """ Get the caller of the caller of this function. If the optional ext parameter is given, returns the line's text as well. """ f=sys._getframe(2) s=(f.f_code.co_filename, f.f_lineno) del f if ext: import linecache s=(s[0], s[1], linecache.g...
1
2009-04-04T09:41:55Z
[ "python", "exception", "event-handling", "stack-trace" ]
Locating (file/line) the invocation of a constructor in python
716,795
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p> <p>So my question is: Is there an effici...
1
2009-04-04T08:58:33Z
716,855
<p>You could simply store a reference to the caller's frame object, but this is probably a bad idea. This keeps the frames alive, and also holds references to all the local variables used, so it may impact performance if they happen to be using large chunks of memory, and could have even worse effects if they're relyi...
1
2009-04-04T10:15:51Z
[ "python", "exception", "event-handling", "stack-trace" ]
Locating (file/line) the invocation of a constructor in python
716,795
<p>I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.</p> <p>So my question is: Is there an effici...
1
2009-04-04T08:58:33Z
718,230
<p>I'd think that the <i>simplest</i> method would be to add an ID field to the event(s) in question, and to have each event source (by whatever definition of 'event source' is appropriate here) provide a unique identifier when it posts the event. You do get slightly more overhead, but probably not enough to be proble...
1
2009-04-05T02:37:33Z
[ "python", "exception", "event-handling", "stack-trace" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
716,953
<p>I don't have any knowledge in this area. But I think you'll have to talk to the mobile operators, and see if they have any API for sending SMS messages. You'll probably have to pay them, or have some scheme for customers to pay them. Alternatively there might be some 3rd party that implements this functionality.</p...
0
2009-04-04T11:58:09Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
716,956
<p>What about using a proper sms gateway. These guys got APIs for several languages:</p> <p><a href="http://www.clickatell.com/developers/php.php" rel="nofollow">http://www.clickatell.com/developers/php.php</a></p> <p>There is an unofficial Python API too </p> <p><a href="http://www.arnebrodowski.de/projects/clickat...
3
2009-04-04T12:01:38Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
716,962
<p>There are a couple of options.</p> <ul> <li>Get some kind of SMS modem or connectivity and use your own cell phone using <a href="http://smslib.org/" rel="nofollow">smslib</a>. I am sorry I don't provide python interfaces but my experience is Java. The downside is that you will pay the full consumer rate. And you w...
4
2009-04-04T12:05:42Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
1,071,496
<p>Another SMS gateway with a Python interface is TextMagic. Their Python API is available from the Google Code project <a href="https://github.com/dfstrauss/textmagic-sms-api-python" rel="nofollow">textmagic-sms-api-python</a>. They have libraries available for other languages as well; all wrapping a simple HTTPS API....
3
2009-07-01T21:30:54Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
5,414,483
<p>The easiest way to accomplish this is by using a third party API. Some I know that work well are:</p> <ul> <li>restSms.me</li> <li>Twilio.com</li> <li>Clicatell.com</li> </ul> <p>I have used all of them and they easiest/cheapest one to implement was restSms.me</p> <p>Hope that helps.</p>
2
2011-03-24T03:38:58Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
35,903,945
<p>Warning: extremely elegant solution ahead! (Android app)</p> <p>If you want to send SMS to any number in as simple of a manner as sending an e-mail:</p> <pre><code>mail('configuredEMail@configuredDomain', '0981122334', 'SMS message'); // PHP </code></pre> <p>or even:</p> <pre><code>echo 'SMS message' | mail -s '...
0
2016-03-09T22:27:46Z
[ "python", "sms", "notifications" ]
How do I enable SMS notifications in my web apps?
716,946
<p>I have a web application and I would like to enable real time SMS notifications to the users of the applications. </p> <p>Note: I currently cannot use the Twitter API because I live in West Africa, and Twitter doesn't send SMS to my country.</p> <p>Also email2sms is not an option because the mobile operators don't...
1
2009-04-04T11:47:00Z
36,032,986
<p>If your country is in <a href="https://www.twilio.com/international" rel="nofollow">this list</a>, Twilio is an extremely easy API to use :)</p>
0
2016-03-16T10:28:38Z
[ "python", "sms", "notifications" ]
Python's subprocess.Popen returns the same stdout even though it shouldn't
717,120
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p> <p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <stron...
1
2009-04-04T13:49:46Z
717,143
<p>Nothing. That works fine, on my own tests (aside from your indentation error at the bottom). The problem is either in your exe. or elsewhere.</p> <p>To clarify, I created a python program tfile.py</p> <pre><code>cat &gt; tfile.py #!/usr/bin/env python import random print random.random() </code></pre> <p>And then ...
1
2009-04-04T13:59:45Z
[ "python", "subprocess", "stdout", "popen" ]
Python's subprocess.Popen returns the same stdout even though it shouldn't
717,120
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p> <p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <stron...
1
2009-04-04T13:49:46Z
717,160
<p>Your code is not executable as is so it's hard to help you out much. Consider fixing indentation and syntax and making it self-contained, so that we can give it a try.</p> <p>On Linux, it seems to work fine according to Devin Jeanpierre.</p>
0
2009-04-04T14:10:51Z
[ "python", "subprocess", "stdout", "popen" ]
Python's subprocess.Popen returns the same stdout even though it shouldn't
717,120
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p> <p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <stron...
1
2009-04-04T13:49:46Z
718,047
<p>I don't know what is going wrong with your example, I cannot replicate this behaviour, however try a more by-the-book approach:</p> <pre><code>def get_key(): from subprocess import Popen, PIPE args = [C_KEY_MAKER, '/26', USER_NAME, ENCRYPTION_TEMPLATE, '0', ] output = Popen(args, stdout=PIPE).stdout ...
1
2009-04-04T23:38:53Z
[ "python", "subprocess", "stdout", "popen" ]
Python's subprocess.Popen returns the same stdout even though it shouldn't
717,120
<p>I'm having a very strange issue with Python's subprocess.Popen. I'm using it to call several times an external exe and keep the output in a list. </p> <p>Every time you call this external exe, it will return <strong>a different string</strong>. However, if I call it several times using Popen, it will always <stron...
1
2009-04-04T13:49:46Z
1,124,714
<p>It is possible (if <code>C_KEY_MAKER</code>'s random behaviour is based on the current time in seconds, or similar) that when you run it twice on the command line, the time has changed in between runs and so you get a different output, but when python runs it, it runs it twice in such quick succession that the time ...
3
2009-07-14T11:08:41Z
[ "python", "subprocess", "stdout", "popen" ]
Queue.Queue vs. collections.deque
717,148
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p> <p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p> <p>However, the Queue docs als...
85
2009-04-04T14:03:09Z
717,199
<p><code>deque</code> is thread-safe. "operations that do not require locking" means that you don't have to do the locking yourself, the <code>deque</code> takes care of it.</p> <p>Taking a look at the <code>Queue</code> source, the internal deque is called <code>self.queue</code> and uses a mutex for accessors and mu...
3
2009-04-04T14:42:23Z
[ "python", "thread-safety", "queue" ]
Queue.Queue vs. collections.deque
717,148
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p> <p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p> <p>However, the Queue docs als...
85
2009-04-04T14:03:09Z
717,261
<p><code>Queue.Queue</code> and <code>collections.deque</code> serve different purposes. Queue.Queue is intended for allowing different threads to communicate using queued messages/data, whereas <code>collections.deque</code> is simply intended as a datastructure. That's why <code>Queue.Queue</code> has methods like <c...
142
2009-04-04T15:26:29Z
[ "python", "thread-safety", "queue" ]
Queue.Queue vs. collections.deque
717,148
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p> <p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p> <p>However, the Queue docs als...
85
2009-04-04T14:03:09Z
20,330,499
<p>If all you're looking for is <strong>a thread-safe way to transfer objects between threads</strong>, then both would work (both for FIFO and LIFO). For FIFO:</p> <ul> <li><a href="http://docs.python.org/2/library/queue.html#"><code>Queue.put()</code> and <code>Queue.get()</code> are thread-safe</a></li> <li><a href...
18
2013-12-02T14:20:14Z
[ "python", "thread-safety", "queue" ]
Queue.Queue vs. collections.deque
717,148
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p> <p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p> <p>However, the Queue docs als...
85
2009-04-04T14:03:09Z
31,672,446
<p>(seems I don't have reputation to comment...) You need to be careful which methods of the deque you use from different threads.</p> <p>deque.get() appears to be threadsafe, but I have found that doing</p> <pre><code>for item in a_deque: process(item) </code></pre> <p>can fail if another thread is adding items ...
0
2015-07-28T09:31:09Z
[ "python", "thread-safety", "queue" ]
Queue.Queue vs. collections.deque
717,148
<p>I need a queue which multiple threads can put stuff into, and multiple threads may read from.</p> <p>Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.</p> <p>However, the Queue docs als...
85
2009-04-04T14:03:09Z
34,239,413
<p>For information there is a Python ticket referenced for deque thread-safety (<a href="https://bugs.python.org/issue15329" rel="nofollow">https://bugs.python.org/issue15329</a>). Title "clarify which deque methods are thread-safe"</p> <p>Bottom line here: <a href="https://bugs.python.org/issue15329#msg199368" rel="n...
1
2015-12-12T11:41:50Z
[ "python", "thread-safety", "queue" ]
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p> <p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python langua...
12
2009-04-04T17:54:50Z
717,527
<p>The languages might permit it, but neither community condones the practice. Monkeypatching isn't condoned in either language, but you hear about it more often in Ruby because the form of open class it uses makes it very, very easy to monkeypatch a class and because of this, <a href="http://avdi.org/devblog/2008/02/2...
13
2009-04-04T18:03:18Z
[ "python", "ruby", "language-features", "monkeypatching" ]
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
717,506
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p> <p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python langua...
12
2009-04-04T17:54:50Z
717,553
<p>"Does Python include different types of safeguards to minimize the risks of this feature?" </p> <p>Yes. The community refuses to do it. The safeguard is entirely social.</p>
13
2009-04-04T18:17:20Z
[ "python", "ruby", "language-features", "monkeypatching" ]