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
Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file
2,016,777
<p>So far here is the code I have (it is working and extracting text as it should.)</p> <pre><code>import pyPdf def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from ...
0
2010-01-06T22:26:18Z
2,016,834
<p>The <code>glob</code> module can help you find all files in a single directory that match a wildcard pattern.</p>
0
2010-01-06T22:32:21Z
[ "python", "pdf", "csv" ]
Have writen a program to extract text from a PDF in python, and now need to make it run for every PDF in the folder and save as a text file
2,016,777
<p>So far here is the code I have (it is working and extracting text as it should.)</p> <pre><code>import pyPdf def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from ...
0
2010-01-06T22:26:18Z
2,016,865
<p><em>for loop to get it to run on all PDF's in a directory</em>: look at the glob module</p> <p><em>save the text as a CSV</em>: look at the csv module</p> <p><em>count the pictures</em>: look at the pyPDF module :-)</p> <p>Two comments on this statement:</p> <pre><code>content = " ".join(content.replace(u"\xa0",...
0
2010-01-06T22:36:11Z
[ "python", "pdf", "csv" ]
Selecting indices for a 2d array in numpy
2,016,842
<p>This works quite well in 1 dimension:</p> <pre><code># This will sort bar by the order of the values in foo (Pdb) bar = np.array([1,2,3]) (Pdb) foo = np.array([5,4,6]) (Pdb) bar[np.argsort(foo)] array([2, 1, 3]) </code></pre> <p>But how do I do that in two dimensions? Argsort works nicely, but the select no longe...
0
2010-01-06T22:33:54Z
2,016,977
<p><code>bar.take(np.argsort(foo))</code> produced your desired output, so you should take a look at its <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.take.html" rel="nofollow">documentation</a> to make sure it actually does what you think you want. </p> <p>Edit:</p> <p>Try this: <code>bar.take(n...
0
2010-01-06T22:55:54Z
[ "python", "numpy" ]
Selecting indices for a 2d array in numpy
2,016,842
<p>This works quite well in 1 dimension:</p> <pre><code># This will sort bar by the order of the values in foo (Pdb) bar = np.array([1,2,3]) (Pdb) foo = np.array([5,4,6]) (Pdb) bar[np.argsort(foo)] array([2, 1, 3]) </code></pre> <p>But how do I do that in two dimensions? Argsort works nicely, but the select no longe...
0
2010-01-06T22:33:54Z
2,016,980
<p>You want</p> <pre><code>bar[[[0],[1]], np.argsort(foo)] </code></pre> <p>This is because you need two indices to index <code>bar</code>. The <code>[[0], [1]]</code> is to get correct broadcasting. See <a href="http://mail.scipy.org/pipermail/numpy-discussion/2009-February/040128.html" rel="nofollow">this post on...
2
2010-01-06T22:56:30Z
[ "python", "numpy" ]
Selecting indices for a 2d array in numpy
2,016,842
<p>This works quite well in 1 dimension:</p> <pre><code># This will sort bar by the order of the values in foo (Pdb) bar = np.array([1,2,3]) (Pdb) foo = np.array([5,4,6]) (Pdb) bar[np.argsort(foo)] array([2, 1, 3]) </code></pre> <p>But how do I do that in two dimensions? Argsort works nicely, but the select no longe...
0
2010-01-06T22:33:54Z
4,200,006
<p>A nice generic solution (with n rows to sort) is offered <a href="http://mail.scipy.org/pipermail/numpy-discussion/2010-April/049949.html" rel="nofollow">at this post</a>, i.e.,</p> <pre><code>bar[np.arange(foo.shape[0])[:,None], np.argsort(foo)] </code></pre>
1
2010-11-16T23:11:41Z
[ "python", "numpy" ]
Python: recursively create dictionary from paths
2,017,045
<p>I have several hundred thousand endpoint URLs that I want to generate stats for. For example I have:</p> <pre><code>/a/b/c /a/b/d /a/c/d /b/c/d /b/d/e /a/b/c /b/c/d </code></pre> <p>I want to create a dictionary that looks like this</p> <pre><code>{ {'a': {'b': {'c': 2 }, {'d...
5
2010-01-06T23:08:32Z
2,017,083
<p>If the paths all look like in your example, this would work:</p> <pre><code>counts = {} for p in paths: parts = p.split('/') branch = counts for part in parts[1:-1]: branch = branch.setdefault(part, {}) branch[parts[-1]] = 1 + branch.get(parts[-1], 0) </code></pre> <p>This uses dictionary methods...
5
2010-01-06T23:18:03Z
[ "python", "recursion" ]
Python: recursively create dictionary from paths
2,017,045
<p>I have several hundred thousand endpoint URLs that I want to generate stats for. For example I have:</p> <pre><code>/a/b/c /a/b/d /a/c/d /b/c/d /b/d/e /a/b/c /b/c/d </code></pre> <p>I want to create a dictionary that looks like this</p> <pre><code>{ {'a': {'b': {'c': 2 }, {'d...
5
2010-01-06T23:08:32Z
2,017,154
<p><strong>EDIT:</strong></p> <p>I've amended my code to fit your last comment, above (no complex data structure now).</p> <pre><code>def dictizeString(string, dictionary): while string.startswith('/'): string = string[1:] parts = string.split('/', 1) if len(parts) &gt; 1: branch = diction...
2
2010-01-06T23:32:26Z
[ "python", "recursion" ]
Python: recursively create dictionary from paths
2,017,045
<p>I have several hundred thousand endpoint URLs that I want to generate stats for. For example I have:</p> <pre><code>/a/b/c /a/b/d /a/c/d /b/c/d /b/d/e /a/b/c /b/c/d </code></pre> <p>I want to create a dictionary that looks like this</p> <pre><code>{ {'a': {'b': {'c': 2 }, {'d...
5
2010-01-06T23:08:32Z
2,017,226
<p>Here's my attempt:</p> <pre><code>class Result(object): def __init__(self): self.count = 0 self._sub_results = {} def __getitem__(self, key): if key not in self._sub_results: self._sub_results[key] = Result() return self._sub_results[key] def __str__(self): ...
1
2010-01-06T23:51:48Z
[ "python", "recursion" ]
Python: recursively create dictionary from paths
2,017,045
<p>I have several hundred thousand endpoint URLs that I want to generate stats for. For example I have:</p> <pre><code>/a/b/c /a/b/d /a/c/d /b/c/d /b/d/e /a/b/c /b/c/d </code></pre> <p>I want to create a dictionary that looks like this</p> <pre><code>{ {'a': {'b': {'c': 2 }, {'d...
5
2010-01-06T23:08:32Z
16,508,060
<p>Old result, but still near the top in google, so I'll update: You could use dpath-python for this.</p> <pre><code>$ easy_install dpath &gt;&gt;&gt; result = {} &gt;&gt;&gt; for path in my_list_of_paths: &gt;&gt;&gt; ... dpath.util.set(result, path, SOME_VALUE) </code></pre> <p>... and that's it. I don't understand...
1
2013-05-12T13:50:13Z
[ "python", "recursion" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,131
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" rel="nofollow">Decorators</a> are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function.</p> <pre><code>def entry_exit(f): def new_f(*args, **kwargs...
7
2010-01-06T23:28:18Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,137
<p><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" rel="nofollow">Python Decorators</a></p> <p>This is actually another topic to learn, but if you look at the stuff on 'Using Functions as Decorators', you'll see some examples of nested functions.</p>
0
2010-01-06T23:28:57Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,197
<p>Nested functions avoid cluttering other parts of the program with other functions and variables that only make sense locally.</p> <p>A function that return Fibonacci numbers could be defined as follows:</p> <pre><code>&gt;&gt;&gt; def fib(n): def rec(): return fib(n-1) + fib(n-2) if n ...
3
2010-01-06T23:44:41Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,203
<p>I have only had to use nested functions when creating decorators. A nested function is basically a way of adding some behavior to a function without knowing what the function is that you are adding behavior to.</p> <pre><code>from functools import wraps from types import InstanceType def printCall(func): def...
2
2010-01-06T23:47:12Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,288
<p>Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.</p> <p>One very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the ...
10
2010-01-07T00:08:56Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,339
<p>They are useful when using functions that take other functions as input. Say you're in a function, and want to sort a list of items based on the items' value in a dict:</p> <pre><code>def f(items): vals = {} for i in items: vals[i] = random.randint(0,100) def key(i): return vals[i] items.sort(key=k...
2
2010-01-07T00:17:12Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,017,345
<p>OK, besides decorators: Say you had an application where you needed to sort a list of strings based on substrings which varied from time to time. Now the <code>sorted</code> functions takes a <code>key=</code> argument which is a function of one argument: the items (strings in this case) to be sorted. So how to tell...
1
2010-01-07T00:19:05Z
[ "python", "function", "nested" ]
Real-world examples of nested functions
2,017,101
<p>I asked previously how the <a href="http://stackoverflow.com/questions/2005956/nested-functions-in-python">nested functions</a> work, but unfortunately I still don't quite get it. To understand it better, can someone please show some real-wold, practical usage examples of nested functions?</p> <p>Many thanks</p>
11
2010-01-06T23:22:08Z
2,018,658
<p>Yet another (very simple) example. A function that returns another function. Note how the inner function (that is returned) can use variables from the outer function's scope.</p> <pre><code>def create_adder(x): def _adder(y): return x + y return _adder add2 = create_adder(2) add100 = create_adder(100)...
2
2010-01-07T06:39:31Z
[ "python", "function", "nested" ]
Trouble with pycurl.POSTFIELDS
2,017,112
<p>I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl.</p> <p>I keep getting the error:</p> <pre><code>Exception Type: error Exception Value: (2, '') </code></pre> <p>I have no idea what this could mean. Here is my code:</p> <pre><code>data = {'cmd': '_notify-synch', ...
2
2010-01-06T23:24:36Z
2,017,751
<p>It would appear that your pycurl installation (or curl library) is damaged somehow. From the curl error codes documentation:</p> <pre><code>CURLE_FAILED_INIT (2) Very early initialization code failed. This is likely to be an internal error or problem. </code></pre> <p>You will possibly need to re-install or recomp...
1
2010-01-07T02:06:49Z
[ "python", "django", "curl", "libcurl", "pycurl" ]
Trouble with pycurl.POSTFIELDS
2,017,112
<p>I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl.</p> <p>I keep getting the error:</p> <pre><code>Exception Type: error Exception Value: (2, '') </code></pre> <p>I have no idea what this could mean. Here is my code:</p> <pre><code>data = {'cmd': '_notify-synch', ...
2
2010-01-06T23:24:36Z
2,684,138
<p>I do like that:</p> <pre><code>post_params = [ ('ASYNCPOST',True), ('PREVIOUSPAGE','yahoo.com'), ('EVENTID',5), ] resp_data = urllib.urlencode(post_params) mycurl.setopt(pycurl.POSTFIELDS, resp_data) mycurl.setopt(pycurl.POST, 1) ... mycurl.perform() </code></pre>
3
2010-04-21T15:08:36Z
[ "python", "django", "curl", "libcurl", "pycurl" ]
Trouble with pycurl.POSTFIELDS
2,017,112
<p>I'm familiar with CURL in PHP but am using it for the first time in Python with pycurl.</p> <p>I keep getting the error:</p> <pre><code>Exception Type: error Exception Value: (2, '') </code></pre> <p>I have no idea what this could mean. Here is my code:</p> <pre><code>data = {'cmd': '_notify-synch', ...
2
2010-01-06T23:24:36Z
6,207,144
<p>I know this is an old post but I've just spent my morning trying to track down this same error. It turns out that there's a bug in pycurl that was <a href="http://pycurl.sourceforge.net/ChangeLog" rel="nofollow">fixed in 7.16.2.1</a> that caused setopt() to break on 64-bit machines.</p>
2
2011-06-01T20:20:04Z
[ "python", "django", "curl", "libcurl", "pycurl" ]
Why aren't "and" and "or" operators in Python?
2,017,230
<p>I wasn't aware of this, but apparently the <code>and</code> and <code>or</code> keywords aren't operators. They don't appear in the <a href="http://docs.python.org/reference/lexical_analysis.html#operators">list of python operators</a>. Just out of sheer curiosity, why is this? And if they aren't operators, what ...
19
2010-01-06T23:52:50Z
2,017,233
<p>They're classifying them as keywords earlier in the document.</p>
0
2010-01-06T23:54:09Z
[ "python", "operators", "language-design", "boolean", "keyword" ]
Why aren't "and" and "or" operators in Python?
2,017,230
<p>I wasn't aware of this, but apparently the <code>and</code> and <code>or</code> keywords aren't operators. They don't appear in the <a href="http://docs.python.org/reference/lexical_analysis.html#operators">list of python operators</a>. Just out of sheer curiosity, why is this? And if they aren't operators, what ...
19
2010-01-06T23:52:50Z
2,017,236
<p>They're <a href="http://docs.python.org/reference/lexical_analysis.html#keywords" rel="nofollow">keywords</a>, because they're reserved identifiers, not special tokens of symbols.</p>
0
2010-01-06T23:55:12Z
[ "python", "operators", "language-design", "boolean", "keyword" ]
Why aren't "and" and "or" operators in Python?
2,017,230
<p>I wasn't aware of this, but apparently the <code>and</code> and <code>or</code> keywords aren't operators. They don't appear in the <a href="http://docs.python.org/reference/lexical_analysis.html#operators">list of python operators</a>. Just out of sheer curiosity, why is this? And if they aren't operators, what ...
19
2010-01-06T23:52:50Z
2,017,240
<p>They can't be redefined to support type-specific operations, so they don't fall under the scope of the other operators.</p>
0
2010-01-06T23:56:11Z
[ "python", "operators", "language-design", "boolean", "keyword" ]
Why aren't "and" and "or" operators in Python?
2,017,230
<p>I wasn't aware of this, but apparently the <code>and</code> and <code>or</code> keywords aren't operators. They don't appear in the <a href="http://docs.python.org/reference/lexical_analysis.html#operators">list of python operators</a>. Just out of sheer curiosity, why is this? And if they aren't operators, what ...
19
2010-01-06T23:52:50Z
2,017,249
<p>Because they're control flow constructs. Specifically:</p> <ul> <li>if the left argument to <code>and</code> evaluates to False, the right argument doesn't get evaluated at all</li> <li>if the left argument to <code>or</code> evaluates to True, the right argument doesn't get evaluated at all</li> </ul> <p>Thus, it...
40
2010-01-06T23:58:58Z
[ "python", "operators", "language-design", "boolean", "keyword" ]
Why aren't "and" and "or" operators in Python?
2,017,230
<p>I wasn't aware of this, but apparently the <code>and</code> and <code>or</code> keywords aren't operators. They don't appear in the <a href="http://docs.python.org/reference/lexical_analysis.html#operators">list of python operators</a>. Just out of sheer curiosity, why is this? And if they aren't operators, what ...
19
2010-01-06T23:52:50Z
2,017,313
<blockquote> <p>Python does not currently provide any '<strong>xxx</strong>' special methods corresponding to the 'and', 'or' and 'not' boolean operators. In the case of 'and' and 'or', the most likely reason is that these operators have short-circuiting semantics, i.e. the second operand is not evaluated if the resu...
6
2010-01-07T00:13:26Z
[ "python", "operators", "language-design", "boolean", "keyword" ]
Python Thread Pause and Wait
2,017,261
<p>I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait.</p> <p>How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2, 3, 4 - 1, 2, 3, 4...)...
2
2010-01-07T00:00:58Z
2,017,326
<p>maybe something like</p> <pre><code>while True: list = [] for i in xrange(100): t = myThread(data[i]) list.append(t) t.start() for t in list: t.join() </code></pre>
0
2010-01-07T00:15:26Z
[ "python", "multithreading" ]
Python Thread Pause and Wait
2,017,261
<p>I have an array of threads. Each of them call the run method continuously. At the end of each run method I want them to pause and wait.</p> <p>How can I get the threads to execute one at a time, and then continue the loop when all are finished? I need them to ALWAYS execute in order (ie: 1, 2, 3, 4 - 1, 2, 3, 4...)...
2
2010-01-07T00:00:58Z
2,017,386
<p>Your description seems to imply you don't want the threads to execute concurrently, which would bring into question why you're using threading in the first place. </p> <p>I sense two possible answers as to why you'd want to do this.</p> <p>The first possibility is that you are trying to prevent your threads from w...
3
2010-01-07T00:28:07Z
[ "python", "multithreading" ]
Newbie needs help with Python Tutorial
2,017,320
<p>I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Progra...
2
2010-01-07T00:14:29Z
2,017,344
<p>That's not giving you the help for the shell command <code>zip</code>, it's giving you the help for the python function <code>zip</code>, which is unrelated to zip file compression.</p>
1
2010-01-07T00:18:17Z
[ "python" ]
Newbie needs help with Python Tutorial
2,017,320
<p>I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Progra...
2
2010-01-07T00:14:29Z
2,017,348
<p>The reason "<code>zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b</code>" failed at the prompt is because in this case, "zip" is supposed to be a command you're sending the operating system... nothing to do with Python.</p> <p>This is a little confusing, I'm afraid - when you did "<code>zip(r'C:AB\a')</code>",...
1
2010-01-07T00:20:06Z
[ "python" ]
Newbie needs help with Python Tutorial
2,017,320
<p>I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Progra...
2
2010-01-07T00:14:29Z
2,017,352
<p><strong>A couple suggestions for you to use to improve:</strong></p> <p>Use the <code>subprocess.call([command', 'arg', 'arg', 'arg'])</code> command to call the external zip command. This will ensure that the command gets called correctly with data escaped properly.</p> <p>Use <code>os.path.join</code> to join p...
1
2010-01-07T00:21:23Z
[ "python" ]
Newbie needs help with Python Tutorial
2,017,320
<p>I am a newbie going through a byte of python (3.0). This is the first programming language I have ever used. I am stuck at the point where you make a simple program that creates a backup zip file (p.75). I'm running Windows 7 (64 bit) with python 3.1. Prior to this I installed GNUWin32 + sources, and added C:\Progra...
2
2010-01-07T00:14:29Z
2,017,354
<pre><code>&gt;&gt;&gt; zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b </code></pre> <p>sounds like a command you should type in your operating system's shell, not in python's shell. Maybe you can try </p> <pre><code>os.system('zip -qr C:\Backup\20100106143030.zip C:\AB\a C:\AB\b') </code></pre> <p>in the py...
2
2010-01-07T00:21:33Z
[ "python" ]
Is it possible to have an actual memory leak in Python because of your code?
2,017,381
<p>I don't have a code example, but I'm curious whether it's possible to write Python code that results in essentially a memory leak.</p>
15
2010-01-07T00:27:33Z
2,017,407
<p>Of course you can. The typical example of a memory leak is if you build a cache that you never flush manually and that has no automatic eviction policy.</p>
6
2010-01-07T00:33:27Z
[ "python", "memory-leaks" ]
Is it possible to have an actual memory leak in Python because of your code?
2,017,381
<p>I don't have a code example, but I'm curious whether it's possible to write Python code that results in essentially a memory leak.</p>
15
2010-01-07T00:27:33Z
2,017,430
<p>In the sense of orphaning allocated objects after they go out of scope because you forgot to deallocate them, no; Python will automatically deallocate out of scope objects (<a href="http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29" rel="nofollow">Garbage Collection</a>). But in the sense that @...
1
2010-01-07T00:39:12Z
[ "python", "memory-leaks" ]
Is it possible to have an actual memory leak in Python because of your code?
2,017,381
<p>I don't have a code example, but I'm curious whether it's possible to write Python code that results in essentially a memory leak.</p>
15
2010-01-07T00:27:33Z
2,017,431
<p>It is possible, yes.</p> <p>It depends on what kind of memory leak you are talking about. Within pure python code, it's not possible to "forget to free" memory such as in C, but it is possible to leave a reference hanging somewhere. Some examples of such:</p> <ul> <li><p>an unhandled traceback object that is keep...
37
2010-01-07T00:39:47Z
[ "python", "memory-leaks" ]
Is it possible to have an actual memory leak in Python because of your code?
2,017,381
<p>I don't have a code example, but I'm curious whether it's possible to write Python code that results in essentially a memory leak.</p>
15
2010-01-07T00:27:33Z
2,017,432
<p>The classic definition of a memory leak is memory that was used once, and now is not, but has not been reclaimed. That nearly impossible with pure Python code. But as Antoine points out, you can easily have the effect of consuming all your memory inadvertently by allowing data structures to grow without bound, eve...
5
2010-01-07T00:39:51Z
[ "python", "memory-leaks" ]
Get memory usage of computer in Windows with Python
2,017,545
<p>How can I tell what the computer's overall memory usage is from Python, running on Windows XP?</p>
11
2010-01-07T01:09:40Z
2,017,608
<p>You'll want to use the <a href="http://timgolden.me.uk/python/wmi/index.html">wmi</a> module. Something like this:</p> <pre><code>import wmi comp = wmi.WMI() for i in comp.Win32_ComputerSystem(): print i.TotalPhysicalMemory, "bytes of physical memory" for os in comp.Win32_OperatingSystem(): print os.FreePh...
11
2010-01-07T01:27:57Z
[ "python", "memory", "winapi", "memory-management", "pywin32" ]
Get memory usage of computer in Windows with Python
2,017,545
<p>How can I tell what the computer's overall memory usage is from Python, running on Windows XP?</p>
11
2010-01-07T01:09:40Z
2,017,612
<p>You can query the performance counters in WMI. I've done something similar but with disk space instead.</p> <p>A very useful link is the <a href="http://timgolden.me.uk/python/wmi/tutorial.html" rel="nofollow">Python WMI Tutorial by Tim Golden</a>.</p>
0
2010-01-07T01:29:38Z
[ "python", "memory", "winapi", "memory-management", "pywin32" ]
Get memory usage of computer in Windows with Python
2,017,545
<p>How can I tell what the computer's overall memory usage is from Python, running on Windows XP?</p>
11
2010-01-07T01:09:40Z
2,017,659
<p>You can also just call GlobalMemoryStatusEx() (or any other kernel32 or user32 export) directly from python: </p> <pre><code>import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulong...
17
2010-01-07T01:42:13Z
[ "python", "memory", "winapi", "memory-management", "pywin32" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,558
<p>When you're calling a function, using an asterisk before a <code>list</code> or <code>dict</code> will pass it in as positional parameters.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; a(*('test', 'testing')) ('test', 'testing') &gt;&gt;&gt; a(*{'a': 'b', 'c': 'd'}) ('a', 'c') </code></pre>
2
2010-01-07T01:14:40Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,559
<p>That's how dictionaries get converted to sequences.</p> <p>tuple(dictionary) = tuple(dictionary.keys())</p> <p>for a similar reason</p> <pre><code>for x in dictionary: </code></pre> <p>assigns keys, not pairs, to x</p>
5
2010-01-07T01:14:45Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,562
<pre><code>a(*{'q' : 'qqq'}) </code></pre> <p>will try to expand your <code>dict</code> (<code>{'q':'qqq'}</code>) into an itemized list of arguments for the function. </p> <p>Note that: </p> <pre><code>tuple({'q' : 'qqq'}) </code></pre> <p>returns <code>('q',)</code>, which is exactly what you're seeing. When you ...
1
2010-01-07T01:15:03Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,567
<p>Using <code>*</code> in front of an expression in a function call iterates over the value of the expression (your dict, in this case) and makes each item in the iteration another parameter to the function invocation. Iterating over a dict in Python yields the keys (for better or worse).</p>
2
2010-01-07T01:16:03Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,574
<p>Iterating a dictionary will yield its keys.</p> <pre><code>d = {'a': 1, 'b': 2, 'c': 3 } for x in d: print x # prints a, b, c but not necessarily in that order sorted(d): # Gives a, b, c in that order. No 1/2/3. </code></pre> <p>If you want to get both keys and values from a dictionary, you can use .items()...
1
2010-01-07T01:17:13Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,578
<p>You are asking for a list of arguments, and then telling python to send a dict as a sequence of arguments. When a dict is converted to a sequence, it uses the keys.</p> <p>I guess you are <strong>really</strong> looking for <code>**</code>, not <code>*</code>.</p>
1
2010-01-07T01:18:26Z
[ "python" ]
a(*{'q':'qqq'}),why only print key
2,017,548
<pre><code>def a(*x): print x a({'q':'qqq'}) a(*{'q':'qqq'})#why only print key. </code></pre> <p>traceback:</p> <pre><code>({'q': 'qqq'},) ('q',) </code></pre>
1
2010-01-07T01:10:59Z
2,017,580
<p>Probably because that's what a dictionary returns when you do a standard iteration over it. It gets converted to a sequence containing it's keys. This example exhibits the same behaviour:</p> <pre><code>&gt;&gt;&gt; for i in {"a": "1", "b": "2"}: ... print i ... a b </code></pre> <p>To get what I assume you ex...
0
2010-01-07T01:18:41Z
[ "python" ]
Runing bcdedit from python in Windows 2008 SP2
2,017,557
<p>I do not know windows well, so that may explain my dilemma ...</p> <p>I am trying to run <strong>bcdedit</strong> in Windows 2008R2 from Python 2.6.</p> <p>My Python routine to run a command looks like this:</p> <pre><code>def run_program(cmd_str): """Run the specified command, returning its output as an arra...
0
2010-01-07T01:13:48Z
2,017,588
<p>Perhaps the path to <code>bcdedit.exe</code> isn't in your system path when Python is running for some reason (a different user account, for example). You can find this out by printing:</p> <pre><code>os.environ.get("PATH") </code></pre> <p>It's semicolon-delimited, so <code>os.environ.get("PATH").split(';')</code...
0
2010-01-07T01:20:47Z
[ "python", "windows-vista" ]
Runing bcdedit from python in Windows 2008 SP2
2,017,557
<p>I do not know windows well, so that may explain my dilemma ...</p> <p>I am trying to run <strong>bcdedit</strong> in Windows 2008R2 from Python 2.6.</p> <p>My Python routine to run a command looks like this:</p> <pre><code>def run_program(cmd_str): """Run the specified command, returning its output as an arra...
0
2010-01-07T01:13:48Z
2,017,861
<p>Check your PATH variable and see if C:\windows\system32 is there. (use set in DOS)</p>
0
2010-01-07T02:36:45Z
[ "python", "windows-vista" ]
Runing bcdedit from python in Windows 2008 SP2
2,017,557
<p>I do not know windows well, so that may explain my dilemma ...</p> <p>I am trying to run <strong>bcdedit</strong> in Windows 2008R2 from Python 2.6.</p> <p>My Python routine to run a command looks like this:</p> <pre><code>def run_program(cmd_str): """Run the specified command, returning its output as an arra...
0
2010-01-07T01:13:48Z
2,261,665
<p>For some reason I experiment the same trouble from c#. If I list the files it was not here, but when I was looking from Explorer it was there. maybe it is some kind of protected file. To call bcdedit.exe, I manually copied it from system32 to my application folder and it worked. There is also another one in windows\...
0
2010-02-14T15:59:16Z
[ "python", "windows-vista" ]
Runing bcdedit from python in Windows 2008 SP2
2,017,557
<p>I do not know windows well, so that may explain my dilemma ...</p> <p>I am trying to run <strong>bcdedit</strong> in Windows 2008R2 from Python 2.6.</p> <p>My Python routine to run a command looks like this:</p> <pre><code>def run_program(cmd_str): """Run the specified command, returning its output as an arra...
0
2010-01-07T01:13:48Z
2,261,714
<p>Windows 2008 R2 is 64-bit-only, yes? Python's a 32-bit process. When a 32-bit app runs something from <code>C:\Windows\System32</code>, Windows actually looks in <code>C:\Windows\SysWOW64</code>. <a href="http://www.tipandtrick.net/2008/how-to-suppress-and-bypass-system32-file-system-redirect-to-syswow64-folder-with...
0
2010-02-14T16:11:20Z
[ "python", "windows-vista" ]
Why does tarfile.extractall ignore errors by default?
2,017,725
<p>Python's <a href="http://docs.python.org/library/tarfile.html#tarfile-objects" rel="nofollow">tarfile</a> module ignores errors during extraction <strong>by default</strong>, unless <code>errorlevel</code> is set to either <code>1</code> or <code>2</code> (or <code>debug</code> to <code>1</code> if only error messag...
3
2010-01-07T01:58:29Z
2,017,897
<p>FWIW, this nasty behavior is will be changed in Python 2.7 and 3.2. <a href="http://svn.python.org/view?view=rev&amp;revision=76780" rel="nofollow">http://svn.python.org/view?view=rev&amp;revision=76780</a> Apparently the reason for ignoring the errors before was to be more like GNU tar, which ignores errors.</p>
2
2010-01-07T02:46:50Z
[ "python", "permissions", "tarfile" ]
why defined '__new__' and '__init__' all in a class
2,017,876
<p>i think you can defined either '<code>__init__</code>' or '<code>__new__</code>' in a class,but why all defined in django.utils.datastructures.py.</p> <p>my code:</p> <pre><code>class a(object): def __init__(self): print 'aaa' def __new__(self): print 'sss' a()#print 'sss' class b: ...
9
2010-01-07T02:41:09Z
2,017,936
<p><code>__new__</code> and <code>__init__</code> do completely different things. The method <code>__init__</code> initiates a new instance of a class --- it is a constructor. <code>__new__</code> is a far more subtle thing --- it can change arguments and, in fact, the class of the initiated object. For example, the fo...
9
2010-01-07T02:58:37Z
[ "python", "class" ]
why defined '__new__' and '__init__' all in a class
2,017,876
<p>i think you can defined either '<code>__init__</code>' or '<code>__new__</code>' in a class,but why all defined in django.utils.datastructures.py.</p> <p>my code:</p> <pre><code>class a(object): def __init__(self): print 'aaa' def __new__(self): print 'sss' a()#print 'sss' class b: ...
9
2010-01-07T02:41:09Z
2,017,980
<p>You can define either or both of <code>__new__</code> and <code>__init__</code>.</p> <p><code>__new__</code> must return an object -- which can be a new one (typically that task is delegated to <code>type.__new__</code>), an existing one (to implement singletons, "recycle" instances from a pool, and so on), or even...
18
2010-01-07T03:13:43Z
[ "python", "class" ]
why defined '__new__' and '__init__' all in a class
2,017,876
<p>i think you can defined either '<code>__init__</code>' or '<code>__new__</code>' in a class,but why all defined in django.utils.datastructures.py.</p> <p>my code:</p> <pre><code>class a(object): def __init__(self): print 'aaa' def __new__(self): print 'sss' a()#print 'sss' class b: ...
9
2010-01-07T02:41:09Z
2,017,983
<p>My only guess is that in this case, they (author of this class) want the keyOrder list to exist on the class even before <code>SortedDict.__init__</code> is called. </p> <p>Note that SortedDict calls <code>super()</code> in its <code>__init__</code>, this would ordinarily go to <code>dict.__init__</code>, which wou...
2
2010-01-07T03:14:36Z
[ "python", "class" ]
why defined '__new__' and '__init__' all in a class
2,017,876
<p>i think you can defined either '<code>__init__</code>' or '<code>__new__</code>' in a class,but why all defined in django.utils.datastructures.py.</p> <p>my code:</p> <pre><code>class a(object): def __init__(self): print 'aaa' def __new__(self): print 'sss' a()#print 'sss' class b: ...
9
2010-01-07T02:41:09Z
31,905,363
<p>In my opinion, there was no need of overriding <code>__new__</code> in the example you described. Creation of an instance and actual memory allocation happens in <code>__new__</code>, <code>__init__</code> is called after <code>__new__</code> and is meant for initialization of instance serving the job of constructor...
0
2015-08-09T14:38:49Z
[ "python", "class" ]
Database Design Inquiry
2,017,930
<p>I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.</p> <p>Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone e...
1
2010-01-07T02:56:54Z
2,017,941
<p>It's hard to say without more information, but having the following relations would be sensible, based on what you've said:</p> <pre><code>Quiz (id, title) Question (id, question, answer) QuizQuestion (quiz_id, question_id) </code></pre> <p>That way questions can appear in multiple quizzes. </p>
3
2010-01-07T03:01:16Z
[ "python", "database-design", "google-app-engine", "schema" ]
Database Design Inquiry
2,017,930
<p>I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.</p> <p>Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone e...
1
2010-01-07T02:56:54Z
2,017,943
<p>Have a table of questions, a table of quizzes and a mapping table between them. That will give you the most flexibility. This is simple enough that you wouldn't even necessarily need a whole relational database <em>management system</em>. I think people tend to forget that relations are pretty simple mathematical/lo...
0
2010-01-07T03:01:34Z
[ "python", "database-design", "google-app-engine", "schema" ]
Database Design Inquiry
2,017,930
<p>I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.</p> <p>Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone e...
1
2010-01-07T02:56:54Z
2,017,958
<p>My first cut (I assumed the questions were multiple choice):</p> <ul> <li>I'd have a table of Questions, with ID_Question as the PK, the question text, and a category (if you want).</li> <li>I'd have a table of Answers, with ID_Answer as the PK, QuestionID as a FK back to the Questions table, the answer text, and a...
1
2010-01-07T03:06:48Z
[ "python", "database-design", "google-app-engine", "schema" ]
Database Design Inquiry
2,017,930
<p>I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.</p> <p>Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone e...
1
2010-01-07T02:56:54Z
2,018,339
<p>I recently completed an App Engine app for taking personality quizzes.</p> <p>I would say go the super simple route and store everything about each quiz in a single Quiz entity. If you don't need to reuse questions between quizzes, don't need to search or in any other way access the structure of a quiz besides taki...
1
2010-01-07T05:10:26Z
[ "python", "database-design", "google-app-engine", "schema" ]
Database Design Inquiry
2,017,930
<p>I'm making a trivia webapp that will feature both standalone questions, and 5+ question quizzes. I'm looking for suggestions for designing this model.</p> <p>Should a quiz and its questions be stored in separate tables/objects, with a key to tie them together, or am I better off creating the quiz as a standalone e...
1
2010-01-07T02:56:54Z
2,022,278
<p>Here's a design that will account for having a many-to-many relationship between Quizess and Questions. In other words, a Quiz can have many questions, and a Question can belong to many Quizzes. There is only one copy of a Question, so changes can be made to it that will then be reflected in each Quiz to which the Q...
0
2010-01-07T17:36:07Z
[ "python", "database-design", "google-app-engine", "schema" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
2,018,038
<p>urllib2.urlopen accepts an instance of the Request class or a url, whereas urllib.urlopen only accepts a url.</p> <p>A similar discussion took place here: <a href="http://www.velocityreviews.com/forums/t326690-urllib-urllib2-what-is-the-difference.html">http://www.velocityreviews.com/forums/t326690-urllib-urllib2-w...
10
2010-01-07T03:29:44Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
2,018,052
<p>You should generally use urllib2, since this makes things a bit easier at times by accepting Request objects and will also raise a URLException on protocol errors. With Google App Engine though, you can't use either. You have to use the <a href="http://code.google.com/appengine/docs/python/urlfetch/" rel="nofollow">...
4
2010-01-07T03:36:46Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
2,018,074
<p>urllib2 provides some extra functionality, namely the <code>urlopen()</code> function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the <code>Request</code> class, which allows for a more declarative approac...
138
2010-01-07T03:43:08Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
2,018,103
<p>I like the <code>urllib.urlencode</code> function, and it doesn't appear to exist in <code>urllib2</code>. </p> <pre><code>&gt;&gt;&gt; urllib.urlencode({'abc':'d f', 'def': '-!2'}) 'abc=d+f&amp;def=-%212' </code></pre>
8
2010-01-07T03:51:08Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
14,804,320
<p>I know its been said already, but I'd highly recommend the Requests python package: <a href="http://docs.python-requests.org/en/latest/index.html">http://docs.python-requests.org/en/latest/index.html</a></p> <p>If you've used languages other than python, you're probably thinking urllib and urllib2 are easy to use, ...
357
2013-02-11T00:32:09Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
36,878,545
<p>One considerable difference is about porting Python2 to Python3. urllib2 does not exist for python3 and its methods ported to urllib. So you are using that heavily and want to migrate to Python3 in future, consider using urllib. However 2to3 tool will automatically to most of the work for you.</p>
1
2016-04-27T01:07:59Z
[ "python", "urllib2", "urllib", "python-requests" ]
What are the differences between the urllib, urllib2, and requests module?
2,018,026
<p>In Python, what are the differences between the <code>urllib</code>, <code>urllib2</code>, and <a href="http://docs.python-requests.org/en/latest/index.html"><code>requests</code></a> module? Why are there three? They seem to do the same thing...</p>
340
2010-01-07T03:26:35Z
39,422,481
<p><strong>urllib</strong> and <strong>urllib2</strong> are both Python modules that do URL request related stuff but offer different functionalities.</p> <p>1) urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL.</p> <p>2) urllib provides the <strong>urlencode</strong>...
3
2016-09-10T04:14:30Z
[ "python", "urllib2", "urllib", "python-requests" ]
Given a unicode error I don't understand
2,018,058
<p>Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line...</p> <pre><code>import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ ...
1
2010-01-07T03:38:02Z
2,018,237
<p>Here's the code that answered that question. But now it only writes the last file. </p> <pre><code> import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.exce...
1
2010-01-07T04:37:55Z
[ "python", "unicode", "ascii" ]
Given a unicode error I don't understand
2,018,058
<p>Here is my code, I'm sure it looks terrible but it all works as it should, only problem I'm having is with the last line...</p> <pre><code>import pyPdf import os import csv class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ ...
1
2010-01-07T03:38:02Z
2,020,233
<p>as I Underestand you put a large number in a small varible and its throw an exception.</p> <p>I introduce you a C# tool that work very fine with unicode , you can find it at <a href="http://unicode.codeplex.com" rel="nofollow">http://unicode.codeplex.com</a></p> <p>in your case I recommand to change the </p> <pre...
-1
2010-01-07T12:31:02Z
[ "python", "unicode", "ascii" ]
Data Carving loop improvements
2,018,210
<p>I currently have a Python app I am developing which will data carve a block device for jpeg files. Let's just say that it sometimes works and sometimes doesn't. I have created it so that I read the block device till I find a ffd8, then I keep the stream open and search via looping for the ffd9 closure. Though I a...
1
2010-01-07T04:28:50Z
2,018,389
<p>The trouble with reading the block device directly is that there is no guarantee that the blocks of any given file are contiguous. That means that even if you find your magic marker bytes 0xFFD8 in block 13, say, there is no guarantee that block 14 belongs to the same file, whether or not it contains the 0xFFD9 end...
2
2010-01-07T05:23:47Z
[ "python", "io" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,321
<p>The main idea behind objects is that an object is data plus methods. Whenever you are thinking about making something an object, you must ask yourself what will be the object's data, and what operations (methods) will you want to perform on that data.</p> <p>Functions, more readily translate to methods than classes...
2
2010-01-07T05:06:37Z
[ "python", "class" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,337
<p>If you want to write a lot of CSV files with the same <code>dictList</code> (is that what you're saying...?), turning the function into a class would let you perform initialization just once, and then write repeatedly from the same initialized instance. E.g., with other minor opts:</p> <pre><code>class CsvWriter(o...
1
2010-01-07T05:09:34Z
[ "python", "class" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,350
<p>I don't think your writeCSV is in need of a class, typicaly class would be used when you have to update some state(data) and then act on it, may be with various options.<br> e.g. if you need to pass around your object, so that other function/method can add values to it or your final action/output function has many o...
0
2010-01-07T05:14:11Z
[ "python", "class" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,352
<p>When thinking about making objects, remember this:</p> <ol> <li><p>Classes have attributes - things that describe different instances of the class differently</p></li> <li><p>Classes have methods - things that the objects do (often involving using their attributes)</p></li> </ol> <p>Objects and classes are wonderf...
1
2010-01-07T05:14:40Z
[ "python", "class" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,383
<p>I think question 1 is pretty crucial as it goes to the heart of what a class is.</p> <p>Yes, you can put this function in a class. A class is a set of functions (called methods) and data together in one logical unit. As other posters noted, probably overkill to have a class with one method.</p>
0
2010-01-07T05:23:10Z
[ "python", "class" ]
How to create a class from function
2,018,282
<p>I am still struggling with understanding classes, I am not certain but I have an idea that this function I have created is probably a good candidate for a class. The function takes a list of dictionaries, identifies the keys and writes out a csv file.</p> <p>First Q, is this function a good candidate for a class ...
0
2010-01-07T04:54:30Z
2,018,395
<p>For this you need to understand little bit <a href="http://en.wikipedia.org/wiki/Class_%28computer_science%29" rel="nofollow">concepts of classes</a> first and then follow the next step. I too faced a same problem and followed this <a href="http://stackoverflow.com/questions/1959295/i-cant-create-a-clear-picture-of-...
2
2010-01-07T05:26:09Z
[ "python", "class" ]
how to update a record using DBSession in turbogears 2
2,018,494
<p>Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method:</p> <pre><code>@expose() def post_login(self, came_from=url('/')): """ Redirect the user to the initially requested page on success...
0
2010-01-07T05:54:06Z
2,020,991
<p>You must tell the session object to update the object:</p> <pre><code>DBSession.update(user) </code></pre>
1
2010-01-07T14:39:14Z
[ "python", "sqlalchemy", "turbogears2" ]
how to update a record using DBSession in turbogears 2
2,018,494
<p>Hi I'm trying to update a user row upon the user logging in. I simply want to increase the users login count by one. Here is the code in the post_login controller method:</p> <pre><code>@expose() def post_login(self, came_from=url('/')): """ Redirect the user to the initially requested page on success...
0
2010-01-07T05:54:06Z
2,022,078
<p>Sorry all, turns out the TG2 transaction manager was working after all. The error came because I was calling the post_login function outside of the transaction manager and so the record update was not getting flushed. I'm not sure why it wasn't letting me commit. But I moved the post_login controller and now the abo...
2
2010-01-07T17:02:39Z
[ "python", "sqlalchemy", "turbogears2" ]
reading tar file contents without untarring it, in python script
2,018,512
<p>I have a tar file which has number of files within it. I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file.</p>
31
2010-01-07T05:58:08Z
2,018,523
<p>you need to use the tarfile module. Specifically, you use an instance of the class TarFile to access the file, and then access the names with TarFile.getnames() </p> <pre><code> | getnames(self) | Return the members of the archive as a list of their names. It has | the same order as the list return...
7
2010-01-07T06:01:43Z
[ "python", "tar" ]
reading tar file contents without untarring it, in python script
2,018,512
<p>I have a tar file which has number of files within it. I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file.</p>
31
2010-01-07T05:58:08Z
2,018,576
<p>you can use getmembers()</p> <pre><code>&gt;&gt;&gt; import tarfile &gt;&gt;&gt; tar = tarfile.open("test.tar") &gt;&gt;&gt; tar.getmembers() </code></pre> <p>After that, you can use extractfile() to extract the members as file object. Just an example</p> <pre><code>import tarfile,os import sys os.chdir("/tmp/fo...
61
2010-01-07T06:17:30Z
[ "python", "tar" ]
reading tar file contents without untarring it, in python script
2,018,512
<p>I have a tar file which has number of files within it. I need to write a python script which will read the contents of the files and gives the count o total characters, including total number of letters, spaces, newline characters, everything, without untarring the tar file.</p>
31
2010-01-07T05:58:08Z
23,308,087
<p>An implementation of the methods mentioned by @stefano-borini Access a tar archives member via file name like so </p> <pre><code>#python3 myFile = myArchive.extractfile( dict(zip( myArchive.getnames(), myArchive.getmembers() ))['path/to/file'] ).read()` </code></pre> <p>Credits:</p> <ul...
2
2014-04-26T07:35:13Z
[ "python", "tar" ]
What is the difference between these two classes?
2,018,543
<pre><code>class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) </code></pre> <p>and </p> <pre><code>class SortedDict(dict): def __init__(self, data={}): dict(data) </code></pre> <p>I think they are same.<...
1
2010-01-07T06:06:23Z
2,018,569
<p>The first class doesn't seem to work</p> <pre><code>class SortedDict2(dict): def __init__(self, data={}): dict(data) class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) x = SortedDict2("bleh") y = So...
1
2010-01-07T06:16:01Z
[ "python" ]
What is the difference between these two classes?
2,018,543
<pre><code>class SortedDict(dict): def __init__(self, data=None): if data is None: data = {} super(SortedDict, self).__init__(data) </code></pre> <p>and </p> <pre><code>class SortedDict(dict): def __init__(self, data={}): dict(data) </code></pre> <p>I think they are same.<...
1
2010-01-07T06:06:23Z
2,018,574
<p><code>dict(data)</code> just creates a dictionary from <code>data</code> without saving the result anywhere. <code>super(SortedDict, self).__init__(data)</code> on the other hand calls the parent class constructor.</p> <p>Also, in the case of multiple inheritance, using <code>super</code> ensures that all the right...
5
2010-01-07T06:17:19Z
[ "python" ]
3d Histogram in Python
2,018,572
<p>I am trying to generate a 3D histogram using python. I tried the following code but I am getting an error too many values to unpack. </p> <pre><code>from matplotlib import pyplot import pylab from mpl_toolkits.mplot3d import Axes3D import numpy fig = pylab.figure() ax = Axes3D(fig) data_filename = 'C:\csvfile...
2
2010-01-07T06:16:28Z
2,018,709
<p>"Too many values to unpack" happens when you do something like this: </p> <pre><code>(a, b) = (1, 2, 3) </code></pre> <p>That is, not enough variables on the left to accept all of the values on the right of the <code>=</code>. </p> <p><strong>Update:</strong></p> <p>Try: <code>ax.hist( (X, Y, Z) )</code></p> <p...
3
2010-01-07T06:50:38Z
[ "python", "matplotlib" ]
using python expect to run openvpn
2,018,606
<p>i need a python script to run open vpn automaticaly but i use sudo for run the open vpn</p> <pre><code>sudo openvpn --cd /etc/openvpn --config openvpn.conf &amp; </code></pre> <p>thats my terminal command. i have to give the password for sudo, can i use pexpect to run that command? and i have to get the exit code...
1
2010-01-07T06:24:36Z
2,019,330
<p>You can change /etc/sudoers so that openvpn command can be run without giving the password. </p> <pre><code>yourusername ALL=(all) NOPASSWD: /path/to/openvpn </code></pre> <p>and in python, do something like:</p> <pre><code>import subprocess exitcode = subprocess.call(["sudo","openvpn","--cd /etc/openvpn --config...
1
2010-01-07T09:32:15Z
[ "python", "expect", "openvpn" ]
Problems with Trac post commit script (SyntaxError: invalid syntax)
2,018,888
<p>I've setup a post commit script found at <a href="http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook" rel="nofollow">http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook</a> to associate changesets with tickets</p> <p>When I try to commit, I get the following error</p> <p><code> '...
1
2010-01-07T07:35:02Z
2,018,998
<p>Wow, that is weird. The line is definitely valid syntax, and the Python version should also not be a problem since the script's copyright statement has the same year Python 2.4 was released in. Do you have multiple Python installations on your machine? If so, can you check whether <code>/usr/bin/env python</code> re...
2
2010-01-07T08:09:33Z
[ "python", "svn", "trac", "post-commit" ]
Problems with Trac post commit script (SyntaxError: invalid syntax)
2,018,888
<p>I've setup a post commit script found at <a href="http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook" rel="nofollow">http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook</a> to associate changesets with tickets</p> <p>When I try to commit, I get the following error</p> <p><code> '...
1
2010-01-07T07:35:02Z
2,019,097
<p>May be you have space or tab before (options,args)? may be like this.</p> <pre><code>&gt;&gt;&gt; (options, args) = parser.parse_args(sys.argv[1:]) &gt;&gt;&gt; # this is fine &gt;&gt;&gt; &gt;&gt;&gt; (options, args) = parser.parse_args(sys.argv[1:]) File "&lt;stdin&gt;", line 1 (options, args) = parser.par...
3
2010-01-07T08:35:29Z
[ "python", "svn", "trac", "post-commit" ]
What is the relationship between '@1' and '@2'
2,018,900
<pre><code>class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __setitem__(self, key, value): super(SortedDict, self).__setitem__(key, value)#@1 ...
0
2010-01-07T07:38:30Z
2,018,934
<p>Because this is a <em>Sorted</em> dict. Dictionaries normally are unsorted, so this implementation adds a keyOrder to record the order that items are added.</p>
2
2010-01-07T07:46:06Z
[ "python", "django" ]
What is the relationship between '@1' and '@2'
2,018,900
<pre><code>class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder = [] return instance def __setitem__(self, key, value): super(SortedDict, self).__setitem__(key, value)#@1 ...
0
2010-01-07T07:38:30Z
2,018,941
<p>The SortedDict is "A dictionary that keeps its keys in the order in which they're inserted." (See: <a href="http://code.djangoproject.com/wiki/SortedDict" rel="nofollow">documentation</a>). </p> <p>Your @1 line is storing the key-value pair in the dictionary. The @2 stores the key in an internal list to maintain or...
3
2010-01-07T07:48:23Z
[ "python", "django" ]
building boost python examples using Visual Studio 2008
2,018,908
<p>I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:</p> <pre><code>#include &lt;boost/python/module.hpp&gt; #include &lt;boost/python/def.hpp&gt; char const* greet() { return "hello, world"; } B...
9
2010-01-07T07:40:04Z
2,018,939
<p>Please make sure you have flag <code>-lpython26</code> (if you are using python2.6) and filename should be <code>hello_ext.pyd</code> in your case.</p>
0
2010-01-07T07:47:03Z
[ "c++", "python", "boost-python" ]
building boost python examples using Visual Studio 2008
2,018,908
<p>I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:</p> <pre><code>#include &lt;boost/python/module.hpp&gt; #include &lt;boost/python/def.hpp&gt; char const* greet() { return "hello, world"; } B...
9
2010-01-07T07:40:04Z
2,020,097
<p>Firstly, make sure you only try to import the release version from Python; importing the debug version will fail because the runtime library versions don't match. I also change my project properties so that the release version outputs a .pyd file:</p> <p>Properties >> Linker >> Output:</p> <pre><code>$(OutDir)\$(P...
9
2010-01-07T12:08:05Z
[ "c++", "python", "boost-python" ]
building boost python examples using Visual Studio 2008
2,018,908
<p>I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:</p> <pre><code>#include &lt;boost/python/module.hpp&gt; #include &lt;boost/python/def.hpp&gt; char const* greet() { return "hello, world"; } B...
9
2010-01-07T07:40:04Z
2,030,903
<p>The error <em>ImportError: Dll load failed</em> usually means that your .pyd module depends on other DLLs that couldn't be found - often <em>msvc*.dll</em>. You may want to try opening the .pyd file in Notepad and searching for ".dll". Then check if all of the DLL dependencies exist in your directory or PATH.</p> <...
5
2010-01-08T21:32:12Z
[ "c++", "python", "boost-python" ]
building boost python examples using Visual Studio 2008
2,018,908
<p>I'm using Boost Python library to create python extensions to my C++ code. I'd like to be able to invoke from python the 'greet' function from the C++ code shown below:</p> <pre><code>#include &lt;boost/python/module.hpp&gt; #include &lt;boost/python/def.hpp&gt; char const* greet() { return "hello, world"; } B...
9
2010-01-07T07:40:04Z
38,156,722
<p>Even though this is a question issued several years ago(still not easy to find solution), but I meet the same problem today, and after hours searching, finally I found a feasible solution.</p> <ul> <li>The reason is just as simple as which is noticed by @AndiDog, the <em>.pyd</em> file you build depends on some oth...
0
2016-07-02T05:13:59Z
[ "c++", "python", "boost-python" ]
convert excel to pdf in python
2,018,932
<p>Is there a good python module to convert .xls file to PDF?</p>
5
2010-01-07T07:45:45Z
2,018,958
<p>Try <a href="http://www.packtpub.com/article/Using_xtopdf" rel="nofollow">xtopdf</a>.</p> <p>Note that there are some limitations:</p> <blockquote> <p>Only simple spreadsheets that have plain text content, such as strings, numbers and dates, are supported. Spreadsheets with formatted cells (bold, italic, right-j...
-2
2010-01-07T07:52:32Z
[ "python", "excel", "pdf", "pdf-generation" ]
convert excel to pdf in python
2,018,932
<p>Is there a good python module to convert .xls file to PDF?</p>
5
2010-01-07T07:45:45Z
5,304,619
<p>I know this is super old, but unoconv works. E.g., <code>unoconv -f pdf your_excel.xls</code>. Note its just calling open office to do the actual conversion.</p> <p><a href="http://dag.wieers.com/home-made/unoconv/" rel="nofollow">http://dag.wieers.com/home-made/unoconv/</a></p>
2
2011-03-14T21:12:48Z
[ "python", "excel", "pdf", "pdf-generation" ]
Dynamically Naming Groups in Python Regular Expressions
2,019,005
<p>Is there a way to dynamically update the name of regex groups in Python?</p> <p>For example, if the text is:</p> <pre><code>person 1: name1 person 2: name2 person 3: name3 ... person N: nameN </code></pre> <p>How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand ...
0
2010-01-07T08:12:21Z
2,019,032
<p>No, but you can do something like this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; p = re.compile('(?m)^(.*?)\\s*:\\s*(.*)$') &gt;&gt;&gt; text = '''person 1: name1 person 2: name2 person 3: name3 ... person N: nameN''' &gt;&gt;&gt; p.findall(text) </code></pre> <p>output:</p> <pre><code>[('person 1', 'na...
0
2010-01-07T08:18:36Z
[ "python", "regex", "group" ]
Dynamically Naming Groups in Python Regular Expressions
2,019,005
<p>Is there a way to dynamically update the name of regex groups in Python?</p> <p>For example, if the text is:</p> <pre><code>person 1: name1 person 2: name2 person 3: name3 ... person N: nameN </code></pre> <p>How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand ...
0
2010-01-07T08:12:21Z
2,019,036
<p>named capture groups and numbered groups (\1, \2, etc.) cannot be dynamic, but you can achieve the same thing with findall:</p> <blockquote> <p><a href="http://docs.python.org/library/re.html" rel="nofollow">re.findall(pattern, string[, flags])</a></p> <p>Return all non-overlapping matches of pattern in stri...
1
2010-01-07T08:19:16Z
[ "python", "regex", "group" ]
Dynamically Naming Groups in Python Regular Expressions
2,019,005
<p>Is there a way to dynamically update the name of regex groups in Python?</p> <p>For example, if the text is:</p> <pre><code>person 1: name1 person 2: name2 person 3: name3 ... person N: nameN </code></pre> <p>How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand ...
0
2010-01-07T08:12:21Z
2,019,040
<p>Regexes in Python (and I'm pretty certain that that's true for regexes in general) don't allow for an arbitrary number of matches. You can either capture a repeated match in its entirety (by placing capturing parentheses around a repeated group) or capture the last match in a series of matches (by repeating a captur...
0
2010-01-07T08:20:00Z
[ "python", "regex", "group" ]
Dynamically Naming Groups in Python Regular Expressions
2,019,005
<p>Is there a way to dynamically update the name of regex groups in Python?</p> <p>For example, if the text is:</p> <pre><code>person 1: name1 person 2: name2 person 3: name3 ... person N: nameN </code></pre> <p>How would you name groups 'person1', 'person2', 'person3', ..., and 'personN' without knowing beforehand ...
0
2010-01-07T08:12:21Z
2,019,108
<p>judging from your accepted answer, there's no need for regex</p> <pre><code>p=""" person 1: name1 person 2: name2 person 3: name3 person N: nameN """ ARR=[] for item in p.split("\n"): if item: s=item.split(":") ARR.append(s) print ARR </code></pre> <p>output</p> <pre><code>$ ./python.py [['pe...
0
2010-01-07T08:38:21Z
[ "python", "regex", "group" ]
How to get a flat XML so that external entities are merged to the top level
2,019,317
<p>I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO.</p> <p>I have a pile of XML files that someone in their infinite wisdom have decided to explode to a multiple files using the ta...
5
2010-01-07T09:30:23Z
2,035,836
<p>For the #3 option you can take a look at <a href="http://www.doxdesk.com/software/py/pxdom.html" rel="nofollow">pixdom</a> and look at the documentation at <a href="http://www.doxdesk.com/file/software/py/pxdom.html" rel="nofollow">pxdom 1.5 A Python DOM implementation</a> </p> <blockquote> <p>DOMConfiguration pa...
1
2010-01-10T02:28:58Z
[ "python", "xml", "bash", "editor", "sed" ]
How to get a flat XML so that external entities are merged to the top level
2,019,317
<p>I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO.</p> <p>I have a pile of XML files that someone in their infinite wisdom have decided to explode to a multiple files using the ta...
5
2010-01-07T09:30:23Z
2,053,741
<p>Are you looking for something like this?</p> <pre><code>#!/opt/local/bin/python import sys if len(sys.argv) &lt; 2: print "some files needed." sys.exit() final = """ &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;nodes&gt; """ for a in sys.argv[1:]: ca = a.replace(".xml","") final += "&lt;" ...
0
2010-01-13T01:14:51Z
[ "python", "xml", "bash", "editor", "sed" ]