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
Non-intrusively unlock file on Windows
1,544,275
<p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p> <p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable locking implementation. But this needs a file handle to unlock, which I can not get, as the file is already locked by the locking process.</p> <p>If there is no way, could someone lead me to the Windows API doc which describes the problem further?</p>
1
2009-10-09T14:48:24Z
1,544,333
<p>When backup software can't read locked files, I doubt that you can figure out a way using Python.</p>
0
2009-10-09T14:56:59Z
[ "python", "windows", "file", "winapi", "locking" ]
Non-intrusively unlock file on Windows
1,544,275
<p>Is there a way to unlock a file on Windows with a Python script? The file is exclusively locked by another process. I need a solution without killing or interupting the locking process.</p> <p>I already had a look at <a href="http://code.activestate.com/recipes/65203/" rel="nofollow">portalocker</a>, a portable locking implementation. But this needs a file handle to unlock, which I can not get, as the file is already locked by the locking process.</p> <p>If there is no way, could someone lead me to the Windows API doc which describes the problem further?</p>
1
2009-10-09T14:48:24Z
1,544,567
<p>If you only need to infrequently read the locked file, you might try to use the <a href="http://msdn.microsoft.com/en-us/library/bb968832%28VS.85%29.aspx" rel="nofollow">Volume Shadow Copy Service</a></p>
0
2009-10-09T15:41:07Z
[ "python", "windows", "file", "winapi", "locking" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></pre> <p>or (from main script level):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result)) </code></pre> <p>Can I get this down to one line without making it unreadable?</p> <p>EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.</p>
2
2009-10-09T14:59:14Z
1,544,370
<p>Could you use exceptions to indicate failure, rather than return codes? Then most of your <code>if result != OK:</code> statements would simply go away.</p>
10
2009-10-09T15:01:45Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></pre> <p>or (from main script level):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result)) </code></pre> <p>Can I get this down to one line without making it unreadable?</p> <p>EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.</p>
2
2009-10-09T14:59:14Z
1,544,398
<p><a href="http://docs.python.org/glossary.html#term-pythonic" rel="nofollow">pythonic</a>:</p> <blockquote> <p>An idea or piece of code which closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages.[...]</p> </blockquote> <p>Does not imply writing on-liners!</p>
3
2009-10-09T15:06:10Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></pre> <p>or (from main script level):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result)) </code></pre> <p>Can I get this down to one line without making it unreadable?</p> <p>EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.</p>
2
2009-10-09T14:59:14Z
1,544,584
<p>If you insist on <strong>not using</strong> exceptions, then I would write two lines (one line will be too long here):</p> <pre><code>res = some_function(arg1, arg2) return res if res != OK else ... </code></pre> <p>By the way, I recommend you to come up with some <em>static</em> type of values your function returns (despite of dynamic typing in Python). For example, you may return "either <code>int</code> or <code>None</code>". You can put such a description into a docstring.</p> <p>In case you have <code>int</code> result values and <code>int</code> error codes you may distinguish them by introducing an error class:</p> <pre><code>class ErrorCode(int): pass </code></pre> <p>and then checking if the result <code>isinstance</code> of <code>ErrorCode</code>.</p>
1
2009-10-09T15:43:09Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></pre> <p>or (from main script level):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result)) </code></pre> <p>Can I get this down to one line without making it unreadable?</p> <p>EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.</p>
2
2009-10-09T14:59:14Z
1,544,637
<p>In addition to exceptions, using a decorator is a good solution to this problem:</p> <pre><code># Create a function that creates a decorator given a value to fail on... def fail_unless(ok_val): def _fail_unless(f): def g(*args, **kwargs): val = f(*args, **kwargs) if val != ok_val: print 'CALLING abort_on_error...' else: return val return g return _fail_unless # Now you can use the decorator on any function you'd like to fail @fail_unless('OK') def no_negatives(n): if n &lt; 0: return 'UH OH!' else: return 'OK' </code></pre> <p>In practice:</p> <pre><code>&gt;&gt;&gt; no_negatives(9) 'OK' &gt;&gt;&gt; no_negatives(0) 'OK' &gt;&gt;&gt; no_negatives(-1) 'CALLING abort_on_error...' </code></pre> <p>I know the syntax defining <code>fail_unless</code> is a little tricky if you're not used to decorators and function closures but the <em>application</em> of <code>fail_unless()</code> is quite nice no?</p>
-1
2009-10-09T15:52:43Z
[ "python" ]
Condense this Python statement without destroying readability
1,544,350
<p>I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.</p> <p>I use return codes to verify that my internal functions return successfully. For example (from internal library functions):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: return result </code></pre> <p>or (from main script level):</p> <pre><code>result = some_function(arg1,arg2) if result != OK: abort_on_error("Could not complete 'some_function': %s" % messages(result)) </code></pre> <p>Can I get this down to one line without making it unreadable?</p> <p>EDIT: Some people are recognizing that exceptions might be a better choice. I wanted to save exceptions only for very 'exceptional' scenario capturing. The return codes may be expected to fail at times, and I thought it was generally bad practice to use exceptions for this scenario.</p>
2
2009-10-09T14:59:14Z
1,544,682
<p>It sounds as if you want something like..</p> <pre><code>if result = some_function(arg1, arg2): return result </code></pre> <p>This is very deliberately not possible in Python. It's too common a typo to write <code>if a = b</code> instead of <code>if a == b</code>, and allowing this mixes assignment with flow-control. If this is necessary, split it into two lines:</p> <pre><code>x = some_function() if x: print "Function returned True" </code></pre> <p>A more practical example of this is..</p> <pre><code>result = re.match("a", "b") if result: print result.groups() </code></pre> <p>(more correctly, you should do <code>if result is not None:</code> in this case, although the above works)</p> <p>In your specific case ("to verify that my internal functions return successfully"), it sounds like you should use exceptions. If everything is fine, just return whatever you wish. If something goes badly, raise an exception.</p> <p>Exceptions in Python aren't like many other languages - for example, they are used internally flow control (such as the <a href="http://docs.python.org/library/exceptions.html#exceptions.StopIteration" rel="nofollow">StopIteration</a> exception)</p> <p>I'd consider the following <em>far</em> more Pythonic than using return codes:</p> <pre><code>#!/usr/bin/env python2.6 def some_function(arg1, arg2): if arg1 + arg2 &gt; 5: return "some data for you" else: raise ValueError("Could not complete, arg1+arg2 was too small") </code></pre> <p>Then, you can call the function in a single line:</p> <pre><code>return some_function(3, 2) </code></pre> <p>This either returns the value, or raises an exception, which you could handle the exception somewhere sensible:</p> <pre><code>def main(): try: result = some_function(3, 5) except ValueError, errormsg: print errormsg sys.exit(1) else: print "Everything is perfect, the result was {0}".format(result) </code></pre> <p>Or if this case is actually an error, simply let halt the application with a nice stack trace.</p> <p>Yes, it's much longer than one line, but the idea behind Python is brevity, but explicitness and readability.</p> <p>Basically, if the function can no longer continue, raise an exception. Handle this exception either where you can recover from the problem, or present the user with an error message.. <em>unless</em> you are writing a library, in which case leave the exception to run up the stack to the calling code</p> <p>Or, in poem form:</p> <pre>$ python -m this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!</pre> <p>Finally, it might be worth reading over <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">"PEP 8"</a>, the style guide for Python. It may answer some of your questions, such as "Are one-liner if statements 'pythonic'?"</p> <blockquote> <p>Compound statements (multiple statements on the same line) are generally discouraged.</p> <p>Yes:</p> <pre><code>if foo == 'blah': do_blah_thing() do_one() do_two() do_three() </code></pre> <p>Rather not:</p> <pre><code>if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three() </code></pre> </blockquote>
2
2009-10-09T16:01:27Z
[ "python" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1</strong>: Pumpkin is LDAP ORM (without R) for python.</p></li> <li><p><strong>afpy.ldap 0.3</strong>: This module provide an easy way to deal with ldap stuff in python.</p></li> <li><p><strong>bda.ldap 1.3.1</strong>: LDAP convenience library.</p></li> <li><p><strong>Python LDAP Object Mapper</strong>: Provides an ORM-like (Django, Storm, SQLAlchemy, et al.) layer for LDAP in Python.</p></li> <li><p><strong>ldapdict 1.4</strong>: Python package for connecting to LDAP, returning results as dictionary like classes. Results are cached.</p></li> </ul> <p>Which of these packages could you recommend? Or should I better use something different?</p>
9
2009-10-09T15:35:53Z
1,580,486
<p>If I were you I would either use python-ldap or ldaptor. Python-ldap is a wrapper for OpenLDAP so you may have problems with using it on Windows unless you are able to build from source.</p> <p>LDAPtor, is pure python so you avoid that problem. Also, there is a very well written, and graphical description of ldaptor on the website so you should be able to tell whether or not it will do the job you need, just by reading through this web page:</p> <p><a href="http://eagain.net/talks/ldaptor/" rel="nofollow">http://eagain.net/talks/ldaptor/</a></p>
4
2009-10-16T21:17:34Z
[ "python", "orm", "ldap" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1</strong>: Pumpkin is LDAP ORM (without R) for python.</p></li> <li><p><strong>afpy.ldap 0.3</strong>: This module provide an easy way to deal with ldap stuff in python.</p></li> <li><p><strong>bda.ldap 1.3.1</strong>: LDAP convenience library.</p></li> <li><p><strong>Python LDAP Object Mapper</strong>: Provides an ORM-like (Django, Storm, SQLAlchemy, et al.) layer for LDAP in Python.</p></li> <li><p><strong>ldapdict 1.4</strong>: Python package for connecting to LDAP, returning results as dictionary like classes. Results are cached.</p></li> </ul> <p>Which of these packages could you recommend? Or should I better use something different?</p>
9
2009-10-09T15:35:53Z
1,781,544
<p>Giving links to the projects in question would help a lot.</p> <p>Being the developer of <a href="https://launchpad.net/python-ldap-om" rel="nofollow">Python LDAP Object Mapper</a>, I can tell that it is quite dead at the moment. If you (or anybody else) is up for taking it over, you're welcome :)</p>
0
2009-11-23T07:14:13Z
[ "python", "orm", "ldap" ]
Which ldap object mapper for python can you recommend?
1,544,535
<p>I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP. I found the following packages via pypi and google that might provide such functionality:</p> <ul> <li><p><strong>pumpkin 0.1.0-beta1</strong>: Pumpkin is LDAP ORM (without R) for python.</p></li> <li><p><strong>afpy.ldap 0.3</strong>: This module provide an easy way to deal with ldap stuff in python.</p></li> <li><p><strong>bda.ldap 1.3.1</strong>: LDAP convenience library.</p></li> <li><p><strong>Python LDAP Object Mapper</strong>: Provides an ORM-like (Django, Storm, SQLAlchemy, et al.) layer for LDAP in Python.</p></li> <li><p><strong>ldapdict 1.4</strong>: Python package for connecting to LDAP, returning results as dictionary like classes. Results are cached.</p></li> </ul> <p>Which of these packages could you recommend? Or should I better use something different?</p>
9
2009-10-09T15:35:53Z
1,959,984
<p>little late maybe...</p> <p>bda.ldap (http://pypi.python.org/pypi/bda.ldap) wraps again python-ldap to a more simple API than python-ldap itself provides.</p> <p>Further it transparently handles query caching of results due to bda.cache (http://pypi.python.org/pypi/bda.cache).</p> <p>Additionally it provides a LDAPNode object for building end editing LDAP trees via a dict like API.</p> <p>It uses some ZTK stuff as well for integration purposes to the zope framework (primary due to zodict package in LDAPNode implementation).</p> <p>We recently released bda.ldap 1.4.0.</p> <p>If you take a look at README.txt#TODO, you see whats missing from our POV to declare the lib as final.</p> <p>Comments are always welcome,</p> <p>Cheers,</p> <p>Robert</p>
2
2009-12-24T22:50:48Z
[ "python", "orm", "ldap" ]
Storing parameters in a class, and how to access them
1,544,672
<p>I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method and riddle are other values needed.</p> <p>I put these in a class so they'd be in one place, where I can go to change them. Is this the best pythonic way to do this? It seems that I can't refer to them by Params.depth. This produces the error 'Params has no attribute 'depth'. I have to create an instance of Params() (p = Params()) and refer to them by p.depth.</p> <p>I'm faily new to Python. Thanks</p> <pre><code>class Params(object): def __init__(self): object.__init__(self) self.atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] self.operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2} self.depth = 1 self.ratio = .4 self.method = '' self.riddle = '1 + np.sin(x)' </code></pre>
0
2009-10-09T16:00:07Z
1,544,694
<p>What you have there are object properties. You mean to use class variables:</p> <pre><code>class Params(object): atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2} depth = 1 ratio = .4 method = '' riddle = '1 + np.sin(x)' # This works fine: Params.riddle </code></pre> <p>It's fairly common in Python to do this, since pretty much everyone agrees that <code>Params.riddle</code> is a lot nicer to type than <code>Params['riddle']</code>. If you find yourself doing this a lot you may want to use <a href="http://code.activestate.com/recipes/52308/" rel="nofollow">this recipe</a> which makes things a bit easier and much clearer semantically.</p> <p><em>Warning:</em> if that <code>Params</code> class gets too big, an older, grumpier Pythonista may appear and tell you to just move all that crap into its own module.</p>
7
2009-10-09T16:03:20Z
[ "python" ]
Storing parameters in a class, and how to access them
1,544,672
<p>I'm writing a program that randomly assembles mathematical expressions using the values stored in this class. The operators are stored in a dictionary along with the number of arguements they need. The arguements are stored in a list. (the four x's ensure that the x variable gets chosen often) depth, ratio, method and riddle are other values needed.</p> <p>I put these in a class so they'd be in one place, where I can go to change them. Is this the best pythonic way to do this? It seems that I can't refer to them by Params.depth. This produces the error 'Params has no attribute 'depth'. I have to create an instance of Params() (p = Params()) and refer to them by p.depth.</p> <p>I'm faily new to Python. Thanks</p> <pre><code>class Params(object): def __init__(self): object.__init__(self) self.atoms =['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'] self.operators = {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2} self.depth = 1 self.ratio = .4 self.method = '' self.riddle = '1 + np.sin(x)' </code></pre>
0
2009-10-09T16:00:07Z
1,544,729
<p>You can do this in a class, but I'd prefer to just put it in a dictionary. Dictionaries are the all-purpose container type in Python, and they're great for this sort of thing.</p> <pre><code>params = { atoms: ['1.0','2.0','3.0','4.0','5.0','6.0','7.0','8.0','9.0','x','x','x','x'], operators: {'+': 2, '-': 2, '*': 2, '/': 2,'+': 2, '-': 2, '*': 2, '/': 2, '**': 2, '%': 2}, depth: 1, ratio: .4, method: '', riddle = '1 + np.sin(x)' } </code></pre> <p>Now you can do <code>params['depth']</code> or <code>params['atoms'][2]</code>. Admittedly, this is slightly more verbose than the object form, but personally I think it's worth it to avoid polluting the namespace with unnecessary class definitions.</p>
0
2009-10-09T16:12:09Z
[ "python" ]
(i'm close - i think) Python loop through list of subdomains with selenium
1,544,701
<p>starting with a base URL, I'm trying to have selenium loop through a short list of subdomains in csv format (ie: one column of 20 subdomains) and printing the html for each. I'm having trouble figuring it out. Thanks!</p> <pre><code>from selenium import selenium import unittest, time, re, csv, logging subds = csv.reader(open('listofsubdomains.txt', 'rb')) for subd in subds: try: class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.sourcedomain.com") self.selenium.start() def test_untitled(self): sel = self.selenium sel.open(subd[0]) html = sel.get_html_source() print html def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() except Exception, e: print&gt;&gt;sys.stderr, "Url % not processed: error (%s) % (url, e)" </code></pre>
0
2009-10-09T16:05:28Z
1,544,890
<p>You're defining the same function again and again in the body of the class. The class is completely created before <code>unittest.main()</code> starts, so only one test method will remain in the class.</p>
1
2009-10-09T16:45:37Z
[ "python", "selenium", "for-loop" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py", line 6, in &lt;module&gt; np.savetxt('test.txt',zip(a,b),fmt="%i %s") File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt fh.write(format % tuple(row) + '\n') TypeError: %d format: a number is required, not numpy.string_ </code></pre>
5
2009-10-09T16:56:49Z
1,545,069
<p>I think the problem you are having is that you are passing tuples through the formating string and it can't interpret the tuple with %i. Try using fmt="%s", assuming this is what you are looking for as the output:</p> <pre><code>1 a 2 b 3 c 4 d 5 e </code></pre>
1
2009-10-09T17:20:33Z
[ "python", "numpy" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py", line 6, in &lt;module&gt; np.savetxt('test.txt',zip(a,b),fmt="%i %s") File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt fh.write(format % tuple(row) + '\n') TypeError: %d format: a number is required, not numpy.string_ </code></pre>
5
2009-10-09T16:56:49Z
1,545,114
<p>You need to construct you array differently:</p> <pre><code>z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')]) np.savetxt('test.txt', z, fmt='%i %s') </code></pre> <p>when you're passing a sequence, <code>savetext</code> performs <a href="http://projects.scipy.org/numpy/browser/branches/1.1.x/numpy/lib/io.py?rev=5500#L444"><code>asarray(sequence)</code> call</a> and resulting array is of type <code>|S4</code>, that is all elements are strings! that's why you see this error.</p>
12
2009-10-09T17:31:52Z
[ "python", "numpy" ]
python numpy savetxt
1,544,948
<p>Can someone indicate what I am doing wrong here?</p> <pre><code>import numpy as np a = np.array([1,2,3,4,5],dtype=int) b = np.array(['a','b','c','d','e'],dtype='|S1') np.savetxt('test.txt',zip(a,b),fmt="%i %s") </code></pre> <p>The output is:</p> <pre><code>Traceback (most recent call last): File "loadtxt.py", line 6, in &lt;module&gt; np.savetxt('test.txt',zip(a,b),fmt="%i %s") File "/Users/tom/Library/Python/2.6/site-packages/numpy/lib/io.py", line 785, in savetxt fh.write(format % tuple(row) + '\n') TypeError: %d format: a number is required, not numpy.string_ </code></pre>
5
2009-10-09T16:56:49Z
1,545,190
<p>If you want to save a CSV file you can also use the function rec2csv (included in matplotlib.mlab)</p> <pre><code>&gt;&gt;&gt; from matplotlib.mlab import rec2csv &gt;&gt;&gt; rec = array([(1.0, 2), (3.0, 4)], dtype=[('x', float), ('y', int)]) &gt;&gt;&gt; rec = array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('x', int), ('y', str)]) &gt;&gt;&gt; rec2csv(rec, 'recordfile.txt', delimiter=' ') </code></pre> <p>hopefully, one day pylab's developers will implement a decent support to writing csv files.</p>
4
2009-10-09T17:53:36Z
[ "python", "numpy" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.</p> <p><strong>Update:</strong> let's say this: <code>array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE</code></p> <p>(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with) </p>
8
2009-10-09T17:17:05Z
1,545,056
<pre><code>for item in array: array2.append (item) </code></pre> <p>Or, in this case:</p> <pre><code>array2 += array </code></pre>
8
2009-10-09T17:18:13Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.</p> <p><strong>Update:</strong> let's say this: <code>array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE</code></p> <p>(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with) </p>
8
2009-10-09T17:17:05Z
1,545,060
<p>The keyword you're looking for is <a href="http://www.python.org/dev/peps/pep-0202/">list comprehensions</a>:</p> <pre><code>&gt;&gt;&gt; x = [1, 2, 3, 4, 5] &gt;&gt;&gt; y = [2*a for a in x if a % 2 == 1] &gt;&gt;&gt; print(y) [2, 6, 10] </code></pre>
21
2009-10-09T17:19:29Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.</p> <p><strong>Update:</strong> let's say this: <code>array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE</code></p> <p>(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with) </p>
8
2009-10-09T17:17:05Z
1,545,066
<p>If you're trying to <em>copy</em> the array:</p> <pre><code>array2 = array[:] </code></pre>
1
2009-10-09T17:20:05Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.</p> <p><strong>Update:</strong> let's say this: <code>array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE</code></p> <p>(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with) </p>
8
2009-10-09T17:17:05Z
1,545,075
<p>If you really only need to add the items in one array to another, the '+' operator is already overloaded to do that, incidentally:</p> <pre><code>a1 = [1,2,3,4,5] a2 = [6,7,8,9] a1 + a2 --&gt; [1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
1
2009-10-09T17:21:33Z
[ "python", "lambda" ]
Python one-line "for" expression
1,545,050
<p>I'm not sure if I need a lambda, or something else. But still, I need the following:</p> <p>I have an <code>array = [1,2,3,4,5]</code>. I need to put this array, for instance, into another array. But write it all in one line.</p> <pre><code>for item in array: array2.append(item) </code></pre> <p>I know that this is completely possible to iterate through the items and make it one-line. But googling and reading manuals didn't help me that much... if you can just give me a hint or name this thing so that I could find what that is, I would really appreciate it.</p> <p><strong>Update:</strong> let's say this: <code>array2 = SOME FANCY EXPRESSION THAT IS GOING TO GET ALL THE DATA FROM THE FIRST ONE</code></p> <p>(the example is NOT real. I'm just trying to iterate through different chunks of data, but that's the best I could come up with) </p>
8
2009-10-09T17:17:05Z
1,545,124
<p>Even <code>array2.extend(array1)</code> will work.</p>
0
2009-10-09T17:34:51Z
[ "python", "lambda" ]
Django - specify which model manager Django admin should use
1,545,067
<p>I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specified model. All that works fine, except - Django Admin is ALSO using the default Manager for this particular model, which means that not all model instances appear in the admin.</p> <p>The Django docs don't help:</p> <blockquote> <p>If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets this first Manager defined in a class as the "default" Manager, and several parts of Django (<strong>though not the admin application</strong>) will use that Manager exclusively for that model. <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/">(Django Managers documentation)</a></p> </blockquote> <p>The admin isn't supposed to use the default Manager, but it seems to be in my case. Note that I have also explicitly add the default Manager <code>objects</code>:</p> <pre><code>subset = CustomManager() # the default manager objects = models.Manager() # the one I want admin to use </code></pre> <p>How can I specify which Manager the admin should use?</p>
24
2009-10-09T17:20:21Z
1,545,338
<p>You can choose the manager by overriding the <code>queryset</code> method in your ModelAdmin subclass.</p> <pre><code>def get_queryset(self, request): # use our manager, rather than the default one qs = self.model.objects.get_query_set() # we need this from the superclass method ordering = self.ordering or () # otherwise we might try to *None, which is bad ;) if ordering: qs = qs.order_by(*ordering) return qs </code></pre>
34
2009-10-09T18:23:09Z
[ "python", "django" ]
Django - specify which model manager Django admin should use
1,545,067
<p>I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specified model. All that works fine, except - Django Admin is ALSO using the default Manager for this particular model, which means that not all model instances appear in the admin.</p> <p>The Django docs don't help:</p> <blockquote> <p>If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they're defined in the model) has a special status. Django interprets this first Manager defined in a class as the "default" Manager, and several parts of Django (<strong>though not the admin application</strong>) will use that Manager exclusively for that model. <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/">(Django Managers documentation)</a></p> </blockquote> <p>The admin isn't supposed to use the default Manager, but it seems to be in my case. Note that I have also explicitly add the default Manager <code>objects</code>:</p> <pre><code>subset = CustomManager() # the default manager objects = models.Manager() # the one I want admin to use </code></pre> <p>How can I specify which Manager the admin should use?</p>
24
2009-10-09T17:20:21Z
17,233,535
<p>Updated code:</p> <pre><code>def get_queryset(self, request): """ Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view. """ qs = self.model._default_manager.get_queryset() # TODO: this should be handled by some parameter to the ChangeList. ordering = self.get_ordering(request) if ordering: qs = qs.order_by(*ordering) return qs </code></pre> <p>_default_manager can be replaced...</p>
5
2013-06-21T10:56:39Z
[ "python", "django" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.</p> <p>For instance, if I need to retrieve the doc string of <code>func()</code>.</p>
3
2009-10-09T17:51:55Z
1,545,262
<p>Are you looking for something along these lines?</p> <pre><code>&gt;&gt;&gt; def dec(f): def inner(): print(f.__doc__) return inner &gt;&gt;&gt; @dec def test(): """abc""" print(1) &gt;&gt;&gt; test() abc </code></pre> <p>You're passing function explicitly to the decorator, of course you can access it.</p>
1
2009-10-09T18:06:08Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.</p> <p>For instance, if I need to retrieve the doc string of <code>func()</code>.</p>
3
2009-10-09T17:51:55Z
1,545,282
<p>See functools.wraps: <a href="http://docs.python.org/library/functools.html" rel="nofollow">http://docs.python.org/library/functools.html</a>. The decorator gets the name and doc string of the original function. You use it like this:</p> <pre><code>def decorator(f): @functools.wraps(f) def wrapper(): .... </code></pre>
4
2009-10-09T18:10:06Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.</p> <p>For instance, if I need to retrieve the doc string of <code>func()</code>.</p>
3
2009-10-09T17:51:55Z
1,545,334
<p>SilentGhost and sri have partial answers for how to deal with this. But the general answer is no: there is no way to get the "wrapped" function out of a decorated function because there is no requirement that the decorator wrap the function in the first place. It may very well have returned an entirely unrelated function, and any references to your original may have already been garbage collected.</p>
2
2009-10-09T18:22:10Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.</p> <p>For instance, if I need to retrieve the doc string of <code>func()</code>.</p>
3
2009-10-09T17:51:55Z
1,546,057
<p>You can attach the wrapped function to the inner function</p> <pre><code>In [1]: def wrapper(f): ...: def inner(): ...: print "inner" ...: inner._orig = f ...: return inner ...: In [2]: @wrapper ...: def foo(): ...: print "foo" ...: ...: In [3]: foo() inner In [4]: foo._orig() foo </code></pre>
0
2009-10-09T21:10:01Z
[ "python", "function", "nested", "decorator" ]
Is there a way to get the function a decorator has wrapped?
1,545,178
<p>Suppose I have </p> <pre><code>@someDecorator def func(): '''this function does something''' print 1 </code></pre> <p>Now, the object <code>func</code> is an instance of <code>someDecorator</code>. Is there some way I can access the function it holds, i.e something like <code>func.getInnerFunction()</code>.</p> <p>For instance, if I need to retrieve the doc string of <code>func()</code>.</p>
3
2009-10-09T17:51:55Z
35,407,564
<p>You can try using the <a href="https://pypi.python.org/pypi/undecorated" rel="nofollow">undecorated library</a>:</p> <p>With your example <code>func</code>, you could simply do this to return the original function:</p> <pre><code>undecorated(func) </code></pre>
0
2016-02-15T10:57:52Z
[ "python", "function", "nested", "decorator" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # This is an o with a hat on it. byte_string = '\xc3\xb4' unicode_string = unicode("\xc3\xb4", "utf-8") print "printed unicode object: %s" % unicode_string # Explode root_logger.info(unicode_string) if __name__ == "__main__": logging_test() </code></pre> <p>This explodes with UnicodeDecodeError on the logging.info() call.</p> <p>At a lower level, Python's logging package is using the codecs package to open the log file, passing in the "UTF-8" argument as the encoding. That's all well and good, but it's trying to write byte strings to the file instead of unicode objects, which explodes. Essentially, Python is doing this:</p> <pre><code>file_handler.write(unicode_string.encode("UTF-8")) </code></pre> <p>When it should be doing this:</p> <pre><code>file_handler.write(unicode_string) </code></pre> <p>Is this a bug in Python, or am I taking crazy pills? FWIW, this is a stock Python 2.6 installation.</p>
23
2009-10-09T18:06:15Z
1,545,315
<p>Try this:</p> <pre><code>import logging def logging_test(): log = open("./logfile.txt", "w") handler = logging.StreamHandler(log) formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # This is an o with a hat on it. byte_string = '\xc3\xb4' unicode_string = unicode("\xc3\xb4", "utf-8") print "printed unicode object: %s" % unicode_string # Explode root_logger.info(unicode_string.encode("utf8", "replace")) if __name__ == "__main__": logging_test() </code></pre> <p>For what it's worth I was expecting to have to use codecs.open to open the file with utf-8 encoding but either that's the default or something else is going on here, since it works as is like this.</p>
1
2009-10-09T18:17:29Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # This is an o with a hat on it. byte_string = '\xc3\xb4' unicode_string = unicode("\xc3\xb4", "utf-8") print "printed unicode object: %s" % unicode_string # Explode root_logger.info(unicode_string) if __name__ == "__main__": logging_test() </code></pre> <p>This explodes with UnicodeDecodeError on the logging.info() call.</p> <p>At a lower level, Python's logging package is using the codecs package to open the log file, passing in the "UTF-8" argument as the encoding. That's all well and good, but it's trying to write byte strings to the file instead of unicode objects, which explodes. Essentially, Python is doing this:</p> <pre><code>file_handler.write(unicode_string.encode("UTF-8")) </code></pre> <p>When it should be doing this:</p> <pre><code>file_handler.write(unicode_string) </code></pre> <p>Is this a bug in Python, or am I taking crazy pills? FWIW, this is a stock Python 2.6 installation.</p>
23
2009-10-09T18:06:15Z
1,545,599
<p>Check that you have the latest Python 2.6 - some Unicode bugs were found and fixed since 2.6 came out. For example, on my Ubuntu Jaunty system, I ran your script copied and pasted, removing only the '/home/ted/' prefix from the log file name. Result (copied and pasted from a terminal window):</p> <pre> vinay@eta-jaunty:~/projects/scratch$ python --version Python 2.6.2 vinay@eta-jaunty:~/projects/scratch$ python utest.py printed unicode object: ô vinay@eta-jaunty:~/projects/scratch$ cat logfile.txt ô vinay@eta-jaunty:~/projects/scratch$ </pre> <p>On a Windows box:</p> <pre> C:\temp>python --version Python 2.6.2 C:\temp>python utest.py printed unicode object: ô </pre> <p>And the contents of the file:</p> <p><img src="http://imgur.com/wKpQF.png" alt="alt text" /></p> <p>This might also explain why Lennart Regebro couldn't reproduce it either.</p>
13
2009-10-09T19:14:49Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # This is an o with a hat on it. byte_string = '\xc3\xb4' unicode_string = unicode("\xc3\xb4", "utf-8") print "printed unicode object: %s" % unicode_string # Explode root_logger.info(unicode_string) if __name__ == "__main__": logging_test() </code></pre> <p>This explodes with UnicodeDecodeError on the logging.info() call.</p> <p>At a lower level, Python's logging package is using the codecs package to open the log file, passing in the "UTF-8" argument as the encoding. That's all well and good, but it's trying to write byte strings to the file instead of unicode objects, which explodes. Essentially, Python is doing this:</p> <pre><code>file_handler.write(unicode_string.encode("UTF-8")) </code></pre> <p>When it should be doing this:</p> <pre><code>file_handler.write(unicode_string) </code></pre> <p>Is this a bug in Python, or am I taking crazy pills? FWIW, this is a stock Python 2.6 installation.</p>
23
2009-10-09T18:06:15Z
1,545,874
<p>If I understood your problem correctly, the same issue should arise on your system when you do just:</p> <pre><code>str(u'ô') </code></pre> <p>I guess automatic encoding to the locale encoding on Unix will not work until you have enabled locale-aware <code>if</code> branch in the <code>setencoding</code> function in your <a href="http://docs.python.org/library/site.html" rel="nofollow"><code>site</code></a> module via <a href="http://docs.python.org/library/locale.html" rel="nofollow"><code>locale</code></a>. This file usually resides in <code>/usr/lib/python2.x</code>, it worth inspecting anyway. AFAIK, locale-aware <code>setencoding</code> is disabled by default (it's true for my Python 2.6 installation).</p> <p>The choices are:</p> <ul> <li>Let the system figure out the right way to encode Unicode strings to bytes or do it in your code (some configuration in site-specific <code>site.py</code> is needed)</li> <li>Encode Unicode strings in your code and output just bytes</li> </ul> <p>See also <a href="http://www.ianbicking.org/illusive-setdefaultencoding.html" rel="nofollow">The Illusive setdefaultencoding</a> by Ian Bicking and related links.</p>
0
2009-10-09T20:24:30Z
[ "python", "logging", "unicode" ]
UTF-8 In Python logging, how?
1,545,263
<p>I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:</p> <pre><code>import logging def logging_test(): handler = logging.FileHandler("/home/ted/logfile.txt", "w", encoding = "UTF-8") formatter = logging.Formatter("%(message)s") handler.setFormatter(formatter) root_logger = logging.getLogger() root_logger.addHandler(handler) root_logger.setLevel(logging.INFO) # This is an o with a hat on it. byte_string = '\xc3\xb4' unicode_string = unicode("\xc3\xb4", "utf-8") print "printed unicode object: %s" % unicode_string # Explode root_logger.info(unicode_string) if __name__ == "__main__": logging_test() </code></pre> <p>This explodes with UnicodeDecodeError on the logging.info() call.</p> <p>At a lower level, Python's logging package is using the codecs package to open the log file, passing in the "UTF-8" argument as the encoding. That's all well and good, but it's trying to write byte strings to the file instead of unicode objects, which explodes. Essentially, Python is doing this:</p> <pre><code>file_handler.write(unicode_string.encode("UTF-8")) </code></pre> <p>When it should be doing this:</p> <pre><code>file_handler.write(unicode_string) </code></pre> <p>Is this a bug in Python, or am I taking crazy pills? FWIW, this is a stock Python 2.6 installation.</p>
23
2009-10-09T18:06:15Z
22,320,208
<p>Having code like:</p> <pre><code>raise Exception(u'щ') </code></pre> <p>Caused:</p> <pre><code> File "/usr/lib/python2.7/logging/__init__.py", line 467, in format s = self._fmt % record.__dict__ UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) </code></pre> <p>This happens because the format string is a byte string, while some of the format string arguments are unicode strings with non-ASCII characters:</p> <pre><code>&gt;&gt;&gt; "%(message)s" % {'message': Exception(u'\u0449')} *** UnicodeEncodeError: 'ascii' codec can't encode character u'\u0449' in position 0: ordinal not in range(128) </code></pre> <p>Making the format string unicode fixes the issue:</p> <pre><code>&gt;&gt;&gt; u"%(message)s" % {'message': Exception(u'\u0449')} u'\u0449' </code></pre> <p>So, in your logging configuration make all format string unicode:</p> <pre><code>'formatters': { 'simple': { 'format': u'%(asctime)-s %(levelname)s [%(name)s]: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, ... </code></pre> <p>And patch the default <code>logging</code> formatter to use unicode format string:</p> <pre><code>logging._defaultFormatter = logging.Formatter(u"%(message)s") </code></pre>
14
2014-03-11T08:31:51Z
[ "python", "logging", "unicode" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
1,545,416
<p>I'm not terribly familiar with Python and any extremely Pythonic methods, but you could look at the <a href="http://en.wikipedia.org/wiki/Interpreter%5Fpattern" rel="nofollow">Interpreter pattern</a>, which is defined in the Gang of Four book. It's designed for processing a "language", and mathematical expressions do follow a particular language with rules. In fact, the example on Wikipedia is actually a Java implementation of a RPN calculator.</p>
1
2009-10-09T18:39:03Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
1,545,441
<p>That's what the "eval" function does in Python.</p> <pre><code>result = eval(expression) </code></pre> <p>Beware though it can do a whole lot more, primarily call functions, so to be safe you should make sure it can't access the locals or globals. Also, you can access the builtin methods, including the tricky <strong>import</strong> so you need to block access to that as well:</p> <pre><code>result = eval(expression, {'__builtins__': None}, {}) </code></pre> <p>But that's only if you need security, that is if you allow anybody to type in any expression.</p> <p>Of course since you this way block all locla variables from use, then you don't have any variables to use, so to have that you need to pass in just those variables which should be accessed in the dictionaries.</p> <pre><code>vars = {'__builtins__': None, 'x': x} result = eval(expression, vars, {}) </code></pre> <p>or similar.</p>
1
2009-10-09T18:45:36Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
1,545,518
<p>If you're "academically interested", you want to learn about how to write a parser with operator precedence.</p> <p><a href="http://effbot.org/zone/simple-top-down-parsing.htm">Simple Top-Down Parsing in Python</a> is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathematical expressions.</p> <p>I can highly recommend having a go at writing your own first parser -- it's one of those "ah, <em>that's</em> how that works" moments!</p>
16
2009-10-09T18:59:59Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
1,545,813
<p>Another possibility is to look at <a href="http://pyparsing.wikispaces.com/" rel="nofollow">Pyparsing</a>, which is a general parser builder. It is more powerful than you need, but it may be faster to implement.</p>
2
2009-10-09T20:08:43Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
4,054,885
<p>The java alternative is here <a href="http://code.google.com/p/expressionoasis/" rel="nofollow">http://code.google.com/p/expressionoasis/</a></p>
0
2010-10-29T18:45:30Z
[ "python", "math" ]
Math Expression Evaluation
1,545,403
<p>What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.</p> <p>clarification: I need something slightly more advanced than eval() - I want to be able to add other operators (for example a maximum operator - 4$2 = 4) or, also I am more interested in this academically than professionaly - I want to know <i>how</i> to do this.</p>
10
2009-10-09T18:35:41Z
5,115,749
<p>This receipe gives the proper answer to your problem:</p> <p><a href="http://code.activestate.com/recipes/496746-restricted-safe-eval/" rel="nofollow">http://code.activestate.com/recipes/496746-restricted-safe-eval/</a></p> <p>It allows you to eval limited statement that can not harm your computer or your program.</p>
0
2011-02-25T09:48:23Z
[ "python", "math" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In this version the Connection should have the 'enable_load_extension' attribute. </p> <p>What I think is going on is that python still uses the native sqlite3 module which I think is 2.4.1 since sqlite3.version (i.s.o. sqlite3.version_info) produces 2.4.1. </p> <p>The question is how do I force python to use the new sqlite3 module for all sqlite3 calls?</p>
26
2009-10-09T18:53:31Z
1,545,853
<p>You need to look at your Python path and make sure that the sqlite you want is installed in an earlier directory than the built-in sqlite.</p> <p>You can see the path with:</p> <pre><code>import sys print sys.path </code></pre> <p>If you want to find out where a module is from, try:</p> <pre><code>print sqlite3.__file__ </code></pre>
3
2009-10-09T20:19:39Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In this version the Connection should have the 'enable_load_extension' attribute. </p> <p>What I think is going on is that python still uses the native sqlite3 module which I think is 2.4.1 since sqlite3.version (i.s.o. sqlite3.version_info) produces 2.4.1. </p> <p>The question is how do I force python to use the new sqlite3 module for all sqlite3 calls?</p>
26
2009-10-09T18:53:31Z
1,546,162
<p><code>sqlite3</code> support in Python can be a bit confusing. The sqlite database adapter started out as a separate project, <a href="https://github.com/ghaering/pysqlite">pysqlite2</a>, but for Python 2.5 a version of it was incorporated into the Python standard library under the name <a href="http://docs.python.org/library/sqlite3.html">sqlite3</a>. The original adapter continues to be developed as that separate project while periodically the version in Python itself is updated to match it. If you are trying to use a newer version of the adapter, it is usually installed as <code>pysqlite2</code> so as not to conflict with the version included in the standard library. And, depending how it was built, it may link to a different version of the underlying <a href="http://www.sqlite.org/">sqlite3 database library</a>. So make sure you are importing it properly:</p> <pre><code>&gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.version_info (2, 4, 1) &gt;&gt;&gt; sqlite3.sqlite_version_info (3, 6, 11) &gt;&gt;&gt; from pysqlite2 import dbapi2 as sqlite3 &gt;&gt;&gt; sqlite3.version_info (2, 5, 5) &gt;&gt;&gt; sqlite3.sqlite_version_info (3, 6, 18) </code></pre> <p><code>version_info</code> is the version of the <code>sqlite3</code> (<code>pysqlite2</code> or built-in <code>sqlite3</code>) database adapter. <code>sqlite_version_info</code> is the version of the underlying <code>sqlite3</code> database library.</p> <p>Using <code>from ... import ... as sqlite3</code> is suggested so that the rest of your code does not need to change if you move from one version to the other. </p> <p>Note, <a href="https://pysqlite.readthedocs.org/en/latest/sqlite3.html#sqlite3.Connection.enable_load_extension"><code>enable_load_extension</code></a> first appeared in <code>pysqlite2</code> 2.5.0.</p> <p><strong>EDIT:</strong> <code>enable_load_extension</code> is disabled by default when you build the adapter. To enable it, you can build <code>pysqlite2</code> manually. The following recipe assumes a <code>unix</code>-y system and the lastest version of <code>pysqlite2</code>, which as of this writing is 2.5.5.</p> <p>First, if you installed the adapter originally via <code>easy_install</code>, uninstall it by first running:</p> <pre><code>$ sudo /path/to/easy_install -m pysqlite # or whatever package name you first used </code></pre> <p>There will be some output from that including lines like:</p> <pre><code>Removing pysqlite 2.5.5 from easy-install.pth file Using /path/to/site-packages/pysqlite-2.5.5-py2.x-something.egg </code></pre> <p>Remove the egg using the file name listed (the name will vary depending on your platform and version and it may refer to a file or a directory):</p> <pre><code>$ sudo rm -r /path/to/site-packages/pysqlite-2.5.5-py2.x-something.egg </code></pre> <p>Now download and extract the <code>pysqlite-2.5.5</code> source tarball:</p> <pre><code>$ mkdir /tmp/build $ cd /tmp/build $ curl http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.5/pysqlite-2.5.5.tar.gz | tar xz $ cd pysqlite-2.5.5 </code></pre> <p>Then edit the <code>setup.cfg</code> file to comment out the <code>SQLITE_OMIT_LOAD_EXTENSION</code> directive:</p> <pre><code>$ ed setup.cfg &lt;&lt;EOF &gt; /SQLITE_OMIT_LOAD_EXTENSION/s/define=/#define=/ &gt; w &gt; q &gt; EOF </code></pre> <p>Since the version of <code>sqlite3</code> is so old (3.4.0), you should also build with the latest <code>sqlite3</code> library. This is made easy in the <code>pysqlite2</code> setup.py script:</p> <pre><code>$ /path/to/python2.x setup.py build_static </code></pre> <p>This will automatically download the latest <a href="http://www.sqlite.org/download.html">sqlite3 amalgamation source</a> and build the adapter along with an up-to-date statically-linked version of <code>sqlite3</code>. This step may take a long while to finish.</p> <p><strong>UPDATE (2015/07/21)</strong>: According to the latest <a href="https://github.com/ghaering/pysqlite/commit/2d7360cc94c652b8ebfd063940beeaa7451db9dd">pysqlite 2.6.3 commit</a> you <strong>have to</strong> download sqlite source code by yourself and put them in pysqlite root folder.</p> <p>Now, install the adapter:</p> <pre><code>$ sudo /path/to/python2.x setup.py install </code></pre> <p>and run the tests:</p> <pre><code>$ cd # somewhere out of the build directory $ /path/to/python2.x &gt;&gt;&gt; from pysqlite2 import test &gt;&gt;&gt; test.test() </code></pre> <p>and, if they pass, you should be all set.</p> <p>As a bonus, if the reason you want load extension support is to use <code>sqlite3</code>'s full text search extension, <code>FTS3</code>, you should find that it was included as part of the static library and no further work is necessary:</p> <pre><code>&gt;&gt;&gt; from pysqlite2 import dbapi2 as sqlite3 &gt;&gt;&gt; con = sqlite3.connect(":memory:") &gt;&gt;&gt; con.execute("create virtual table recipe using fts3(name, ingredients)") &lt;pysqlite2.dbapi2.Cursor object at 0xca5e0&gt; </code></pre>
61
2009-10-09T21:36:55Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In this version the Connection should have the 'enable_load_extension' attribute. </p> <p>What I think is going on is that python still uses the native sqlite3 module which I think is 2.4.1 since sqlite3.version (i.s.o. sqlite3.version_info) produces 2.4.1. </p> <p>The question is how do I force python to use the new sqlite3 module for all sqlite3 calls?</p>
26
2009-10-09T18:53:31Z
8,761,073
<p>I have python 2.7 on a windows machine and the built-in sqlite3.sqlite_version was 3.6.x. By performing the following steps I was able to get it to use sqlite 3.7.9.</p> <ol> <li>Download and unzip the pre-compiled binary DLL ("sqlite-dll-win32-x86-3070900.zip" on <a href="http://www.sqlite.org/download.html">http://www.sqlite.org/download.html</a>)</li> <li>(probably should close all instances of python at this point just to be safe) Go to C:\Python27\DLLs and change filename of "sqlite3.dll" to "sqlite3.dll.old"</li> <li>Copy the file "sqlite3.dll" to the folder C:\Python27\DLLs</li> <li>Open python shell and import sqlite3</li> <li>Verify sqlite3.sqlite_version shows up as '3.7.9'</li> </ol>
12
2012-01-06T16:30:22Z
[ "python", "sqlite", "sqlite3" ]
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version
1,545,479
<p>The error message I am trying to get rid of is:</p> <blockquote> <p>AttributeError: 'sqlite3.Connection' object has no attribute 'enable_load_extension'</p> </blockquote> <p>I have 'easy_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version_info produces 3.6.13. In this version the Connection should have the 'enable_load_extension' attribute. </p> <p>What I think is going on is that python still uses the native sqlite3 module which I think is 2.4.1 since sqlite3.version (i.s.o. sqlite3.version_info) produces 2.4.1. </p> <p>The question is how do I force python to use the new sqlite3 module for all sqlite3 calls?</p>
26
2009-10-09T18:53:31Z
22,231,194
<p>Instead of the standard Python <code>sqlite3</code> module, you might be able to use the <a href="https://github.com/rogerbinns/apsw" rel="nofollow">apsw</a> module, a third-party SQLite module that more closely follows the SQLite API. It includes support for loading extensions, as well as basically anything that is allowed in the SQLite C/C++ API. It also tries as much as possible to keep up to date with any new changes in SQLite.</p>
3
2014-03-06T17:05:22Z
[ "python", "sqlite", "sqlite3" ]
How to apply Loop to working Python Selenium Script?
1,545,602
<p>I'm trying to figure out how to apply a for-loop to this script and I'm having a lot of trouble. I want to iterate through a list of subdomains which are stored in csv format (ie: one column with 20 subdomains) and print the html for each. They all have the same SourceDomain. Thanks!</p> <pre><code>#Python 2.6 from selenium import selenium import unittest, time, re, csv, logging class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.SourceDomain.com") self.selenium.start() def test_untitled(self): sel = self.selenium sel.open("/dns/www.subdomains.com.html") sel.wait_for_page_to_load("30000") html = sel.get_html_source() print html def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() </code></pre>
0
2009-10-09T19:15:41Z
1,545,640
<pre><code>#Python 2.6 from selenium import selenium import unittest, time, re, csv, logging class Untitled(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*firefox", "http://www.SourceDomain.com") self.selenium.start() def test_untitled(self): sel = self.selenium spamReader = csv.reader(open('your_file.csv')) for row in spamReader: sel.open(row[0]) sel.wait_for_page_to_load("30000") print sel.get_html_source() def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() </code></pre> <p>BTW, notice there's no need to place this script wrapped inside a unittest testcase. Even better, you don't need selenium for such a simple task (at least at first sight).</p> <p>Try this:</p> <pre><code>import urllib2, csv def fetchsource(url): page = urllib2.urlopen(url) source = page.read() return source fooReader = csv.reader(open('your_file.csv')) for url in fooReader: print fetchsource(url) </code></pre>
3
2009-10-09T19:27:31Z
[ "python", "list", "csv", "selenium", "loops" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,545,624
<p>From <a href="http://en.wikipedia.org/wiki/K-means%5Fclustering" rel="nofollow">wikipedia</a>, you could use scipy, <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html" rel="nofollow">K-means clustering an vector quantization</a></p> <p>Or, you could use a Python wrapper for OpenCV, <a href="http://code.google.com/p/ctypes-opencv/" rel="nofollow">ctypes-opencv</a>.</p> <p>Or you could <a href="http://opencv.willowgarage.com/wiki/PythonInterface" rel="nofollow">OpenCV's new Python interface</a>, and their <a href="http://opencv.willowgarage.com/documentation/python/miscellaneous%5Ffunctions.html" rel="nofollow">kmeans</a> implementation.</p>
5
2009-10-09T19:21:30Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,545,672
<p>You can also use GDAL, which has many many functions to work with spatial data.</p>
0
2009-10-09T19:35:19Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
1,546,313
<p><a href="http://docs.scipy.org/doc/scipy/reference/cluster.html">Scipy's clustering</a> implementations work well, and they include a <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html">k-means</a> implementation.</p> <p>There's also <a href="http://code.google.com/p/scipy-cluster/">scipy-cluster</a>, which does agglomerative clustering; ths has the advantage that you don't need to decide on the number of clusters ahead of time.</p>
51
2009-10-09T22:10:57Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
2,224,488
<p>SciPy's <a href="http://docs.scipy.org/doc/scipy/reference/cluster.vq.html">kmeans2()</a> has some numerical problems: others have <a href="http://mail.scipy.org/pipermail/scipy-user/2009-February/019777.html">reported</a> error messages such as "Matrix is not positive definite - Cholesky decomposition cannot be computed" in version 0.6.0, and I just encountered the same in version 0.7.1.</p> <p>For now, I would recommend using <a href="http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/cluster/software.htm#pycluster">PyCluster</a> instead. Example usage:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; import Pycluster &gt;&gt;&gt; points = numpy.vstack([numpy.random.multivariate_normal(mean, 0.03 * numpy.diag([1,1]), 20) for mean in [(1, 1), (2, 4), (3, 2)]]) &gt;&gt;&gt; labels, error, nfound = Pycluster.kcluster(points, 3) &gt;&gt;&gt; labels # Cluster number for each point array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int32) &gt;&gt;&gt; error # The within-cluster sum of distances for the solution 1.7721661785401261 &gt;&gt;&gt; nfound # Number of times this solution was found 1 </code></pre>
27
2010-02-08T20:03:43Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
2,605,234
<p>For continuous data, k-means is very easy.</p> <p>You need a list of your means, and for each data point, find the mean its closest to and average the new data point to it. your means will represent the recent salient clusters of points in the input data.</p> <p>I do the averaging continuously, so there is no need to have the old data to obtain the new average. Given the old average <code>k</code>,the next data point <code>x</code>, and a constant <code>n</code> which is the number of past data points to keep the average of, the new average is</p> <pre><code>k*(1-(1/n)) + n*(1/n) </code></pre> <p>Here is the full code in Python</p> <pre><code>from __future__ import division from random import random # init means and data to random values # use real data in your code means = [random() for i in range(10)] data = [random() for i in range(1000)] param = 0.01 # bigger numbers make the means change faster # must be between 0 and 1 for x in data: closest_k = 0; smallest_error = 9999; # this should really be positive infinity for k in enumerate(means): error = abs(x-k[1]) if error &lt; smallest_error: smallest_error = error closest_k = k[0] means[closest_k] = means[closest_k]*(1-param) + x*(param) </code></pre> <p>you could just print the means when all the data has passed through, but its much more fun to watch it change in real time. I used this on frequency envelopes of 20ms bits of sound and after talking to it for a minute or two, it had consistent categories for the short 'a' vowel, the long 'o' vowel, and the 's' consonant. wierd!</p>
17
2010-04-09T05:21:50Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
6,572,959
<p>(Years later) this kmeans.py under <a href="http://stackoverflow.com/questions/5529625/is-it-possible-to-specify-your-own-distance-function-using-scikits-learn-k-means">is-it-possible-to-specify-your-own-distance-function-using-scikits-learn-k-means</a> is straightforward and reasonably fast; it uses any of the 20-odd metrics in scipy.spatial.distance.</p>
5
2011-07-04T14:43:41Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
7,405,341
<p>you can try the scikits-learn implementation: <a href="http://scikit-learn.sourceforge.net/modules/generated/scikits.learn.cluster.KMeans.html" rel="nofollow">http://scikit-learn.sourceforge.net/modules/generated/scikits.learn.cluster.KMeans.html</a></p>
1
2011-09-13T16:35:30Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
25,837,866
<p>Python's Pycluster and pyplot can be used for k-means clustering and for visualization of 2D data. A recent blog post <a href="http://remotalks.blogspot.com/2014/08/stock-pricevolume-analysis-using-python.html" rel="nofollow">Stock Price/Volume Analysis Using Python and PyCluster</a> gives an example of clustering using PyCluster on stock data.</p>
-1
2014-09-14T20:47:16Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
Python k-means algorithm
1,545,606
<p>I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates.</p>
41
2009-10-09T19:16:13Z
36,282,082
<p><strong>*This Code K-Means With Pyhon *</strong></p> <pre><code>from math import math from functions import functions class KMEANS: @staticmethod def KMeans(data,classterCount,globalCounter): counter=0 classes=[] cluster =[[]] cluster_index=[] tempClasses=[] for i in range(0,classterCount): globalCounter+=1 classes.append(cluster) cluster_index.append(cluster) tempClasses.append(cluster) classes2=classes[:] for i in range(0,len(classes)): globalCounter=1 cluster = [data[i]] classes[i]=cluster functions.ResetClasterIndex(cluster_index,classterCount,globalCounter) functions.ResetClasterIndex(classes2,classterCount,globalCounter) def clusterFills(classeses,globalCounter,counter): counter+=1 combinedOfClasses = functions.CopyTo(classeses) functions.ResetClasterIndex(cluster_index,classterCount,globalCounter) functions.ResetClasterIndex(tempClasses,classterCount,globalCounter) avarage=[] for k in range(0,len(combinedOfClasses)): globalCounter+=1 avarage.append(functions.GetAvarage(combinedOfClasses[k])) for i in range(0,len(data)): globalCounter+=1 minimum=0 index=0 for k in range(0,len(avarage)): total=0.0 for j in range(0,len(avarage[k])): total += (avarage[k][j]-data[i][j]) **2 tempp=math.sqrt(total) if(k==0): minimu=tempp if(tempp&amp;lt;=minimu): minimu=tempp index=k tempClasses[index].append(data[i]) cluster_index[index].append(i) if(functions.CompareArray(tempClasses,combinedOfClasses)==1): return clusterFills(tempClasses,globalCounter,counter) returnArray = [] returnArray.append(tempClasses) returnArray.append(cluster_index) returnArray.append(avarage) returnArray.append(counter) return returnArray cdcd = clusterFills(classes,globalCounter,counter) if cdcd !=None: return cdcd @staticmethod def KMeansPer(data,classterCount,globalCounter): perData=data[0:int(float(len(data))/100*30)] result = KMEANS.KMeans(perData,classterCount,globalCounter) cluster_index=[] tempClasses=[] classes=[] cluster =[[]] for i in range(0,classterCount): globalCounter+=1 classes.append(cluster) cluster_index.append(cluster) tempClasses.append(cluster) classes2=classes[:] for i in range(0,len(classes)): globalCounter=1 cluster = [data[i]] classes[i]=cluster functions.ResetClasterIndex(cluster_index,classterCount,globalCounter) functions.ResetClasterIndex(classes2,classterCount,globalCounter) counter=0 def clusterFills(classeses,globalCounter,counter): counter+=1 combinedOfClasses = functions.CopyTo(classeses) functions.ResetClasterIndex(cluster_index,classterCount,globalCounter) functions.ResetClasterIndex(tempClasses,classterCount,globalCounter) avarage=[] for k in range(0,len(combinedOfClasses)): globalCounter+=1 avarage.append(functions.GetAvarage(combinedOfClasses[k])) for i in range(0,len(data)): globalCounter+=1 minimum=0 index=0 for k in range(0,len(avarage)): total=0.0 for j in range(0,len(avarage[k])): total += (avarage[k][j]-data[i][j]) **2 tempp=math.sqrt(total) if(k==0): minimu=tempp if(tempp&amp;lt;=minimu): minimu=tempp index=k tempClasses[index].append(data[i]) cluster_index[index].append(i) if(functions.CompareArray(tempClasses,combinedOfClasses)==1): return clusterFills(tempClasses,globalCounter,counter) returnArray = [] returnArray.append(tempClasses) returnArray.append(cluster_index) returnArray.append(avarage) returnArray.append(counter) return returnArray cdcd = clusterFills(result[0],globalCounter,counter) if cdcd !=None: return cdcd </code></pre> <p><a href="http://teamistech.com/index.php/2016/03/26/python-diliyle-kumeleme-k-means/" rel="nofollow">Read </a>...</p>
-1
2016-03-29T10:44:55Z
[ "python", "algorithm", "cluster-analysis", "k-means" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,678
<p>Simple regular expression:</p> <pre><code>import re &gt;&gt;&gt; s = "Business -- way's" &gt;&gt;&gt; s = re.sub(r'[^\w\s]', '', s) &gt;&gt;&gt; s "Business ways" </code></pre>
14
2009-10-09T19:36:50Z
[ "python", "regex" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,687
<p>Or, if you don't want to use a regular expression for some reason:</p> <pre><code>''.join([x for x in foo if x.isalpha() or x.isspace()]) </code></pre>
6
2009-10-09T19:40:06Z
[ "python", "regex" ]
How do I replace all punctuation in my string with "" in Python?
1,545,655
<p>If my string was:</p> <pre><code>Business -- way's </code></pre> <p>I'd like to turn this into:</p> <pre><code>Business ways </code></pre> <p>ie. replace NON abc/123 into ""</p>
0
2009-10-09T19:32:19Z
1,545,841
<p>(regular expression) replace</p> <pre><code>[[:punct:]] </code></pre> <p>with '' (if Python supports that).</p> <p>[] is a character class, [::] is posix class syntax. [:punct:] is punctuation, so the character class for all punctuation marks would be [[:punct:]]</p> <p>An alternate way of the same thing is \p and friends: \p{IsPunct}</p> <p>See just below "Character Classes and other Special Escapes" in <a href="http://perldoc.perl.org/perlre.html" rel="nofollow">http://perldoc.perl.org/perlre.html</a> (yes, I know it's a Perl document, but this is more about regular expressions than Perl).</p> <p>That being said, the first answer with [^\w\s] answers what you explained a little more explicitly. This was more just an explanation of how to do what your question asked.</p>
-3
2009-10-09T20:16:05Z
[ "python", "regex" ]
Python mechanize doesn't click a button
1,545,698
<p>check the following script:</p> <pre><code>from mechanize import Browser br = Browser() page = br.open('http://scottishladiespool.com/register.php') br.select_form(nr = 5) r = br.click(type = "submit", nr = 0) print r.data #prints username=&amp;password1=&amp;password2=&amp;email=&amp;user_hide_email=1&amp;captcha_code=&amp;user_msn=&amp;user_yahoo=&amp;user_web=&amp;user_location=&amp;user_month=&amp;user_day=&amp;user_year=&amp;user_sig= </code></pre> <p>that is, it doesn't add the name=value pair of the submit button (register=Register). Why is this happening? ClientForm is working properly on other pages, but on this one it is not. I've tried setting the disabled and readonly attributes of submit control to True, but it didn't solve the problem.</p>
1
2009-10-09T19:43:12Z
1,545,819
<p>There is a <code>disabled=disabled</code> attribute on the register button. This prevents the user from clicking and presumably mechanize respects the <code>disabled</code> attribute as well.</p> <p>You'll need to change the source code of that button. Enabling the control means completely removing the <code>disabled=disabled</code> text. </p>
2
2009-10-09T20:10:05Z
[ "python", "mechanize", "clientform" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,887
<pre><code>re.sub('["-]+', '', s) </code></pre>
2
2009-10-09T20:26:43Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,896
<p>I'm curious as to why you are using a regular expression for this simple string replacement. The only advantage that I can see is that you can do it in one line of code instead of two, but I personally think that a replacement method is clearer than a regex for something like this.</p> <p>The string object has a <code>replace</code> method - <code>str.replace(old, new[, count])</code>, so use <code>replace("-", "")</code> and <code>replace("\"", "")</code>.</p> <p>Note that my syntax might be a little off - I'm still a python beginner.</p>
6
2009-10-09T20:28:31Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,898
<p><code>re.sub('[-"]', '', s)</code></p>
1
2009-10-09T20:28:44Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,926
<p>In Python 2.6:</p> <pre><code>print 'Hey -- How are "you"?'.translate(None, '-"') </code></pre> <p>Returns: </p> <pre><code>Hey How are you? </code></pre>
0
2009-10-09T20:34:21Z
[ "python", "regex" ]
How to replace the quote " and hyphen character in a string with nothing in Python?
1,545,878
<p>I'd like to replace <code>"</code> and <code>-</code></p> <p>with <code>""</code> nothing! make it disappear.</p> <p><code>s = re.sub(r'[^\w\s]', '', s)</code> this makes all punctuation disappear, but I just want those 2 characters. Thanks.</p>
1
2009-10-09T20:25:07Z
1,545,929
<p>In Python 2.6/2.7, you can use the helpful <code>translate()</code> method on strings. When using <code>None</code> as the first argument, this method has the special behavior of deleting all occurences of any character in the second argument. </p> <pre><code>&gt;&gt;&gt; s = 'No- dashes or "quotes"' &gt;&gt;&gt; s.translate(None, '"-') 'No dashes or quotes' </code></pre> <p>Per SilentGhost's comment, this gets to be cumbersome pretty quickly in both &lt;2.6 and >=3.0, because you have to explicitly create a translation table. That effort would only be worth it if you are performing this sort of operation a great deal.</p>
2
2009-10-09T20:35:13Z
[ "python", "regex" ]
Cart item management in python Turbogears 2.0
1,545,913
<p>I'm new to python an I decided to give it a try with TG2 by developing a small store. So far I've been loving it, but I'm guessing that my coding parading is still very attached to java's Like for example, the <code>add to cart</code> method in my CartController.</p> <pre><code>def add(self, **kw): pid=kw['pid'] product = model.Product.by_id(pid) cart = self.get_cart() # check if that product is already on the cart isInCart = False for item in cart.items: if item.product == product: # if it is, increment quantity cart.items.remove(item) isInCart = True item.quantity += 1 cart.items.append(item) break if not isInCart: item = model.CartItem(cart, product, 1, product.normalPrice) cart.items.append(item) DBSession.add(item) DBSession.flush() # updating values for fast retrieval showing # how many items are in the cart self.update_session(cart) return u'Item added to cart, %d items in session' % session['cartitems'] </code></pre> <p>This is certainly not the best way to achieve this, but so far it works as expected. In java I would just have to update the Item object, but here I have to remove it from the list then updated, then added again, is this correct?</p>
1
2009-10-09T20:31:31Z
1,548,537
<p>Since you are modifying the <code>item</code> object, I don't see any reason why you would have to remove, then append that item to the list. Why do you think you have to?</p> <p>As for making this more pythonic, you might consider something like this:</p> <pre><code>items_by_pid = dict([(item.product.pid, item) for item in cart.items]) item = items_by_pid.get(pid, None) if item is None: item = model.CartItem(cart, product, 0, product.normalPrice) cart.items.append(item) item.quantity += 1 </code></pre>
3
2009-10-10T17:28:31Z
[ "python", "turbogears2" ]
XML POST REST Request using Python
1,546,041
<p>Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create New Project heading) shown here:</p> <p><a href="http://www.getharvest.com/api/projects" rel="nofollow">http://www.getharvest.com/api/projects</a></p> <p>Here is the code I am trying to execute.</p> <pre><code>def postRequest(): """ Makes POST request to url, and returns a response. """ url = 'http://subdomain.harvestapp.com/projects' opener = urllib2.build_opener() opener.addheaders = [('Accept', 'application/xml'), ('Content-Type', 'application/xml'), ('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]), ('User-Agent', 'Python-urllib/2.6')] req = urllib2.Request(url=url, data=payload) assert req.get_method() == 'POST' response = self.opener.open(req) print response.code return response </code></pre> <p>I receive a response code 200 (Status OK) instead of a response code 201 (Created)...is this a question for the Harvest Support guys?</p> <p>Any hints anyone has would be greatly appreciated.</p> <p>Thanks, Jeff.</p>
5
2009-10-09T21:05:37Z
1,546,053
<p>It's common to return a 200 response even when a 201 response would strictly be more appropriate. Are you sure that the request isn't correctly processed even if you are getting a 'correct' response?</p>
1
2009-10-09T21:08:55Z
[ "python", "xml", "rest", "post", "harvest" ]
XML POST REST Request using Python
1,546,041
<p>Does anyone have a simple example of sending an XML POST request to a RESTful API with Python? I am trying to use the urllib2 Python library to "create a new project" in the Harvest API, with no luck. The payload variable is a valid XML document that is a near copy/paste of their documentation (under the Create New Project heading) shown here:</p> <p><a href="http://www.getharvest.com/api/projects" rel="nofollow">http://www.getharvest.com/api/projects</a></p> <p>Here is the code I am trying to execute.</p> <pre><code>def postRequest(): """ Makes POST request to url, and returns a response. """ url = 'http://subdomain.harvestapp.com/projects' opener = urllib2.build_opener() opener.addheaders = [('Accept', 'application/xml'), ('Content-Type', 'application/xml'), ('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password))[:-1]), ('User-Agent', 'Python-urllib/2.6')] req = urllib2.Request(url=url, data=payload) assert req.get_method() == 'POST' response = self.opener.open(req) print response.code return response </code></pre> <p>I receive a response code 200 (Status OK) instead of a response code 201 (Created)...is this a question for the Harvest Support guys?</p> <p>Any hints anyone has would be greatly appreciated.</p> <p>Thanks, Jeff.</p>
5
2009-10-09T21:05:37Z
5,676,794
<p>You're using a local opener everywhere except on the line where you create the response, where you use <code>self.opener</code>, which looks like the problem.</p>
1
2011-04-15T12:34:14Z
[ "python", "xml", "rest", "post", "harvest" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no trouble displaying the pages, although I can't see the parts I want when I view page source.</p> <p>A sample url is <a href="https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT" rel="nofollow">https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT</a></p> <p>I'd like, for example, average maturity and average duration from the lower right of the page. The problem isn't extracting that info from the page, it's downloading the page so that I can extract the info.</p>
0
2009-10-09T21:16:59Z
1,546,104
<p>The page uses JavaScript to load the data. Firefox and Chrome are only working because you have JavaScript enabled - try disabling it and you'll get a mostly empty page.</p> <p>Python isn't going to be able to do this by itself - your best compromise would be to control a real browser (Internet Explorer is easiest, if you're on Windows) from Python using something like <a href="http://pamie.sourceforge.net/" rel="nofollow">Pamie</a>.</p>
2
2009-10-09T21:21:44Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no trouble displaying the pages, although I can't see the parts I want when I view page source.</p> <p>A sample url is <a href="https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT" rel="nofollow">https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT</a></p> <p>I'd like, for example, average maturity and average duration from the lower right of the page. The problem isn't extracting that info from the page, it's downloading the page so that I can extract the info.</p>
0
2009-10-09T21:16:59Z
1,546,109
<p>The reason why is because it's performing AJAX calls after it loads. You will need to account for searching out those URLs to scrape it's content as well.</p>
0
2009-10-09T21:23:21Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no trouble displaying the pages, although I can't see the parts I want when I view page source.</p> <p>A sample url is <a href="https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT" rel="nofollow">https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT</a></p> <p>I'd like, for example, average maturity and average duration from the lower right of the page. The problem isn't extracting that info from the page, it's downloading the page so that I can extract the info.</p>
0
2009-10-09T21:16:59Z
1,546,134
<p>As RichieHindle mentioned, your best bet on Windows is to use the WebBrowser class to create an instance of an IE rendering engine and then use that to browse the site.</p> <p>The class gives you full access to the DOM tree, so you can do whatever you want with it.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser%28loband%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser%28loband%29.aspx</a></p>
0
2009-10-09T21:29:55Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no trouble displaying the pages, although I can't see the parts I want when I view page source.</p> <p>A sample url is <a href="https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT" rel="nofollow">https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT</a></p> <p>I'd like, for example, average maturity and average duration from the lower right of the page. The problem isn't extracting that info from the page, it's downloading the page so that I can extract the info.</p>
0
2009-10-09T21:16:59Z
1,546,213
<p>Try iMacros. I am very positive it will solve your problem.</p> <p><a href="http://www.iopus.com/imacros/firefox/?ref=fxmoz" rel="nofollow">http://www.iopus.com/imacros/firefox/?ref=fxmoz</a></p>
0
2009-10-09T21:45:18Z
[ "python", "screen-scraping" ]
web scraping a problem site
1,546,089
<p>I'm trying to scrape some information from a web site, but am having trouble reading the relevant pages. The pages seem to first send a basic setup, then more detailed info. My download attempts only seem to capture the basic setup. I've tried urllib and mechanize so far.</p> <p>Firefox and Chrome have no trouble displaying the pages, although I can't see the parts I want when I view page source.</p> <p>A sample url is <a href="https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT" rel="nofollow">https://personal.vanguard.com/us/funds/snapshot?FundId=0542&amp;FundIntExt=INT</a></p> <p>I'd like, for example, average maturity and average duration from the lower right of the page. The problem isn't extracting that info from the page, it's downloading the page so that I can extract the info.</p>
0
2009-10-09T21:16:59Z
1,546,280
<p>The website loads the data via ajax. <a href="http://getfirebug.com" rel="nofollow">Firebug</a> shows the ajax calls. For the given page, the data is loaded from <a href="https://personal.vanguard.com/us/JSP/Funds/VGITab/VGIFundOverviewTabContent.jsf?FundIntExt=INT&amp;FundId=0542" rel="nofollow">https://personal.vanguard.com/us/JSP/Funds/VGITab/VGIFundOverviewTabContent.jsf?FundIntExt=INT&amp;FundId=0542</a></p> <p>See the corresponding javascript code on the original page:</p> <pre><code>&lt;script&gt;populator = new Populator({parentId: "profileForm:vanguardFundTabBox:tab0",execOnLoad:true, populatorUrl:"/us/JSP/Funds/VGITab/VGIFundOverviewTabContent.jsf?FundIntExt=INT&amp;FundId=0542", inline:fals e,type:"once"}); &lt;/script&gt; </code></pre>
1
2009-10-09T22:00:26Z
[ "python", "screen-scraping" ]
What is needed to add an paperprint-like effect to photos in python?
1,546,205
<p>I want to transform photos in python to look like this:</p> <p><img src="http://media.doctype.com/4b4bb461-1f1f-4c0e-9fc4-b4626e672b27.png" alt="a paper printed-like pic" /> taken from <a href="http://doctype.com" rel="nofollow">doctype.com</a></p> <p>I will use it in django, PIL is installed.</p> <p>How can I achieve this?</p>
1
2009-10-09T21:43:42Z
1,546,291
<p>This is a combination of several subtle effects. It starts by a nonlinear deformation, and then a tasteful drop shadow is added. There's also a small border. I'd start by drawing one straight, vertical line on the above picture, and then seeing how you would transform to that from the original picture. Then, apply that transformation to the whole photo, add some drop shadow, and figure out what else is left...</p>
3
2009-10-09T22:04:01Z
[ "python", "django", "image", "python-imaging-library" ]
What is needed to add an paperprint-like effect to photos in python?
1,546,205
<p>I want to transform photos in python to look like this:</p> <p><img src="http://media.doctype.com/4b4bb461-1f1f-4c0e-9fc4-b4626e672b27.png" alt="a paper printed-like pic" /> taken from <a href="http://doctype.com" rel="nofollow">doctype.com</a></p> <p>I will use it in django, PIL is installed.</p> <p>How can I achieve this?</p>
1
2009-10-09T21:43:42Z
1,546,378
<p>I've had a bit better luck with ImageMagick when it comes to more complex transformations. You would have to install it separately and though there is a python library it doesn't appear well documented so I've just used command line calls.</p> <p>Here is a good <a href="http://www.imagemagick.org/Usage/warping/" rel="nofollow">tutorial on warping image</a>: And <a href="http://www.imagemagick.org/Usage/" rel="nofollow">another tutorial on general use</a></p> <p>The drop shadow is probably just a second image which is composited with the first image.</p>
2
2009-10-09T22:33:18Z
[ "python", "django", "image", "python-imaging-library" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,244
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub(' +',' ','The quick brown fox') 'The quick brown fox' </code></pre>
140
2009-10-09T21:52:29Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,245
<pre><code>import re s = "The fox jumped over the log." re.sub("\s\s+" , " ", s) </code></pre> <p>or</p> <pre><code>re.sub("\s\s+", " ", s) </code></pre> <p>since the space before comma is listed as a <em>pet peeve</em> in PEP8, as mentioned by moose in the comments.</p>
46
2009-10-09T21:52:30Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,251
<p>foo is your string:</p> <pre><code>" ".join(foo.split()) </code></pre>
228
2009-10-09T21:52:56Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,272
<p>Similar to the previous solutions, but more specific: replace two or more spaces with one:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "The fox jumped over the log." &gt;&gt;&gt; re.sub('\s{2,}', ' ', s) 'The fox jumped over the log.' </code></pre>
10
2009-10-09T21:58:27Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
1,546,883
<p>Have to agree with Paul McGuire's comment above. To me, </p> <pre><code> ' '.join(the_string.split()) </code></pre> <p>is vastly preferable to whipping out a regex. My measurements (Linux, Python 2.5) show the split-then-join to be almost 5 times faster than doing the "re.sub(...)", and still 3 times faster if you precompile the regex once and do the operation multiple times. And it is by any measure easier to understand -- <em>much</em> more pythonic.</p>
24
2009-10-10T02:39:51Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
11,647,579
<p>Other alternative</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; str = 'this is a string with multiple spaces and tabs' &gt;&gt;&gt; str = re.sub('[ \t]+' , ' ', str) &gt;&gt;&gt; print str this is a string with multiple spaces and tabs </code></pre>
2
2012-07-25T10:19:34Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
15,913,564
<p>Using regexes with "\s" and doing simple string.split()'s will <em>also</em> remove other whitespace - like newlines, carriage returns, tabs. Unless this is desired, to <strong>only</strong> do <em>multiple spaces</em>, I present these examples.</p> <hr> <p><strong>EDIT:</strong> As I'm wont to do, I slept on this, and besides correcting a typo on the last results (v3.3.3 @ 64-bit, <em>not</em> 32-bit), the obvious hit me: the test string was rather trivial.</p> <p>So, I got <a href="http://www.lipsum.com" rel="nofollow">... 11 paragraphs, 1000 words, 6665 bytes of Lorem Ipsum</a> to get more-realistic time tests. I then added random-length extra spaces throughout:</p> <pre><code>original_string = ''.join(word + (' ' * random.randint(1, 10)) for word in lorem_ipsum.split(' ')) </code></pre> <p>I also corrected the "proper <code>join</code>"; if one cares, the one-liner will essentially do a strip of any leading/trailing spaces, this corrected version preserves a leading/trailing space (but only <em>ONE</em> ;-). (I found this because the randomly-spaced <code>lorem_ipsum</code> got extra spaces on the end and thus failed the <code>assert</code>.)</p> <hr> <pre><code># setup = ''' import re def while_replace(string): while ' ' in string: string = string.replace(' ', ' ') return string def re_replace(string): return re.sub(r' {2,}' , ' ', string) def proper_join(string): split_string = string.split(' ') # To account for leading/trailing spaces that would simply be removed beg = ' ' if not split_string[ 0] else '' end = ' ' if not split_string[-1] else '' # versus simply ' '.join(item for item in string.split(' ') if item) return beg + ' '.join(item for item in split_string if item) + end original_string = """Lorem ipsum ... no, really, it kept going... malesuada enim feugiat. Integer imperdiet erat.""" assert while_replace(original_string) == re_replace(original_string) == proper_join(original_string) #''' </code></pre> <hr> <pre><code># while_replace_test new_string = original_string[:] new_string = while_replace(new_string) assert new_string != original_string </code></pre> <hr> <pre><code># re_replace_test new_string = original_string[:] new_string = re_replace(new_string) assert new_string != original_string </code></pre> <hr> <pre><code># proper_join_test new_string = original_string[:] new_string = proper_join(new_string) assert new_string != original_string </code></pre> <p><strong>NOTE:</strong> <s>The "<code>while</code> version" made a copy of the <code>original_string</code>, as I believe once modified on the first run, successive runs would be faster (if only by a bit). As this adds time, I added this string copy to the other two so that the times showed the difference only in the logic.</s> <a href="http://docs.python.org/2/library/timeit.html#timeit.Timer.timeit" rel="nofollow">Keep in mind that the main <code>stmt</code> on <code>timeit</code> instances will only be executed once</a>; the original way I did this, the <code>while</code> loop worked on the same label, <code>original_string</code>, thus the second run, there would be nothing to do. The way it's set up now, calling a function, using two different labels, that isn't a problem. I've added <code>assert</code> statements to all the workers to verify we change something every iteration (for those who may be dubious). E.g., change to this and it breaks:</p> <pre><code># while_replace_test new_string = original_string[:] new_string = while_replace(new_string) assert new_string != original_string # will break the 2nd iteration while ' ' in original_string: original_string = original_string.replace(' ', ' ') </code></pre> <hr> <pre><code>Tests run on a laptop with an i5 processor running Windows 7 (64-bit). timeit.Timer(stmt = test, setup = setup).repeat(7, 1000) test_string = 'The fox jumped over\n\t the log.' # trivial Python 2.7.3, 32-bit, Windows test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.001066 | 0.001260 | 0.001128 | 0.001092 re_replace_test | 0.003074 | 0.003941 | 0.003357 | 0.003349 proper_join_test | 0.002783 | 0.004829 | 0.003554 | 0.003035 Python 2.7.3, 64-bit, Windows test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.001025 | 0.001079 | 0.001052 | 0.001051 re_replace_test | 0.003213 | 0.004512 | 0.003656 | 0.003504 proper_join_test | 0.002760 | 0.006361 | 0.004626 | 0.004600 Python 3.2.3, 32-bit, Windows test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.001350 | 0.002302 | 0.001639 | 0.001357 re_replace_test | 0.006797 | 0.008107 | 0.007319 | 0.007440 proper_join_test | 0.002863 | 0.003356 | 0.003026 | 0.002975 Python 3.3.3, 64-bit, Windows test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.001444 | 0.001490 | 0.001460 | 0.001459 re_replace_test | 0.011771 | 0.012598 | 0.012082 | 0.011910 proper_join_test | 0.003741 | 0.005933 | 0.004341 | 0.004009 </code></pre> <hr> <pre><code>test_string = lorem_ipsum # Thanks to http://www.lipsum.com/ # "Generated 11 paragraphs, 1000 words, 6665 bytes of Lorem Ipsum" Python 2.7.3, 32-bit test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.342602 | 0.387803 | 0.359319 | 0.356284 re_replace_test | 0.337571 | 0.359821 | 0.348876 | 0.348006 proper_join_test | 0.381654 | 0.395349 | 0.388304 | 0.388193 Python 2.7.3, 64-bit test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.227471 | 0.268340 | 0.240884 | 0.236776 re_replace_test | 0.301516 | 0.325730 | 0.308626 | 0.307852 proper_join_test | 0.358766 | 0.383736 | 0.370958 | 0.371866 Python 3.2.3, 32-bit test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.438480 | 0.463380 | 0.447953 | 0.446646 re_replace_test | 0.463729 | 0.490947 | 0.472496 | 0.468778 proper_join_test | 0.397022 | 0.427817 | 0.406612 | 0.402053 Python 3.3.3, 64-bit test | minum | maximum | average | median ---------------------+------------+------------+------------+----------- while_replace_test | 0.284495 | 0.294025 | 0.288735 | 0.289153 re_replace_test | 0.501351 | 0.525673 | 0.511347 | 0.508467 proper_join_test | 0.422011 | 0.448736 | 0.436196 | 0.440318 </code></pre> <p>For the trivial string, it would seem that a while-loop is the fastest, followed by the Pythonic string-split/join, and regex pulling up the rear.</p> <p><strong>For non-trivial strings</strong>, seems there's a bit more to consider. 32-bit 2.7? It's regex to the rescue! 2.7 64-bit? A <code>while</code> loop is best, by a decent margin. 32-bit 3.2, go with the "proper" <code>join</code>. 64-bit 3.3, go for a <code>while</code> loop. Again.</p> <p>In the end, one can improve performance <em>if/where/when needed</em>, but it's always best to <a href="http://c2.com/cgi/wiki?MakeItWorkMakeItRightMakeItFast" rel="nofollow">remember the mantra</a>:</p> <ol> <li>Make It Work</li> <li>Make It Right</li> <li>Make It Fast</li> </ol> <p>IANAL, YMMV, Caveat Emptor!</p>
26
2013-04-09T22:16:21Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
26,810,316
<p>If it's whitespace you're dealing with splitting on None will not include empty string in the returned value.</p> <p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#str.split</a></p>
0
2014-11-07T21:24:11Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
33,514,861
<p>A simple soultion</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s="The fox jumped over the log." &gt;&gt;&gt; print re.sub('\s+',' ', s) The fox jumped over the log. </code></pre>
3
2015-11-04T06:11:39Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
35,391,471
<pre><code>string='This is a string full of spaces and taps' string=string.split(' ') while '' in string: string.remove('') string=' '.join(string) print(string) </code></pre> <p><strong>results</strong>:</p> <blockquote> <p>This is a string full of spaces and taps</p> </blockquote>
0
2016-02-14T11:58:36Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
37,510,714
<p>One line of code to remove all extra spaces before, after, and within a sentence: </p> <pre><code>sentence = " The fox jumped over the log. " sentence = ' '.join(filter(None,sentence.split(' '))) </code></pre> <p>Explanation:</p> <ol> <li>Split entire string into list.</li> <li>Filter empty elements from list.</li> <li>Rejoin remaining elements* with single space </li> </ol> <p>*Remaining elements should be words or words with punctuations, etc. I did not test this extensively, but this should be a good starting point. All the best!</p>
1
2016-05-29T13:52:54Z
[ "python", "regex", "string" ]
A simple way to remove multiple spaces in a string in Python
1,546,226
<p>Suppose this is the string:</p> <pre><code>The fox jumped over the log. </code></pre> <p>It would result in:</p> <pre><code>The fox jumped over the log. </code></pre> <p>What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...</p>
119
2009-10-09T21:48:37Z
39,322,245
<p>This also seems to work:</p> <pre><code>while " " in s: s=s.replace(" "," ") </code></pre> <p>Where the variable s represents your string.</p>
0
2016-09-04T23:11:32Z
[ "python", "regex", "string" ]
Using enums in ctypes.Structure
1,546,355
<p>I have a struct I'm accessing via ctypes:</p> <pre><code>struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; </code></pre> <p>So far I have Python code like:</p> <pre><code># struct attropl class attropl(Structure): pass attrl._fields_ = [ ("next", POINTER(attropl)), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p), </code></pre> <p>But I'm not sure what to use for the <code>batch_op</code> enum. Should I just map it to a <code>c_int</code> or ?</p>
6
2009-10-09T22:25:11Z
1,546,366
<p>Using <code>c_int</code> or <code>c_uint</code> would be fine. Alternatively, there is a <a href="http://code.activestate.com/recipes/576415/" rel="nofollow">recipe in the cookbook</a> for an Enumeration class.</p>
4
2009-10-09T22:29:26Z
[ "python", "enums", "ctypes" ]
Using enums in ctypes.Structure
1,546,355
<p>I have a struct I'm accessing via ctypes:</p> <pre><code>struct attrl { char *name; char *resource; char *value; struct attrl *next; enum batch_op op; }; </code></pre> <p>So far I have Python code like:</p> <pre><code># struct attropl class attropl(Structure): pass attrl._fields_ = [ ("next", POINTER(attropl)), ("name", c_char_p), ("resource", c_char_p), ("value", c_char_p), </code></pre> <p>But I'm not sure what to use for the <code>batch_op</code> enum. Should I just map it to a <code>c_int</code> or ?</p>
6
2009-10-09T22:25:11Z
1,546,467
<p>At least for GCC <code>enum</code> is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as <code>signed</code> or <code>unsigned</code>. I guess it cannot exceed <code>long long int</code>, but practically you should check the range of your <code>enum</code>s and choose something like <code>c_uint</code>.</p> <p>Here is an example. The C program:</p> <pre><code>enum batch_op { OP1 = 2, OP2 = 3, OP3 = -1, }; struct attrl { char *name; struct attrl *next; enum batch_op op; }; void f(struct attrl *x) { x-&gt;op = OP3; } </code></pre> <p>and the Python one:</p> <pre><code>from ctypes import (Structure, c_char_p, c_uint, c_int, POINTER, CDLL) class AttrList(Structure): pass AttrList._fields_ = [ ('name', c_char_p), ('next', POINTER(AttrList)), ('op', c_int), ] (OP1, OP2, OP3) = (2, 3, -1) enum = CDLL('./libenum.so') enum.f.argtypes = [POINTER(AttrList)] enum.f.restype = None a = AttrList(name=None, next=None, op=OP2) assert a.op == OP2 enum.f(a) assert a.op == OP3 </code></pre>
7
2009-10-09T23:05:34Z
[ "python", "enums", "ctypes" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.html"> smtplib </a> supports CC-ing and BCC-ing while sending emails.</p> <p>Looking for suggestions how to do CC or BCC sending messages from the python script.</p> <p>(And — no, I'm not creating a script to spam anyone outside of my testing environment.)</p>
51
2009-10-09T22:29:46Z
1,546,406
<p>The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient. </p> <p>TO - There is a TO: header with this recipient's address</p> <p>CC - There is a CC: header with this recipient's address</p> <p>BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.</p> <p>If you have </p> <pre><code>TO: abc@company.com CC: xyz@company.com BCC: boss@company.com </code></pre> <p>You have three recipients. The headers in the email body will include only the TO: and CC:</p>
12
2009-10-09T22:41:38Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.html"> smtplib </a> supports CC-ing and BCC-ing while sending emails.</p> <p>Looking for suggestions how to do CC or BCC sending messages from the python script.</p> <p>(And — no, I'm not creating a script to spam anyone outside of my testing environment.)</p>
51
2009-10-09T22:29:46Z
1,546,410
<p>You can try MIMEText</p> <pre><code>msg = MIMEText('text') msg['to'] = msg['cc'] = </code></pre> <p>then send msg.as_string()</p> <p><a href="http://docs.python.org/library/email-examples.html">http://docs.python.org/library/email-examples.html</a></p>
12
2009-10-09T22:42:55Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.html"> smtplib </a> supports CC-ing and BCC-ing while sending emails.</p> <p>Looking for suggestions how to do CC or BCC sending messages from the python script.</p> <p>(And — no, I'm not creating a script to spam anyone outside of my testing environment.)</p>
51
2009-10-09T22:29:46Z
1,546,435
<p>Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.</p> <pre><code>toaddr = 'buffy@sunnydale.k12.ca.us' cc = ['alexander@sunydale.k12.ca.us','willow@sunnydale.k12.ca.us'] bcc = ['chairman@slayerscouncil.uk'] fromaddr = 'giles@sunnydale.k12.ca.us' message_subject = "disturbance in sector 7" message_text = "Three are dead in an attack in the sewers below sector 7." message = "From: %s\r\n" % fromaddr + "To: %s\r\n" % toaddr + "CC: %s\r\n" % ",".join(cc) + "Subject: %s\r\n" % message_subject + "\r\n" + message_text toaddrs = [toaddr] + cc + bcc server = smtplib.SMTP('smtp.sunnydale.k12.ca.us') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, message) server.quit() </code></pre>
85
2009-10-09T22:52:29Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.html"> smtplib </a> supports CC-ing and BCC-ing while sending emails.</p> <p>Looking for suggestions how to do CC or BCC sending messages from the python script.</p> <p>(And — no, I'm not creating a script to spam anyone outside of my testing environment.)</p>
51
2009-10-09T22:29:46Z
29,627,094
<p>Don't add the bcc header.</p> <p>See this: <a href="http://mail.python.org/pipermail/email-sig/2004-September/000151.html">http://mail.python.org/pipermail/email-sig/2004-September/000151.html</a></p> <p>And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since the envelope information is separate from the message headers, you can even BCC someone by including them in the method argument but not in the message header.""" from <a href="http://pymotw.com/2/smtplib">http://pymotw.com/2/smtplib</a></p> <pre><code>toaddr = 'buffy@sunnydale.k12.ca.us' cc = ['alexander@sunydale.k12.ca.us','willow@sunnydale.k12.ca.us'] bcc = ['chairman@slayerscouncil.uk'] fromaddr = 'giles@sunnydale.k12.ca.us' message_subject = "disturbance in sector 7" message_text = "Three are dead in an attack in the sewers below sector 7." message = "From: %s\r\n" % fromaddr + "To: %s\r\n" % toaddr + "CC: %s\r\n" % ",".join(cc) # don't add this, otherwise "to and cc" receivers will know who are the bcc receivers # + "BCC: %s\r\n" % ",".join(bcc) + "Subject: %s\r\n" % message_subject + "\r\n" + message_text toaddrs = [toaddr] + cc + bcc server = smtplib.SMTP('smtp.sunnydale.k12.ca.us') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, message) server.quit() </code></pre>
7
2015-04-14T12:17:55Z
[ "python", "email", "testing" ]
python: how to send mail with TO, CC and BCC?
1,546,367
<p>I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like <a href="http://docs.python.org/library/smtplib.html"> smtplib </a> supports CC-ing and BCC-ing while sending emails.</p> <p>Looking for suggestions how to do CC or BCC sending messages from the python script.</p> <p>(And — no, I'm not creating a script to spam anyone outside of my testing environment.)</p>
51
2009-10-09T22:29:46Z
29,936,403
<p>Key thing is to add the recipients as a <em>list of email ids</em> in your sendmail call.</p> <pre><code>import smtplib from email.mime.multipart import MIMEMultipart me = "user63503@gmail.com" to = "someone@gmail.com" cc = "anotherperson@gmail.com,someone@yahoo.com" bcc = "bccperson1@gmail.com,bccperson2@yahoo.com" rcpt = cc.split(",") + bcc.split(",") + [to] msg = MIMEMultipart('alternative') msg['Subject'] = "my subject" msg['To'] = to msg['Cc'] = cc msg['Bcc'] = bcc msg.attach(my_msg_body) server = smtplib.SMTP("localhost") # or your smtp server server.sendmail(me, rcpt, msg.as_string()) server.quit() </code></pre>
6
2015-04-29T06:57:03Z
[ "python", "email", "testing" ]
Parallel Python: How do I supply arguments to 'submit'?
1,546,429
<p>This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.</p> <p>The following is the API (I think it's called) that submits all pertinent info to pp.</p> <pre><code> def submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() """ </code></pre> <p>Here is my submit statement with its arguments:</p> <pre><code>job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) </code></pre> <p>All the capitalized names in <code>depfuncs</code> are the names of classes. I wasn't sure where to put the classes or even if I would need to include them as they are in the <code>globals()</code> dictionary. But when I ran it with the <code>depfuncs()</code> empty, it would raise an error such as "<code>Tree not defined</code>" (for example).</p> <p>Now, <code>key_seq</code> is a generator, so I have to work with an instance of it in order to be able to use <code>.next()</code>:</p> <pre><code>def key_seq(): a = 0 while True: yield a a = a + 1 ks = key_seq() </code></pre> <p><code>ks</code> is defined in <code>globals()</code>. When I didn't include it anywhere else, I got an error saying '<code>ks is not defined</code>'. When I include <code>ks</code> in <code>depfuncs</code>, this is the error:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\Code\gppp.py", line 459, in &lt;module&gt; job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, ks, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) File "C:\Python26\lib\site-packages\pp.py", line 449, in submit sfunc = self.__dumpsfunc((func, ) + depfuncs, modules) File "C:\Python26\lib\site-packages\pp.py", line 634, in __dumpsfunc sources = [self.__get_source(func) for func in funcs] File "C:\Python26\lib\site-packages\pp.py", line 713, in __get_source sourcelines = inspect.getsourcelines(func)[0] File "C:\Python26\lib\inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "C:\Python26\lib\inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "C:\Python26\lib\inspect.py", line 441, in getsourcefile filename = getfile(object) File "C:\Python26\lib\inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object </code></pre> <p>I'm pretty sure <code>arg</code> is referring to <code>ks</code>. So, where do I tell <code>.submit()</code> about <code>ks</code>? I don't understand what's supposed to go where. Thanks.</p>
5
2009-10-09T22:49:43Z
1,546,601
<p>I think you should be passing in lambda:ks.next() instead of plain old ks</p>
0
2009-10-09T23:56:23Z
[ "python", "parallel-python" ]
Parallel Python: How do I supply arguments to 'submit'?
1,546,429
<p>This is only the second question with the parallel-python tag. After looking through the documentation and googling for the subject, I've come here as it's where I've had the best luck with answers and suggestions.</p> <p>The following is the API (I think it's called) that submits all pertinent info to pp.</p> <pre><code> def submit(self, func, args=(), depfuncs=(), modules=(), callback=None, callbackargs=(), group='default', globals=None): """Submits function to the execution queue func - function to be executed args - tuple with arguments of the 'func' depfuncs - tuple with functions which might be called from 'func' modules - tuple with module names to import callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function group - job group, is used when wait(group) is called to wait for jobs in a given group to finish globals - dictionary from which all modules, functions and classes will be imported, for instance: globals=globals() """ </code></pre> <p>Here is my submit statement with its arguments:</p> <pre><code>job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) </code></pre> <p>All the capitalized names in <code>depfuncs</code> are the names of classes. I wasn't sure where to put the classes or even if I would need to include them as they are in the <code>globals()</code> dictionary. But when I ran it with the <code>depfuncs()</code> empty, it would raise an error such as "<code>Tree not defined</code>" (for example).</p> <p>Now, <code>key_seq</code> is a generator, so I have to work with an instance of it in order to be able to use <code>.next()</code>:</p> <pre><code>def key_seq(): a = 0 while True: yield a a = a + 1 ks = key_seq() </code></pre> <p><code>ks</code> is defined in <code>globals()</code>. When I didn't include it anywhere else, I got an error saying '<code>ks is not defined</code>'. When I include <code>ks</code> in <code>depfuncs</code>, this is the error:</p> <pre><code>Traceback (most recent call last): File "C:\Python26\Code\gppp.py", line 459, in &lt;module&gt; job_server.submit(reify, (pop1, pop2, 1000), depfuncs = (key_seq, ks, Chromosome, Params, Node, Tree), modules = ("math",), callback = sum.add, globals = globals()) File "C:\Python26\lib\site-packages\pp.py", line 449, in submit sfunc = self.__dumpsfunc((func, ) + depfuncs, modules) File "C:\Python26\lib\site-packages\pp.py", line 634, in __dumpsfunc sources = [self.__get_source(func) for func in funcs] File "C:\Python26\lib\site-packages\pp.py", line 713, in __get_source sourcelines = inspect.getsourcelines(func)[0] File "C:\Python26\lib\inspect.py", line 678, in getsourcelines lines, lnum = findsource(object) File "C:\Python26\lib\inspect.py", line 519, in findsource file = getsourcefile(object) or getfile(object) File "C:\Python26\lib\inspect.py", line 441, in getsourcefile filename = getfile(object) File "C:\Python26\lib\inspect.py", line 418, in getfile raise TypeError('arg is not a module, class, method, ' TypeError: arg is not a module, class, method, function, traceback, frame, or code object </code></pre> <p>I'm pretty sure <code>arg</code> is referring to <code>ks</code>. So, where do I tell <code>.submit()</code> about <code>ks</code>? I don't understand what's supposed to go where. Thanks.</p>
5
2009-10-09T22:49:43Z
1,547,579
<p>interesting - are you doing genetics simulations? i ask because i see 'Chromosome' in there, and I once developed a population genetics simulation using parallel python.</p> <p>your approach looks really complicated. in my parallel python program, i used the following call:</p> <pre><code>job = jobServer.submit( doRun, (param,)) </code></pre> <p>how did i get away with this? the trick is that the doRun function doesn't run in the same context as the context in which you call sumbit. For instance (contrived example):</p> <pre><code>import os, pp def doRun(param): print "your name is %s!" % os.getlogin() jobServer = pp.Server() jobServer.submit( doRun, (param,)) </code></pre> <p>this code will fail. this is because the os module doesn't exist in doRun - doRun is not running in the same context as submit. sure, you can pass <code>os</code> in the <code>module</code> parameter of <code>submit</code>, but isn't it easier just to call <code>import os</code> in doRun ?</p> <p>parallel python tries to avoid python's GIL by running your function in a totally separate process. it tries to make this easier to swallow by letting you quote-"pass" parameters and namespaces to your function, but it does this using hacks. for instance, your classes will be serialized using some variant of <code>pickle</code> and then unserialized in the new process.</p> <p>But instead of relying on <code>submit</code>'s hacks, just accept the reality that your function is going to need to do all the work of setting up it's run context. you really have two <code>main</code> functions - one that sets up the call to <code>submit</code>, and one, which you call via <code>submit</code>, which actually sets up the work you need to do. </p> <p>if you need the next value from your generator to be available for a pp run, also pass it as a parameter! this avoids lambda functions and generator references, and leaves you with passing a simple variable!</p> <p>my code is not maintained anymore, but if you're curious check it out here: <a href="http://pps-spud.uchicago.edu/viewvc/fps/trunk/python/fps.py?view=markup" rel="nofollow">http://pps-spud.uchicago.edu/viewvc/fps/trunk/python/fps.py?view=markup</a></p>
5
2009-10-10T10:23:51Z
[ "python", "parallel-python" ]
localhost django dev server vs. postgres slow on mac os?
1,546,556
<p>Anyone notice slowness from a django dev server running on Mac OS and connecting to a remote (postgres) db? It doesn't seem to be the DNS problem referenced elsewhere. We've got a staging instance running the exact same code on the same remote staging box that's hosting the db, and the performance on that instance is very crisp.</p> <p>Here's the output of the performance middleware running locally:</p> <blockquote> <p>Total: 19.58 Python: 6.39 DB: 13.19 Queries: 17 </p> </blockquote> <p>And on the staging server:</p> <blockquote> <p>Total: 0.07 Python: 0.05 DB: 0.02 Queries: 16 </p> </blockquote> <p>Maybe it's postgres client network overhead from connecting to the remote db, or something? I don't mind doing the development on the staging server, but it's nice being able to run things locally too.</p>
2
2009-10-09T23:38:02Z
1,546,620
<p>Two things:</p> <ol> <li>The Django dev server is painfully slow. Any external connections will be restricted by it.</li> <li>The connection to an external database is limited by your machine's local upstream and downstream capabilities (the bottleneck usually being your internet connection).</li> </ol> <p>Any time you're developing locally and connecting to an external database server, it will be slow. For concurrent Drupal development at work, we source control our <code>sites</code> folder and use the same database that, though external, never leaves our local network. It's still like molasses in Alaska in January.</p> <p>I strongly recommend <a href="http://developer.apple.com/internet/opensource/postgres.html" rel="nofollow">setting up PostgreSQL locally</a> and <a href="http://www.postgresql.org/docs/8.1/static/backup.html" rel="nofollow">copying your external database</a> to a local one. It isn't a very time-intensive process and will save you headaches and keep you much more productive.</p>
5
2009-10-10T00:03:10Z
[ "python", "django", "osx", "performance" ]
localhost django dev server vs. postgres slow on mac os?
1,546,556
<p>Anyone notice slowness from a django dev server running on Mac OS and connecting to a remote (postgres) db? It doesn't seem to be the DNS problem referenced elsewhere. We've got a staging instance running the exact same code on the same remote staging box that's hosting the db, and the performance on that instance is very crisp.</p> <p>Here's the output of the performance middleware running locally:</p> <blockquote> <p>Total: 19.58 Python: 6.39 DB: 13.19 Queries: 17 </p> </blockquote> <p>And on the staging server:</p> <blockquote> <p>Total: 0.07 Python: 0.05 DB: 0.02 Queries: 16 </p> </blockquote> <p>Maybe it's postgres client network overhead from connecting to the remote db, or something? I don't mind doing the development on the staging server, but it's nice being able to run things locally too.</p>
2
2009-10-09T23:38:02Z
29,394,138
<p>I faced the same problem when I was using replica of my production database in development environment. The problem turned out to to be in <code>django_session</code> table which had a size near Gigabytes. Simplest solution was to clear that table as I did not need to use users session data in development. I used simple command:</p> <p><code>TRUNCATE TABLE 'django_session'</code></p> <p>also additional info on the issue can be found here: <a href="http://dba.stackexchange.com/questions/52733/why-django-session-table-grows-on-postgresql">http://dba.stackexchange.com/questions/52733/why-django-session-table-grows-on-postgresql</a></p>
0
2015-04-01T14:56:15Z
[ "python", "django", "osx", "performance" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
1,546,738
<p>Something like this?</p> <pre><code>&gt;&gt;&gt; from xml.sax.saxutils import escape &gt;&gt;&gt; escape("&lt; &amp; &gt;") '&amp;lt; &amp;amp; &amp;gt;' </code></pre>
55
2009-10-10T01:05:56Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
1,546,747
<p>Do you mean you do something like this:</p> <pre><code>from xml.dom.minidom import Text, Element t = Text() e = Element('p') t.data = '&lt;bar&gt;&lt;a/&gt;&lt;baz spam="eggs"&gt; &amp; blabla &amp;entity;&lt;/&gt;' e.appendChild(t) </code></pre> <p>Then you will get nicely escaped XML string:</p> <pre><code>&gt;&gt;&gt; e.toxml() '&lt;p&gt;&amp;lt;bar&amp;gt;&amp;lt;a/&amp;gt;&amp;lt;baz spam=&amp;quot;eggs&amp;quot;&amp;gt; &amp;amp; blabla &amp;amp;entity;&amp;lt;/&amp;gt;&lt;/p&gt;' </code></pre>
10
2009-10-10T01:09:51Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
21,107,835
<p>If you don't want another project import and you already have <code>cgi</code>, you could use this:</p> <pre><code>&gt;&gt;&gt; import cgi &gt;&gt;&gt; cgi.escape("&lt; &amp; &gt;") '&amp;lt; &amp;amp; &amp;gt;' </code></pre> <p>Note however that with this code legibility suffers - you should probably put it in a function to better describe your intention: (and write unit tests for it while you are at it ;)</p> <pre><code>def xml_escape(s): return cgi.escape(s) # escapes "&lt;", "&gt;" and "&amp;" </code></pre>
2
2014-01-14T07:13:19Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
28,703,510
<p>xml.sax.saxutils does not escape quotation characters (")</p> <p>So here is another one:</p> <pre><code>def escape( str ): str = str.replace("&lt;", "&amp;lt;") str = str.replace("&gt;", "&amp;gt;") str = str.replace("&amp;", "&amp;amp;") str = str.replace("\"", "&amp;quot;") return str </code></pre> <p>if you look it up then xml.sax.saxutils only does string replace </p>
4
2015-02-24T18:30:18Z
[ "python", "xml", "security" ]
Python: Escaping strings for use in XML
1,546,717
<p>I'm using Python's <code>xml.dom.minidom</code> to create an XML document. (Logical structure -> XML string, not the other way around.)</p> <p>How do I make it escape the strings I provide so they won't be able to mess up the XML?</p>
23
2009-10-10T00:51:10Z
35,302,133
<p><code>xml.sax.saxutils.escape</code> only escapes <code>&amp;</code>, <code>&lt;</code>, and <code>&gt;</code> by default, but it does provide an <code>entities</code> parameter to additionally escape other strings:</p> <pre><code>from xml.sax.saxutils import escape def xmlescape(data): return escape(data, entities={ "'": "&amp;apos;", "\"": "&amp;quot;" }) </code></pre> <p><code>xml.sax.saxutils.escape</code> uses <code>str.replace()</code> internally, so you can also skip the import and write your own function, as shown in MichealMoser's answer.</p>
4
2016-02-09T21:02:45Z
[ "python", "xml", "security" ]
Manually giving the twisted (web) network stack a packet to process?
1,546,745
<p>I am running an HTTP server using the twisted framework. Is there any way I can "manually" ask it to process some payload? For example, if I've constructed some Ethernet frame can I ask twisted's reactor to handle it just as if it had just arrived on my network card?</p>
1
2009-10-10T01:09:29Z
1,619,223
<p>What is the use-case?</p> <p>Perhaps you want to create your own <a href="http://twistedmatrix.com/projects/core/documentation/howto/udp.html" rel="nofollow">Datagram Protocol</a></p> <blockquote> <p>At the base, the place where you actually implement the protocol parsing and handling, is the DatagramProtocol class. This class will usually be decended from twisted.internet.protocol.DatagramProtocol. Most protocol handlers inherit either from this class or from one of its convenience children. The DatagramProtocol class receives datagrams, and can send them out over the network. Received datagrams include the address they were sent from, and when sending datagrams the address to send to must be specified.</p> </blockquote> <p>If you want to see wire-level transmissions rather than inject them, install and run <a href="http://www.wireshark.org/" rel="nofollow">WireShark, the fantastic, free packet sniffer</a>.</p>
0
2009-10-24T21:42:16Z
[ "python", "twisted" ]