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
Python script to print all function definitions of a C/C++ file
1,620,851
<p>I want a python script to print list of all functions defined in a C/C++ file.</p> <p>e.g. <code>abc.c</code> defines two functions as:</p> <pre><code>void func1() { } int func2(int i) { printf("%d", i); return 1; } </code></pre> <p>I just want to search the file (<code>abc.c</code>) and print all the functions d...
3
2009-10-25T12:59:17Z
1,621,011
<p>I would suggest using the PLY lex/yacc tool. There's a prebuilt C parser, and the parser itself is quite fast. Once you have the file parsed, it shouldn't be too hard to find all of the functions.</p> <p><a href="http://www.dabeaz.com/ply/" rel="nofollow">http://www.dabeaz.com/ply/</a></p>
3
2009-10-25T14:11:29Z
[ "python", "parsing", "string" ]
Python script to print all function definitions of a C/C++ file
1,620,851
<p>I want a python script to print list of all functions defined in a C/C++ file.</p> <p>e.g. <code>abc.c</code> defines two functions as:</p> <pre><code>void func1() { } int func2(int i) { printf("%d", i); return 1; } </code></pre> <p>I just want to search the file (<code>abc.c</code>) and print all the functions d...
3
2009-10-25T12:59:17Z
1,621,055
<p>To do this reliably, you'd need to parse the C or C++ code, and then grab the function definitions from the AST the parser produces.</p> <p>C is fairly easy to parse. As <a href="http://stackoverflow.com/questions/1620851/python-script-to-print-all-function-definitions-of-a-c-c-file/1621011#1621011">pavpanchekha</a...
1
2009-10-25T14:30:54Z
[ "python", "parsing", "string" ]
Python script to print all function definitions of a C/C++ file
1,620,851
<p>I want a python script to print list of all functions defined in a C/C++ file.</p> <p>e.g. <code>abc.c</code> defines two functions as:</p> <pre><code>void func1() { } int func2(int i) { printf("%d", i); return 1; } </code></pre> <p>I just want to search the file (<code>abc.c</code>) and print all the functions d...
3
2009-10-25T12:59:17Z
1,621,135
<p>This page, <a href="http://www.nobugs.org/developer/parsingcpp/" rel="nofollow">Parsing C++</a>, mentions a couple of ANTLR grammars for C++. Since <a href="http://www.antlr.org/api/Python/index.html" rel="nofollow">ANTLR has a Python API</a> this seems like a reasonable way to proceed.</p> <p>Even though parsing m...
1
2009-10-25T15:13:03Z
[ "python", "parsing", "string" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,620,903
<pre><code> x = re.match('.*(&lt;body&gt;.*?&lt;/body&gt;)', fileString) </code></pre> <p>Consider minidom for HTML parsing.</p>
-2
2009-10-25T13:18:22Z
[ "python", "regex", "html-parsing" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,620,906
<p>Here is some example code which uses regex to find all the text between <code>&lt;body&gt;...&lt;/body&gt;</code> tags. Although this demonstrates some features of python's re module, note that the <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html" rel="nofollow">Beautiful Soup</a> module is v...
2
2009-10-25T13:18:43Z
[ "python", "regex", "html-parsing" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,620,917
<pre><code>x = re.search('(&lt;body&gt;.*&lt;/body&gt;)', fileString) x.group(1) </code></pre> <p>Less typing than the match answers</p>
-2
2009-10-25T13:25:40Z
[ "python", "regex", "html-parsing" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,620,931
<p>I don't know Python, but here's a quick example thrown together using <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>, which I often see recommended for Python HTML parsing.</p> <pre><code>import BeautifulSoup soup = BeautifulSoup(fileString) bodyTag = soup.html.body.stri...
9
2009-10-25T13:32:09Z
[ "python", "regex", "html-parsing" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,620,948
<p>Does your fileString contain <strong>multiple lines</strong>? In that case you may need to specify it or skip the lines explicitly:</p> <pre><code>x = re.match(r"(?:.|\n)*(&lt;body&gt;(?:.|\n)*&lt;/body&gt;)", fileString) </code></pre> <p>or, more simply with the re module:</p> <pre><code>x = re.match(r".*(&lt;bo...
-2
2009-10-25T13:41:02Z
[ "python", "regex", "html-parsing" ]
Python RegEx skipping the first few characters?
1,620,889
<p>Hey I have a fairly basic question about regular expressions. I want to just return the text inside (and including) the body tags, and I know the following isn't right because it'll also match all the characters before the opening body tag. I was wondering how you would go about skipping those?</p> <pre><code>x = r...
1
2009-10-25T13:13:53Z
1,621,230
<p>You cannot parse HTML with regex. HTML is not a regular language. Use an HTML parser like lxml instead.</p>
0
2009-10-25T15:50:23Z
[ "python", "regex", "html-parsing" ]
place labels between ticks
1,620,927
<p>in matplotlib, how do i place ticks labels between ticks (not below ticks)</p> <p>for example: when plotting a the stock price over time i would like the x axis minor ticks to display months and the years to show up between consecutive x axis major ticks (not just below the major ticks)</p> <pre><code>---|---|---|...
7
2009-10-25T13:30:55Z
1,620,999
<p>Do you mean something like this: - <a href="http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/barchart%5Fdemo.html" rel="nofollow">http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/barchart%5Fdemo.html</a> ??</p> <p>You must use xticks and the ha (or 'horizontalalignment') parameter:</p> <pre><...
0
2009-10-25T14:04:51Z
[ "python", "matplotlib" ]
place labels between ticks
1,620,927
<p>in matplotlib, how do i place ticks labels between ticks (not below ticks)</p> <p>for example: when plotting a the stock price over time i would like the x axis minor ticks to display months and the years to show up between consecutive x axis major ticks (not just below the major ticks)</p> <pre><code>---|---|---|...
7
2009-10-25T13:30:55Z
1,621,035
<p>Will this do the trick?</p> <pre><code>enter code here x = 'j f m a m j j a s o n d j f m a m j j a s o n d'.split() y = abs(randn(24)) x[6] = 'j\n2008' x[18] = 'j\n2009' bar(xrange(len(x)), y, width=0.1) bar(xrange(len(x)), y, width=0.1) xticks(xrange(len(x)), x, ha='center') </code></pre> <p><img src="http://img...
5
2009-10-25T14:23:20Z
[ "python", "matplotlib" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,620,955
<p>Here is your list:</p> <pre><code>(x - 1, y - 1) (x, y - 1) (x + 1, y - 1) (x - 1, y) (x, y) (x + 1, y) (x - 1, y + 1) (x, y + 1) (x + 1, y + 1) </code></pre> <p>So the horizontal neighbors of (x, y) are (x +/- 1, y).</p> <p>The vertical neighbors are (x, y +/- 1).</p> <p>Diagonal neighbors are (x +/- 1,...
1
2009-10-25T13:44:04Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,007
<p>There's no cleaner way to do this. If you really want you could create a function:</p> <pre><code>def top(matrix, x, y): try: return matrix[x][y - 1]; except IndexError: return None </code></pre>
2
2009-10-25T14:08:36Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,023
<pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; def sl(lst, i, j): il, iu = max(0, i-1), min(len(lst)-1, i+1) jl, ju = max(0, j-1), min(len(lst[0])-1, j+1) return (il, iu), (jl, ju) &gt;&gt;&gt; lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; tup = 0, 2 &gt;&gt;&gt; [lst[i][j] for i, j in iterto...
0
2009-10-25T14:17:37Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,041
<pre><code>for x_ in range(max(0,x-1),min(width,x+2)): for y_ in range(max(0,y-1),min(height,y+2)): if (x,y)==(x_,y_): continue # do stuff with the neighbours &gt;&gt;&gt; a=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; width=height=3 &gt;&gt;&gt; x,y=0,2 &gt;&gt;&gt; for x_ in range(max(0,x-1),min(width,x+...
2
2009-10-25T14:25:47Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,050
<p>This generates all indices:</p> <pre><code>def neighboring( array ): nn,mm = len(array), len(array[0]) offset = (0,-1,1) # 0 first so the current cell is the first in the gen indices = ( (i,j) for i in range(nn) for j in range(mm) ) for i,j in indices: all_neigh = ( (i+x,j+y) for x in offse...
0
2009-10-25T14:28:47Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,064
<p>maybe you are checking a sudoku box. If the box is n x n and current cell is (x,y) start checking:</p> <pre><code>startingRow = x / n * n; startingCol = y/ n * n </code></pre>
0
2009-10-25T14:33:40Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
1,621,118
<pre><code># Size of "board" X = 10 Y = 10 neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2) for y2 in range(y-1, y+2) if (-1 &lt; x &lt;= X and -1 &lt; y &lt;= Y and (x != x2...
9
2009-10-25T15:03:58Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
10,606,663
<p>mb...</p> <pre><code>from itertools import product, starmap x, y = (8, 13) cells = starmap(lambda a,b: (x+a, y+b), product((0,-1,+1), (0,-1,+1))) // [(8, 12), (8, 14), (7, 13), (7, 12), (7, 14), (9, 13), (9, 12), (9, 14)] print(list(cells)[1:]) </code></pre>
4
2012-05-15T18:27:08Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
34,362,272
<p>Assuming you have a square matrix:</p> <pre><code>from itertools import product size = 3 def neighbours(cell): for c in product(*(range(n-1, n+2) for n in cell)): if c != cell and all(0 &lt;= n &lt; size for n in c): yield c </code></pre> <p>Using <a href="https://docs.python.org/2/librar...
0
2015-12-18T19:00:20Z
[ "python", "matrix" ]
Determining neighbours of cell two dimensional list
1,620,940
<p>I have a list of lists, something like </p> <p><code>[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]</code>.</p> <p>Represented graphically as: </p> <pre><code>1 2 3 4 5 6 7 8 9 </code></pre> <p>I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For inst...
4
2009-10-25T13:36:41Z
38,157,488
<p>If someone is curious about alternative way to pick direct (non-diagonal) neighbors, here you go:</p> <pre><code>neighbors = [(x+a[0], y+a[1]) for a in [(-1,0), (1,0), (0,-1), (0,1)] if ( (0 &lt;= x+a[0] &lt; w) and (0 &lt;= y+a[1] &lt; h))] </code></pre>
0
2016-07-02T07:05:08Z
[ "python", "matrix" ]
Nesting generator expressions in the argument list for a python function call
1,620,957
<p>I like to use the following idiom for combining lists together, sometimes:</p> <pre><code>&gt;&gt;&gt; list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))])) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] </code></pre> <p>(I know there are easier ways to get this particular result, but it c...
1
2009-10-25T13:44:38Z
1,621,014
<p>wouldn't a nested list comprehension be more appropriate?</p> <pre><code>&gt;&gt;&gt; tt = (('a', [1,2]),('b',[3,4])) &gt;&gt;&gt; [(s, i) for i, l in tt for s in l] [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] </code></pre>
6
2009-10-25T14:12:29Z
[ "python", "generator", "list-comprehension" ]
Nesting generator expressions in the argument list for a python function call
1,620,957
<p>I like to use the following idiom for combining lists together, sometimes:</p> <pre><code>&gt;&gt;&gt; list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))])) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] </code></pre> <p>(I know there are easier ways to get this particular result, but it c...
1
2009-10-25T13:44:38Z
1,621,090
<p>Your approach almost works, you just need to flatten the generators. See how the <code>for e in l</code> is moved to the very right</p> <pre><code>&gt;&gt;&gt; list(itertools.chain((e, n) for n, l in (('a', [1,2]),('b',[3,4])) for e in l )) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] </code></pre> <p>Here is how to d...
1
2009-10-25T14:49:08Z
[ "python", "generator", "list-comprehension" ]
Nesting generator expressions in the argument list for a python function call
1,620,957
<p>I like to use the following idiom for combining lists together, sometimes:</p> <pre><code>&gt;&gt;&gt; list(itertools.chain(*[[(e, n) for e in l] for n, l in (('a', [1,2]),('b',[3,4]))])) [(1, 'a'), (2, 'a'), (3, 'b'), (4, 'b')] </code></pre> <p>(I know there are easier ways to get this particular result, but it c...
1
2009-10-25T13:44:38Z
1,621,223
<p>I'm going to suggest</p> <pre><code>data = (('a', [1,2]), ('b', [3,4])) result = [] for letter, numbers in data: for number in numbers: result.append((number, letter)) </code></pre> <p>It's a lot more readable than your solution family. Fancy is not a good thing.</p>
0
2009-10-25T15:47:19Z
[ "python", "generator", "list-comprehension" ]
Problem declaring global variable in python/GAE
1,621,259
<p>I'm new to python and I'm trying to obtain a username from the UI and query the result to get the phone book contacts of the user. But I am not able to set the user name to be a global variable to use it for multiple queries. Here's the code, I believe I am doing some syntax error/improper usage, please help out in ...
1
2009-10-25T16:02:55Z
1,621,431
<p>First and foremost, App Engine's execution model is quite "loose" -- that's why it's so scalable! When a request arrives for your URL, GAE may reuse an existing process that's already running your script, <em>or</em> it may start another process running the same script if that balances overall system load better; o...
7
2009-10-25T17:10:55Z
[ "python", "google-app-engine" ]
Problem declaring global variable in python/GAE
1,621,259
<p>I'm new to python and I'm trying to obtain a username from the UI and query the result to get the phone book contacts of the user. But I am not able to set the user name to be a global variable to use it for multiple queries. Here's the code, I believe I am doing some syntax error/improper usage, please help out in ...
1
2009-10-25T16:02:55Z
1,621,471
<p>Simples!</p> <p>You seem to be storing user_name as a class variable, not a global. There is some tricky behavior here where a reference to it in a method will create an instance variable with the same name that hides the class variable.</p> <pre><code>class curious(object): hide = 11 def get(self): return...
0
2009-10-25T17:24:58Z
[ "python", "google-app-engine" ]
Problem declaring global variable in python/GAE
1,621,259
<p>I'm new to python and I'm trying to obtain a username from the UI and query the result to get the phone book contacts of the user. But I am not able to set the user name to be a global variable to use it for multiple queries. Here's the code, I believe I am doing some syntax error/improper usage, please help out in ...
1
2009-10-25T16:02:55Z
12,505,699
<p>Answer by Aaron Hampton here <a href="http://stackoverflow.com/questions/11565313/passing-variables-to-a-template-on-a-redirect-in-python">passing variables to a template on a redirect in python</a></p> <p>looks like it might work for you, and also avoid the pitfalls of global vars as mentioned by others.</p>
0
2012-09-20T03:26:59Z
[ "python", "google-app-engine" ]
dynamically adding functions to a Python module
1,621,350
<p>Our framework requires wrapping certain functions in some ugly boilerplate code:</p> <pre><code>def prefix_myname_suffix(obj): def actual(): print 'hello world' obj.register(actual) return obj </code></pre> <p>I figured this might be simplified with a decorator:</p> <pre><code>@register def my...
6
2009-10-25T16:40:50Z
1,621,382
<p>use either </p> <pre><code>current_module.new_name = func </code></pre> <p>or </p> <pre><code>setattr(current_module, new_name, func) </code></pre>
10
2009-10-25T16:51:37Z
[ "python", "metaprogramming", "decorator" ]
dynamically adding functions to a Python module
1,621,350
<p>Our framework requires wrapping certain functions in some ugly boilerplate code:</p> <pre><code>def prefix_myname_suffix(obj): def actual(): print 'hello world' obj.register(actual) return obj </code></pre> <p>I figured this might be simplified with a decorator:</p> <pre><code>@register def my...
6
2009-10-25T16:40:50Z
1,621,420
<p>It seems the solution to your problem would be to make the decorated function act as the original function. </p> <p>Try using the function <code>mergeFunctionMetadata</code> from Twisted, found here: <a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.1.0/twisted/python/util.py" rel="nofollow">tw...
0
2009-10-25T17:04:57Z
[ "python", "metaprogramming", "decorator" ]
how to extract some text by use lxml?
1,621,410
<p>i want to extract some text in certain website. here is web address what i want to extract some text to make scraper. <a href="http://news.search.naver.com/search.naver?sm=tab%5Fhty&amp;where=news&amp;query=times&amp;x=0&amp;y=0" rel="nofollow">http://news.search.naver.com/search.naver?sm=tab%5Fhty&amp;where=news&am...
0
2009-10-25T17:01:57Z
1,621,730
<p>In general, to solve such problems you must first download the page of interest as text (use <code>urllib.urlopen</code> or anything else, even external utilities such as curl or wget, but not a browser since you want to see how the page looks <em>before</em> any Javascript has had a chance to run) and study it to u...
2
2009-10-25T19:01:12Z
[ "python", "parsing", "lxml" ]
How do I display real-time python script output on a website?
1,621,430
<p>I have a Python script that outputs something every second or two, but takes a long while to finish completely. I want to set up a website such that someone can directly invoke the script, and the output is sent to the screen while the script is running. </p> <p>I don't want the user to wait until the script finish...
2
2009-10-25T17:10:53Z
1,621,465
<p>The solution is to flush the output buffer at select points in the script's execution - I've only ever done this in PHP via flush() but this looks like <a href="http://74.125.93.132/search?q=cache%3Aq3BNDBYUX%5F0J%3Awww.pyzine.com/Issue008/Section%5FArticles/article%5FCGIOne.html+python+flush+buffer+webapp&amp;cd=4&...
1
2009-10-25T17:23:55Z
[ "python", "ajax", "cgi", "web-applications", "fastcgi" ]
How do I display real-time python script output on a website?
1,621,430
<p>I have a Python script that outputs something every second or two, but takes a long while to finish completely. I want to set up a website such that someone can directly invoke the script, and the output is sent to the screen while the script is running. </p> <p>I don't want the user to wait until the script finish...
2
2009-10-25T17:10:53Z
1,621,473
<p>nginx doesn't support CGI, so you will need to use fastcgi or wsgi</p> <p>Alternatively you could use something like <a href="http://webpy.org/" rel="nofollow">webpy</a> and proxy to it through nginx</p>
0
2009-10-25T17:25:42Z
[ "python", "ajax", "cgi", "web-applications", "fastcgi" ]
How do I display real-time python script output on a website?
1,621,430
<p>I have a Python script that outputs something every second or two, but takes a long while to finish completely. I want to set up a website such that someone can directly invoke the script, and the output is sent to the screen while the script is running. </p> <p>I don't want the user to wait until the script finish...
2
2009-10-25T17:10:53Z
1,621,939
<p>First of all - your script must output header:</p> <blockquote> <p>Connection: Keep-Alive</p> </blockquote> <p>Because browser must know that it will have to wait.</p> <p>And your script must output data without buffering. And stackoverflow has <a href="http://stackoverflow.com/questions/107705/python-output-bu...
2
2009-10-25T20:08:58Z
[ "python", "ajax", "cgi", "web-applications", "fastcgi" ]
How do I display real-time python script output on a website?
1,621,430
<p>I have a Python script that outputs something every second or two, but takes a long while to finish completely. I want to set up a website such that someone can directly invoke the script, and the output is sent to the screen while the script is running. </p> <p>I don't want the user to wait until the script finish...
2
2009-10-25T17:10:53Z
1,622,342
<p>From <a href="http://tools.cherrypy.org/wiki/Comet" rel="nofollow">http://tools.cherrypy.org/wiki/Comet</a> "Wikipedia describes Comet as, "a neologism to describe a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.". ...
0
2009-10-25T22:43:37Z
[ "python", "ajax", "cgi", "web-applications", "fastcgi" ]
How do I display real-time python script output on a website?
1,621,430
<p>I have a Python script that outputs something every second or two, but takes a long while to finish completely. I want to set up a website such that someone can directly invoke the script, and the output is sent to the screen while the script is running. </p> <p>I don't want the user to wait until the script finish...
2
2009-10-25T17:10:53Z
11,067,328
<p>As suggested by a few of the others you can use a keep alive connection and instead of "return" statements use yield statements and instead of "print" statements also use yield statements. This will basically show everything that happens in the python script onto the website page.</p> <p>After extensive searching a...
0
2012-06-16T21:54:37Z
[ "python", "ajax", "cgi", "web-applications", "fastcgi" ]
How can I strip comments and doc strings from python source code?
1,621,521
<p>Is there a program which I can run like this:</p> <pre><code>py2py.py &lt; orig.py &gt; smaller.py </code></pre> <p>Where orig.py contains python source code with comments and doc strings, and smaller.py contains identical, runnable source code but without the comments and doc strings?</p> <p>Code which originall...
4
2009-10-25T17:43:25Z
1,621,551
<p><a href="https://pypi.python.org/pypi/pyminifier" rel="nofollow">This Python minifier</a> looks like it does what you need.</p>
8
2009-10-25T17:54:03Z
[ "python", "comments", "code-formatting" ]
Python Selenium handling Timeout Exceptions with a long list of URLs
1,621,806
<p>I am using selenium RC to cycle through a long list of URLs, sequentially writing the HTML from each URL to a csv file. Problem: the program frequently exits at various points in list due to URL "Timed out after 30000ms" exceptions. Instead of stopping the program when it hits a URL time-out, I was trying to have t...
1
2009-10-25T19:24:26Z
1,622,194
<p>Try the following:</p> <pre><code>from selenium import selenium import unittest, time, re, csv, logging class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://example.com") self.selenium.start() ...
3
2009-10-25T21:48:28Z
[ "python", "exception", "selenium", "timeout", "loops" ]
Finding and adding twitter users?
1,621,863
<p>Any suggestions for a good twitter library (preferably in Ruby or Python)? I have a list of usernames, and I need to be able to programmatically follow these users.</p> <ol> <li><p>I tried twitter4r in Ruby, but finding users doesn't seem to work. When I do</p> <pre><code>twitter = Twitter::Client.new(:login =&gt;...
3
2009-10-25T19:42:22Z
1,621,898
<p><a href="http://github.com/jnunemaker/twitter/" rel="nofollow">http://github.com/jnunemaker/twitter/</a> has been working pretty good for me.</p> <p>Although, If I am just doing something simple, I usually resort to the bare HTTP API. In this case it would be this one: <a href="http://apiwiki.twitter.com/Twitter-RE...
1
2009-10-25T19:54:14Z
[ "python", "ruby", "twitter" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,621,928
<pre><code>l = 'this-is-a-string'.split() nl = [] ss = "" c = 0 for s in l: c += 1 if c%2 == 0: ss = s else: ss = "%s-%s"%(ss,s) nl.insert(ss) print nl </code></pre>
0
2009-10-25T20:05:52Z
[ "python", "string", "split" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,621,950
<p><strong>EDIT:</strong> The original code I posted didn't work. This version does:</p> <p>I don't think you can split on every other one, but you could split on every - and join every pair.</p> <pre><code>chunks = [] content = "this-is-a-string" split_string = content.split('-') for i in range(0, len(split_string)...
0
2009-10-25T20:13:20Z
[ "python", "string", "split" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,621,952
<p>Here’s another solution:</p> <pre><code>span = 2 words = "this-is-a-string".split("-") print ["-".join(words[i:i+span]) for i in range(0, len(words), span)] </code></pre>
25
2009-10-25T20:13:39Z
[ "python", "string", "split" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,621,957
<p>Regular expressions handle this easily:</p> <pre><code>import re s = "aaaa-aa-bbbb-bb-c-ccccc-d-ddddd" print re.findall("[^-]+-[^-]+", s) </code></pre> <p>Output:</p> <pre><code>['aaaa-aa', 'bbbb-bb', 'c-ccccc', 'd-ddddd'] </code></pre> <p>Update for Nick D:</p> <pre><code>n = 3 print re.findall("-".join(["[^-]...
9
2009-10-25T20:14:56Z
[ "python", "string", "split" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,621,986
<pre><code>&gt;&gt;&gt; s="a-b-c-d-e-f-g-h-i-j-k-l" # use zip(*[i]*n) &gt;&gt;&gt; i=iter(s.split('-')) # for the nth case &gt;&gt;&gt; map("-".join,zip(i,i)) ['a-b', 'c-d', 'e-f', 'g-h', 'i-j', 'k-l'] &gt;&gt;&gt; i=iter(s.split('-')) &gt;&gt;&gt; map("-".join,zip(*[i]*3)) ['a-b-c', 'd-...
16
2009-10-25T20:27:23Z
[ "python", "string", "split" ]
Is there a way to split a string by every nth separator in Python?
1,621,906
<p>For example, if I had the following string:</p> <p>"this-is-a-string"</p> <p>Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four?</p>
7
2009-10-25T19:56:34Z
1,622,006
<p>I think several of the already given solutions are good enough, but just for fun, I did this version:</p> <pre><code>def twosplit(s,sep): first=s.find(sep) if first&gt;=0: second=s.find(sep,first+1) if second&gt;=0: return [s[0:second]] + twosplit(s[second+1:],sep) else: return [...
0
2009-10-25T20:39:51Z
[ "python", "string", "split" ]
python package import fails
1,621,999
<p>I've got a trac installation which works correctly from the command line. I deployed the trac.cgi to the proper directory, but when I open the page, I get:</p> <pre><code>Trac detected an internal error: No module named pkg_resources Traceback (most recent call last): File "/some/path/htdocs/trac.cgi", line 22, ...
0
2009-10-25T20:36:54Z
1,622,193
<p>I found the answer in the end. The script was run on a cluster - since I was using a virtual-python installation, some symlinks were not resolvable on other nodes. They were ok only on the machine that I was testing.</p> <p>Installing setuptools in a folder created by virtual-python (i.e. in a directory that is rep...
0
2009-10-25T21:48:22Z
[ "python", "import", "module" ]
python package import fails
1,621,999
<p>I've got a trac installation which works correctly from the command line. I deployed the trac.cgi to the proper directory, but when I open the page, I get:</p> <pre><code>Trac detected an internal error: No module named pkg_resources Traceback (most recent call last): File "/some/path/htdocs/trac.cgi", line 22, ...
0
2009-10-25T20:36:54Z
11,576,566
<p>Add a file <strong>__<em>init</em>__</strong>.py into your directory, where you already have pkg_resources.py module. It will work for you .</p>
1
2012-07-20T09:25:32Z
[ "python", "import", "module" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
1,622,052
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today = datetime.date.today() &gt;&gt;&gt; today + datetime.timedelta(days=-today.weekday(), weeks=1) datetime.date(2009, 10, 26) </code></pre> <p><em>Some words of explanation:</em></p> <p>Take todays date. Subtract the number of days which already passed this wee...
86
2009-10-25T21:02:20Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
1,622,069
<p>Using timedeltas and datetime module:</p> <pre><code>import datetime datetime.date.today()+datetime.timedelta(days=-datetime.date.today().weekday()) </code></pre>
0
2009-10-25T21:06:02Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
1,622,075
<pre><code>d = datetime.datetime.today().weekday() </code></pre> <p>gives you today's day of the week, counting 0 (monday) to 6 (sunday)</p> <pre><code>datetime.datetime.today() + datetime.timedelta(days=(7-d)%7) </code></pre> <p>(7-d)%7 gives you days until Monday, or leaves you where you are if today is Monday</p>...
0
2009-10-25T21:07:42Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
1,622,130
<p>Note: The OP says in the comments, "<em>I was looking for the past Monday</em>". I take this to mean we are looking for the last Monday that occurred strictly before today. </p> <p>The calculation is a little difficult to get right using only the <code>datetime</code> module (especially given the above interpretati...
7
2009-10-25T21:28:28Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
1,622,263
<p>ChristopheD's post is close to what you want. I don't have enough rep to make a comment :(</p> <p>Instead of (which actually gives you the next upcoming monday):</p> <pre> >>> today + datetime.timedelta(days=-today.weekday(), weeks=1) datetime.date(2009, 10, 26) </pre> <p>I would say:</p> <pre> >>> last_monday =...
24
2009-10-25T22:12:27Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
9,317,560
<p>I think the easiest way is using <a href="https://dateutil.readthedocs.org/en/latest" rel="nofollow">python-dateutil</a> like this:</p> <pre><code>from datetime import date from dateutil.relativedelta import relativedelta, MO today = date.today() last_monday = today + relativedelta(weekday=MO(-1)) print last_monda...
15
2012-02-16T19:13:25Z
[ "python", "django" ]
Find Monday's date with Python
1,622,038
<p>How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: <code>datetime.weekday()</code> to do it, but I am getting stuck.</p> <p>I basically want to find today's date and Mondays date to construct a date range query in django using: <code>created__range=(st...
33
2009-10-25T20:53:47Z
38,850,298
<p>You can use <strong>Natty</strong>. I tried <em>parsedatetime</em> and <em>dateparser</em>. Comparing these three, I think <strong>Natty</strong> is the best one.</p> <p>To get your result, use like this:</p> <pre><code>&gt;&gt;&gt; from natty import DateParser &gt;&gt;&gt; dp = DateParser('last monday') &gt;&gt;&...
0
2016-08-09T12:08:28Z
[ "python", "django" ]
White listing certain HTML tags in python?
1,622,314
<p>Let's say <code>allowed_bits = ['a', 'p']</code></p> <pre><code>re.compile(r'&lt;(%s)[^&gt;]*(/&gt;|.*?&lt;/\1&gt;)' % ('|'.join(allowed_bits))) </code></pre> <p>matches:</p> <pre><code>&lt;a href="blah blah"&gt;blah&lt;/a&gt; &lt;p /&gt; </code></pre> <p>and not:</p> <pre><code>&lt;html&gt;blah blah blah&lt;/h...
0
2009-10-25T22:34:18Z
1,622,321
<p>Use a <a href="http://www.regular-expressions.info/lookaround.html#lookahead" rel="nofollow">negative lookahead assertion <code>(?! … )</code></a>:</p> <pre><code>re.compile(r'&lt;(?!%s)[^&gt;](/&gt;|.?)' % ('|'.join(allowed_bits))) </code></pre>
2
2009-10-25T22:37:53Z
[ "python", "regex", "regex-negation" ]
How do I trim the number of words in Python?
1,622,421
<p>For example...</p> <pre><code>s = 'The fox jumped over a big brown log.' k = FUNCTION(s,4) k should be... "The fox jumped over" </code></pre> <p>I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.</p> <p>Anyone else knows a simpler way?</p>
-2
2009-10-25T23:10:58Z
1,622,429
<p>Something like this:</p> <pre><code>def f(s, n): return ' '.join(s.split()[:n]) </code></pre> <p>But it is still splitting, slicing and joining...</p>
6
2009-10-25T23:13:46Z
[ "python", "string" ]
How do I trim the number of words in Python?
1,622,421
<p>For example...</p> <pre><code>s = 'The fox jumped over a big brown log.' k = FUNCTION(s,4) k should be... "The fox jumped over" </code></pre> <p>I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.</p> <p>Anyone else knows a simpler way?</p>
-2
2009-10-25T23:10:58Z
1,622,432
<p>Why do you say "that is too much work"? Too much work for you, or too much for the computer? Is that code part of some performance critical code? </p> <p>Just do what works and move on to something more important.</p>
1
2009-10-25T23:15:04Z
[ "python", "string" ]
How do I trim the number of words in Python?
1,622,421
<p>For example...</p> <pre><code>s = 'The fox jumped over a big brown log.' k = FUNCTION(s,4) k should be... "The fox jumped over" </code></pre> <p>I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.</p> <p>Anyone else knows a simpler way?</p>
-2
2009-10-25T23:10:58Z
1,622,436
<pre><code>x = "Hello how are you?" ' '.join(x.split()[1:3]) &gt;&gt;&gt; "how are" </code></pre> <p>you can then change the numbers 1 and 3 in the list to get which words you want it to return</p> <pre><code>def split_me(string, start, end, skip): return ' '.join(string.split()[start:end:skip]) </code></pre> <p...
2
2009-10-25T23:15:55Z
[ "python", "string" ]
How do I trim the number of words in Python?
1,622,421
<p>For example...</p> <pre><code>s = 'The fox jumped over a big brown log.' k = FUNCTION(s,4) k should be... "The fox jumped over" </code></pre> <p>I can write my own function that splits on whitespace, cuts the list and then joins the list. But that is too much work.</p> <p>Anyone else knows a simpler way?</p>
-2
2009-10-25T23:10:58Z
1,622,447
<p>Try something like this:</p> <pre><code>def f(s, n): return " ".join( s.split()[:n] ) </code></pre>
1
2009-10-25T23:19:44Z
[ "python", "string" ]
Twisted: source IP address for outbound connections
1,622,454
<p>I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC com...
3
2009-10-25T23:21:51Z
1,623,083
<p>If you are using UDP then the endpoint is determined by either:</p> <ol> <li>calling <code>bind()</code> on the socket and explicitly giving it an address</li> <li>sending a packet</li> </ol> <p>If you want a few more details, <a href="http://stackoverflow.com/questions/1516972/udp-socket-port-allocation-failure/1...
0
2009-10-26T04:32:01Z
[ "python", "linux", "networking", "network-programming", "twisted" ]
Twisted: source IP address for outbound connections
1,622,454
<p>I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC com...
3
2009-10-25T23:21:51Z
1,657,207
<p>Did you see if that you want to do is possible with the SIP implementation that is part of Twisted?</p> <p>In any case, how you set the source address and port for UDP in Twisted is quite similar to how you set them without Twisted. In Twisted, <code>reactor.listenUDP(port, protocol, interface)</code> binds an UDP ...
0
2009-11-01T13:51:09Z
[ "python", "linux", "networking", "network-programming", "twisted" ]
Twisted: source IP address for outbound connections
1,622,454
<p>I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC com...
3
2009-10-25T23:21:51Z
1,758,184
<p>For the sake of completeness I answer my own question:</p> <p>Make sure you use connect() on the transport before trying to determine the host's source IP address. The following excerpt shows the relevant part of a protocol implementation:</p> <pre><code>class FooBarProtocol(protocol.DatagramProtocol): def st...
8
2009-11-18T18:46:04Z
[ "python", "linux", "networking", "network-programming", "twisted" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,541
<p>A register machine is an abstract machine whose opcodes are defined by reference to their operation on a set of named registers, rather than by their operation on the top portion of a stack.</p> <p>In a register machine: add could be defined to take three register names as operands, add the contents of the first tw...
2
2009-10-25T23:58:21Z
[ "python", "language-design", "language-theory", "language-implementation" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,542
<p>A register machine is a hardware or software unit that when working with data takes it from memory, puts it in a location where it can work with it quickly, and then returns the result.</p> <p>For example a regular CPU is a register machine. Since the ALU (the unit that works with numbers in a CPU) can only work wi...
18
2009-10-25T23:58:22Z
[ "python", "language-design", "language-theory", "language-implementation" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,544
<p>A register machine uses a fixed number of registers or buckets for storing intermediate values for computation. For example the "add" instruction could add the values in two specific registers and store the result in another register.</p> <p>A stack based machine uses a stack for storing intermediate values during...
5
2009-10-25T23:59:02Z
[ "python", "language-design", "language-theory", "language-implementation" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,555
<p>Did your compiler generate machine code? If so, then its target was a register machine (nearly all CPU designs are register machines).</p> <p>Stack machines store all values on a stack, whereas register machines have a fixed number of storage slots whose "addresses" do not change (unlike stack machines).</p>
2
2009-10-26T00:02:41Z
[ "python", "language-design", "language-theory", "language-implementation" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,589
<blockquote> <p>1) Am I right in thinking that what I implemented would be considered a "stack-based machine" given the terminology used in the quotation above?</p> </blockquote> <p>Not really. A stack of some sort is pretty much the only way to implement recursive function calls. But a "stack-based machine"...
4
2009-10-26T00:21:59Z
[ "python", "language-design", "language-theory", "language-implementation" ]
what exactly is a "register machine"?
1,622,530
<p>From <a href="http://code.google.com/p/unladen-swallow/wiki/ProjectPlan">http://code.google.com/p/unladen-swallow/wiki/ProjectPlan</a> I quote:</p> <p>"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languag...
20
2009-10-25T23:54:04Z
1,622,590
<p>A register machine almost always has a stack, also.</p> <p>But a stack machine rarely has architecturally visible registers, or it may only have one or two.</p> <p>A register machine may have some stack ops and may even have a stack addressing mode.</p> <p>The difference is one of orientation. The register machin...
10
2009-10-26T00:22:01Z
[ "python", "language-design", "language-theory", "language-implementation" ]
Overriding set methods in Python
1,622,722
<p>I want to create a custom set that will automatically convert objects into a different form for storage in the set (see <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key-non-nested">Using a Python Dictionary as a key non-nested</a>) for background. </p> <p>If I override <code>ad...
1
2009-10-26T01:30:02Z
1,622,872
<p>In Python 2.6:</p> <pre><code>import collections print collections.MutableSet.__abstractmethods__ # prints: # frozenset(['discard', 'add', '__iter__', '__len__', '__contains__']) </code></pre> <p>subclass <code>collections.MutableSet</code> and override the methods in the list above.</p> <p>the update method itse...
1
2009-10-26T02:46:01Z
[ "python", "python-3.x", "set" ]
Overriding set methods in Python
1,622,722
<p>I want to create a custom set that will automatically convert objects into a different form for storage in the set (see <a href="http://stackoverflow.com/questions/1600591/using-a-python-dictionary-as-a-key-non-nested">Using a Python Dictionary as a key non-nested</a>) for background. </p> <p>If I override <code>ad...
1
2009-10-26T01:30:02Z
1,623,156
<p>Working from <code>collections</code>'s abstract classes, as @kaizer.se suggests, is the appropriate solution in 2.6 (not sure why you want to call super -- what functionality are you trying to delegate that can't best done by containment rather than inheritance?!).</p> <p>It's true that you don't get <code>update<...
6
2009-10-26T05:03:40Z
[ "python", "python-3.x", "set" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
1,623,060
<p>Just a guess, but could the difference be the order of magnitude of difference in range() values?</p> <p>From your original source:</p> <pre><code>alist=range(1000000) </code></pre> <p>From your <code>timeit</code> example:</p> <pre><code>alist=range(100000) </code></pre> <p>For what it's worth, here are the re...
2
2009-10-26T04:24:39Z
[ "python", "timing", "timeit" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
1,624,600
<p>regardless of this particular exercise, I'd imagine that using <code>timeit</code> is much safer and reliable option. it is also cross-platform, unlike your solution.</p>
1
2009-10-26T12:48:52Z
[ "python", "timing", "timeit" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
1,624,688
<p>Use timeit. Running the test more than once gives me much better results.</p> <pre><code>func_list=[locals()[key] for key in locals().keys() if callable(locals()[key]) and key.startswith('time')] alist=range(1000000) times=[] for f in func_list: n = 10 times.append( min( t for t,_,_ in (f(alis...
11
2009-10-26T13:10:14Z
[ "python", "timing", "timeit" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
1,630,626
<p>I got tired of <code>from __main__ import foo</code>, now use this -- for simple args, for which %r works, and not in Ipython.<br> (Why does <code>timeit</code> works only on strings, not thunks / closures i.e. timefunc( f, arbitrary args ) ?)</p> <pre><code> import timeit def timef( funcname, *args, **kwargs ): ...
5
2009-10-27T12:57:51Z
[ "python", "timing", "timeit" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
15,136,422
<p>I would use a timing decorator, because you can use annotations to sprinkle the timing around your code rather than making you code messy with timing logic.</p> <pre><code>import time def timeit(f): def timed(*args, **kw): ts = time.time() result = f(*args, **kw) te = time.time() ...
13
2013-02-28T13:10:30Z
[ "python", "timing", "timeit" ]
timeit versus timing decorator
1,622,943
<p>I'm trying to time some code. First I used a timing decorator:</p> <pre><code>#!/usr/bin/env python import time from itertools import izip from random import shuffle def timing_val(func): def wrapper(*arg, **kw): '''source: http://www.daniweb.com/code/snippet368.html''' t1 = time.time() ...
33
2009-10-26T03:23:34Z
27,737,385
<p>Use wrapping from <code>functools</code> to improve Matt Alcock's answer. </p> <pre><code>from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() print 'func:%r args:[%r, %r] took: %2.4...
11
2015-01-02T04:30:10Z
[ "python", "timing", "timeit" ]
Execute and monitor multiple instances of external program in Python
1,623,192
<p>Main program is like this:</p> <pre><code>PREPARE PARAMETERS FOR CHILD PROCESSES subprocess.Popen('python child.py param=example1'.split(' ')) subprocess.Popen('python child.py param=example2'.split(' ')) ... </code></pre> <p>How to make main program to monitor each instances of child process it launched and resta...
2
2009-10-26T05:14:49Z
1,623,224
<p>Keep a dict with the <code>.pid</code>s of the child processes as keys, and the commandlines to restart them as corresponding values. i.e.:</p> <pre><code>childid = [] for cmdline in cmdlines: p = subprocess.Popen(cmdline.split()) childid[p.pid] = cmdline </code></pre> <p><a href="http://docs.python.org/libra...
4
2009-10-26T05:28:06Z
[ "python", "external-process" ]
Restrict access to images on my website except through my own htmls
1,623,311
<p>On my website I store user pictures in a simple manner such as: "image/user_1.jpg".</p> <p>I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)</p> <p>So far I have three solutions in mind:</p> ...
2
2009-10-26T06:06:14Z
1,623,325
<p>You are right considering option #3. Use service script that would validate user and readfile() an image. Be sure to set correct Content-Type HTTP header via header() function prior to serving an image. For better isolation images should be put above web root directory, or protected by well written .htaccess rules -...
2
2009-10-26T06:13:28Z
[ "php", "python", "linux", "perl" ]
Restrict access to images on my website except through my own htmls
1,623,311
<p>On my website I store user pictures in a simple manner such as: "image/user_1.jpg".</p> <p>I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)</p> <p>So far I have three solutions in mind:</p> ...
2
2009-10-26T06:06:14Z
1,623,338
<p>Any method you choose to determine the source of a request is only as reliable as the HTTP_REFERER information that is sent by the user's browser, which is not very. Requiring authentication is the only good way to protect content. </p>
6
2009-10-26T06:18:36Z
[ "php", "python", "linux", "perl" ]
Restrict access to images on my website except through my own htmls
1,623,311
<p>On my website I store user pictures in a simple manner such as: "image/user_1.jpg".</p> <p>I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)</p> <p>So far I have three solutions in mind:</p> ...
2
2009-10-26T06:06:14Z
1,623,341
<p>You can look up "Hotlinking prevention" via htaccess and i think that should be a simple solution for the type of protection you need. However its not fool proof , people who will really want to get those images will find a work around by faking the referrer.</p> <p><a href="http://altlab.com/htaccess%5Ftutorial.ht...
2
2009-10-26T06:19:24Z
[ "php", "python", "linux", "perl" ]
Restrict access to images on my website except through my own htmls
1,623,311
<p>On my website I store user pictures in a simple manner such as: "image/user_1.jpg".</p> <p>I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)</p> <p>So far I have three solutions in mind:</p> ...
2
2009-10-26T06:06:14Z
1,623,344
<p>Method #1 is not viable as it will ask for user name and password on each and every image requested. You probably got the prompt for some of the images and not for others due to caching issues.</p> <p>Method #2 looks the most appealing to me by being the least processor intensive, but with only the user_id passed t...
5
2009-10-26T06:20:57Z
[ "php", "python", "linux", "perl" ]
Restrict access to images on my website except through my own htmls
1,623,311
<p>On my website I store user pictures in a simple manner such as: "image/user_1.jpg".</p> <p>I don't want visitors to be able to view images on my server just by trying user_ids. (Ex: www.mydomain.com/images/user_2.jpg, www.mydomain.com/images/user_3.jpg, so on...)</p> <p>So far I have three solutions in mind:</p> ...
2
2009-10-26T06:06:14Z
1,623,793
<p>As has been said hotlinking protection does not protect your files from listing just by altering their id. Plus Refferer can be easily faked.</p> <p>In this case I would recommend some kind of authentication. You must create PHP script that will serve images only if it verify logged user via COOKIES or SESSION. (I ...
0
2009-10-26T09:07:34Z
[ "php", "python", "linux", "perl" ]
Adventure game - walking around inside a room
1,623,331
<p>I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is qu...
0
2009-10-26T06:16:11Z
1,623,346
<blockquote> <p>Sadly, I have never studied algorithms so I have no clue on how to calculate a path.</p> </blockquote> <p>Before you start writing games, you should educate yourself on those. This takes a little more effort at the beginning, but will save you much time later. </p>
3
2009-10-26T06:21:38Z
[ "python", "pygame" ]
Adventure game - walking around inside a room
1,623,331
<p>I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is qu...
0
2009-10-26T06:16:11Z
1,623,347
<p>I am not familiar with pygame, but many applications commonly use <a href="http://en.wikipedia.org/wiki/Bounding%5Fvolume" rel="nofollow">bounding volumes</a> to define the edge of some region. The idea is that as your character walks, you will check if the characters volume intersects with the volume of a wall. You...
1
2009-10-26T06:21:51Z
[ "python", "pygame" ]
Adventure game - walking around inside a room
1,623,331
<p>I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is qu...
0
2009-10-26T06:16:11Z
1,623,349
<p>I recommend you read up on the <a href="http://en.wikipedia.org/wiki/A%2A%5Fsearch%5Falgorithm" rel="nofollow">A*</a> search algorithm as it is commonly used in games for pathing problems. </p> <p>If this game is two dimensional (or 2.5) I suggest you use a tile system as checking for collisions will be easier. The...
3
2009-10-26T06:22:07Z
[ "python", "pygame" ]
Adventure game - walking around inside a room
1,623,331
<p>I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is qu...
0
2009-10-26T06:16:11Z
1,623,398
<p>There are two easy ways of defining your boundaries which are appropriate for such a game.</p> <p>The simpler method is to divide your area into a grid, and use a 2D array to keep track of which squares in the grid are passable. Usually, this array stores your map information too, so in each position, there is a nu...
4
2009-10-26T06:46:32Z
[ "python", "pygame" ]
Pylons importing Psycopg2 error
1,623,449
<pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in &lt;module&gt; from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_ps...
2
2009-10-26T07:06:41Z
1,623,501
<p>Could it be that the postgres installation was removed/updated? The symbol is supposed to come from libpq.</p>
1
2009-10-26T07:34:42Z
[ "python", "pylons", "psycopg2" ]
Pylons importing Psycopg2 error
1,623,449
<pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in &lt;module&gt; from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_ps...
2
2009-10-26T07:06:41Z
2,024,731
<p>You get this error because your 64-bit version of python can't find a 64-bit psycopg2.</p> <p>You can either downgrade your python to run in 32-bit mode or try to get a 64-bit psycopg2. There is more discussion on this topic over on <a href="http://benkreeger.com/post/312281790/snow-leopards-python-26-site-package...
4
2010-01-08T00:38:13Z
[ "python", "pylons", "psycopg2" ]
Pylons importing Psycopg2 error
1,623,449
<pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in &lt;module&gt; from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_ps...
2
2009-10-26T07:06:41Z
2,645,014
<p>This is broken for me too, and in my case it doesn't appear to be a 32 vs 64 bit issue:</p> <pre><code>decibel@workbook.1[6:55]~/src:85%file /opt/local/lib/postgresql83/libpq.dylib /opt/local/lib/postgresql83/libpq.dylib: Mach-O 64-bit dynamically linked shared library x86_64 decibel@workbook.1[6:56]~/src:86%file ...
1
2010-04-15T12:06:56Z
[ "python", "pylons", "psycopg2" ]
Pylons importing Psycopg2 error
1,623,449
<pre><code> Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.6/site-packages/psycopg2/__init__.py", line 60, in &lt;module&gt; from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: dlopen(/Library/Python/2.6/site-packages/psycopg2/_ps...
2
2009-10-26T07:06:41Z
3,228,173
<p>resolved similar issue by <a href="http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Forcing_32_Bit_Execution" rel="nofollow">forcing Apache executables 32 bit execution</a></p>
1
2010-07-12T11:44:32Z
[ "python", "pylons", "psycopg2" ]
Does using Psyco with django make any sense?
1,623,538
<p>I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?</p>
3
2009-10-26T07:50:03Z
1,623,547
<p>You should be using fastcgi or wsgi with django, so the process won't be starting up for each request.</p> <p>You really need to write your code to be psyco friendly if you want decent gains, and you will not benefit if your bottleneck is the database.</p>
4
2009-10-26T07:51:56Z
[ "python", "django", "psyco" ]
Does using Psyco with django make any sense?
1,623,538
<p>I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?</p>
3
2009-10-26T07:50:03Z
1,623,581
<p>First, as gribbler and Ibrahim mentioned, your process won't die unless you are using pure CGI... which you shouldn't be using.</p> <p>Secondly, the bottleneck in most web apps are database queries, for which Psyco won't help.</p> <p>If you happen to have a some logic that is computationally intensive it can certa...
4
2009-10-26T08:03:40Z
[ "python", "django", "psyco" ]
Does using Psyco with django make any sense?
1,623,538
<p>I know the benefits of Psyco for a Desktop app, but in a Web app where a process ( = a web page or an AJAX call) dies immediately after been fired, isn't it pointless ?</p>
3
2009-10-26T07:50:03Z
1,623,590
<p>This guy got a performance increase out of it:</p> <p><a href="http://www.alrond.com/en/2007/jan/25/performance-test-of-6-leading-frameworks/" rel="nofollow">http://www.alrond.com/en/2007/jan/25/performance-test-of-6-leading-frameworks/</a></p> <p>It's a little bit outdated though.</p>
3
2009-10-26T08:06:18Z
[ "python", "django", "psyco" ]
Escaping '<' and '>' in xml when using xml.dom.minidom
1,623,607
<p>I am stuck while escaping "&lt;" and ">" in the xml file using xml.dom.minidom. I tried to get the unicode hex value and use that instead<br /> <a href="http://slayeroffice.com/tools/unicode%5Flookup/" rel="nofollow">http://slayeroffice.com/tools/unicode%5Flookup/</a> </p> <p>Tried to use the standard "&lt;" an...
1
2009-10-26T08:13:28Z
1,623,629
<p>This is not a bug, it is a feature. To insert actual XML, insert DOM objects instead. Text inside an XML tag needs to be entity escaped though to be valid XML.</p> <pre><code>from xml.dom.minidom import Document doc = Document() e = doc.createElement("abc") eh = doc.createElement("hello") s1 = 'bhaskar' text = doc....
6
2009-10-26T08:18:57Z
[ "python", "xml" ]
Escaping '<' and '>' in xml when using xml.dom.minidom
1,623,607
<p>I am stuck while escaping "&lt;" and ">" in the xml file using xml.dom.minidom. I tried to get the unicode hex value and use that instead<br /> <a href="http://slayeroffice.com/tools/unicode%5Flookup/" rel="nofollow">http://slayeroffice.com/tools/unicode%5Flookup/</a> </p> <p>Tried to use the standard "&lt;" an...
1
2009-10-26T08:13:28Z
1,623,638
<p>If you use <code>"&lt;"</code> <strong>as text</strong> in XML, you need to escape it, else it is considered markup. So xml.dom is right in escaping it, since you've asked for a text node.</p> <p>Assuming you really want to insert a piece of XML, I recommend to use <code>createElement("hello")</code>. If you have a...
3
2009-10-26T08:21:57Z
[ "python", "xml" ]
SQLAlchemy: Shallow copy avoiding lazy loading
1,623,661
<p><br /> I'm trying to automatically build a shallow copy of a SA-mapped object.. At the moment my function is just:</p> <pre><code>newobj = src.__class__() for prop in class_mapper(src.__class__).iterate_properties: setattr(newobj, prop.key, getattr(src, prop.key)) </code></pre> <p>but I'm having troubles with ...
5
2009-10-26T08:28:47Z
1,623,726
<p>What you need is to copy column properties only, which can be easily filtered using <code>isinstance(prop, sqlalchemy.orm.ColumnProperty)</code>. Note, that you HAVE to copy externally stored relations (all many-to-many), since there is no columns corresponding to them in the main table. This can't be done with high...
6
2009-10-26T08:51:15Z
[ "python", "sqlalchemy" ]
Fastest way to zero out low values in array?
1,623,849
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0....
22
2009-10-26T09:24:02Z
1,623,868
<p>The simplest way would be:</p> <pre><code>topX = sorted([x for x in array if x &gt; lowValY], reverse=True)[highCountX-1] print [x if x &gt;= topX else 0 for x in array] </code></pre> <p>In pieces, this selects all the elements greater than <code>lowValY</code>:</p> <pre><code>[x for x in array if x &gt; lowValY]...
4
2009-10-26T09:29:35Z
[ "python", "arrays", "floating-point", "max", "min" ]
Fastest way to zero out low values in array?
1,623,849
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0....
22
2009-10-26T09:24:02Z
1,623,939
<p>This is a typical job for <a href="http://www.scipy.org/Tentative_NumPy_Tutorial">NumPy</a>, which is very fast for these kinds of operations:</p> <pre><code>array_np = numpy.asarray(array) low_values_indices = array_np &lt; lowValY # Where values are low array_np[low_values_indices] = 0 # All low values set to 0...
49
2009-10-26T09:49:08Z
[ "python", "arrays", "floating-point", "max", "min" ]
Fastest way to zero out low values in array?
1,623,849
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0....
22
2009-10-26T09:24:02Z
1,623,949
<p>Settings elements below some threshold to zero is easy:</p> <pre><code>array = [ x if x &gt; threshold else 0.0 for x in array ] </code></pre> <p>(plus the occasional abs() if needed.)</p> <p>The requirement of the N highest numbers is a bit vague, however. What if there are e.g. N+1 equal numbers above the thres...
1
2009-10-26T09:51:39Z
[ "python", "arrays", "floating-point", "max", "min" ]
Fastest way to zero out low values in array?
1,623,849
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0....
22
2009-10-26T09:24:02Z
1,623,952
<p>Using <code>numpy</code>:</p> <pre><code># assign zero to all elements less than or equal to `lowValY` a[a&lt;=lowValY] = 0 # find n-th largest element in the array (where n=highCountX) x = partial_sort(a, highCountX, reverse=True)[:highCountX][-1] # a[a&lt;x] = 0 #NOTE: it might leave more than highCountX non-ze...
5
2009-10-26T09:52:46Z
[ "python", "arrays", "floating-point", "max", "min" ]
Fastest way to zero out low values in array?
1,623,849
<p>So, lets say I have 100,000 float arrays with 100 elements each. I need the highest X number of values, BUT only if they are greater than Y. Any element not matching this should be set to 0. What would be the fastest way to do this in Python? Order must be maintained. Most of the elements are already set to 0....
22
2009-10-26T09:24:02Z
1,623,966
<p>You can use map and lambda, it should be fast enough.</p> <pre><code>new_array = map(lambda x: x if x&gt;y else 0, array) </code></pre>
1
2009-10-26T09:56:40Z
[ "python", "arrays", "floating-point", "max", "min" ]