title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Pylons error "No object (name: request) has been registered for this thread" with debug = false
2,496,347
<p>I'm unable to access the <code>request</code> object in my Pylons 0.9.7 controller when I set <code>debug = false</code> in the .ini file. I have the following code:</p> <pre><code>def run_something(self): print('!!! request = %r' % request) print('!!! request.params = %r' % request.params) yield 'Stuff...
0
2010-03-22T22:55:24Z
24,314,538
<p>When you set up your middleware, enable streaming support in RegistryManager:</p> <pre><code>app = RegistryManager(app, streaming=True) </code></pre> <p>This keeps the registry (aoo_globals etc.) alive until your response has finished iterating.</p>
0
2014-06-19T19:11:43Z
[ "python", "debugging", "pylons" ]
Problems serving static files in CherryPy 3.1
2,496,458
<p>I'm having some trouble serving a static XML stylesheet to accompany some dynamically generated output from a CherryPy web app. Even my test case serving a static text file fails.</p> <p>Static file <code>blah.txt</code> is in the <code>/static</code> directory in my application root directory.</p> <p>In my main s...
3
2010-03-22T23:20:34Z
2,498,261
<p>I serve static files like this:</p> <pre><code>config = {'/static': {'tools.staticdir.on': True, 'tools.staticdir.dir': PATH_TO_STATIC_FILES, } } cherrypy.tree.mount(MyApp(), '/', config=config) </code></pre>
3
2010-03-23T07:42:06Z
[ "python", "cherrypy" ]
Problems serving static files in CherryPy 3.1
2,496,458
<p>I'm having some trouble serving a static XML stylesheet to accompany some dynamically generated output from a CherryPy web app. Even my test case serving a static text file fails.</p> <p>Static file <code>blah.txt</code> is in the <code>/static</code> directory in my application root directory.</p> <p>In my main s...
3
2010-03-22T23:20:34Z
2,503,852
<p><code>cherrypy.config.update</code> should only receive a single-level dictionary (mostly <code>server.*</code> entries), but you're passing it a multi-level dictionary of settings that should really be per-app (and therefore passed to <code>tree.mount</code>).</p> <p>Move those <code>[/]</code> and <code>[/static]...
4
2010-03-23T21:44:24Z
[ "python", "cherrypy" ]
Problems serving static files in CherryPy 3.1
2,496,458
<p>I'm having some trouble serving a static XML stylesheet to accompany some dynamically generated output from a CherryPy web app. Even my test case serving a static text file fails.</p> <p>Static file <code>blah.txt</code> is in the <code>/static</code> directory in my application root directory.</p> <p>In my main s...
3
2010-03-22T23:20:34Z
2,732,462
<p>I have a similar setup. Let's say that I want the root of my site to be at <a href="http://mysite.com/site" rel="nofollow">http://mysite.com/site</a> and that the root of my site/app is at <em>/path/to/www</em>.</p> <p>I have the following config settings in my server.cfg and am finding my static files without a p...
1
2010-04-28T19:16:30Z
[ "python", "cherrypy" ]
Asynchronous background processes in Python?
2,496,772
<p>I have been using this as a reference, but not able to accomplish exactly what I need: <a href="http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395">http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python/92395#92395</a></p> <p>I also was reading this:...
6
2010-03-23T00:40:48Z
2,496,824
<p>Don't use <code>shell=True</code>. It will needlessy invoke the shell to call your <code>svn</code> program, and that will give you the shell's return code instead of svn's.</p> <pre><code>repos = ['/repo1', '/repo2', '/repo3'] # launch 3 async calls: procs = [subprocess.Popen(['svn', 'update', repo]) for repo in r...
15
2010-03-23T00:50:32Z
[ "python", "asynchronous", "background-process" ]
convert a binary file in a list (python)
2,496,854
<p>I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ?</p> <p>Thanks !</p>
1
2010-03-23T01:02:11Z
2,496,877
<p>Assume that <code>myfile.txt</code> has 'abcdef\n' in it...</p> <pre><code>&gt;&gt;&gt; fh = open('myfile.txt', 'rb') &gt;&gt;&gt; list(fh.read()) ['a', 'b', 'c', 'd', 'e', 'f', '\n'] </code></pre>
0
2010-03-23T01:08:07Z
[ "python", "list", "binary" ]
convert a binary file in a list (python)
2,496,854
<p>I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ?</p> <p>Thanks !</p>
1
2010-03-23T01:02:11Z
2,496,887
<p>You can read the binary data into a string just like you would do with text data, just make sure to open the file in binary mode (the <code>b</code> flag in the call to <code>open()</code>):</p> <pre><code>with open('file.bin', 'rb') as f: data = f.read() </code></pre> <p><code>data</code> now contains the char...
2
2010-03-23T01:10:04Z
[ "python", "list", "binary" ]
convert a binary file in a list (python)
2,496,854
<p>I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ?</p> <p>Thanks !</p>
1
2010-03-23T01:02:11Z
2,496,957
<p>You need to understand that "\x21" and "!" are two ways of representing the same thing</p> <p>so <code>"\x21\x23\x22\x21\x22\x31"</code> is the same as <code>'!#"!"1'</code></p> <pre><code>&gt;&gt;&gt; "\x21\x23\x22\x21\x22\x31" == '!#"!"1' True &gt;&gt;&gt; infile = open('infile.txt', 'rb') &gt;&gt;&gt; list(in...
4
2010-03-23T01:27:33Z
[ "python", "list", "binary" ]
convert a binary file in a list (python)
2,496,854
<p>I'd like to be able to open a binary file, and make a list (kind of array) with all the chars in, like : "\x21\x23\x22\x21\x22\x31" to ["\x21","\x23","\x22","\x21","\x22","\x31"] What would be the best solution to convert it ?</p> <p>Thanks !</p>
1
2010-03-23T01:02:11Z
2,497,088
<p>To make "a kind of array" of characters, an extremely efficient way (more than using a list!) is to use Python's standard library <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a> module:</p> <pre><code>res = array.array('c') with open('binaryfile', 'rb') as f: while True: try...
1
2010-03-23T02:02:52Z
[ "python", "list", "binary" ]
Is there a function in C that does the same as raw_input in Python?
2,496,857
<p>Is there a C function that does the same as <code>raw_input</code> in Python?</p> <pre><code>#in Python:: x = raw_input("Message Here:") </code></pre> <p>How can I write something like that in C?</p> <p><strong>Update::</strong></p> <p>I make this, but i get an error ::</p> <pre><code>#include&lt;stdio.h&gt; #i...
1
2010-03-23T01:03:14Z
2,496,878
<p>You can write one pretty easily, but you'll want to be careful about buffer overflows:</p> <pre><code>void raw_input(char *prompt, char *buffer, size_t length) { printf("%s", prompt); fflush(stdout); fgets(buffer, length, stdin) } </code></pre> <p>Then use it like this:</p> <pre><code>char x[MAX_INPUT...
5
2010-03-23T01:08:07Z
[ "python", "c", "raw-input" ]
Is there a function in C that does the same as raw_input in Python?
2,496,857
<p>Is there a C function that does the same as <code>raw_input</code> in Python?</p> <pre><code>#in Python:: x = raw_input("Message Here:") </code></pre> <p>How can I write something like that in C?</p> <p><strong>Update::</strong></p> <p>I make this, but i get an error ::</p> <pre><code>#include&lt;stdio.h&gt; #i...
1
2010-03-23T01:03:14Z
2,496,879
<p>Use <code>printf</code> to print your prompt, then use <a href="http://www.cplusplus.com/reference/clibrary/cstdio/fgets/" rel="nofollow"><code>fgets</code></a> to read the reply.</p>
0
2010-03-23T01:08:16Z
[ "python", "c", "raw-input" ]
Is there a function in C that does the same as raw_input in Python?
2,496,857
<p>Is there a C function that does the same as <code>raw_input</code> in Python?</p> <pre><code>#in Python:: x = raw_input("Message Here:") </code></pre> <p>How can I write something like that in C?</p> <p><strong>Update::</strong></p> <p>I make this, but i get an error ::</p> <pre><code>#include&lt;stdio.h&gt; #i...
1
2010-03-23T01:03:14Z
2,497,246
<p>The <a href="http://www.opengroup.org/onlinepubs/9699919799/mindex.html" rel="nofollow">POSIX.1-2008</a> standard specifies the function <a href="http://www.opengroup.org/onlinepubs/9699919799/functions/getline.html" rel="nofollow">getline</a>, which will dynamically (re)allocate memory to make space for a line of ...
2
2010-03-23T02:42:00Z
[ "python", "c", "raw-input" ]
Is there a function in C that does the same as raw_input in Python?
2,496,857
<p>Is there a C function that does the same as <code>raw_input</code> in Python?</p> <pre><code>#in Python:: x = raw_input("Message Here:") </code></pre> <p>How can I write something like that in C?</p> <p><strong>Update::</strong></p> <p>I make this, but i get an error ::</p> <pre><code>#include&lt;stdio.h&gt; #i...
1
2010-03-23T01:03:14Z
29,636,153
<p>The selected answer seems a complex to me.</p> <p>A little easier for learning:</p> <pre><code>#include "stdio.h" int main() { char array[100]; printf("Type here: "); gets(array); printf("You said: %s\n", array); return 0; } </code></pre>
0
2015-04-14T19:49:03Z
[ "python", "c", "raw-input" ]
add/remove items in a list
2,496,926
<p>I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appears in the program! I know I'm...
4
2010-03-23T01:18:46Z
2,496,953
<p>The problem is this statement:</p> <pre><code>print "Inventory:", player.inventory() </code></pre> <p>You're telling Python to print the value returned from player.inventory(). But your inventory() method just prints the inventory, it doesn't return anything - so the return value is implicitly None.</p> <p>You pr...
4
2010-03-23T01:26:15Z
[ "python" ]
add/remove items in a list
2,496,926
<p>I'm trying to create a player who can add and remove items from their inventory. I have everything working, I just have 1 small problem. Every time it prints the inventory, 'None' also appears. I've been messing with it to try and remove that, but no matter what I do, 'None' always appears in the program! I know I'm...
4
2010-03-23T01:18:46Z
2,496,964
<p>Would you mind replacing the function:</p> <pre><code>def inventory(self): for item in self.items: print item </code></pre> <p>with this:</p> <pre><code>def inventory(self): print self.items </code></pre> <p>and then call:</p> <pre><code>print "Inventory" player.inventory() </code></pre> <p>Or you ...
0
2010-03-23T01:28:31Z
[ "python" ]
Can I create class properties during __new__ or __init__?
2,496,930
<p>I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:</p> <pre><code>class Base(object): def __init__(self): for attr in self._myattrs: setattr(self, attr, property(lambda self: self._l...
3
2010-03-23T01:19:59Z
2,497,009
<p>You can access class attributes through the __ class __ dict</p> <pre><code>self.__class__.attr </code></pre>
0
2010-03-23T01:41:17Z
[ "python" ]
Can I create class properties during __new__ or __init__?
2,496,930
<p>I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:</p> <pre><code>class Base(object): def __init__(self): for attr in self._myattrs: setattr(self, attr, property(lambda self: self._l...
3
2010-03-23T01:19:59Z
2,497,012
<p>You could consider using <code>__getattr__()</code> instead:</p> <pre> class Base(object): def __getattr__(self, attr): if attr not in self._myattrs: raise AttributeError return self._lazy_eval(attr) def _lazy_eval(self, attr): #Do complex stuff here return attr ...
0
2010-03-23T01:41:45Z
[ "python" ]
Can I create class properties during __new__ or __init__?
2,496,930
<p>I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:</p> <pre><code>class Base(object): def __init__(self): for attr in self._myattrs: setattr(self, attr, property(lambda self: self._l...
3
2010-03-23T01:19:59Z
2,497,042
<p>Descriptors (such as instances of the <code>property</code> type) are only meaningful when they're held in the <em>class</em> object, not the <em>instance</em> object. So, you need to change the class, not the instance, and (in Python 2.6 or better) a class decorator is very handy for that purpose:</p> <pre><code>...
5
2010-03-23T01:50:50Z
[ "python" ]
Can I create class properties during __new__ or __init__?
2,496,930
<p>I want to do something like this, but I haven't had much success so far. I would like to make each attr a property that computes _lazy_eval only when accessed:</p> <pre><code>class Base(object): def __init__(self): for attr in self._myattrs: setattr(self, attr, property(lambda self: self._l...
3
2010-03-23T01:19:59Z
2,497,162
<p>Technically you want a metaclass:</p> <pre><code>class LazyMeta(type): def __init__(cls, name, bases, attr): super(LazyMeta, cls).__init__(name, bases, attr) def prop( x ): return property(lambda self: self._lazy_eval(x)) for x in attr['lazyattrs']: setattr(cls, x...
1
2010-03-23T02:22:49Z
[ "python" ]
python duration of a file object in an argument list
2,496,983
<p>In the <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle module documentation</a> there is a snippet of example code:</p> <pre><code>reader = pickle.load(open('save.p', 'rb')) </code></pre> <p>which upon first read looked like it would allocate a system file descriptor, read its contents a...
2
2010-03-23T01:33:30Z
2,497,015
<blockquote> <p>What is the duration of the file object returned by the example code above?</p> </blockquote> <p>That code does not <em>return</em> the file object (as the Q's title correctly says, it receives it as an argument).</p> <p>In current CPython, the file will be closed at the time the function return...
3
2010-03-23T01:42:22Z
[ "python", "internals" ]
How to disable Excel's auto recognition of numbers and text
2,496,990
<p>I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. </p> <p>e.g.<code>33E105</code> becomes <code>33*10^105</code>, which is actually an ID, not a number. </p> <p>How to disable this in Excel while opening a CSV file? Or I ne...
8
2010-03-23T01:35:16Z
2,497,006
<p>I think you can put a single <code>'</code> in front to stop numeric strings being turned into ints</p> <p>Eg.</p> <pre><code>...,"'33E105",... </code></pre> <p>OpenXML is a more flexible (and complicated) option, but only works with Office2003 or newer and is overkill for this problem. More suited to cases when ...
2
2010-03-23T01:40:49Z
[ "python", "excel" ]
How to disable Excel's auto recognition of numbers and text
2,496,990
<p>I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. </p> <p>e.g.<code>33E105</code> becomes <code>33*10^105</code>, which is actually an ID, not a number. </p> <p>How to disable this in Excel while opening a CSV file? Or I ne...
8
2010-03-23T01:35:16Z
2,497,010
<p>You could precede it with a single quote, forcing it to text.</p> <p>A fun answer is you could keep the first eight rows blank (it only processes the first eight rows to determine data type), although I think this may blank all your data entirely. You could hide those empty rows.</p>
4
2010-03-23T01:41:33Z
[ "python", "excel" ]
How to disable Excel's auto recognition of numbers and text
2,496,990
<p>I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. </p> <p>e.g.<code>33E105</code> becomes <code>33*10^105</code>, which is actually an ID, not a number. </p> <p>How to disable this in Excel while opening a CSV file? Or I ne...
8
2010-03-23T01:35:16Z
2,497,011
<p>You have 3 options:</p> <ul> <li><p>Output a specially formatted XML file that Excel can read. I don't recall any details but if interested, I can dig them up. We did that with our Perl code. I don't know if excel-python does just that.</p></li> <li><p><strong>Place <code>'</code> (apostrophe) before each string.</...
3
2010-03-23T01:41:43Z
[ "python", "excel" ]
How to disable Excel's auto recognition of numbers and text
2,496,990
<p>I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. </p> <p>e.g.<code>33E105</code> becomes <code>33*10^105</code>, which is actually an ID, not a number. </p> <p>How to disable this in Excel while opening a CSV file? Or I ne...
8
2010-03-23T01:35:16Z
2,497,013
<p>If you dont' want to change how you're writing the CSV file you can use the Text Import Wizard in Excel to specify how you want the individual columns to be treated. There is one step in the wizard that lets you select what type of data is in each column. Set the column(s) you want to Text and it will treat it as ...
0
2010-03-23T01:41:55Z
[ "python", "excel" ]
How to disable Excel's auto recognition of numbers and text
2,496,990
<p>I used Python to generate a CSV file. But when I open it in Excel, Excel will auto recognize a string into a number if it could be converted. </p> <p>e.g.<code>33E105</code> becomes <code>33*10^105</code>, which is actually an ID, not a number. </p> <p>How to disable this in Excel while opening a CSV file? Or I ne...
8
2010-03-23T01:35:16Z
2,497,061
<p>To write actual <code>.xls</code> files in Python, rather than <code>.csv</code> ones that Excel might misinterpret, you can use the <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> third-party Python package.</p>
1
2010-03-23T01:56:00Z
[ "python", "excel" ]
read a binary file (python)
2,497,027
<p>I cant read a file, and I dont understand why:</p> <pre><code>f = open("test/test.pdf", "r") data = list(f.read()) print data </code></pre> <p>Returns : <code>[]</code></p> <p>I would like to open a PDF, and extract every bytes, and put it in a List.</p> <p>What's wrong with my code ? :(</p> <p>Thanks,</p>
5
2010-03-23T01:46:20Z
2,497,038
<pre><code>f = open("test/test.pdf", "rb") </code></pre> <p>You must include the pseudo-mode "b" for binary when reading and writing on Windows. Otherwise the OS silently translates what it considers to be "line endings", causing i/o corruption.</p>
10
2010-03-23T01:49:40Z
[ "python", "file", "io" ]
read a binary file (python)
2,497,027
<p>I cant read a file, and I dont understand why:</p> <pre><code>f = open("test/test.pdf", "r") data = list(f.read()) print data </code></pre> <p>Returns : <code>[]</code></p> <p>I would like to open a PDF, and extract every bytes, and put it in a List.</p> <p>What's wrong with my code ? :(</p> <p>Thanks,</p>
5
2010-03-23T01:46:20Z
2,497,099
<p>Jonathan is correct that you should be opening the file in binary mode if you are on windows.</p> <p>However, a PDF file will start with "%PDF-", which would at least be read in regardless of whether you are using binary mode or not.</p> <p>So it appears to me that your "test/test.pdf" is an empty file</p>
1
2010-03-23T02:06:13Z
[ "python", "file", "io" ]
read a binary file (python)
2,497,027
<p>I cant read a file, and I dont understand why:</p> <pre><code>f = open("test/test.pdf", "r") data = list(f.read()) print data </code></pre> <p>Returns : <code>[]</code></p> <p>I would like to open a PDF, and extract every bytes, and put it in a List.</p> <p>What's wrong with my code ? :(</p> <p>Thanks,</p>
5
2010-03-23T01:46:20Z
2,497,387
<ul> <li>As best as I understand the pdf format, a pdf file shouldn't be a binary file. It should be a text file that may contain lots of binary blobs. I could be wrong.</li> <li>On Windows, if you are opening a binary file, you need to include <code>b</code> in the mode of your file, i.e. <code>open(filename, "rb")</c...
0
2010-03-23T03:21:59Z
[ "python", "file", "io" ]
read a binary file (python)
2,497,027
<p>I cant read a file, and I dont understand why:</p> <pre><code>f = open("test/test.pdf", "r") data = list(f.read()) print data </code></pre> <p>Returns : <code>[]</code></p> <p>I would like to open a PDF, and extract every bytes, and put it in a List.</p> <p>What's wrong with my code ? :(</p> <p>Thanks,</p>
5
2010-03-23T01:46:20Z
2,497,406
<p>What platform are you running on?</p> <p>Using python 2.6 on Windows XP, I get:</p> <blockquote> <blockquote> <blockquote> <p>f = open("14500lf.pdf", "r")<br> data = list(f.read())<br> print data<br> ['%', 'P', 'D', 'F', '-', '1', '.', '5', '\r', '%', '\xe2', '\xe3', '\xcf', '\xd3', '...
0
2010-03-23T03:30:26Z
[ "python", "file", "io" ]
Python: Dynamic attribute name generation without exec() or eval()
2,497,168
<p>I'm trying to dynamically create buttons at runtime with PyQT4.7</p> <p>However, this being my first python program I'm not sure how to get the functionality I want.</p> <p>I would like to be able to substitute a text string for an attribute name:</p> <p>i.e. </p> <pre><code>for each in xrange(4): myname = ...
0
2010-03-23T02:23:39Z
2,497,188
<p>If I interpreted this correctly, I think what you want is this:</p> <p><code>self.ui.gridLayout.addWidget(getattr(self.ui,myname))</code></p> <p>Give that a go. In Python the following two statements are functionally equivalent (from the link below):</p> <pre><code>value = obj.attribute value = getattr(obj, "att...
3
2010-03-23T02:27:29Z
[ "python", "pyqt4" ]
Python: Dynamic attribute name generation without exec() or eval()
2,497,168
<p>I'm trying to dynamically create buttons at runtime with PyQT4.7</p> <p>However, this being my first python program I'm not sure how to get the functionality I want.</p> <p>I would like to be able to substitute a text string for an attribute name:</p> <p>i.e. </p> <pre><code>for each in xrange(4): myname = ...
0
2010-03-23T02:23:39Z
2,497,193
<p>Just assign the button to a variable so you can both set the attribute and add the widget.</p> <pre><code>for i in range(4): name = 'button%d' % i button = QtGui.QPushButton(...) setattr(self, name, button) self.ui.gridLayout.addWidget(button) </code></pre> <p>Personally I would add the buttons to ...
0
2010-03-23T02:28:26Z
[ "python", "pyqt4" ]
Python: Dynamic attribute name generation without exec() or eval()
2,497,168
<p>I'm trying to dynamically create buttons at runtime with PyQT4.7</p> <p>However, this being my first python program I'm not sure how to get the functionality I want.</p> <p>I would like to be able to substitute a text string for an attribute name:</p> <p>i.e. </p> <pre><code>for each in xrange(4): myname = ...
0
2010-03-23T02:23:39Z
2,497,249
<p>I think you might benefit from knowledge of lists (commonly called arrays in other languages)</p> <pre><code>self.buttons = [None, None, None, None] for each in xrange(4): self.buttons[each] = QtGui.QPushButton(self.ui.tab) self.ui.gridLayout.addWidget(self.buttons[each]) </code></pre> <p>For a tutorial ...
0
2010-03-23T02:42:23Z
[ "python", "pyqt4" ]
Plot string values in matplotlib
2,497,449
<p>I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using <code>plot</code> function expects a numeric value for X.</p> <p>How can I use string X values?</p>
3
2010-03-23T03:47:44Z
2,497,637
<p>Here's one way which i know works, though i would think creating custom symbols is a more natural way accomplish this.</p> <pre><code>from matplotlib import pyplot as PLT # make up some data for this example t = range(8) s = 7 * t + 5 # make up some data labels which we want to appear in place of the symbols x = 8...
1
2010-03-23T04:44:58Z
[ "python", "matplotlib" ]
Plot string values in matplotlib
2,497,449
<p>I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using <code>plot</code> function expects a numeric value for X.</p> <p>How can I use string X values?</p>
3
2010-03-23T03:47:44Z
2,497,667
<p>Why not just make the x value some auto-incrementing number and then change the label?</p> <p>--jed</p>
3
2010-03-23T04:55:28Z
[ "python", "matplotlib" ]
Plot string values in matplotlib
2,497,449
<p>I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using <code>plot</code> function expects a numeric value for X.</p> <p>How can I use string X values?</p>
3
2010-03-23T03:47:44Z
8,971,220
<p>I couldn't find a convenient way to accomplish that, so I resorted to this little helper function.</p> <pre><code>import matplotlib.pyplot as p def plot_classes(x, y, plotfun=p.scatter, **kwargs): from itertools import count import numpy as np classes = sorted(set(x)) class_dict = dict(zip(classes, ...
0
2012-01-23T11:56:20Z
[ "python", "matplotlib" ]
Plot string values in matplotlib
2,497,449
<p>I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using <code>plot</code> function expects a numeric value for X.</p> <p>How can I use string X values?</p>
3
2010-03-23T03:47:44Z
15,947,634
<p>You should try xticks</p> <pre><code>import pylab names = ['anne','barbara','cathy'] counts = [3230,2002,5456] pylab.figure(1) x = range(3) pylab.xticks(x, names) pylab.plot(x,counts,"g") pylab.show() </code></pre>
5
2013-04-11T11:30:02Z
[ "python", "matplotlib" ]
I am currently serving my static files in Django. How do I use Apache2 to do this?
2,497,485
<pre><code>(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), </code></pre> <p>As you can see, I have a directory called "media" under my Django project.</p> <p>I would like to delete this line in my <code>urls.py</code> and instead us Apache to serve my static files....
1
2010-03-23T04:01:17Z
2,497,506
<p>I would read Django's <a href="http://docs.djangoproject.com/en/dev/howto/static-files/" rel="nofollow">official static files docs</a> and <a href="http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#serving-media-files" rel="nofollow">apache mod_python documentation</a>.</p> <blockquote> <p>This exa...
4
2010-03-23T04:04:57Z
[ "python", "linux", "django", "apache", "unix" ]
I'm making a simulated tv
2,497,525
<p>I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please.</p> <pre><c...
1
2010-03-23T04:11:13Z
2,497,571
<ol> <li><p>The channel number is integer, but raw_input returns string. Should be:</p> <pre><code>change = int(raw_input("What would you like to change the channel to?")) </code></pre></li> <li><p>also your <code>set_channel</code> function has this:</p> <pre><code>channel=self.__channel </code></pre> <p>When it sh...
5
2010-03-23T04:26:17Z
[ "python", "class", "properties" ]
I'm making a simulated tv
2,497,525
<p>I need to make a tv that shows the user the channel and the volume, and shows whether or not the television is on. I have the majority of the code made, but for some reason the channels won't switch. I'm fairly unfamiliar with how properties work, and I think that's what my problem here is. Help please.</p> <pre><c...
1
2010-03-23T04:11:13Z
2,497,650
<p>EXTRA HINTS:</p> <p><em><strong>Posting this as community wiki so everybody can help with ideas and hints.</em></strong></p> <ul> <li>Don't name your attributes starting with two underscores. It <strong>doesn't</strong> mean private. If you want some private name, use a single underscore.</li> <li>You're not reall...
3
2010-03-23T04:50:43Z
[ "python", "class", "properties" ]
How can I tell [G]vim where to look for python26.dll?
2,497,551
<p>I have a version of Vim compiled with python 2.6 support enabled (<a href="http://www.gooli.org/blog/">from here</a>). however vim cannot find the python26.dll.</p> <pre><code>:version confirms +python/dyn :version and gvim.exe confirms DYNAMIC_PYTHON_DLL="python26.dll" echo PATH confirms python26.dll is in the sea...
8
2010-03-23T04:20:55Z
2,497,651
<p>Be sure that any dll you try to load is compiled for the same architecture as the exe. e.g. If you have x86 Vim installed. Make sure that the python dll you are loading is not x64, or vice-versa.</p>
8
2010-03-23T04:50:51Z
[ "python", "vim" ]
Updating section in ConfigParser (or an alternative)
2,497,717
<p>I am making a plugin for another program and so I am trying to make thing as lightweight as possible. </p> <p>What i need to do is be able to update the name of a section in the ConfigParser's config file.</p> <pre><code>[project name] author:john doe email: spam@example.com year: 2010 </code></pre> <p>I then hav...
1
2010-03-23T05:10:23Z
2,497,767
<p>ini files are probably best suited for <em>configuring</em> applications, with well-defined inputs and so forth. It sounds like you want a more generic serialization tool; JSON would probably work well for this. Perhaps you want to store a JSON representation of a list (hence your incrementing indices) of dicts with...
2
2010-03-23T05:27:40Z
[ "python", "configparser" ]
Python overriding class (not instance) special methods
2,497,790
<p>How do I override a class special method?</p> <p>I want to be able to call the <code>__str__()</code> method of the class without creating an instance. Example:</p> <pre><code>class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' c...
8
2010-03-23T05:35:25Z
2,497,805
<p>Why do you want to abuse the meaning of <code>__str__</code>? That method is reserved for the meaning "return a string representation of <em>this instance</em>".</p> <p>If you want a function that just returns a static string, it would be better to have that as a separate function not inside a class.</p> <p>If you...
1
2010-03-23T05:41:05Z
[ "python", "class", "override" ]
Python overriding class (not instance) special methods
2,497,790
<p>How do I override a class special method?</p> <p>I want to be able to call the <code>__str__()</code> method of the class without creating an instance. Example:</p> <pre><code>class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' c...
8
2010-03-23T05:35:25Z
2,497,807
<p>Special method <code>__str__</code> defined in a class works only for the instances of that class, to have the different behavior for class objects you will have to do it in a metaclass of that class e.g. (python 2.5)</p> <pre><code>class Meta(type): def __str__(self): return "Klass" class A(object): ...
15
2010-03-23T05:41:34Z
[ "python", "class", "override" ]
Python overriding class (not instance) special methods
2,497,790
<p>How do I override a class special method?</p> <p>I want to be able to call the <code>__str__()</code> method of the class without creating an instance. Example:</p> <pre><code>class Foo: def __str__(self): return 'Bar' class StaticFoo: @staticmethod def __str__(): return 'StaticBar' c...
8
2010-03-23T05:35:25Z
2,497,924
<p>I'm not sure what you are trying to do, exactly. Let me just add a bit of random information.</p> <p>First, add this class:</p> <pre><code>class FooNew(object): def __str__(self): return 'Fubar' </code></pre> <p>Print this instead:</p> <pre><code>if __name__ == '__main__': print "You are calling type f...
0
2010-03-23T06:15:31Z
[ "python", "class", "override" ]
creating matrix with probabilities
2,497,843
<p>I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities). </p> <p>Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in fact most of the elements shou...
1
2010-03-23T05:53:15Z
2,497,922
<pre><code>import random N = 10 matrix = [] for j in range(N): t = [int(random.random()&lt;0.6) for i in range(N)] ones = t.count(1) row = [float(x)/ones for x in t] if ones else t matrix.append(row) for r in matrix: print r </code></pre>
2
2010-03-23T06:14:47Z
[ "c++", "python" ]
creating matrix with probabilities
2,497,843
<p>I want to generate a matrix of NxN to test some code that I have where each row contains floats as the elements and has to add up to 1 (i.e. a row with a set of probabilities). </p> <p>Where it gets tricky is that I want to make sure that randomly some of the elements should be 0 (in fact most of the elements shou...
1
2010-03-23T05:53:15Z
2,497,974
<p>By C++ array, do you mean a C array or a STL <code>vector&lt;vector&lt; &gt; &gt;</code>? The latter would be cleaner, but here's an example using C arrays:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; float* makeProbabilityMatrix(int N, float zeroProbability) { float* matrix = (float*)mal...
0
2010-03-23T06:28:19Z
[ "c++", "python" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,034
<p>I still say 7-zip is the answer. It hasn't been "cracked".</p>
3
2010-03-23T06:40:53Z
[ "java", ".net", "c++", "python", "encryption" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,045
<p>The <strong>OpenSSL</strong> library has a variety of block cipher implementations including the well-known AES. It has both a function-call interface (for use with languages like C/C++) and a program-call interface (for use in shell scripts). <a href="http://www.openssl.org/" rel="nofollow">http://www.openssl.org...
3
2010-03-23T06:43:22Z
[ "java", ".net", "c++", "python", "encryption" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,052
<p>Use <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="nofollow">AES</a>. You'll find implementations in your favourite programming language by asking google for <code>AES encryption + myfavouritelanguage</code>. </p>
2
2010-03-23T06:44:27Z
[ "java", ".net", "c++", "python", "encryption" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,054
<blockquote> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> </blockquote> <ul> <li>tar and gzip the directory. </li> <li>Generate a random bit stream of equal size to the file</li> <li>Run bitwise XOR on the streams</li> </ul> <p>Only truly secure method is a trul...
4
2010-03-23T06:44:55Z
[ "java", ".net", "c++", "python", "encryption" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,271
<p><b>4096</b>-Bit (<b>Open</b>)PGP: '<b>Pretty Good</b>' <i>Privacy</i> ! <br /><br /></p> <blockquote> GnuPG is the GNU project's complete and free implementation of the OpenPGP standard as defined by RFC4880 . GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as...
3
2010-03-23T07:44:20Z
[ "java", ".net", "c++", "python", "encryption" ]
Best way to encrypt a directory of files?
2,498,009
<p>I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.</p> <p>How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?</p> <p>Programming language doesn't matter. I am dictioned in all syntax.</p>
3
2010-03-23T06:36:17Z
2,498,283
<p>If you're using .NET, why not use a free compression framework (<a href="http://www.icsharpcode.net/OpenSource/SharpZipLib/" rel="nofollow">http://www.icsharpcode.net/OpenSource/SharpZipLib/</a>) that supports Encryption?</p>
0
2010-03-23T07:46:47Z
[ "java", ".net", "c++", "python", "encryption" ]
GAE Datastore Put()
2,498,264
<pre><code>def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update)) personal.name = self.request.get('name') personal.gender = self.request.get('ge...
3
2010-03-23T07:42:51Z
2,498,917
<p>There's no need to do a query when you know the key: Simply call db.get() on the key to retrieve it directly, which is much faster than doing a query.</p> <p>As to why you're creating a new record each time, it looks like you're not passing in 'update' to your page correctly. Try logging the query string parameters...
0
2010-03-23T10:02:16Z
[ "python", "google-app-engine", "gae-datastore" ]
GAE Datastore Put()
2,498,264
<pre><code>def post(self): update = self.request.get('update') if users.get_current_user(): if update: personal = db.GqlQuery("SELECT * FROM Personal WHERE __key__ = :1", db.Key(update)) personal.name = self.request.get('name') personal.gender = self.request.get('ge...
3
2010-03-23T07:42:51Z
2,502,809
<p>I finally answer this myself, Thanks for Nick Johnson guide on this. I cannot get the query string url as 'string key' that always raise BadKeyError: Invalid string key exception.</p> <p>I try to put this 'update' string as hidden field on html edit form and this works since 'update' is a valid 'string key' now.</p...
0
2010-03-23T19:01:08Z
[ "python", "google-app-engine", "gae-datastore" ]
Flash in Python
2,498,269
<p>I was exploring possibilities of <a href="http://en.wikipedia.org/wiki/Rich_Internet_application" rel="nofollow">Rich Internet applications</a> using Python. The most awesome possibility I found was of programming in <a href="http://en.wikipedia.org/wiki/IronPython" rel="nofollow">IronPython</a> and running it as a ...
2
2010-03-23T07:44:19Z
2,498,339
<p>You can use <a href="http://www.libming.org/" rel="nofollow">libming</a> to generate Macromedia Flash files, it has Python bindings too, you can see some Python examples at "<a href="http://code.rancidbacon.com/PythonMingAndFlash" rel="nofollow">Python, Ming and Flash</a>".</p> <p>Another library is "<a href="http:...
1
2010-03-23T08:04:37Z
[ "python", "air", "rich-internet-application" ]
Flash in Python
2,498,269
<p>I was exploring possibilities of <a href="http://en.wikipedia.org/wiki/Rich_Internet_application" rel="nofollow">Rich Internet applications</a> using Python. The most awesome possibility I found was of programming in <a href="http://en.wikipedia.org/wiki/IronPython" rel="nofollow">IronPython</a> and running it as a ...
2
2010-03-23T07:44:19Z
2,498,371
<p>There are plenty of resources out there for Flex/AIR integration with Python, just google the two of them together. A good one is "<a href="http://blog.jodybrewster.net/2008/04/17/python-resources-for-flex-development/" rel="nofollow">Python Resources for Flex Development</a>".</p>
1
2010-03-23T08:13:35Z
[ "python", "air", "rich-internet-application" ]
How to Pythonically yield all values from a list?
2,498,388
<p>Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that?</p> <p>Here is what I mean. Thanks to some non-lazy computation I have computed the list <code>['a', 'b', 'c', 'd']</code>, but my code through the project uses lazy computation, so I'd like to yield ...
17
2010-03-23T08:17:57Z
2,498,392
<p>You can build a generator by saying</p> <pre><code>(x for x in List) </code></pre>
2
2010-03-23T08:18:51Z
[ "python", "generator", "yield" ]
How to Pythonically yield all values from a list?
2,498,388
<p>Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that?</p> <p>Here is what I mean. Thanks to some non-lazy computation I have computed the list <code>['a', 'b', 'c', 'd']</code>, but my code through the project uses lazy computation, so I'd like to yield ...
17
2010-03-23T08:17:57Z
2,498,412
<p>Use <code>iter</code> to create a list iterator e.g.</p> <pre><code>return iter(List) </code></pre> <p>though if you already have a list, you can just return that, which will be more efficient.</p>
21
2010-03-23T08:24:34Z
[ "python", "generator", "yield" ]
How to Pythonically yield all values from a list?
2,498,388
<p>Suppose I have a list that I wish not to return but to yield values from. What is the most Pythonic way to do that?</p> <p>Here is what I mean. Thanks to some non-lazy computation I have computed the list <code>['a', 'b', 'c', 'd']</code>, but my code through the project uses lazy computation, so I'd like to yield ...
17
2010-03-23T08:17:57Z
18,620,655
<p>Since this question doesn't specify; I'll provide an answer that applies in <a href="http://www.python.org/dev/peps/pep-0380/">Python >= 3.3</a> </p> <p>If you need only to return that list, do as <a href="http://stackoverflow.com/a/2498412/65696">Anurag suggests</a>, but if for some reason the function in question...
20
2013-09-04T17:53:31Z
[ "python", "generator", "yield" ]
Django: request object to template context transparancy
2,498,582
<p>I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:</p> <pre><code>render_to_response(...., ( {'menu': RequestContext(request)})) </code></pre> <p>The re...
1
2010-03-23T09:06:15Z
2,498,911
<p>To accomplish this, you will probably have to <a href="http://docs.djangoproject.com/en/dev/topics/http/middleware/#writing-your-own-middleware" rel="nofollow">create your own middleware</a>. That way, you have full control of the request, both before and after the view function.</p> <p>Middleware is a very powerfu...
1
2010-03-23T10:01:30Z
[ "python", "django", "templates", "request", "django-context" ]
Django: request object to template context transparancy
2,498,582
<p>I want to include an initialized data structure in my request object, making it accessible in the context object from my templates. What I'm doing right now is passing it manually and tiresome within all my views:</p> <pre><code>render_to_response(...., ( {'menu': RequestContext(request)})) </code></pre> <p>The re...
1
2010-03-23T09:06:15Z
2,499,123
<p>I don't necessarily understand your question well enough.</p> <p>Either you are complaining having to include the <code>RequestContext</code> in all views, in which case you need to write a wrapper that passes RequestContext for you. But you will still have to pass to it the request. If you don't want to pass that ...
0
2010-03-23T10:37:08Z
[ "python", "django", "templates", "request", "django-context" ]
Python: Pretty printing a xml file directly from a tar.gz package
2,498,732
<p>This is the first Python script I've tried to create. I'm reading a xml file from a tar.gz package and then I want to pretty print it. However I can't seem to turn it from a file-like object to a string. I've tried to do it a few different ways including str(), tostring(), etc but nothing is working for me. </p> <...
0
2010-03-23T09:31:55Z
2,498,757
<p>Untested but you probably just need a <code>read()</code> call on the file-like object returned by tarfile, e.g.:</p> <pre><code>myfile = getfile.read() </code></pre>
2
2010-03-23T09:34:20Z
[ "python", "tar", "pretty-print" ]
Django parallel arrays in a template
2,498,870
<p>I have 2 arrays that I would like to render in a template, one is the data to be output, the other is a formset for deleting items. since it seems django does not support boolean operators in the template tag, I have tried packaging the items, but they return the first item and the first form in 2 rows only. </p> <...
0
2010-03-23T09:53:30Z
2,498,924
<p>Use <code>zip</code> builtin. If both post and delpostformset.forms are iterables, <code>zip</code> will return a list of tuples. In view:</p> <pre><code>post_and_form = zip(post, delpostformset.forms) </code></pre> <p>and in template:</p> <pre><code>{% for post, form in post_and_form %} {% endfor %} </code></pre...
8
2010-03-23T10:03:03Z
[ "python", "django", "django-templates", "django-views" ]
How to invert colors of image with PIL (Python-Imaging)?
2,498,875
<p>I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?</p>
18
2010-03-23T09:54:25Z
2,498,909
<p>Try the following from the docs: <a href="http://effbot.org/imagingbook/imageops.htm">http://effbot.org/imagingbook/imageops.htm</a></p> <pre><code>from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') inverted_image = PIL.ImageOps.invert(image) inverted_image.save('new_name.png') </...
32
2010-03-23T10:01:24Z
[ "python", "python-imaging-library" ]
How to invert colors of image with PIL (Python-Imaging)?
2,498,875
<p>I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?</p>
18
2010-03-23T09:54:25Z
12,880,019
<p>If the image is RGBA transparent this will fail... This should work though:</p> <pre><code>from PIL import Image import PIL.ImageOps image = Image.open('your_image.png') if image.mode == 'RGBA': r,g,b,a = image.split() rgb_image = Image.merge('RGB', (r,g,b)) inverted_image = PIL.ImageOps.invert(rg...
8
2012-10-14T06:57:45Z
[ "python", "python-imaging-library" ]
How to invert colors of image with PIL (Python-Imaging)?
2,498,875
<p>I need to convert series of images drawn as white on black background letters to images where white and black are inverted (as negative). How can I achieve this using PIL?</p>
18
2010-03-23T09:54:25Z
38,378,828
<p>For anyone working with an image in "1" mode (i.e., 1-bit pixels, black and white, stored with one pixel per byte -- <a href="http://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes" rel="nofollow">see docs</a>), you need to convert it into "L" mode before calling <code>PIL.ImageOps.invert</code>....
3
2016-07-14T15:53:09Z
[ "python", "python-imaging-library" ]
How to extract the first non-Null match from a group of regexp matches in Python?
2,498,935
<p>Suppose I have a regular expression <code>(a)|(b)|(c)|(d)</code>. If I apply it to text <code>'foobar'</code> I get a match object</p> <pre><code>&gt;&gt;&gt; compiled = re.compile('(a)|(b)|(c)|(d)') &gt;&gt;&gt; compiled.search('foobar').groups() (None, 'b', None, None) </code></pre> <p>How do I extract the <code...
1
2010-03-23T10:05:06Z
2,498,955
<pre><code>reduce(lambda x, y : (x, y)[x is None], groups, None) </code></pre>
1
2010-03-23T10:09:09Z
[ "python", "regex" ]
How to extract the first non-Null match from a group of regexp matches in Python?
2,498,935
<p>Suppose I have a regular expression <code>(a)|(b)|(c)|(d)</code>. If I apply it to text <code>'foobar'</code> I get a match object</p> <pre><code>&gt;&gt;&gt; compiled = re.compile('(a)|(b)|(c)|(d)') &gt;&gt;&gt; compiled.search('foobar').groups() (None, 'b', None, None) </code></pre> <p>How do I extract the <code...
1
2010-03-23T10:05:06Z
2,498,957
<pre><code>&gt;&gt;&gt; g = (None, 'b', None, None) &gt;&gt;&gt; next(x for x in g if x is not None) 'b' &gt;&gt;&gt; g = (None, None, None) &gt;&gt;&gt; next((x for x in g if x is not None), "default") # try this with filter :) 'default' &gt;&gt;&gt; g = (None, None, None) # so you know what happens, and what you ...
4
2010-03-23T10:09:21Z
[ "python", "regex" ]
How to extract the first non-Null match from a group of regexp matches in Python?
2,498,935
<p>Suppose I have a regular expression <code>(a)|(b)|(c)|(d)</code>. If I apply it to text <code>'foobar'</code> I get a match object</p> <pre><code>&gt;&gt;&gt; compiled = re.compile('(a)|(b)|(c)|(d)') &gt;&gt;&gt; compiled.search('foobar').groups() (None, 'b', None, None) </code></pre> <p>How do I extract the <code...
1
2010-03-23T10:05:06Z
2,498,966
<pre><code>filter(lambda x : x is not None, groups)[0] </code></pre>
1
2010-03-23T10:12:30Z
[ "python", "regex" ]
How to extract the first non-Null match from a group of regexp matches in Python?
2,498,935
<p>Suppose I have a regular expression <code>(a)|(b)|(c)|(d)</code>. If I apply it to text <code>'foobar'</code> I get a match object</p> <pre><code>&gt;&gt;&gt; compiled = re.compile('(a)|(b)|(c)|(d)') &gt;&gt;&gt; compiled.search('foobar').groups() (None, 'b', None, None) </code></pre> <p>How do I extract the <code...
1
2010-03-23T10:05:06Z
2,498,991
<pre><code>&gt;&gt;&gt; g = (None,'b',None,None) &gt;&gt;&gt; filter(None,g) ('b',) &gt;&gt;&gt; h = (None,None,None) &gt;&gt;&gt; filter(None,h) () </code></pre>
1
2010-03-23T10:16:37Z
[ "python", "regex" ]
Dynamically creating page definitions in Cherrypy
2,499,219
<p>I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing...</p> <p>My current class looks something like this:</p> <pre><code>import managerUtils class WebManager: def A(self, **kwds): ...
2
2010-03-23T10:51:28Z
2,503,737
<pre><code>class WebManager: def default(self, action, **kwds): return managerUtils.runAction(action, kwds) default.exposed = True </code></pre> <p>Two notes about why this is different than other answers:</p> <ol> <li><code>.exposed</code> is the correct attribute for publishing methods, not <code>.e...
3
2010-03-23T21:23:50Z
[ "python", "cherrypy" ]
Python Ctypes Read/WriteProcessMemory() - Error 5/998 Help!
2,499,256
<p>Please don't get scared but the following code, if you are familiar with ctypes or C it should be easy to read.</p> <p>I have been trying to get my ReadProcessMemory() and WriteProcessMemory() functions to be working for so long and have tried almost every possibility but the right one.</p> <p>It launches the targ...
1
2010-03-23T10:56:34Z
2,569,856
<p>One possible reason for your access denied error is that the user under which you run WriteProcessMemory runs needs to have DEBUG privilege.</p> <p>Starting with Vista, this privilege is only activated for Administrators, and only when running the application with "Run as Admin".</p> <p>You can add the privilege t...
0
2010-04-03T00:30:36Z
[ "python", "ctypes", "readprocessmemory" ]
Python Ctypes Read/WriteProcessMemory() - Error 5/998 Help!
2,499,256
<p>Please don't get scared but the following code, if you are familiar with ctypes or C it should be easy to read.</p> <p>I have been trying to get my ReadProcessMemory() and WriteProcessMemory() functions to be working for so long and have tried almost every possibility but the right one.</p> <p>It launches the targ...
1
2010-03-23T10:56:34Z
2,980,858
<p>Maybe this will help you: <a href="http://msdn.microsoft.com/en-us/library/aa446595%28VS.85%29.aspx" rel="nofollow">Creating a Security Descriptor for a New Object in C++</a></p>
1
2010-06-05T15:05:33Z
[ "python", "ctypes", "readprocessmemory" ]
Python Ctypes Read/WriteProcessMemory() - Error 5/998 Help!
2,499,256
<p>Please don't get scared but the following code, if you are familiar with ctypes or C it should be easy to read.</p> <p>I have been trying to get my ReadProcessMemory() and WriteProcessMemory() functions to be working for so long and have tried almost every possibility but the right one.</p> <p>It launches the targ...
1
2010-03-23T10:56:34Z
3,673,047
<p>I see several problems with your code, and it's difficult to know which one is the underlying cause of your exact problem. For example, the line:</p> <pre><code>address = raw_input('Enter and address: ') </code></pre> <p>Should probably be something like:</p> <pre><code>address = long(raw_input('Enter and addres...
0
2010-09-09T00:57:04Z
[ "python", "ctypes", "readprocessmemory" ]
Python Ctypes Read/WriteProcessMemory() - Error 5/998 Help!
2,499,256
<p>Please don't get scared but the following code, if you are familiar with ctypes or C it should be easy to read.</p> <p>I have been trying to get my ReadProcessMemory() and WriteProcessMemory() functions to be working for so long and have tried almost every possibility but the right one.</p> <p>It launches the targ...
1
2010-03-23T10:56:34Z
5,276,783
<p>You should try to set debugging privileges to your process. Use the following code once before you try to Open / Create a process.</p> <pre><code>class TOKEN_PRIVILEGES( Structure ): _fields_ = [ ('PrivilegeCount', c_uint), ('Luid', LUID), ('Attributes', c_ui...
1
2011-03-11T18:20:44Z
[ "python", "ctypes", "readprocessmemory" ]
Get document DOCTYPE with BeautifulSoup
2,499,358
<p>I've just started tinkering with <a href="http://scrapy.org/">scrapy</a> in conjunction with <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> and I'm wondering if I'm missing something very obvious but I can't seem to figure out how to get the doctype of a returned html document from the res...
5
2010-03-23T11:16:37Z
2,503,128
<p>You could just fetch the first item in soup contents:</p> <pre><code>&gt;&gt;&gt; soup.contents[0] u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"' </code></pre>
0
2010-03-23T19:53:40Z
[ "python", "parsing", "beautifulsoup", "scrapy" ]
Get document DOCTYPE with BeautifulSoup
2,499,358
<p>I've just started tinkering with <a href="http://scrapy.org/">scrapy</a> in conjunction with <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> and I'm wondering if I'm missing something very obvious but I can't seem to figure out how to get the doctype of a returned html document from the res...
5
2010-03-23T11:16:37Z
5,497,797
<p>You can go through top-level elements and check each to see whether it is a declaration. Then you can inspect it to find out what kind of declaration it is:</p> <pre><code>for child in soup.contents: if isinstance(child, BS.Declaration): declaration_type = child.string.split()[0] if declaration_...
3
2011-03-31T09:33:11Z
[ "python", "parsing", "beautifulsoup", "scrapy" ]
Get document DOCTYPE with BeautifulSoup
2,499,358
<p>I've just started tinkering with <a href="http://scrapy.org/">scrapy</a> in conjunction with <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> and I'm wondering if I'm missing something very obvious but I can't seem to figure out how to get the doctype of a returned html document from the res...
5
2010-03-23T11:16:37Z
16,882,069
<p>Beautiful Soup 4 has a class for DOCTYPE declarations, so you can use that to extract all the declarations at top level (though you're no doubt expecting one or none!)</p> <pre><code>def doctype(soup): items = [item for item in soup.contents if isinstance(item, bs4.Doctype)] return items[0] if items else No...
2
2013-06-02T10:54:41Z
[ "python", "parsing", "beautifulsoup", "scrapy" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,499,513
<p>No.</p> <p>Once the first program exits, its memory is completely gone.<br> You need to write to disk.</p>
1
2010-03-23T11:40:52Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,499,521
<p>Store you data into "memory" using things like databases, eg dbm, sqlite, shelve, pickle, etc where your 2nd program can pick up later.</p>
2
2010-03-23T11:42:47Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,499,529
<blockquote> <p>The first one will write some data (str) to computer memory, and then exit.</p> </blockquote> <p>The OS will then ensure all that memory is zeroed before any other program can see it. (This is an important security measure, as the first program may have been processing your bank statement or may...
1
2010-03-23T11:44:02Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,499,840
<p>Sort of.</p> <pre><code>python p1.py | python p2.py </code></pre> <p>If p1 writes to stdout, the data goes to memory. If p2 reads from stdin, it reads from memory. </p> <p>The issue is that there's no "I will then start the second program". You must start both programs so that they share the appropriate memory...
4
2010-03-23T12:35:09Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,500,073
<p>Yes.</p> <p>Define a RAM file-system. </p> <p><a href="http://www.vanemery.com/Linux/Ramdisk/ramdisk.html" rel="nofollow">http://www.vanemery.com/Linux/Ramdisk/ramdisk.html</a></p> <p><a href="http://www.cyberciti.biz/faq/howto-create-linux-ram-disk-filesystem/" rel="nofollow">http://www.cyberciti.biz/faq/howto-...
1
2010-03-23T13:09:39Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,500,096
<p>You can also set up persistent shared memory area and have one program write to it and the other read it. However, setting up such things is somewhat dependent on the underlying O/S. </p>
1
2010-03-23T13:13:16Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,500,168
<p>Maybe the poster is talking about something like shared memory? Have a look at this: <a href="http://poshmodule.sourceforge.net/" rel="nofollow">http://poshmodule.sourceforge.net/</a></p>
1
2010-03-23T13:22:59Z
[ "python", "memory", "buffer" ]
Reading and writing to/from memory in Python
2,499,491
<p>Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program. </p> <p>Is this possible?</p>
1
2010-03-23T11:37:36Z
2,936,986
<p>What are all these nonsense answers? Of course you can share memory the way you asked, there's no technical reason you shouldn't be able to persist memory other than lack of usermode API.</p> <p>In Linux you can use shared memory segments which persist even after the program that made them is gone. You can view/edi...
2
2010-05-29T23:45:30Z
[ "python", "memory", "buffer" ]
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
<p>I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.</p> <p>On Unix I could do this:</p> <pre><code>cut -d " " -f 1-3 &lt;my file&gt; </code></pre> <p>How can I do this on Windows?</p>
9
2010-03-23T12:20:07Z
2,499,791
<p>That's rather simple Python script:</p> <pre><code>for line in open("my file"): parts = line.split(" ") print " ".join(parts[0:3]) </code></pre>
2
2010-03-23T12:26:40Z
[ "python", "perl", "unix", "batch-file" ]
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
<p>I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.</p> <p>On Unix I could do this:</p> <pre><code>cut -d " " -f 1-3 &lt;my file&gt; </code></pre> <p>How can I do this on Windows?</p>
9
2010-03-23T12:20:07Z
2,499,796
<p>The easiest way to do it would be to install <a href="http://www.cygwin.com/" rel="nofollow">Cygwin</a> and use the Unix <code>cut</code> command.</p>
1
2010-03-23T12:27:23Z
[ "python", "perl", "unix", "batch-file" ]
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
<p>I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.</p> <p>On Unix I could do this:</p> <pre><code>cut -d " " -f 1-3 &lt;my file&gt; </code></pre> <p>How can I do this on Windows?</p>
9
2010-03-23T12:20:07Z
2,499,833
<p>Here is a Perl one-liner to print the first 3 whitespace-delimited columns of a file. This can be run on Windows (or Unix). Refer to <a href="http://perldoc.perl.org/perlrun.html">perlrun</a>.</p> <pre><code>perl -ane "print qq(@F[0..2]\n)" file.txt </code></pre>
10
2010-03-23T12:34:19Z
[ "python", "perl", "unix", "batch-file" ]
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
<p>I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.</p> <p>On Unix I could do this:</p> <pre><code>cut -d " " -f 1-3 &lt;my file&gt; </code></pre> <p>How can I do this on Windows?</p>
9
2010-03-23T12:20:07Z
2,499,903
<p>you can download <a href="http://gnuwin32.sourceforge.net/packages.html" rel="nofollow">GNU windows</a> and use your normal cut/awk etc.. Or natively, you can use vbscript</p> <pre><code>Set objFS = CreateObject("Scripting.FileSystemObject") Set objArgs = WScript.Arguments strFile = objArgs(0) Set objFile = objFS.O...
3
2010-03-23T12:44:26Z
[ "python", "perl", "unix", "batch-file" ]
Extracting columns from text file using Perl one-liner: similar to Unix cut
2,499,746
<p>I'm using Windows, and I would like to extract certain columns from a text file using a Perl, Python, batch etc. one-liner.</p> <p>On Unix I could do this:</p> <pre><code>cut -d " " -f 1-3 &lt;my file&gt; </code></pre> <p>How can I do this on Windows?</p>
9
2010-03-23T12:20:07Z
28,190,883
<p>If you are dealing with a text file that has very long lines and you are only interested in the first 3 columns, then splitting a fixed number of times yourself will be a lot faster than using the <code>-a</code> option:</p> <p><code>perl -ne "@F = split /\s/, $_, 4; print qq(@F[0..2]\n)" file.txt</code></p> <p>ra...
0
2015-01-28T11:17:33Z
[ "python", "perl", "unix", "batch-file" ]
In Elixir or SQLAlchemy, is there a way to also store a comment for a/each field in my entities?
2,499,821
<p>Our project is basically a web interface to several systems of record. We have many tables mapped, and the names of each column aren't as well named and intuitive as we'd like... The users would like to know what data fields are available (i.e. what's been mapped from the database). But, it's pointless to just give ...
1
2010-03-23T12:32:22Z
2,500,484
<p>Doing some research thru the SQLAlchemy <a href="http://www.sqlalchemy.org/docs/reference/sqlalchemy/schema.html#tables-and-columns" rel="nofollow">documentation</a>, my buddy and I found a line that says the Column object has a default dictionary called <code>info</code> that is a space to store "application specif...
1
2010-03-23T14:03:01Z
[ "python", "sqlalchemy", "python-elixir" ]
Segment string into array, regex?
2,499,865
<p>I have a string which looks like this:</p> <pre><code>"[segment1][segment2][segment2]" </code></pre> <p>What I'd like is to be able to split the string into an array, so I'd end up with:</p> <pre><code>Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3" </code></pre> <p>I've tried using the strin...
1
2010-03-23T12:38:32Z
2,499,893
<p>You could use the <code>re.split()</code> function:</p> <pre><code>subject = "[segment1][segment2][segment2]" reobj = re.compile("[][]+") result = reobj.split(subject.strip("[]")) print result </code></pre> <p>gives you:</p> <pre><code>['segment1', 'segment2', 'segment2'] </code></pre> <p>Edit: Added a <code>.st...
1
2010-03-23T12:42:36Z
[ "python", "regex" ]
Segment string into array, regex?
2,499,865
<p>I have a string which looks like this:</p> <pre><code>"[segment1][segment2][segment2]" </code></pre> <p>What I'd like is to be able to split the string into an array, so I'd end up with:</p> <pre><code>Array[0] = "segment1", Array[1] = "segment2", Array[2] = "segment3" </code></pre> <p>I've tried using the strin...
1
2010-03-23T12:38:32Z
2,499,907
<p>You could take the slice of the string without the first and last characters, then split on <code>][</code>:</p> <pre><code>s = "[segment1][segment2][segment2]" s[1:-1].split('][') </code></pre> <p>outputs</p> <pre><code>['segment1', 'segment2', 'segment2'] </code></pre>
4
2010-03-23T12:44:37Z
[ "python", "regex" ]
format printing
2,499,917
<p>How to format printing stmt in python? </p> <pre><code>print"---------------------------------" print"client:mount-point:logfile:status" print"---------------------------------" print clientname,mntpt,logfile,status </code></pre> <p>Currently it prints something like this :</p> <pre><code>---------------------...
0
2010-03-23T12:45:58Z
2,500,011
<p>Take a look at string formatting : <a href="http://docs.python.org/release/2.5.2/lib/typesseq-strings.html" rel="nofollow">http://docs.python.org/release/2.5.2/lib/typesseq-strings.html</a></p>
1
2010-03-23T12:59:39Z
[ "python", "printing" ]
format printing
2,499,917
<p>How to format printing stmt in python? </p> <pre><code>print"---------------------------------" print"client:mount-point:logfile:status" print"---------------------------------" print clientname,mntpt,logfile,status </code></pre> <p>Currently it prints something like this :</p> <pre><code>---------------------...
0
2010-03-23T12:45:58Z
2,500,038
<p>If you're trying to format a table, consider using other software for table formatting.</p> <p>As an example, you can produce HTML with the <code>print</code> statements and view the table with a browser. Another option is to generate <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow"><code...
0
2010-03-23T13:03:19Z
[ "python", "printing" ]
format printing
2,499,917
<p>How to format printing stmt in python? </p> <pre><code>print"---------------------------------" print"client:mount-point:logfile:status" print"---------------------------------" print clientname,mntpt,logfile,status </code></pre> <p>Currently it prints something like this :</p> <pre><code>---------------------...
0
2010-03-23T12:45:58Z
2,501,904
<p>Stick some tab spacing in for a start?</p> <pre><code>'\t' </code></pre>
0
2010-03-23T16:55:21Z
[ "python", "printing" ]
Faster float to int conversion in Python
2,499,933
<p>Here's a piece of code that takes most time in my program, according to timeit statistics. It's a dirty function to convert floats in [-1.0, 1.0] interval into unsigned integer [0, 2**32]. How can I accelerate <code>floatToInt</code>?</p> <pre><code>piece = [] rng = range(32) for i in rng: piece.append(1.0/2**i...
2
2010-03-23T12:49:39Z
2,499,965
<p>Did you try the obvious one?</p> <pre><code>def floatToInt(x): return int((x+1.0) * (2**31)) </code></pre>
4
2010-03-23T12:53:20Z
[ "python", "floating-point", "binary-data" ]
Python, a smarter way of string to integer conversion
2,499,966
<p>Hello I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 .</p> <pre><code>class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. def to_int(self): return i...
1
2010-03-23T12:53:27Z
2,500,023
<pre><code>p = "0(532) 222 22 22" print ''.join([x for x in p if x.isdigit()]) </code></pre> <p>Note that you'll "lose" the leading zero if you want to convert it to int (like you suggested in the title). If you want to do that, just wrap the above in a <code>int()</code> call. A telephone number does make more sense ...
7
2010-03-23T13:00:57Z
[ "python", "string", "integer", "type-conversion" ]
Python, a smarter way of string to integer conversion
2,499,966
<p>Hello I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 .</p> <pre><code>class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. def to_int(self): return i...
1
2010-03-23T12:53:27Z
2,500,025
<p>In Python 2.6 or 2.7,<br> <code>(self.phone).translate(None,' ()')</code><br> will remove any spaces or <code>(</code> or <code>)</code> from the phone string. See <a href="http://docs.python.org/library/stdtypes.html#str.translate" rel="nofollow">Python 2.6 doc on str.translate</a> for details.</p> <p>In Python 3...
6
2010-03-23T13:01:09Z
[ "python", "string", "integer", "type-conversion" ]