title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sy...
2
2009-09-21T20:47:37Z
1,456,817
<p>try:</p> <pre><code>for line in handle: result += 1 if eval(pred) else 0 </code></pre>
5
2009-09-21T20:57:49Z
[ "python", "eval", "syntax-error" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sy...
2
2009-09-21T20:47:37Z
1,456,827
<p>Really, you are looking for the compile function:</p> <pre><code>&gt;&gt; a = compile("toAdd = 1 if int('0') == 0 else 0", 'tmp2.py', 'exec') &gt;&gt;&gt; eval(a) &gt;&gt;&gt; toAdd 1 </code></pre> <p>eval is intended only for expressions... compile while compile sequence of statements into a codeblock that can th...
0
2009-09-21T20:59:33Z
[ "python", "eval", "syntax-error" ]
Python Eval: What's wrong with this code?
1,456,760
<p>I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code:</p> <pre><code>import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sy...
2
2009-09-21T20:47:37Z
1,456,860
<pre><code>#!/usr/bin/env python import fileinput, sys pred = eval('lambda line: ' + sys.argv[1]) print sum(1 for line in fileinput.input(sys.argv[2:]) if pred(line)) </code></pre> <p>Usage: <code>pywc.py predicate [FILE]...</code><br /> Print number of lines that satisfy <code>predicate</code> for given <code>FILE</...
3
2009-09-21T21:06:57Z
[ "python", "eval", "syntax-error" ]
Can Python encode a string to match ASP.NET membership provider's EncodePassword
1,456,770
<p>I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a base64 encoding, somehow treating the original string as Unicode. Let's try some co...
1
2009-09-21T20:49:41Z
1,457,539
<p>This is the trick:</p> <blockquote> <p>Encoding.Unicode</p> </blockquote> <p>“Unicode” encoding is confusing Microsoft-speak for UTF-16LE (specifically, without any BOM). Encode the string to that before hashing and you get the right answer:</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; p= u'passw...
4
2009-09-22T00:14:44Z
[ "c#", ".net", "asp.net", "python", "unicode" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these set...
6
2009-09-21T21:43:11Z
1,459,497
<p>Not being able to use GPL is often a matter of abstraction; that is if it is the license you have problems with. So if you create a small GPL application (released under GPL) you can call this from your non-GPL application. Why re-invent the wheel?</p> <p>Especially if you can use a python script which already exis...
1
2009-09-22T11:28:12Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these set...
6
2009-09-21T21:43:11Z
1,603,692
<p>This code is out of my head, and thus covered by whatever license applies for code samples in this site.</p> <pre><code># given two finite sequences of unique and hashable data, # return needed opcodes and data needed for reconciliation def set_reconcile(src_seq, dst_seq): "Return required operations to mutate...
1
2009-10-21T21:13:57Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Implementation of set reconciliation algorithm
1,457,045
<p>I'm looking for implementations of set reconciliation algorithm. The problem is following: there are two sets with elements identified by some relatively compact value (e.g. UUID or MD5/SHA1/whatever hash) sitting on different machines. These sets differ in relatively few elements and I want to synchronize these set...
6
2009-09-21T21:43:11Z
27,048,441
<p>The <a href="https://bitbucket.org/skskeyserver/sks-keyserver/wiki/Home" rel="nofollow">Synchronizing Keyserver</a> project implements efficient set reconciliation in OCaml.</p>
0
2014-11-20T20:01:34Z
[ "python", "c", "algorithm", "synchronization", "set" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need ...
0
2009-09-21T21:54:45Z
1,457,127
<p>Personally, if it is this structured of a document, don't bother with a regex.</p> <p>Just loop through the file, do a split on the " " character, then simply omit the second entry.</p>
1
2009-09-21T22:01:34Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need ...
0
2009-09-21T21:54:45Z
1,457,137
<p>Something like...:</p> <pre><code>for theline in fileinput.input(inplace=1): print re.sub(r'(\w+\s*+)\d+\s+(.*)', r'\1\2', theline), </code></pre> <p>...should meet your needs.</p>
2
2009-09-21T22:04:05Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need ...
0
2009-09-21T21:54:45Z
1,457,142
<p>I don't know what platform you're using Eclipse on, but if it's linux or you have cygwin, cut is very fast!</p> <pre><code>cut -d" " --complement -f2 $FILE </code></pre> <p>This will use space as the delimiter, and select the complement of the second field.</p> <p>If you really want to use a regular expression, y...
0
2009-09-21T22:04:46Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need ...
0
2009-09-21T21:54:45Z
1,457,153
<p>This is basically what the <code>cut</code> utility is for:</p> <pre><code>cut -d " " -f 1,3- </code></pre> <p>(update: I forgot the <code>-f</code> option, sorry.)</p> <p>This takes a file, considers fields delimited by spaces, and outputs the first, third and following fields.</p> <p>(If you're on Windows, you...
4
2009-09-21T22:07:09Z
[ "python", "regex", "eclipse" ]
Renaming contents of text file using Regular Expressions
1,457,100
<p>I have a text file with several lines in the following format:</p> <pre><code>gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) </code></pre> <p>What I need ...
0
2009-09-21T21:54:45Z
1,457,179
<p>You can indeed use Eclipse's find and replace feature, using the following:</p> <pre><code>Find: ^([a-z]+) \d Replace with: \1 </code></pre> <p>This is essentially matching the gatename at the beginning of each line (<code>^([a-z]+)</code>) followed by the output (<code> \d</code>), and replacing it with just the ...
1
2009-09-21T22:14:39Z
[ "python", "regex", "eclipse" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
1,457,852
<p>This behavior is almost certainly because your files are not named in accordance with nose's test matching behavior. From <a href="https://nose.readthedocs.org/en/latest/usage.html#extended-usage">the nose docs</a>:</p> <blockquote> <p>nose collects tests automatically from python source files, directories and p...
47
2009-09-22T02:24:24Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
1,579,787
<p>The other thing which <em>always</em> gets me with <code>nose</code> is that it won't run tests in executable files. I'm not exactly sure why that would make a difference across Mac/Ubuntu, but it's worth a shot.</p> <p>Make sure that the scripts didn't somehow get <code>chmod +x</code>'d on the Mac… And if they ...
70
2009-10-16T18:57:16Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
5,644,762
<p>I can confirm that as @david-wolever said, they <strong>cannot</strong> be executable on Ubuntu. Run</p> <pre><code>nosetests -vv --collect-only </code></pre> <p>to see full details on which files were examined.</p>
14
2011-04-13T05:22:34Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
7,410,349
<p>I had the same problem. My tests ran just fine in Windows, but not in Ubuntu.</p> <p>In Ubuntu, if you run:</p> <pre><code>nosetests -vv --collect-only </code></pre> <p>You'll probably see that it's skipping your test file because it's an executable: _Tools/LintControlFiles/test_HgLint.py <strong>is executable; s...
25
2011-09-14T01:34:38Z
[ "python", "nose", "nosetests" ]
Nose unable to find tests in ubuntu
1,457,104
<p>Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. </p> <p>The same project runs tests fine on my Mac, so i'm quite stumped. </p>
39
2009-09-21T21:55:22Z
18,860,584
<p>Some what related, if you're running tests off of a directory i.e </p> <pre><code>nosetests ... tests/ </code></pre> <p>where tests is the name of the folder with my tests, and have separate python test functions in one of the .py modules... Your functions have to start with 'test' for nosetests to recognize that ...
3
2013-09-17T21:55:35Z
[ "python", "nose", "nosetests" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,354
<p>In the top-level of c.py (i.e. outside of any function or class), you should be able to get the information you need by running</p> <pre><code>import traceback </code></pre> <p>and then examining the result of traceback.extract_stack(). At the time that top-level code is run, the importer of the module (and its im...
1
2009-09-21T23:11:20Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,358
<p>It can be done by <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspecting</a> the stack:</p> <pre><code>#inside c.py: import inspect FRAME_FILENAME = 1 print "Imported from: ", inspect.getouterframes(inspect.currentframe())[-1][FRAME_FILENAME] #or: print "Imported from: ", inspect.stack()[-1...
1
2009-09-21T23:13:54Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,700
<p>That's why you have parameters.</p> <p>It's not the job of <code>c.py</code> to determine who imported it.</p> <p>It's the job of <code>a.py</code> or <code>b.py</code> to pass the variable <code>__name__</code> to the functions or classes in <code>c.py</code>.</p>
2
2009-09-22T01:25:09Z
[ "python", "import" ]
How do I find the name of the file that is the importer, within the imported file?
1,457,308
<p>How do I find the name of the file that is the "importer", within the imported file?</p> <p>If <code>a.py</code> and <code>b.py</code> both import <code>c.py</code>, is there anyway that c.py can know the name of the file importing it?</p>
2
2009-09-21T22:56:31Z
1,457,942
<p>Use</p> <p>sys.path[0]</p> <p>returns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.</p> <p>See <a href="http://arcoleo.org/dsawiki...
1
2009-09-22T03:11:06Z
[ "python", "import" ]
TurtleGraphics Python: Bouncing turtle off the walls?
1,457,332
<p>So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:</p> <pre><code>def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bottom = -top right = turtle.window_wid...
1
2009-09-21T23:04:29Z
1,457,659
<p>Try something like this:</p> <pre><code>if not (left &lt;= x &lt;= right): turtle.left(180 - 2 * turtle.heading()) elif not (bottom &lt;= y &lt;= top): turtle.left(-2 * turtle.heading()) else: pass </code></pre> <p>My python syntax is a little rusty, sorry :P. But the math is a little different for a ...
1
2009-09-22T01:02:33Z
[ "python", "turtle-graphics" ]
TurtleGraphics Python: Bouncing turtle off the walls?
1,457,332
<p>So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this:</p> <pre><code>def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bottom = -top right = turtle.window_wid...
1
2009-09-21T23:04:29Z
1,458,020
<p>Gday,</p> <p>Your problem seems to be that you are using the same trigonometry to calculate the right and left walls, as you are the top and bottom. A piece of paper and a pencil should suffice to calculate the required deflections. </p> <pre><code>def inbounds(limit, value): 'returns boolean answer to questio...
0
2009-09-22T03:47:19Z
[ "python", "turtle-graphics" ]
python shell command - why won't it work?
1,457,757
<p>I wonder if anyone has any insights into this. I have a bash script that should put my ssh key onto a remote machine. Adopted from <a href="http://www.macosxhints.com/article.php?story=2007091814022049" rel="nofollow">here</a>, the script reads,</p> <pre><code>#!/usr/bin/sh REMOTEHOST=user@remote KEY="$HOME/.ssh/id...
1
2009-09-22T01:51:11Z
1,457,789
<p>You have a serious question -- in that <code>os.system</code> isn't behaving the way you expect it to -- but also, you should seriously rethink the approach as a whole.</p> <p>You're launching a Python interpreter -- but then, via <code>os.system</code>, telling that Python interpreter to launch a shell! <code>os.s...
5
2009-09-22T01:59:17Z
[ "python", "shell" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem i...
3
2009-09-22T02:09:25Z
1,457,836
<p>Assuming you DO mean combinations (no repetitions, order does not matter):</p> <pre><code>import itertools S = [ 'a', 'ab', 'ba' ] for i in range(len(S)+1): for c in itertools.combinations(S, i): cc = ''.join(c) if len(cc) &lt;= 6: print c </code></pre> <p>emits all the possibilities:</p> <pre><...
8
2009-09-22T02:17:59Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem i...
3
2009-09-22T02:09:25Z
1,457,875
<p>You can iteratively generate all the strings made from one part, two parts, three parts and so on, until all the strings generated in a step are longer than six characters. Further steps would only generate even longer strings, so all possible short strings have already been generated. If you collect these short str...
6
2009-09-22T02:34:30Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem i...
3
2009-09-22T02:09:25Z
1,457,927
<p>Doing it recursively is one way:</p> <pre><code>cache = {} def words_of_length(s, n=6): # memoise results if n in cache: return cache[n] # base cases if n &lt; 0: return [] if n == 0: return [""] # inductive case res = set() for x in s: res |= set( (x+y for y in words_of_le...
1
2009-09-22T03:03:02Z
[ "python", "string", "combinatorics" ]
Get every combination of strings
1,457,814
<p>I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings.</p> <p>In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem i...
3
2009-09-22T02:09:25Z
1,457,982
<pre><code>def combos(S,n): if (n &lt;= 0): return for s in S: if len(s) &lt;= n: yield s for t in combos(S,n-len(s)): yield s+t for x in combos(["a","ab","ba"],6): print x </code></pre> <p>Prints output:</p> <pre><code>a aa aaa aaaa aaaaa aaaaaa aaaaab aaaaba aaaab aaaaba aaaba aaabaa aaab a...
3
2009-09-22T03:28:38Z
[ "python", "string", "combinatorics" ]
Python socket programming and ISO-OSI model
1,458,087
<p>I am sending packets from one pc to other. I am using python socket <code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM )</code>. Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the pr...
1
2009-09-22T04:23:42Z
1,458,109
<p><code>SOCK_DGRAM</code> means you want to send packets by UDP -- no order guarantee, no guarantee of reception, no guarantee of lack of repetition. <code>SOCK_STREAM</code> would imply TCP -- no packet boundary guarantee, but (unless the connection's dropped;-) guarantee of order, reception, and no duplication. TCP...
4
2009-09-22T04:31:25Z
[ "python", "sockets" ]
Python socket programming and ISO-OSI model
1,458,087
<p>I am sending packets from one pc to other. I am using python socket <code>socket.socket(socket.AF_INET, socket.SOCK_DGRAM )</code>. Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the pr...
1
2009-09-22T04:23:42Z
1,458,734
<p>To answer your immediate question, if you're using *SOCK_STREAM*, then you're actually using TCP, which is an implementation of the transport layer which <strong>does</strong> take care of packet ordering and integrity for you. So it sounds like that's what you want to use. *SOCK_DGRAM* is actually UDP, which doesn'...
2
2009-09-22T08:13:11Z
[ "python", "sockets" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>T...
1
2009-09-22T05:13:00Z
1,458,217
<p><strong>Direct answer</strong>: You can't. Floats are imprecise, by design. While python's floats have more than enough precision to represent 1.0000, they will <em>never</em> represent a "1-point-zero-zero-zero-zero". Chances are, this is as good as you need. You can always use string formatting, if you need to ...
9
2009-09-22T05:17:00Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>T...
1
2009-09-22T05:13:00Z
1,458,226
<pre><code>&gt;&gt;&gt; 1.0 == 1.00 == 1.000 True </code></pre> <p>In other words, you're losing no info -- Python considers trailing zeros in floats' decimal parts to be irrelevant. If you need to keep track very specifically of "number of significant digits", that's also feasible, but you'll need to explain to us a...
5
2009-09-22T05:18:46Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>T...
1
2009-09-22T05:13:00Z
1,458,306
<p>Indulge me while I reinvent the wheel a little bit! ;)</p> <p>Should you want the <code>repr</code>sentation of the object (the way it is displayed in the shell) to have the form 1.0000 then you may need to change the <code>__repr__</code> method of the float. If you would like the object to be printed to a file or...
1
2009-09-22T05:46:58Z
[ "python", "string", "floating-point" ]
Reading a float from string
1,458,203
<p>I have a simple string that I want to read into a float without losing any <strong>visible</strong> information as illustrated below:</p> <pre><code>s = ' 1.0000\n' </code></pre> <p>When I do <code>f = float(s)</code>, I get <code>f=1.0</code></p> <p>How to trick this to get <code>f=1.0000</code> ?</p> <p>T...
1
2009-09-22T05:13:00Z
1,459,292
<p>Here's an even shinier version of @Simon Edwards' <code>ExactFloat</code>, that counts the number of digits after the period and displays that number of digits when the number is converted to a string.</p> <pre><code>import re class ExactFloat(float): def __init__(self, str_value): float.__init__(self,...
1
2009-09-22T10:32:59Z
[ "python", "string", "floating-point" ]
With python.multiprocessing, how do I create a proxy in the current process to pass to other processes?
1,458,205
<p>I'm using the <code>multiprocessing</code> library in Python. I can see how to define that objects <em>returned</em> from functions should have proxies created, but I'd like to have objects in the current process turned into proxies so I can pass them as parameters.</p> <p>For example, running the following script...
2
2009-09-22T05:13:08Z
1,486,301
<p>Why do you say *serve_forever* is not supported?</p> <pre><code>manager = Mymanager() s = manager.get_server() s.serve_forever() </code></pre> <p>should work.</p> <p>See <strong>*<a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.managers.BaseManager.get%5Fserver" rel="nofollow">managers...
1
2009-09-28T10:12:23Z
[ "python", "proxy", "multiprocessing", "manager" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = paren...
22
2009-09-22T06:37:10Z
1,458,677
<p>Indirect answer: instead of using JSON, you could use <a href="http://pyyaml.org/wiki/PyYAMLDocumentation" rel="nofollow">YAML</a>, which has no problem doing what you want. (JSON is essentially a subset of YAML.)</p> <p>Example:</p> <pre><code>import yaml o1 = gwebpage("url") o2 = gpagelet(o1) o1.gpagelets = [o2...
5
2009-09-22T07:48:29Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = paren...
22
2009-09-22T06:37:10Z
1,458,716
<p>Write your own encoder and decoder, which can be very simple like <code>return __dict__</code></p> <p>e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose</p> <pre><code>import json class Tree(object): def __init__(self, name, childTrees=None...
42
2009-09-22T08:06:26Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = paren...
22
2009-09-22T06:37:10Z
11,023,172
<p><a href="http://jsonpickle.github.com/">jsonpickle</a> FOR THE WIN!</p> <p>(Just had this same question... json pickle handles recursive/nested object graphs as well as short circuits for cyclical object graphs).</p>
12
2012-06-13T20:57:33Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = paren...
22
2009-09-22T06:37:10Z
31,060,745
<p>My solution for this was to extend the 'dict' class and perform checks around required/allowed attributes by overriding init, update, and set class methods.</p> <pre><code>class StrictDict(dict): required=set() at_least_one_required=set() cannot_coexist=set() allowed=set() def __init__(self, ite...
0
2015-06-25T21:03:08Z
[ "python", "json", "serializable" ]
Python serializable objects json
1,458,450
<pre><code>class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = paren...
22
2009-09-22T06:37:10Z
35,832,502
<p>I implemented a very simple <code>todict</code> method with the help of <a href="http://stackoverflow.com/a/11637457/1766716">http://stackoverflow.com/a/11637457/1766716</a></p> <ul> <li>Iterate over properties that is not starts with <code>__</code></li> <li>Eliminate methods</li> <li>Eliminate some properties man...
0
2016-03-06T21:00:59Z
[ "python", "json", "serializable" ]
Find the file with a given SVN URL within a SVN working copy
1,458,457
<p>Given a starting point in a Subversion working copy (e.g. current working directory), and a target SVN URL, I'd like to find the file in the working copy that has that SVN URL.</p> <p>For example, given this current directory:</p> <pre><code>c:\Subversion\ProjectA\a\b\c\ </code></pre> <p>which has this SVN URL:</...
2
2009-09-22T06:39:39Z
1,458,688
<p>Subversion doesn't use this backward mapping from url to working copy location itself. The most stable way to check for the url use would be to perform a recursive 'svn info' call over the working copy.</p> <p>This gives you the url for all files and directories and you can do the matching yourself.</p> <p>You cou...
4
2009-09-22T07:51:50Z
[ "python", "svn", "pysvn" ]
Need help installing MySQL for Python
1,458,500
<p>Trying to install <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQL for Python</a>. Two problems:</p> <p>1) Instructions over the net says installation is <pre>python setup.py</pre> For me, it results with <pre>can't open file 'setup.py': [Errno 2] No such file or directory</pre></p> <p>...
0
2009-09-22T06:55:02Z
1,458,507
<p>If you're using a Debian based distro you can :</p> <p><code>apt-get install python-mysqldb</code> ( or aptitude if you prefer ).</p>
1
2009-09-22T06:57:24Z
[ "python", "mysql", "adapter", "zope" ]
Need help installing MySQL for Python
1,458,500
<p>Trying to install <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">MySQL for Python</a>. Two problems:</p> <p>1) Instructions over the net says installation is <pre>python setup.py</pre> For me, it results with <pre>can't open file 'setup.py': [Errno 2] No such file or directory</pre></p> <p>...
0
2009-09-22T06:55:02Z
1,458,554
<p>You are confusing A <a href="http://en.wikipedia.org/wiki/Zope" rel="nofollow"><code>Zope product</code></a> (<code>ZMySQLDA</code>) with the <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">python-mysqldb</a> package. Try one of the <a href="http://sourceforge.net/projects/mysql-python/files/"...
2
2009-09-22T07:13:06Z
[ "python", "mysql", "adapter", "zope" ]
Json encoder python recursive reference
1,458,671
<p>Hey everyone I don't know whether I am doing the right thing here, basically I want both of my class to be json-serializable.</p> <pre><code>import json class gpagelet(json.JSONEncoder): """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __...
0
2009-09-22T07:46:24Z
1,464,208
<p>FYI I am seeing a lot of trouble with this: u['gpagelets'] = [ gpageletEncoder.default( each) for each in gw.gpagelets ]</p>
0
2009-09-23T06:09:42Z
[ "python", "json" ]
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
1,458,690
<p>Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. </p> <p>I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. </p> ...
1
2009-09-22T07:53:03Z
1,483,115
<p>OK, to answer my own question. I need to build a DLL with "MAPISendDocuments" and/or "MAPISendMail" functions defined.</p> <p>This DLL can have any name, and is referenced in the registry at HKLM/Software/Clients/Mail/MyMailApp/DLLPath.</p> <p>Found examples using Delphi...</p>
0
2009-09-27T08:37:31Z
[ "c#", "python", "outlook", "ms-word", "mapi" ]
How to create a MAPI32.dll stub to be able to "send as attachment" from MS Word?
1,458,690
<p>Microsoft Word has "send as attachment" functionality which creates a new message in Outlook with the document attached. </p> <p>I would like to replace Outlook with a custom mail agent, but I do not know how to achieve this. Now my mail agent is simply a program that runs, and takes a file name as parameter. </p> ...
1
2009-09-22T07:53:03Z
2,674,286
<p>When writing your own mapi implementation it is critical to create a dll with both the proper exports and calling conventions in order for the system stub mapi dll (c:\windows\system32\mapi32.dll, should be the same as mapistub.dll) to pass calls through to your dll. MAPI functions are called with the __stdcall cal...
1
2010-04-20T10:32:07Z
[ "c#", "python", "outlook", "ms-word", "mapi" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not...
2
2009-09-22T08:37:38Z
1,459,197
<p>Have you tried to use the <a href="http://docs.python.org/library/ctypes.html#ctypes.HRESULT" rel="nofollow">ctypes.HRESULT</a>? </p>
0
2009-09-22T10:10:20Z
[ "python", "windows", "ctypes" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not...
2
2009-09-22T08:37:38Z
1,459,422
<p>At the very least, you'll get more descriptive errors if you properly set up the <a href="http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes" rel="nofollow"><code>argtypes</code></a> and the <a href="http://docs.python.org/library/ctypes.html#return-types" rel="nofo...
2
2009-09-22T11:05:42Z
[ "python", "windows", "ctypes" ]
Python ctypes and not enough arguments (4 bytes missing)
1,458,813
<p>The function i'm trying to call is:</p> <pre><code>void FormatError (HRESULT hrError,PCHAR pszText); </code></pre> <p>from a custom dll using windll.</p> <pre><code>c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) </code></pre> <p>Results in:</p> <pre><code>ValueError: Procedure probably called with not...
2
2009-09-22T08:37:38Z
1,459,789
<p>Actually I think you want to use FormatError as provided by ctypes</p> <p><a href="http://docs.python.org/library/ctypes.html#ctypes.FormatError" rel="nofollow">http://docs.python.org/library/ctypes.html#ctypes.FormatError</a></p> <blockquote> <p>ctypes.FormatError([code])</p> <p>Windows only: Returns a tex...
0
2009-09-22T12:24:52Z
[ "python", "windows", "ctypes" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and repla...
3
2009-09-22T08:41:05Z
1,458,940
<pre><code>class YourRedirectMiddleware: def process_request(self, request): redirect_url = request.path+'?par1=1&amp;par2=2' return HttpResponsePermanentRedirect(redirect_url) </code></pre> <p>what are you trying to accomplish and why this way?</p>
4
2009-09-22T09:03:49Z
[ "python", "django", "django-urls", "django-middleware" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and repla...
3
2009-09-22T08:41:05Z
1,458,950
<p>You can do whatever you like in the middleware. You have access to the request object, you can get the URL and redirect to a new one if you want.</p> <p>My question would be, why do you want to do this? If you need to keep information about the request, the proper place to do this is in the session.</p>
0
2009-09-22T09:06:21Z
[ "python", "django", "django-urls", "django-middleware" ]
Modify address in Django middleware
1,458,829
<p>I don't know if it's possible but I'd like to add few parameters at the end of the URL using middleware. Can it be done without redirect after modyfing requested URL?</p> <p>ie. user clicks: .../some_link and middleware rewrites it to: .../some_link?par1=1&amp;par2=2</p> <p>Other way is to modify reponse and repla...
3
2009-09-22T08:41:05Z
1,460,317
<p>I think this really depends on your problem and what exactly you are trying to do.</p> <p>You cannot change the URL without redirecting the user, as you cannot modify the URL on a page without a reload. Basically a redirect is a response telling the user to move on, there is no way to actually change the URL. Note ...
1
2009-09-22T14:06:31Z
[ "python", "django", "django-urls", "django-middleware" ]
Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name?
1,458,847
<p>I have a simple script written in Python:</p> <pre><code>import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") </code></pre> <p>When i run this it recurses through a remote share on the LAN and just simply displays the names of ...
3
2009-09-22T08:45:30Z
1,458,877
<p>That is not (<a href="http://en.wikipedia.org/wiki/Gibberish" rel="nofollow">g</a>|<a href="http://www.urbandictionary.com/define.php?term=jibberish" rel="nofollow">j</a>)ibberish, it's a <a href="http://en.wikipedia.org/wiki/8.3%5Ffilename" rel="nofollow">short (8.3) filename</a>. It's Windows-specific, but you mig...
3
2009-09-22T08:51:08Z
[ "python" ]
Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name?
1,458,847
<p>I have a simple script written in Python:</p> <pre><code>import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") </code></pre> <p>When i run this it recurses through a remote share on the LAN and just simply displays the names of ...
3
2009-09-22T08:45:30Z
1,459,011
<p>Windows uses generated 8.3 "placeholders" when a filename over CIFS contains characters which are illegal in a Windows filename.</p> <p>In this case, it's happening because your "Santas Chocolate " filename ends with a space. Windows filenames can't end with spaces, so it uses a placeholder to make the file access...
4
2009-09-22T09:19:42Z
[ "python" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,090
<p>If the ZIP decompressor you use can provide the data on original and compressed size you can use that data. Otherwise start unzipping and monitor the output size - if it grows too much cut it loose.</p>
4
2009-09-22T09:38:53Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,095
<p>Check a zip header first :)</p>
5
2009-09-22T09:40:43Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,096
<p>Make sure you are not using your system drive for temp storage. I am not sure if a virusscanner will check it if it encounters it. </p> <p>Also you can look at the information inside the zip file and retrieve a list of the content. How to do this depends on the utility used to extract the file, so you need to provi...
1
2009-09-22T09:40:43Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,154
<p>Try this in Python:</p> <pre><code>import zipfile z = zipfile.ZipFile('c:/a_zip_file') print 'total files size=', sum(e.file_size for e in z.infolist()) z.close() </code></pre>
19
2009-09-22T09:57:29Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,157
<p>Reading over the description on Wikipedia - </p> <p>Deny any compressed files that contain compressed files.<br> &nbsp;&nbsp;&nbsp;&nbsp; Use <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/ZipFile.html#entries%28%29">ZipFile.entries()</a> to retrieve a list of files, then <a href="http://java.sun.com/...
6
2009-09-22T09:58:04Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,186
<p>Don't allow the upload process to write enough data to fill up the disk, ie solve the problem, not just one possible cause of the problem.</p>
4
2009-09-22T10:07:22Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
1,459,369
<p>Zip is, erm, an "interesting" format. A robust solution is to stream the data out, and stop when you have had enough. In Java, use <code>ZipInputStream</code> rather than <code>ZipFile</code>. The latter also requires you to store the data in a temporary file, which is also not the greatest of ideas.</p>
17
2009-09-22T10:50:22Z
[ "java", "python", "security", "compression", "zip" ]
How can I protect myself from a zip bomb?
1,459,080
<p>I just read about <a href="http://en.wikipedia.org/wiki/Zip%5Fbomb">zip bombs</a>, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...).</p> <p>When opened they fill the server's disk.</p> <p>How can I detect a zip file is a zip bomb <strong>before</strong> unzipping it?...
39
2009-09-22T09:36:21Z
17,905,491
<p>Why would you want to? The moment you zip the first layer and find so many multiple files with weird numbering, you'd automatically know. There is no autoextracting sfx archive zip bomb that I know of.</p>
-1
2013-07-28T06:06:05Z
[ "java", "python", "security", "compression", "zip" ]
module reimported if imported from different path
1,459,236
<p>In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes</p> <p>e.g. suppose I have a package mypakcage with three file mymodule.py...
7
2009-09-22T10:17:31Z
1,459,587
<p>I can only replicate this if main.py is the file you are actually running. In that case you will get the current directory of main.py on the sys path. But you apparently also have a system path set so that mypackage can be imported.</p> <p>Python will in that situation not realize that mymodule and mypackage.mymodu...
3
2009-09-22T11:46:25Z
[ "python", "python-import" ]
module reimported if imported from different path
1,459,236
<p>In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes</p> <p>e.g. suppose I have a package mypakcage with three file mymodule.py...
7
2009-09-22T10:17:31Z
1,459,594
<p>Each module namespace is imported only once. Issue is, you're importing them differently. On the first you're importing from the global package, and on the second you're doing a local, non-packaged <code>import</code>. Python sees modules as different. The first import is internally cached as <code>mypackage.mymodul...
2
2009-09-22T11:47:06Z
[ "python", "python-import" ]
pyparsing - load ABNF?
1,459,371
<p>can pyparsing read ABNF from a file instead of having to define it in terms of python objects? </p> <p>If not, is there something which can do similar (load an ABNF file into a parser object)</p>
9
2009-09-22T10:50:31Z
1,459,433
<p>There are lots of Python parsing packages: <a href="http://nedbatchelder.com/text/python-parsers.html" rel="nofollow">Python Parsing Tools</a>. <a href="http://antlr.org" rel="nofollow">ANTLR</a> in particular is very well-respected, and reads a grammar from a dedicated file. </p>
2
2009-09-22T11:08:24Z
[ "python", "parsing", "pyparsing" ]
pyparsing - load ABNF?
1,459,371
<p>can pyparsing read ABNF from a file instead of having to define it in terms of python objects? </p> <p>If not, is there something which can do similar (load an ABNF file into a parser object)</p>
9
2009-09-22T10:50:31Z
1,459,981
<p>See <a href="http://pyparsing.wikispaces.com/file/view/ebnf.py" rel="nofollow" title="EBNF parser">this example</a> submitted by Seo Sanghyeon, which reads EBNF and parses it (using pyparsing) to create a pyparsing parser.</p>
9
2009-09-22T13:04:07Z
[ "python", "parsing", "pyparsing" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/director...
2
2009-09-22T11:46:33Z
1,459,658
<p>May be <a href="http://miketeo.net/wp/index.php/projects/pysmb">pysmb</a> can help</p>
5
2009-09-22T12:01:27Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/director...
2
2009-09-22T11:46:33Z
1,459,771
<p>Sorry. I'm not able to try this as I'm not in a PC. Have you tried:</p> <pre><code>os.listdir("\\\\remotehost\\") </code></pre>
0
2009-09-22T12:21:12Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/director...
2
2009-09-22T11:46:33Z
1,459,813
<p>Maybe the following script will help you. See <a href="http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b" rel="nofollow">http://gallery.technet.microsoft.com/ScriptCenter/en-us/7338e3bd-1f88-4da9-a585-17877fa37e3b</a></p>
1
2009-09-22T12:28:57Z
[ "python", "networking", "drive" ]
listing network shares with python
1,459,590
<p>if I explicitly attempt to list the contents of a shared directory on a remote host using python on a windows machine, the operation succeeds, for example, the following snippet works fine:</p> <pre><code>os.listdir("\\\\remotehost\\share") </code></pre> <p>However, if I attempt to list the network drives/director...
2
2009-09-22T11:46:33Z
2,715,897
<p>I'm sure the OP has forgotten about this question by now, but here's (maybe) an explanation:</p> <p><a href="http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories" rel="nofollow">http://www.python.org/doc/faq/windows/#why-does-os-path-isdir-fail-on-nt-shared-directories</a></p>...
1
2010-04-26T18:31:18Z
[ "python", "networking", "drive" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it ...
7
2009-09-22T11:59:05Z
1,467,966
<p>If you won't use threads, you can use an event loop and poll non-blocking sockets.</p> <p><a href="http://docs.python.org/library/asyncore.html" rel="nofollow"><code>asyncore</code></a> is the standard library module for such stuff. <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> is <strong>the<...
1
2009-09-23T18:58:00Z
[ "python", "xml", "parsing", "nonblocking" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it ...
7
2009-09-22T11:59:05Z
1,468,092
<p>I think there are two components to this, the non-blocking network I/O, and a stream-oriented XML parser.</p> <p>For the former, you'd have to pick a non-blocking network framework, or roll your own solution for this. Twisted certainly would work, but I personally find inversion of control frameworks difficult to w...
4
2009-09-23T19:24:28Z
[ "python", "xml", "parsing", "nonblocking" ]
Non-Blocking method for parsing (streaming) XML in python
1,459,648
<p>I have an XML document coming in over a socket that I need to parse and react to on the fly (ie parsing a partial tree). What I'd like is a non blocking method of doing so, so that I can do other things while waiting for more data to come in (without threading).</p> <p>Something like iterparse would be ideal if it ...
7
2009-09-22T11:59:05Z
2,270,249
<p>Diving into the iterparse source provided the solution for me. Here's a simple example of building an XML tree on the fly and processing elements after their close tags:</p> <pre><code>import xml.etree.ElementTree as etree parser = etree.XMLTreeBuilder() def end_tag_event(tag): node = self.parser._end(tag) ...
6
2010-02-16T02:18:32Z
[ "python", "xml", "parsing", "nonblocking" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,792
<p>Take a look at <a href="http://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a></p> <p>This is the best reference I found for learning how to use it: <a href="http://www.dev-explorer.com/articles/excel-spreadsheets-and-python" rel="nofollow">http://www.dev-explorer.com/articles/excel-spreadsheets-and-python</a></...
6
2009-09-22T12:25:42Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,837
<p>Not sure if this is exactly what you're talking about, but:</p> <p>If you have a very simple excel file (i.e. basically just one table filled with string-values, nothing fancy), and all you want to do is basic processing, then I'd suggest just converting it to a <a href="http://en.wikipedia.org/wiki/Comma%5Fseparat...
2
2009-09-22T12:34:41Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
1,459,904
<p>If you can save as a csv file with headers: </p> <pre><code>Attrib1, Attrib2, Attrib3 value1.1, value1.2, value1.3 value2,1,... </code></pre> <p>Then I would highly recommend looking at built-in the <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a> </p> <p>With that you can do things...
0
2009-09-22T12:52:12Z
[ "python" ]
Get the inputs from Excel and use those inputs in python script
1,459,788
<p>How to get the inputs from excel and use those inputs in python.</p>
1
2009-09-22T12:24:40Z
2,978,744
<pre><code>import win32com Excel=win32com.client.Dispatch("Excel.Application") Excel.Workbooks.Open(file path) Cells=Excel.ActiveWorkBook.ActiveSheet.Cells Cells(row,column).Value=Input Output=Cells(row,column).Value </code></pre>
1
2010-06-05T01:25:18Z
[ "python" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(l...
3
2009-09-22T12:54:56Z
1,462,689
<p>Can you explain why <code>nullable=True</code> would not be the solution?</p> <p>To me it seems useless to store empty strings in the database and I would not encourage it. If there is no data than choose the more efficient type for the database.</p> <p>Personally I think the Django solution in case of strings is ...
3
2009-09-22T21:22:02Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(l...
3
2009-09-22T12:54:56Z
1,464,363
<p>Finally found a (klugde, but seems this is the only sane choice) way to do this.</p> <pre><code> fs.serial_number.validators.remove(formalchemy.validators.required) fs.mac.validators.remove(formalchemy.validators.required) </code></pre> <p>(Regarding my validator) Note, that FA will <em>completely</em> skip all...
4
2009-09-23T07:02:08Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(l...
3
2009-09-22T12:54:56Z
4,484,806
<p>This is exactly the same issue i'm having, where I often write interfaces for existing databases and want to use formalchemy but end up having to manually remove 'requiredness' as I am not able to change the database. </p>
0
2010-12-19T19:58:20Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
Do not require non-NULL field (allow empty strings) in FormAlchemy
1,459,919
<p>I'm fairly novice to FormAlchemy and it seems that I don't get something. I have a SQLAlchemy model defined like this:</p> <pre><code>... class Device(meta.Base): __tablename__ = 'devices' id = sa.Column('id_device', sa.types.Integer, primary_key=True) serial_number = sa.Column('sn', sa.types.Unicode(l...
3
2009-09-22T12:54:56Z
23,969,483
<p>You can teach FormAlchemy to not replace an empty input with None by changing the <code>null_as</code> column attribute.</p> <pre><code> whatever = Column(Unicode(999), required=False, null_as=("","\0"), nullable=False, default="", doc="Whatever for ever") </code></pre> <p>Formalchemy will replace input that's equ...
0
2014-05-31T11:25:01Z
[ "python", "sqlalchemy", "validation", "pylons", "formalchemy" ]
KindError on setting a ReferenceProperty value
1,460,105
<p>This seemingly perfect Google App Engine code fails with a KindError.</p> <pre><code># in a django project 'stars' from google.appengine.ext import db class User(db.Model): pass class Picture(db.Model): user = db.ReferenceProperty(User) user = User() user.put() picture = Picture() picture.user = user # ...
1
2009-09-22T13:26:51Z
1,460,108
<p>Turns out that I was importing the model in admin.py as</p> <pre><code>from frontend.stars.models import Star </code></pre> <p>This line had contaminated the module namespace of <code>Star</code> and the <code>isinstance</code> query was failing.</p> <pre><code>&gt;&gt;&gt; user.__class__ &lt;class 'frontend.star...
1
2009-09-22T13:27:12Z
[ "python", "google-app-engine" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: ...
1
2009-09-22T13:34:17Z
1,460,176
<blockquote> <p>I just ignored the last line and decided to continue.</p> </blockquote> <p>You can't just ignore the last line. It was telling you there was an error, so it couldn't compile. The next thing you ran told you it couldn't install because it couldn't compile. Then, your python told you it couldn't run th...
3
2009-09-22T13:41:09Z
[ "python", "sqlite", "installation", "pysqlite" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: ...
1
2009-09-22T13:34:17Z
1,460,311
<p>A lesson in compiling python extensions is needed, which distribution are you using ? You seem to be missing the sqlite headers with the given macro definitions. When the python setup runs it compiles bindings to the sqlite native binary and copies a few .py files to the library. The _sqlite is typically a .pyd file...
2
2009-09-22T14:04:18Z
[ "python", "sqlite", "installation", "pysqlite" ]
Why pysqlite does not work properly?
1,460,136
<p>I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:</p> <pre><code>python setup.py build </code></pre> <p>I got the following message in the end:</p> <pre><code>src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function) src/module.c:287: ...
1
2009-09-22T13:34:17Z
4,222,096
<p>The correct way to build pysqlite is now on the website.</p> <pre><code>$ tar xvfz &lt;version&gt;.tar.gz $ cd &lt;version&gt; $ python setup.py build_static install </code></pre> <p>The build_static will download the latest sqlite code and statically compile against it. For a note I just did this on a 1and1 s...
2
2010-11-19T04:30:21Z
[ "python", "sqlite", "installation", "pysqlite" ]
epylint script is not working on Windows
1,460,275
<p>I have installed <a href="http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz" rel="nofollow">http://ftp.logilab.org/pub/pylint/pylint-0.18.1.tar.gz</a> on Windows and now I am trying to configure my Emacs's flymake mode using epylint script. But it is not working. Here is the output of I got when I tried epylint...
0
2009-09-22T13:58:53Z
1,461,686
<p>Reading the documentation of the <code>epylint.lint</code> function:</p> <blockquote> <p>When run from emacs we will be in the directory of a file, and passed its filename. If this file is part of a package and is trying to import other modules from within its own package or another package rooted in a direct...
0
2009-09-22T18:09:28Z
[ "python", "windows", "emacs", "pylint" ]
Why does Python keep a reference count on False and True?
1,460,454
<p>I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest:</p> <pre><code>Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; </code></pre> <p>Aren't <code>Py_False</code> and <code>Py_True</code> global values? Just out of ...
20
2009-09-22T14:33:04Z
1,460,492
<p>It's to make all object handling uniform. If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipulate...
20
2009-09-22T14:39:43Z
[ "python", "reference-counting", "python-c-api" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for ...
0
2009-09-22T14:37:55Z
1,460,496
<p>You can use filter() (at least in the Python 2.x series... I think it might have been removed in 3.0)</p> <pre><code>newlist = filter(lambda item: item &lt; limit, oldlist) </code></pre> <p>The first argument can be any callable (its result will be coerced to boolean, so it's best to use a callable that returns bo...
1
2009-09-22T14:40:15Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for ...
0
2009-09-22T14:37:55Z
1,460,497
<p>You could use <a href="http://docs.python.org/library/functions.html#filter" rel="nofollow">filter</a></p> <pre><code>&gt;&gt;&gt; filter(lambda i: i &lt; limit, a) [0, 1, 2, 3, 4, 5, 6, 7, 8] </code></pre> <p>But list comprehensions are the preferred way to do it</p> <p>Here is what <a href="http://docs.python.o...
4
2009-09-22T14:40:16Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for ...
0
2009-09-22T14:37:55Z
1,460,514
<p>This is about the best you can do. You may be able to do better with filter, but I wouldn't recommend it. Bear in mind that the list comprehension reads almost like english: "i for i in a if i &lt; limit". This makes it much easier to read and understand, if a little on the verbose side.</p>
2
2009-09-22T14:43:39Z
[ "python", "list-comprehension" ]
Verbose list comprehension in Python
1,460,484
<p>I have a list of integers and I want to create a new list with all elements smaller than a given limit.</p> <pre><code>a=range(15) #example list limit=9 #example limit </code></pre> <p>My approach to solve this problem was</p> <pre><code>[i for i in a if i &lt; limit] </code></pre> <p>To me the beginning 'i for ...
0
2009-09-22T14:37:55Z
1,460,582
<p>The nicer versions require boilerplate code, so the list comprehension is as nice as you can get.</p> <p>This would be one different way to do it:</p> <pre><code>from operator import ge from functools import partial filter(partial(ge, limit), a) </code></pre> <p>(But if you were to use <code>filter</code>, <a hr...
0
2009-09-22T14:54:43Z
[ "python", "list-comprehension" ]
How can I get the element of a list that has a minimum/maximum property in Python?
1,460,512
<p>I have the following array in Python:</p> <pre><code>points_list = [point0, point1, point2] </code></pre> <p>where each of <code>points_list</code> is of the type:</p> <pre><code>class point: __init__(self, coord, value): self.coord = numpy.array(coord) self.value = value # etc... </code></pre...
2
2009-09-22T14:43:06Z
1,460,531
<p>Have you tried this?</p> <pre><code>min(points_list, key=lambda x: distance(x, point_a)) </code></pre> <p><strong>To answer a question in comment</strong>: <code>lambda</code> is indeed necessary here since <a href="http://docs.python.org/3.1/library/functions.html#min" rel="nofollow">function specified as a <code...
13
2009-09-22T14:46:56Z
[ "python", "list" ]
Charts with proper unicode support
1,460,587
<p>I want to create simple charts like pies and bars in python.</p> <p>I tried out <code>CairoPlot</code> and <code>pycha</code>. Both look amazing, but they seem not to be able to handle unicode characters properly.</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'...
1
2009-09-22T14:55:21Z
1,460,633
<p>Be careful including non-ASCII directly in your source. Are you including an encoding hint in your source?</p> <pre><code>#!/usr/bin/env python # -*- encoding: utf-8 -*- </code></pre> <p>And, of course, are you sure your editor is properly saving the file in the encoding you think it is? The safest bet is still to...
1
2009-09-22T15:01:59Z
[ "python", "unicode", "encoding", "charts", "cairoplot" ]
Charts with proper unicode support
1,460,587
<p>I want to create simple charts like pies and bars in python.</p> <p>I tried out <code>CairoPlot</code> and <code>pycha</code>. Both look amazing, but they seem not to be able to handle unicode characters properly.</p> <pre><code>CairoPlot.pie_plot(name='test.png', width=800, height=600, data={'...
1
2009-09-22T14:55:21Z
29,546,019
<p>Try to use a third party library to replace the garbage unicode , i will be happy to provide you with a one upon professional consulation</p>
1
2015-04-09T18:18:05Z
[ "python", "unicode", "encoding", "charts", "cairoplot" ]
Related to executing Java programs through Python
1,460,590
<p>I am using os.system to execute a java program through a python script. I need to pass a file name to the java program as an argument. I am not able to figure out how to pass the relative file location. What should be my reference for determining the relative location. I tried to use the location of the python scrip...
1
2009-09-22T14:55:50Z
1,460,615
<p>See the subprocess module for all your external process invoking needs.</p> <pre><code>p = subprocess.Popen(['myjavaapp', 'afilename.txt']) </code></pre> <p>If you need to get the relative location and you aren't sure how the other command is going to take it, make it absolute.</p> <pre><code>p = subprocess.Popen...
2
2009-09-22T14:59:20Z
[ "java", "python" ]
How to decompile a regex?
1,460,686
<p>Is there any way to decompile a regular expression once compiled?</p>
14
2009-09-22T15:09:24Z
1,460,695
<pre><code>r = re.compile('some[pattern]'); print r.pattern </code></pre>
8
2009-09-22T15:11:01Z
[ "python", "regex" ]
How to decompile a regex?
1,460,686
<p>Is there any way to decompile a regular expression once compiled?</p>
14
2009-09-22T15:09:24Z
1,460,699
<p>Compiled regular expression objects have a "pattern" attribute which gives the original text pattern.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = re.compile('foo (?:bar)*') &gt;&gt;&gt; regex.pattern 'foo (?:bar)*' </code></pre>
32
2009-09-22T15:11:31Z
[ "python", "regex" ]
wxpython drag&drop focus problem
1,460,722
<p>I'd like to implement drag&amp;drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:</p> <p>when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.</p> <p>W...
2
2009-09-22T15:16:49Z
1,461,564
<p>Wouldn't this work?</p> <pre><code>class DropFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) text = wx.TextCtrl(self, wx.ID_ANY) self.SetFocus() # Set's the focus to this window, allowing it to receive keyboard input. text.SetDropTarget(TextDropTarget(text)) </...
0
2009-09-22T17:52:20Z
[ "python", "drag-and-drop", "wxpython", "focus" ]
wxpython drag&drop focus problem
1,460,722
<p>I'd like to implement drag&amp;drop in wxPython that works in similar way that in WordPad/Eclipse etc. I mean the following:</p> <p>when something is being dropped to WordPad, WordPad window is on top with focus and text is added. In Eclipse editor text is pasted, Eclipse window gains focus and is on top.</p> <p>W...
2
2009-09-22T15:16:49Z
1,464,342
<p>You need to do anything you want int DragOver method of DropTarget e.g. there you can raise and set focus on your window</p> <p>sample working code for target</p> <pre><code>import wx class TextDropTarget(wx.TextDropTarget): def __init__(self, obj, callback): wx.TextDropTarget.__init__(self) se...
1
2009-09-23T06:56:19Z
[ "python", "drag-and-drop", "wxpython", "focus" ]
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
<h1>Installing Mercurial on Mac OS X 10.6 Snow Leopard</h1> <p>I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following:</p> <pre><code>cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make i...
13
2009-09-22T17:13:09Z
1,462,607
<p>Especially since you have Python 2.6 available you can do something like <code>python setup.py install --user</code>, which will install Mercurial with ~/.local as prefix. You don't have to change the PYTHONPATH for this but only add ~/.local/bin to your PATH.</p> <p>Regarding advantages and disadvantages: That all...
8
2009-09-22T21:08:11Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]