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
NameError: name 'self' is not defined
1,802,971
<p>Why such structure</p> <pre><code>class A: def __init__(self, a): self.a = a def p(self, b=self.a): print b </code></pre> <p>gives an error <code>NameError: name 'self' is not defined</code>?</p>
88
2009-11-26T10:47:54Z
1,802,980
<p>Default argument values are evaluated at function define-time, but <code>self</code> is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.</p> <p>It's a common pattern to default an argument to <code>None</code> and add a test for that in code:</p> <pre><...
84
2009-11-26T10:50:14Z
[ "python", "oop" ]
NameError: name 'self' is not defined
1,802,971
<p>Why such structure</p> <pre><code>class A: def __init__(self, a): self.a = a def p(self, b=self.a): print b </code></pre> <p>gives an error <code>NameError: name 'self' is not defined</code>?</p>
88
2009-11-26T10:47:54Z
1,804,892
<p>For cases where you also wish to have the option of setting 'b' to None:</p> <pre><code>def p(self, **kwargs): b = kwargs.get('b', self.a) print b </code></pre>
11
2009-11-26T17:28:10Z
[ "python", "oop" ]
Speeding up computations with numpy matrices
1,803,054
<p>I have two matrices. Both are filled with zeros and ones. One is a big one (3000 x 2000 elements), and the other is smaller ( 20 x 20 ) elements. I am doing something like:</p> <pre><code>newMatrix = (size of bigMatrix), filled with zeros l = (a constant) for y in xrange(0, len(bigMatrix[0])): for x in xrange(...
0
2009-11-26T11:07:44Z
1,803,708
<p>I can think of a couple of optimisations there - As you are using 4 nested python "for" statements, you are about as slow as you can be.</p> <p>I can't figure out exactly what you are looking for - but for one thing, if your big matrix "1"s density is low, you can certainly use python's "any" function on bigMtari...
1
2009-11-26T13:36:49Z
[ "python", "matrix", "numpy" ]
Speeding up computations with numpy matrices
1,803,054
<p>I have two matrices. Both are filled with zeros and ones. One is a big one (3000 x 2000 elements), and the other is smaller ( 20 x 20 ) elements. I am doing something like:</p> <pre><code>newMatrix = (size of bigMatrix), filled with zeros l = (a constant) for y in xrange(0, len(bigMatrix[0])): for x in xrange(...
0
2009-11-26T11:07:44Z
1,804,172
<p>Your example code makes no sense, but the description of your problem sounds like you are trying to do a 2d convolution of a small bitarray over the big bitarray. There's a convolve2d function in scipy.signal package that does exactly this. Just do <code>convolve2d(bigMatrix, smallMatrix)</code> to get the result. U...
1
2009-11-26T14:59:43Z
[ "python", "matrix", "numpy" ]
Speeding up computations with numpy matrices
1,803,054
<p>I have two matrices. Both are filled with zeros and ones. One is a big one (3000 x 2000 elements), and the other is smaller ( 20 x 20 ) elements. I am doing something like:</p> <pre><code>newMatrix = (size of bigMatrix), filled with zeros l = (a constant) for y in xrange(0, len(bigMatrix[0])): for x in xrange(...
0
2009-11-26T11:07:44Z
1,847,776
<p>If your bits are really packed 8 per byte / 32 per int, and you can reduce your smallMatrix to 20x16,<br> then try the following, here for a single row.<br> (<code>newMatrix[x, y] = 1</code> when <em>any</em> bit of the 20x16 around x,y is 1 ?? What are you really looking for ?)</p> <pre><code>python -m timeit -s '...
0
2009-12-04T15:39:12Z
[ "python", "matrix", "numpy" ]
Initialize project layout in python?
1,803,292
<p>Suppose a programmer has the following problem: he wants to start a new python project. He needs a basic layout of boilerplate stuff, like test directory, source directory, setuptools script etc.. How does he create all this stuff and layout with a single command ?</p> <p>For example, paster (as suggested in one of...
11
2009-11-26T12:02:10Z
1,803,321
<p>You need something that supports templating to pull this off. The most used in the python community is pastescript.</p> <pre><code>easy_install pastescript # A one-time install paster create </code></pre> <p>If you've already decided on the name of the package, than it's just:</p> <pre><code>paster create mypack...
10
2009-11-26T12:07:14Z
[ "python" ]
Initialize project layout in python?
1,803,292
<p>Suppose a programmer has the following problem: he wants to start a new python project. He needs a basic layout of boilerplate stuff, like test directory, source directory, setuptools script etc.. How does he create all this stuff and layout with a single command ?</p> <p>For example, paster (as suggested in one of...
11
2009-11-26T12:02:10Z
1,803,597
<p>You can make your own templates. Really useful, for instance for in-house project structure standards.</p> <p>Best way to start making your own is to start with an existing example and to copy/paste relevant bits from it. Suggestion: <a href="http://pypi.python.org/pypi/ZopeSkel" rel="nofollow">ZopeSkel</a> as it ...
1
2009-11-26T13:10:52Z
[ "python" ]
Initialize project layout in python?
1,803,292
<p>Suppose a programmer has the following problem: he wants to start a new python project. He needs a basic layout of boilerplate stuff, like test directory, source directory, setuptools script etc.. How does he create all this stuff and layout with a single command ?</p> <p>For example, paster (as suggested in one of...
11
2009-11-26T12:02:10Z
6,044,584
<p>I'm using <code>modern-package-template</code> to layout my Python projects.</p> <blockquote> <p>modern-package-template is a PasteScript template to create an initial layout for your Python projects using modern tools and practices followed in the Python community. Thus, your projects will have the following cha...
3
2011-05-18T12:22:31Z
[ "python" ]
Initialize project layout in python?
1,803,292
<p>Suppose a programmer has the following problem: he wants to start a new python project. He needs a basic layout of boilerplate stuff, like test directory, source directory, setuptools script etc.. How does he create all this stuff and layout with a single command ?</p> <p>For example, paster (as suggested in one of...
11
2009-11-26T12:02:10Z
24,637,202
<p>I've been using <a href="https://github.com/audreyr/cookiecutter" rel="nofollow">cookiecutter</a>. It's written in python but can be used for any kind of project; not just python. It uses Jinja for templating and features pre and post hooks (written in python or bash) that can easily create/manage one's virtualenvs ...
1
2014-07-08T16:38:07Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,349
<p>Did you mean returning first value for what <code>bool(value)==True</code>? Then you can just rely on the fact that <a href="http://docs.python.org/reference/expressions.html#boolean-operations">boolean operators return last evaluated argument</a>:</p> <pre><code>result = a or b or c or default </code></pre>
19
2009-11-26T12:14:49Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,350
<p>If one variable is not "defined", you can't access its name. So any reference to 'a' raises a NameError Exception.</p> <p>In the other hand, if you have something like:</p> <pre><code>a = None b = None c = 3 </code></pre> <p>you can do</p> <pre><code>default = 1 r = a or b or c or default # r value is 3 </code><...
17
2009-11-26T12:15:03Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,366
<p>Don't know if this works in every case, but this works for this case.</p> <pre><code>a = False b = "b" c = False default = "default" print a or b or c or default # b </code></pre>
1
2009-11-26T12:17:24Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,412
<p>How about this ? </p> <pre><code>a=None b=None c=None val= reduce(lambda x,y:x or y,(a,b,c,"default")) print val </code></pre> <p>The above prints <code>"default"</code>. If any of the inputs is defined, <code>val</code> would contain the first defined input.</p>
1
2009-11-26T12:28:30Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,448
<p>So long as <code>default</code> evaluates to True:</p> <pre><code>result = next((x for x in (a, b, c, d , e, default) if x)) </code></pre>
5
2009-11-26T12:39:21Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,803,489
<p>You could do something like this (in contrast to the other answers this is a solution where you don't <strong>have</strong> to define the 'missing' values as being either <code>None</code> or <code>False</code>):</p> <pre><code>b = 6 c = 8 def first_defined(items): for x in items: try: retu...
2
2009-11-26T12:46:45Z
[ "python" ]
Pythonic way to select first variable that evaluates to True
1,803,302
<p>I have some variables and I want to select the first one that evaluates to True, or else return a default value.</p> <p>For instance I have <code>a</code>, <code>b</code>, and <code>c</code>. My existing code:</p> <pre><code>result = a if a else (b if b else (c if c else default)) </code></pre> <p>Another approac...
5
2009-11-26T12:03:49Z
1,805,096
<p>If by <code>defined</code> you mean <code>ever assigned any value whatsoever to in any scope accessible from here</code>, then trying to access an "undefined" variable will raise a NameError exception (or some subclass thereof, but catching NameError will catch the subclass too). So, the simplest way to perform, li...
1
2009-11-26T18:28:43Z
[ "python" ]
Fast Graphics with XServer
1,803,458
<p>I am working on <strong>embedded linux platform with limited system resources</strong>.</p> <p><strong>I want to do fullscreen slideshow with simple transistions (like slide in-out, fade in-out )</strong>.</p> <p>I tried PyGtk+GTK+Cairo but its very slow, when I animate GTK image controls I get just two or three f...
0
2009-11-26T12:40:42Z
1,803,507
<p>I would try this first using just PyCairo, not using GTK controls at all.</p> <p>However, if that does not give you the speed that you need, then you might want to try PyGame which gives you access to SDL including OpenGL backends. PyGame is very actively developed and used in building applications that include ful...
2
2009-11-26T12:50:12Z
[ "python", "linux" ]
replace the NaN value zero after an operation with arrays
1,803,516
<p>how can I replace the NaN value in an array, zero if an operation is performed such that as a result instead of the NaN value is zero operations as</p> <p>0 / 0 = NaN can be replaced by 0</p>
3
2009-11-26T12:54:13Z
1,803,598
<p>If you have Python 2.6 you have the <a href="http://docs.python.org/library/math.html#math.isnan"><code>math.isnan()</code></a> function to find <code>NaN</code> values.</p> <p>With this we can use a list comprehension to replace the <code>NaN</code> values in a list as follows:</p> <pre><code>import math mylist =...
6
2009-11-26T13:10:56Z
[ "python" ]
replace the NaN value zero after an operation with arrays
1,803,516
<p>how can I replace the NaN value in an array, zero if an operation is performed such that as a result instead of the NaN value is zero operations as</p> <p>0 / 0 = NaN can be replaced by 0</p>
3
2009-11-26T12:54:13Z
30,315,147
<pre><code>import numpy a=numpy.array([1,2,3,'NaN',4]) s=numpy.isnan(a) a[s]=0.0 </code></pre>
1
2015-05-19T01:02:37Z
[ "python" ]
How to set User-Agent in python-twitter?
1,803,669
<p>i'm writing a small script to tweet messages from the monitoring systems. The only issue i ran into so far is that i can't set the User-Agent correctly, all tweets show up as "from API" which ain't a huge deal but i wonder what I'm doing wrong. An example to reproduce this behavior:</p> <pre><code>import sys impor...
0
2009-11-26T13:28:45Z
1,804,076
<p>In order to get Twitter to recognize your application you have to use OAuth nowadays and register your application.</p> <p>See <a href="http://bit.ly/JGu34" rel="nofollow">this FAQ entry</a> and <a href="http://twitter.com/oauth%5Fclients/new" rel="nofollow">Twitter's application registration form</a>.</p>
2
2009-11-26T14:43:57Z
[ "python", "twitter", "user-agent", "python-twitter" ]
communicate with a process in utf-8 on a cp1252 consoless
1,803,675
<p>I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using <code>subprocess.Popen()</code>:</p> <pre><code>proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) proc.stdin.write(u'ééé'.encode('utf_8')) </code></pre> <p>I...
0
2009-11-26T13:31:19Z
1,803,730
<p>I wonder if this caveat, from the <a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="nofollow">subprocess documentation</a>, is relevant:</p> <blockquote> <p>The only reason you would need to specify shell=True on Windows is where the command you wish to execute is actually built in to...
0
2009-11-26T13:41:10Z
[ "python", "windows", "utf-8", "cp1252" ]
communicate with a process in utf-8 on a cp1252 consoless
1,803,675
<p>I need to control a program by sending commands in utf-8 encoding to its standard input. For this I run the program using <code>subprocess.Popen()</code>:</p> <pre><code>proc = Popen("myexecutable.exe", shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) proc.stdin.write(u'ééé'.encode('utf_8')) </code></pre> <p>I...
0
2009-11-26T13:31:19Z
1,803,811
<p>Why do you need to force utf-8 pipes? Couldn't you do something like</p> <pre><code>import sys current_encoding = sys.stdout.encoding ... proc.stdin.write(u'ééé'.encode(current_encoding)) </code></pre> <p>EDIT: I wrote this answer before you edited your question. I guess this is not what you're looking for, the...
0
2009-11-26T13:57:12Z
[ "python", "windows", "utf-8", "cp1252" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,739
<p>I would add a docstring which explains what it compares, as you did in your question.</p>
9
2009-11-26T13:42:49Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,746
<p>I would break the logic up into separate chunks that are easier to understand, each one checking a different condition (and each one assuming the previous thing was checked). Easiest just to show the code:</p> <pre><code># First, check if we have the same list of variables. my_vars = [var for var in self.metainf if...
1
2009-11-26T13:45:06Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,752
<p>Use <a href="http://docs.python.org/3.1/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a>'s third argument to set distinct default values:</p> <pre><code>def __eq__(self, other): return all(getattr(self, a, Ellipsis) == getattr(other, a, Ellipsis) for a in self.metainfo) </c...
9
2009-11-26T13:45:52Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,757
<pre><code>def __eq__(self, other): """Returns True if both instances have the same variables from metainfo and they have the same values.""" for attr in self.metainfo: if attr in self.__dict__: if attr not in other.__dict__: return False if getattr(self, attr...
5
2009-11-26T13:46:29Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,866
<p>The try/excepts make your code harder to read. I'd use getattr with a default value that is guaranteed not to otherwise be there. In the code below I just make a temp object. That way if object do not have a given value they'll both return "NOT_PRESENT" and thus count as being equal.</p> <pre><code> def __eq__(s...
1
2009-11-26T14:09:16Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,901
<p>Going with <em>"Flat is better than nested"</em> I would remove the nested try statements. Instead, getattr should return a sentinel that only equals itself. Unlike Stephan202, however, I prefer to keep the for loop. I also would create a sentinel by myself, and not re-use some existing Python object. This guarantee...
2
2009-11-26T14:15:03Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,908
<p><strong>Since it's about to make it easy to understand, not short or very fast :</strong></p> <pre><code>class Test(object): def __init__(self): self.metainfo = ["foo", "bar"] # adding a docstring helps a lot # adding a doctest even more : you have an example and a unit test # at the same ...
3
2009-11-26T14:16:35Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,910
<p>I like Stephan202's answer, but I think that his code doesn't make equality conditions clear enough. Here's my take on it:</p> <pre><code>def __eq__(self, other): wehave = [attr for attr in self.metainfo if hasattr(self, attr)] theyhave = [attr for attr in self.metainfo if hasattr(other, attr)] if wehav...
0
2009-11-26T14:16:38Z
[ "python", "equality" ]
Python: Can you make this __eq__ easy to understand?
1,803,710
<p>I have another question for you.</p> <p>I have a python class with a list 'metainfo'. This list contains variable names that my class <em>might</em> contain. I wrote a <code>__eq__</code> method that returns True if the both <code>self</code> and <code>other</code> have the same variables from <code>metainfo</code>...
4
2009-11-26T13:37:55Z
1,803,913
<p>Here is a variant that is pretty easy to read IMO, without using sentinel objects. It will first compare if both has or hasnt the attribute, then compare the values.</p> <p>It could be done in one line using all() and a generator expression as Stephen did, but I feel this is more readable.</p> <pre><code>def __eq_...
1
2009-11-26T14:16:58Z
[ "python", "equality" ]
Python regular expression matching a multiline block of text but not replacing it
1,803,713
<p>Ok so i have this piece of code:</p> <pre><code>def findNReplaceRegExp(file_name, regexp, replaceString, verbose=True, confirmationNeeded=True): '''Replaces the oldString with the replaceString in the file given,\ returns the number of replaces ''' # initialize local variables cregexp = re.compile(regexp...
0
2009-11-26T13:38:31Z
1,803,742
<p>You're finding with <code>cregexp</code>, which has the multiline option set, but then replacing with <code>regexp</code>, which may or may not.</p>
1
2009-11-26T13:43:52Z
[ "python", "regex", "replace", "multiline" ]
Error codes returned by urllib/urllib2 and the actual page
1,803,741
<p>the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised. </p> <p>How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you read the actual data being returned HTML/JSON etc (The ...
4
2009-11-26T13:43:32Z
1,803,773
<p>urllib2 raises a <a href="http://docs.python.org/library/urllib2.html#urllib2.HTTPError"><code>HTTPError</code></a> when HTTP errors happen. You can get to the response code using <code>code</code> on the exception object. You can get the response data using <code>read()</code>:</p> <pre> >>> req = urllib2.Request(...
7
2009-11-26T13:49:57Z
[ "python", "error-handling" ]
Error codes returned by urllib/urllib2 and the actual page
1,803,741
<p>the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised. </p> <p>How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you read the actual data being returned HTML/JSON etc (The ...
4
2009-11-26T13:43:32Z
1,803,796
<p>In <code>urllib2</code> <code>HTTPError</code> exception is also a valid HTTP response, so you can treat an HTTP error as an exceptional event or valid response. But in <code>urllib</code> you have to subclass URLopener and define <code>http_error_&lt;code&gt;</code> method[s] or redefine <code>http_error_default</c...
1
2009-11-26T13:54:06Z
[ "python", "error-handling" ]
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
1,803,860
<p>as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal</p> <pre><code>array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37] [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ] [1.37, 1.73, 1.37, 0. , 1....
1
2009-11-26T14:07:49Z
1,803,919
<p>Can you just do the calculation as normal, then afterwards set the diagonal back to zero?</p>
0
2009-11-26T14:18:11Z
[ "python", "arrays", "numpy", "scipy" ]
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
1,803,860
<p>as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal</p> <pre><code>array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37] [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ] [1.37, 1.73, 1.37, 0. , 1....
1
2009-11-26T14:07:49Z
1,804,036
<pre><code>&gt;&gt;&gt; arr = [ ... [0., 1.37, 1., 1.37, 1., 1.37, 1.], ... [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37], ... [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ], ... [1.37, 1.73, 1.37, 0. , 1.37, 1.73, 2.37], ... [1. , 2.37, 2. , 1.37, 0. , 1.37, 2. ], ... [1.37, 1.73, 2.37, 1.73, 1.37, 0. , 1.37], ... [...
1
2009-11-26T14:39:09Z
[ "python", "arrays", "numpy", "scipy" ]
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
1,803,860
<p>as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal</p> <pre><code>array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37] [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ] [1.37, 1.73, 1.37, 0. , 1....
1
2009-11-26T14:07:49Z
1,817,953
<p>Do your calculation as normal and then</p> <pre><code>myarray[arange(len(array)), arange(len(array))] = 0. </code></pre>
1
2009-11-30T05:13:32Z
[ "python", "arrays", "numpy", "scipy" ]
Performing operations on a NumPy arrray but masking values along the diagonal from these operations
1,803,860
<p>as I can perform operations on arrays so that does nothing on the diagonal is calculated such that all but the diagonal</p> <pre><code>array ([[0., 1.37, 1., 1.37, 1., 1.37, 1.] [1.37, 0. , 1.37, 1.73, 2.37, 1.73, 1.37] [1. , 1.37, 0. , 1.37, 2. , 2.37, 2. ] [1.37, 1.73, 1.37, 0. , 1....
1
2009-11-26T14:07:49Z
1,831,239
<p>I wonder if masked arrays might do what you want, e.g.,</p> <pre><code>import numpy as NP A = NP.random.random_integers(0, 9, 16).reshape(4, 4) dg = NP.r_[ [NP.nan] * 4 ] # proper syntax is 'nan' not 'NaN' dg = NP.diag(dg) A += dg # a 4x4 array w/ NaNs down the main diagonal NP.sum(A, axis=1) ...
2
2009-12-02T07:40:15Z
[ "python", "arrays", "numpy", "scipy" ]
PyAudio.open, how to use?
1,803,894
<p>I'm trying to make a pyaudio input stream but can't figure out how to make it. What I did is:</p> <pre><code>a = pyaudio.PyAudio() </code></pre> <p>Then tried to call a.open() but I don't know the arguments I should type in. It asks me to check Stream.<strong>init</strong> for a reference, but I don't know what a ...
0
2009-11-26T14:13:59Z
1,803,960
<p>Perhaps you could start by modfying some of the <a href="http://people.csail.mit.edu/hubert/pyaudio/#examples" rel="nofollow">examples</a>?</p>
1
2009-11-26T14:25:02Z
[ "python", "audio" ]
Running methods on different cores on python
1,803,955
<p>Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.</p> <p>edit: And what about</p> <p><a href="http://docs.python.org/dev/library/multiproce...
0
2009-11-26T14:23:37Z
1,803,984
<p>Assuming you use CPython (the reference implementation) the answer is <strong>NO</strong> because of the <a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">Global Interpreter Lock</a>. In CPython threads are mainly used when there is much IO to do (one thread waits, another does comput...
0
2009-11-26T14:28:18Z
[ "python", "multicore" ]
Running methods on different cores on python
1,803,955
<p>Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.</p> <p>edit: And what about</p> <p><a href="http://docs.python.org/dev/library/multiproce...
0
2009-11-26T14:23:37Z
1,803,985
<p>In general, running different threads is the best portable way to run on multiple cores. Of course, in Python, the global interpreter lock makes this a moot point -- only one thread will make progress at a time.</p>
0
2009-11-26T14:28:26Z
[ "python", "multicore" ]
Running methods on different cores on python
1,803,955
<p>Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.</p> <p>edit: And what about</p> <p><a href="http://docs.python.org/dev/library/multiproce...
0
2009-11-26T14:23:37Z
1,803,990
<p>Because of the global interpreter lock, Python programs only ever run one thread at a time. If you want true multicore Python programming, you could look into <a href="http://www.jython.org/" rel="nofollow">Jython</a> (which has access to the JVM's threads), or the brilliant <a href="http://www.stackless.com/" rel="...
0
2009-11-26T14:29:27Z
[ "python", "multicore" ]
Running methods on different cores on python
1,803,955
<p>Is there any easy way to make 2 methods, let's say MethodA() and MethodB() run in 2 different cores? I don't mean 2 different threads. I'm running in Windows, but I'd like to know if it is possible to be platform independent.</p> <p>edit: And what about</p> <p><a href="http://docs.python.org/dev/library/multiproce...
0
2009-11-26T14:23:37Z
1,804,005
<p>You have to use separate processes (because of the often-mentioned GIL). The <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing module</a> is here to help.</p> <pre><code>from multiprocessing import Process from somewhere import A, B if __name__ == '__main__': procs = ...
8
2009-11-26T14:33:06Z
[ "python", "multicore" ]
How to save double to file in python?
1,804,049
<p>Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?</p>
3
2009-11-26T14:40:24Z
1,804,083
<p>You can save them in binary format as well. Please see the documentation on the <code>struct</code> standard module, it has a <code>pack</code> function for converting Python object into binary data.</p> <p>For example:</p> <pre><code>import struct value = 3.141592654 data = struct.pack('d', value) open('file.ext...
5
2009-11-26T14:45:03Z
[ "python", "file", "double", "numbers" ]
How to save double to file in python?
1,804,049
<p>Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?</p>
3
2009-11-26T14:40:24Z
1,804,085
<p>I don't know fortran, so it's hard to tell what is easy for you to perform on that side for parsing.</p> <p>It sounds like your options are either saving the doubles in plaintext (meaning, 'converting' them to string), or in binary (using <code>struct</code> and the likes). The decision for which one is better depe...
2
2009-11-26T14:45:28Z
[ "python", "file", "double", "numbers" ]
How to save double to file in python?
1,804,049
<p>Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?</p>
3
2009-11-26T14:40:24Z
1,804,170
<p>You can use <a href="http://docs.python.org/library/json.html" rel="nofollow">JSON</a></p> <pre><code>import json matrix = [[2.3452452435, 3.34134], [4.5, 7.9]] data = json.dumps(matrix) open('file.ext', 'wb').write(data) </code></pre> <p>File content will look like:</p> <pre><code>[[2.3452452435, 3.3413400000000...
1
2009-11-26T14:59:19Z
[ "python", "file", "double", "numbers" ]
How to save double to file in python?
1,804,049
<p>Let's say I need to save a matrix(each line corresponds one row) that could be loaded from fortran later. What method should I prefer? Is converting everything to string is the only one approach?</p>
3
2009-11-26T14:40:24Z
1,804,726
<p>If legibility and ease of access is important (and file size is reasonable), Fortran can easily parse a simple array of numbers, at least if it knows the size of the matrix beforehand (with something like READ(FILE_ID, '2(F)'), I think):</p> <pre><code>1.234 5.6789e4 3.1415 9.265358978 42 ... </code></pre> <p...
1
2009-11-26T16:43:55Z
[ "python", "file", "double", "numbers" ]
Writing crawler that stay logged in with any server
1,804,258
<p>I am writing a crawler. Once after the crawler logs into a website I want to make the crawler to "stay-always-logged-in". How can I do that? Is a client (like browser, crawler etc.,) make a server to obey this rule? This scenario could occur when the server allows limited logins in day. </p>
0
2009-11-26T15:18:31Z
1,804,288
<p>"Logged-in state" is usually represented by cookies. So what your have to do is to store the cookie information sent by that server on login, then send that cookie with each of your subsequent requests (as noted by Aiden Bell in his message, thx).</p> <p>See also this question:</p> <p><a href="http://stackoverflow...
5
2009-11-26T15:23:46Z
[ "c#", "python", "http", "session", "web-crawler" ]
Lpr -module in Python
1,804,365
<p><strong>How can you call lpr in Python?</strong></p> <p>It is not in the sys -module which is surprising.</p> <p>I aim to use the lpr as follows shown by pseudo-code</p> <pre><code>10*i for i in range(77): lpr --pages(i,i+1) file.pdf </code></pre>
0
2009-11-26T11:14:26Z
1,805,014
<p>Just call it from the commandline:</p> <pre><code>import commands for i in range(77): # I'm making no assumptions about lpr command syntax here. cmd = "lpr --pages(%s,%s) file.pdf" % (2*i, 2*i+1) commands.getoutput(cmd) </code></pre> <p>Something like that.</p>
2
2009-11-26T18:05:44Z
[ "python", "printing", "lpr" ]
Lpr -module in Python
1,804,365
<p><strong>How can you call lpr in Python?</strong></p> <p>It is not in the sys -module which is surprising.</p> <p>I aim to use the lpr as follows shown by pseudo-code</p> <pre><code>10*i for i in range(77): lpr --pages(i,i+1) file.pdf </code></pre>
0
2009-11-26T11:14:26Z
1,805,015
<p>First of, I don't understand your pseudo code. (What does <code>10*i for i in range(77):</code> mean in this case?)</p> <p>Generally, you use <a href="http://docs.python.org/3.1/library/subprocess.html#subprocess.Popen"><code>subprocess.Popen</code></a> to run external commands. <a href="http://code.activestate.com...
5
2009-11-26T18:06:57Z
[ "python", "printing", "lpr" ]
Lpr -module in Python
1,804,365
<p><strong>How can you call lpr in Python?</strong></p> <p>It is not in the sys -module which is surprising.</p> <p>I aim to use the lpr as follows shown by pseudo-code</p> <pre><code>10*i for i in range(77): lpr --pages(i,i+1) file.pdf </code></pre>
0
2009-11-26T11:14:26Z
1,805,088
<p>I haven't tried it, but pycups appears to be python bindings for cups.</p> <p><a href="http://cyberelk.net/tim/software/pycups/" rel="nofollow">http://cyberelk.net/tim/software/pycups/</a></p>
0
2009-11-26T18:26:49Z
[ "python", "printing", "lpr" ]
Playing MP3 files with Python
1,804,366
<p>I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it...
8
2009-11-26T15:35:30Z
1,804,434
<p>Maybe it'd be simpler to write that part of your application in Python 2.4 as a separate "backend". This way you could use PyMedia (<a href="http://pymedia.org/" rel="nofollow">http://pymedia.org/</a>) (as you mentioned) for the actual playback. It'd allow you to write your GUI in another Python version (like 2.6), ...
0
2009-11-26T15:48:07Z
[ "python", "mp3", "playback" ]
Playing MP3 files with Python
1,804,366
<p>I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it...
8
2009-11-26T15:35:30Z
1,804,483
<p>There is <a href="http://www.pyglet.org/" rel="nofollow">http://www.pyglet.org/</a> and also have you tried <a href="http://code.google.com/p/mp3play/" rel="nofollow">http://code.google.com/p/mp3play/</a>? It's also available from PyPi (<a href="http://pypi.python.org/pypi/mp3play/" rel="nofollow">http://pypi.python...
3
2009-11-26T15:54:44Z
[ "python", "mp3", "playback" ]
Playing MP3 files with Python
1,804,366
<p>I'm trying to write my own media player (like Foobar), and I'm having trouble tracking down a Python library that'll play MP3s. I know Pymedia does mp3s, but it looks outdated - the latest installer is for Python version 2.4, and I'm using 2.6. I've never had much success with Pygame, and Pyglet doesn't look like it...
8
2009-11-26T15:35:30Z
3,711,265
<p>I've been using PyMedia in Python 2.6.5 on Windows successfully. Caveats: the documentation is bad and wrong -- many of the tutorials have glaring errors or otherwise don't work -- so I had to do some experimentation and Googling to get my code to work right. Also for whatever reason the maintainers seem to have sto...
1
2010-09-14T17:15:46Z
[ "python", "mp3", "playback" ]
Appengine reference order
1,804,573
<p>I have declared models in AppEngine's models.py:</p> <pre><code>class Post(db.Model): topic = db.ReferenceProperty(Topic, collection_name='posts', verbose_name=_('Topic')) (..) class Topic(db.Model): (..) last_post = db.ReferenceProperty(Post, collection_name='last_topic_post') </code></pre> <p>Problem is Referen...
0
2009-11-26T16:16:21Z
1,804,620
<p>ReferenceProperty accepts None in place of a model class, which means "no type restriction" on that field. It is not a nice solution, however.</p> <p>See:</p> <p><a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ReferenceProperty" rel="nofollow">http://code.google.com/app...
2
2009-11-26T16:25:24Z
[ "python", "django", "django-models" ]
Defining models in a top level Django directory
1,804,591
<p>I've noticed that in order for me to define models, I need to do something like:</p> <pre><code>python manage.py startapp app_name </code></pre> <p>Is there anyway to avoid this convention and be able to create a models.py directly in the top level site that django-admin.py has created for me? Sometimes I'm buildi...
0
2009-11-26T16:20:32Z
1,804,607
<p>Not really. The django admin programs expect <code>app/models.py</code> file names.</p>
1
2009-11-26T16:23:59Z
[ "python", "django" ]
Scrapy domain_name for spider
1,804,694
<p>From the Scrapy tutorial:</p> <blockquote> <p>domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders.</p> </blockquote> <p>Does this mean that <code>domain_name</code> must be a valid domain name, like </p> <blockquote> <p>domain_name = 'exam...
1
2009-11-26T16:38:28Z
1,804,936
<p>To answer my own question:</p> <blockquote> <p>domain_name = 'wc2'</p> </blockquote> <p>works.</p>
1
2009-11-26T17:40:22Z
[ "python", "scrapy" ]
Scrapy domain_name for spider
1,804,694
<p>From the Scrapy tutorial:</p> <blockquote> <p>domain_name: identifies the Spider. It must be unique, that is, you can’t set the same domain name for different Spiders.</p> </blockquote> <p>Does this mean that <code>domain_name</code> must be a valid domain name, like </p> <blockquote> <p>domain_name = 'exam...
1
2009-11-26T16:38:28Z
2,615,334
<p>As you have found out yourself, <code>domain_name</code> shouldn't be real. It's used when calling the spider to crawl.</p>
0
2010-04-10T22:57:28Z
[ "python", "scrapy" ]
Reading socket buffer using asyncore
1,804,980
<p>I'm new to Python (I have been programming in Java for multiple years now though), and I am working on a simple socket-based networking application (just for fun). The idea is that my code connects to a remote TCP end-point and then listens for any data being pushed from the server to the client, and perform some pa...
1
2009-11-26T17:56:48Z
1,805,034
<p>TCP is a stream, and you are not guaranteed that your buffer will not contain the end of one message and the beginning of the next. So, checking for \n\r at the end of the buffer will not work as expected in all situations. You have to check each byte in the stream.</p> <p>And, I would strongly recommend that you ...
5
2009-11-26T18:12:12Z
[ "python", "sockets", "buffer", "asyncore" ]
Reading socket buffer using asyncore
1,804,980
<p>I'm new to Python (I have been programming in Java for multiple years now though), and I am working on a simple socket-based networking application (just for fun). The idea is that my code connects to a remote TCP end-point and then listens for any data being pushed from the server to the client, and perform some pa...
1
2009-11-26T17:56:48Z
1,805,052
<p>It's even simpler -- look at <a href="http://docs.python.org/library/asynchat.html" rel="nofollow">asynchat</a> and its <a href="http://docs.python.org/library/asynchat.html#asynchat.async%5Fchat.set%5Fterminator" rel="nofollow">set_terminator</a> method (and other helpful tidbits in that module). <a href="http://t...
6
2009-11-26T18:16:25Z
[ "python", "sockets", "buffer", "asyncore" ]
Scrapy spider index error
1,805,050
<p>This is the code for Spyder1 that I've been trying to write within Scrapy framework:</p> <pre><code>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from firm.items import ...
2
2009-11-26T18:16:20Z
1,805,440
<p>SgmlLinkExtractor doesn't support selectors in its "allow" argument.</p> <p>So this is wrong:</p> <pre><code>SgmlLinkExtractor(allow=["hxs.select('//td[@class='altRow'] ...')"]) </code></pre> <p>This is right:</p> <pre><code>SgmlLinkExtractor(allow=[r"product\.php"]) </code></pre>
1
2009-11-26T20:02:09Z
[ "python", "web-crawler", "scrapy" ]
Scrapy spider index error
1,805,050
<p>This is the code for Spyder1 that I've been trying to write within Scrapy framework:</p> <pre><code>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from firm.items import ...
2
2009-11-26T18:16:20Z
1,805,458
<p>The parse function is called for each match of your SgmlLinkExtractor.</p> <p>As Pablo mentioned you want to simplify your SgmlLinkExtractor.</p>
0
2009-11-26T20:09:07Z
[ "python", "web-crawler", "scrapy" ]
Scrapy spider index error
1,805,050
<p>This is the code for Spyder1 that I've been trying to write within Scrapy framework:</p> <pre><code>from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from firm.items import ...
2
2009-11-26T18:16:20Z
1,805,673
<p>I also tried to put the names scraped from the initial url into a list and then pass each name to parse in the form of absolute url as <code>http://www.whitecase.com/aabbas</code> (for /aabbas). </p> <p>The following code loops over the list, but I don't know how to pass this to parse . Do you think this is a bette...
0
2009-11-26T21:15:23Z
[ "python", "web-crawler", "scrapy" ]
Python JSON parse_float=decimal.Decimal not working
1,805,072
<p>I have a string with a floating point number in it, but I can't get JSON to load it as a decimal.</p> <pre><code>x = u'{"14": [4.5899999999999999, "susan"]}' json.loads(x, parse_float = decimal.Decimal) </code></pre> <p>This returns:</p> <pre><code>{u'14': [Decimal('4.5899999999999999'), u'susan']} </code></pre> ...
0
2009-11-26T18:21:08Z
1,805,107
<p>You need to define a function that performs whatever rounding you desire, then uses the altered string to build the <code>Decimal</code>. Your current solution does work perfectly well: it just does exactly what you tell it to, i.e., use the entire string, as opposed to what you desire (and have not told either the...
6
2009-11-26T18:32:30Z
[ "python", "json" ]
Python JSON parse_float=decimal.Decimal not working
1,805,072
<p>I have a string with a floating point number in it, but I can't get JSON to load it as a decimal.</p> <pre><code>x = u'{"14": [4.5899999999999999, "susan"]}' json.loads(x, parse_float = decimal.Decimal) </code></pre> <p>This returns:</p> <pre><code>{u'14': [Decimal('4.5899999999999999'), u'susan']} </code></pre> ...
0
2009-11-26T18:21:08Z
1,805,111
<p>You can't. That number isn't 4.59, it's 4.589999999999999999, as far as the json parser knows. You'd need to add some more complicated logic that rounds numbers like that, as a wrapper around decimal.Decimal.</p>
1
2009-11-26T18:32:47Z
[ "python", "json" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,155
<p>By design. </p> <p>The authors wanted something where they can write scripts into.</p> <p>Python gets compiled the first time it is executed though </p>
1
2009-11-26T18:49:09Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,157
<p>Well, isn't one of the strengths of these languages that they are so easily scriptable? They wouldn't be if they were compiled. And on the other hand, dynamic languages are easier to intereprete than to compile.</p>
2
2009-11-26T18:49:34Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,158
<p>I think the biggest reason for the languages being interpreted is portability. As a programmer you can write code that will run in an interpreter not a specific OS. So your programs behave more uniformly across platforms (more so than compiled languages). Another advantage I can think of is it's easier to have a dyn...
6
2009-11-26T18:49:43Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,169
<p>In a compiled language, the loop you get into when making software is</p> <ol> <li>Make a change</li> <li>Compile changes</li> <li>Test changes</li> <li>goto 1</li> </ol> <p>Interpreted languages tend to be faster to make stuff in because you get to cut out step two of that process (and when you're dealing with a ...
2
2009-11-26T18:53:28Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,172
<p>Several reasons:</p> <ul> <li>faster development loop, <em>write-test</em> vs <em>write-compile-link-test</em></li> <li>easier to arrange for dynamic behavior (reflection, metaprogramming)</li> <li>makes the whole system portable (just recompile the underlying C code and you are good to go on a new platform)</li> <...
31
2009-11-26T18:54:11Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,201
<p>Today, there is no longer a strong distinction between "compiled" and "interpreted" languages. Python is in fact compiled just as much as Java is, the only differences are:</p> <ul> <li>The Python compiler is much faster than the Java compiler</li> <li>Python automatically compiles source code as it is executed, th...
5
2009-11-26T19:01:00Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,243
<p>Exactly like (in the typical implementation of) Java or C#, Python gets first compiled into some form of bytecode, depending on the implementation (CPython uses a specialized form of its own, Jython uses JVM just like a typical Java, IronPython uses CLR just like a typical C#, and so forth) -- that bytecode then get...
15
2009-11-26T19:09:53Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,805,899
<p>Merely replacing an interpreter with a compiler won't give you as big a performance boost as you might think for a language like Python. When most time is actually spend doing symbolic lookups of object members in dictionaries, it doesn't really matter if the call to the function performing such lookup is interprete...
8
2009-11-26T22:16:13Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,806,035
<p>The effort required to create a good compiler to generate native code for a new language is <em>staggering</em>. Small research groups typically take 5 to 10 years (examples: <a href="http://www.smlnj.org/" rel="nofollow">SML/NJ</a>, Haskell, Clean, Cecil, <a href="http://www.cs.princeton.edu/software/lcc/" rel="no...
5
2009-11-26T22:59:22Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,806,134
<p><a href="http://en.wikipedia.org/wiki/Read-eval-print%5Floop" rel="nofollow">REPL</a>. Don't knock it 'till you've tried it. :)</p>
2
2009-11-26T23:38:18Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,928,710
<p>Compiling Ruby at least is notoriously hard. I'm working on one, and as part of that I wrote a blog post <a href="http://www.hokstad.com/the-problem-with-compiling-ruby.html" rel="nofollow">enumerating some of the issues here</a>. </p> <p>Specifically, Ruby is suffering from a very unclear (i.e. non-existent) bound...
1
2009-12-18T15:00:34Z
[ "python", "ruby", "compiler-construction" ]
Why is (python|ruby) interpreted?
1,805,148
<p>What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains....
17
2009-11-26T18:47:29Z
1,928,816
<p>Raw compute performance is probably not a goal of most interpreted languages. Interpreted languages are typically more concerned about programmer productivity than raw speed. In most cases these languages are plenty fast enough for the tasks the languages were designed to tackle. </p> <p>Given that, and that just a...
1
2009-12-18T15:19:13Z
[ "python", "ruby", "compiler-construction" ]
How to write a simple spider in Python?
1,805,231
<p>I've been trying to write this spider for weeks but without success. What is the best way for me to code this in Python:</p> <p>1) Initial url: <code>http://www.whitecase.com/Attorneys/List.aspx?LastName=A</code></p> <p>2) from initial url pick up these urls with this regex:</p> <p><code>hxs.select('//td[@class="...
1
2009-11-26T19:07:55Z
1,805,244
<p><a href="http://www.ibm.com/developerworks/linux/library/l-spider/" rel="nofollow">http://www.ibm.com/developerworks/linux/library/l-spider/</a> IBM article with good description </p> <p>or</p> <p><a href="http://code.activestate.com/recipes/576551/" rel="nofollow">http://code.activestate.com/recipes/576551/</a> P...
4
2009-11-26T19:10:26Z
[ "python", "web-crawler", "scrapy" ]
How to write a simple spider in Python?
1,805,231
<p>I've been trying to write this spider for weeks but without success. What is the best way for me to code this in Python:</p> <p>1) Initial url: <code>http://www.whitecase.com/Attorneys/List.aspx?LastName=A</code></p> <p>2) from initial url pick up these urls with this regex:</p> <p><code>hxs.select('//td[@class="...
1
2009-11-26T19:07:55Z
1,805,785
<p>Also, I suggest you read:</p> <p><a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454</a></p> <p>Before you try to parse HTML with...
0
2009-11-26T21:39:34Z
[ "python", "web-crawler", "scrapy" ]
Django / Python / PIL / sorl-thumbnail generation in bulk - memory error
1,805,256
<p>I'm trying to bulk generate 4 thumnails for each of around 40k images with <a href="http://code.google.com/p/sorl-thumbnail/" rel="nofollow">sorl-thumbnail</a> for my django app. I iterate through all django objects with an ImageWithThumbnailsFieldFile, and then call its generate_thumbnails() function.</p> <p>This ...
2
2009-11-26T19:13:35Z
1,805,340
<p>Your problem relates to how Django caches the results of a queryset as you loop through them. Django keeps all the objects in memory so that next time you iterate through the same queryset you don't have to hit the database again to get all the data.</p> <p>What you need to do is use the <a href="http://docs.djang...
4
2009-11-26T19:35:07Z
[ "python", "django", "memory", "python-imaging-library", "sorl-thumbnail" ]
How to fix value produced by Random?
1,805,265
<p>I got an issue which is, in my code,anyone can help will be great. this is the example code.</p> <pre><code>from random import * from numpy import * r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)]) def Ft(r): for i in range(3): do something here, call r return something </code></pre> <p>ho...
1
2009-11-26T19:15:22Z
1,805,307
<p>I think you mean 'list' instead of 'array', you're trying to use functions when you really don't need to. If I understand you correctly, you want to edit a list of random floats:</p> <pre><code> import random r=[random.uniform(-R,R) for x in range(3)] def ft(r): for i in range(len(r)): r[i]=???...
1
2009-11-26T19:25:54Z
[ "python", "random" ]
How to fix value produced by Random?
1,805,265
<p>I got an issue which is, in my code,anyone can help will be great. this is the example code.</p> <pre><code>from random import * from numpy import * r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)]) def Ft(r): for i in range(3): do something here, call r return something </code></pre> <p>ho...
1
2009-11-26T19:15:22Z
1,805,415
<p>Do you mean that you want the calls to <code>randon.uniform()</code> to return the same sequence of values each time you run the function?<br> If so, you need to call <code>random.seed()</code> to set the start of the sequence to a fixed value. If you don't, the current system time is used to initialise the random n...
6
2009-11-26T19:53:44Z
[ "python", "random" ]
How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern
1,805,309
<p>I am new to Python and pyparsing. I need to accomplish the following.</p> <p>My sample line of text is like this:</p> <pre><code>12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009 Washing service (3 Shirt) 23 Mar 2009 </code></pre> <p>I need to extract the item description, period</p> <pre><code>tok_date...
2
2009-11-26T19:26:19Z
1,805,804
<p>M K Saravanan, this particular parsing problem is not so hard to do with good 'ole re:</p> <pre><code>import re import string text=''' 12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009 Washing service (3 Shirt) 23 Mar 2009 This line does not match ''' date_pat=re.compile( r'(\d{1,2}\s+[a-zA-Z]{3}\s+\d...
3
2009-11-26T21:43:25Z
[ "python", "pyparsing" ]
How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern
1,805,309
<p>I am new to Python and pyparsing. I need to accomplish the following.</p> <p>My sample line of text is like this:</p> <pre><code>12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009 Washing service (3 Shirt) 23 Mar 2009 </code></pre> <p>I need to extract the item description, period</p> <pre><code>tok_date...
2
2009-11-26T19:26:19Z
1,811,560
<p>I would suggest looking at SkipTo as the pyparsing class that is most appropriate, since you have a good definition of the <em>unwanted</em> text, but will accept pretty much anything before that. Here are a couple of ways to use SkipTo:</p> <pre><code>text = """\ 12 items - Ironing Service 11 Mar 2009 to 10 Ap...
4
2009-11-28T04:31:23Z
[ "python", "pyparsing" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
1,805,509
<p>you could use a 2 dimensional array, holding objects for the state of each field:</p> <pre><code>class FieldState(object): def __init__(self): self.unexplored = True self.mine = Random() self.flag = Random() ... for x in range(12): for y in range(24): list[x][y] = FieldState() </code></pre>...
6
2009-11-26T20:26:27Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
1,805,540
<p>Use a nested list. It's easy to set up:</p> <pre><code>field = [([None] * height) for x in range(width)] field[x][y] = "*" </code></pre> <p>The clearest thing would probably be a new class:</p> <pre><code>class MineField(object): class _SingleField(object): mine = False flagged = False ...
8
2009-11-26T20:35:31Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
1,805,601
<p>If you use an instance of <code>Board</code> class you can always change the internal representation later.</p> <pre><code>class Board(object): def __init__(self, width, height): self.__width, self.__height = width, height self._board = [[FieldState() for y in xrange(height)] ...
1
2009-11-26T20:54:41Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
1,805,894
<p>Just to throw another option in the mix, you could use dicts indexed by tuples</p> <pre><code>board = {} board[1, 2] = 9 </code></pre>
3
2009-11-26T22:14:49Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
1,806,045
<p>I think there are basically two layers of data: 1) map data: does square have a bomb (e.g represented by -1) or how many bombs are around it, 2) display data, what is shown on the square: bomb count, bomb, flag, question mark, empty, unopened.</p> <p>So two nested lists (or one nested list of tuples) might be enoug...
1
2009-11-26T23:01:30Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
6,241,641
<p>You could mark locations with a single int showing exactly what sits there, easing your coding considerably. You wouldnt need two data layers. </p> <pre><code>00 nothing, noflag 10 bomb, noflag 01 nothing,flagged 11 bomb, flagged </code></pre> <p>Now since the first bit of that int shows whether there is a bomb or...
0
2011-06-05T07:53:53Z
[ "python", "data-structures" ]
How would you represent a MineSweeper grid in Python?
1,805,480
<p>What datastructure would you use in Python to represent the internal state of a MineSweeper grid?</p> <p>Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).</p> <p>Should I use nested lists? This seems like the closest thing to a 2D array and it is wh...
3
2009-11-26T20:17:31Z
9,080,176
<p>A map of 'tile' or 'cell' objects, keyed to the coordinates as a pair. </p> <pre><code>current = (1,1) if grid[current].isFlagged(): do_whatever; </code></pre> <p>Of course, map takes a little more space than array, and the tile class will have a tiny bit more footprint than a primitive bitmap or number, but I ...
0
2012-01-31T13:17:30Z
[ "python", "data-structures" ]
What is the performance cost of named keys or "pre-generated" keys in Google App Engine?
1,805,555
<p>If you used named keys in Google App Engine, does this incur any additional cost? Put another way, is it any more expensive to create a new entity with a named key rather than a randomly generated id?</p> <p>In a similar line of reasoning, I note that you can ask Google App Engine to give you a set of keys that wil...
2
2009-11-26T20:38:41Z
1,805,774
<p>There is no intrinsic penalty to using a key name instead of an auto-generated ID, except the overhead of a (potentially) longer key on the entity and any ReferenceProperties that reference it.</p> <p>In certain cases, in fact, using auto-allocated IDs can have a performance penalty: If you insert new entities at a...
4
2009-11-26T21:37:34Z
[ "python", "google-app-engine" ]
Where/How should I do validation and transformations on entities in Google App Engine?
1,805,830
<p>In Ruby on Rails, each model entity has a "validate_on_*something*" hook method, that will be called before the entity is actually persisted to the database. I would like similar functionality in Google App Engine. I am aware that you can do validation on individual Properties by passing arguments to them in their d...
0
2009-11-26T21:51:46Z
1,805,973
<p>Are you using any kind of web framework on top of the raw app engine api's? Rails is a very high level framework. Have you looked into Django or any of the other web frameworks? You may find those are closer to rails than raw appengine entities.</p> <p>Alternatively, if you want something <em>lower</em> level, h...
1
2009-11-26T22:36:32Z
[ "python", "validation", "google-app-engine", "transformation" ]
Where/How should I do validation and transformations on entities in Google App Engine?
1,805,830
<p>In Ruby on Rails, each model entity has a "validate_on_*something*" hook method, that will be called before the entity is actually persisted to the database. I would like similar functionality in Google App Engine. I am aware that you can do validation on individual Properties by passing arguments to them in their d...
0
2009-11-26T21:51:46Z
1,806,004
<p>The best answer depends on what sort of transformations you need to do. There's no generalized pre-/post- put methods for models, but there are several other options:</p> <ul> <li>As you mentioned, you can pass validation functions to Property class constructors</li> <li>You can use a custom property class that gen...
2
2009-11-26T22:45:41Z
[ "python", "validation", "google-app-engine", "transformation" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
1,805,875
<p>A guess is that the file is actually not in that dir. If you have UAC enabled windows 7 will make it look like the file is at that location (it will show up in windows explorer). However the file is really stored in c:\users\yourusername\AppData\Local\VirtualStore\Software\Sqlite\databases or a similar location.</p>...
0
2009-11-26T22:06:26Z
[ "python", "windows", "django", "sqlite", "windows-7" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
1,805,889
<p>I don't think you can use a full windows path to access your sqlite database. I've run some tests here and the only way I could use a sqlite3 database on django not in the same directory of the project was using DATABASE_NAME = '../anotherfolder/db.db' (this was located at c:\anotherfolder\ and project was located ...
2
2009-11-26T22:12:02Z
[ "python", "windows", "django", "sqlite", "windows-7" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
1,805,891
<p>Have a look at the permissions of the folder. Can your regular user edit files there?</p>
0
2009-11-26T22:13:36Z
[ "python", "windows", "django", "sqlite", "windows-7" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
1,805,904
<p>I know this question has already an accepted answer, but I think you missed something. You should use raw strings when your strings contain backslashes:</p> <pre><code>DATABASE_NAME = r'C:\Software\Sqlite\databases\blog.db' </code></pre> <p>This is what happens if you don't use a raw string:</p> <pre><code>&gt;&g...
9
2009-11-26T22:17:36Z
[ "python", "windows", "django", "sqlite", "windows-7" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
13,522,967
<p>Reverse the slashes in DATABASE_NAME: from <code>C:\Software\Sqlite\databases\blog.db</code> to <code>C:/Software/Sqlite/databases/blog.db</code></p> <p>I am using django 1.4 on Win7 and this was the solution for me - the file doesn't need to exist already</p>
0
2012-11-23T04:09:39Z
[ "python", "windows", "django", "sqlite", "windows-7" ]
How can I use SQLITE with DJANGO on WIndows 7
1,805,852
<p>I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:</p> <pre><code>sqlite3.OperationalError: unable to open database file </code></pre> <p>I use the following:</p> <pre><code>python manage.py sql Blog </code>...
2
2009-11-26T21:57:31Z
18,604,470
<p>Reversing the slashes in the database name solved the problem for me.</p>
0
2013-09-04T02:25:30Z
[ "python", "windows", "django", "sqlite", "windows-7" ]