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 |
|---|---|---|---|---|---|---|---|---|---|
How to find the sum of a ASCII value in a file to find the max number of ASCII and to print out the name of the highest sum of ASCII value | 1,293,404 | <p>Here is the code I'm working with</p>
<pre><code>def ascii_sum():
x = 0
infile = open("30075165.txt","r")
for line in infile:
return sum([ord(x) for x in line])
infile.close()
</code></pre>
<p>This code only prints out the first ASCII value in the file not the max ASCII value</p>
| -1 | 2009-08-18T11:58:13Z | 1,293,464 | <p>This is a snippet from an answer to one to of your <a href="http://stackoverflow.com/questions/1292630/how-to-open-a-file-and-find-the-longest-length-of-a-line-and-then-print-it-out/1292676#1292676">previous questions</a></p>
<pre><code>def get_file_data(filename):
def ascii_sum(line):
return sum([ord(x) for x in line])
def word_count(line):
return len(line.split(None))
filedata = [{'line': line,
'line_len': len(line),
'ascii_sum': ascii_sum(line),
'word_count': word_count(line)}
for line in open(filename, 'r')]
return filedata
afile = r"C:\Tmp\TestFile.txt"
file_data = get_file_data(afile)
print max(file_data, key=lambda line: line['line_len']) # Longest Line
print max(file_data, key=lambda line: line['ascii_sum']) # Largest ASCII sum
print max(file_data, key=lambda line: line['word_count']) # Most Words
</code></pre>
| 1 | 2009-08-18T12:11:52Z | [
"python"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 1,293,579 | <p>Standard module <code>ftplib</code> doesn't support proxies. It seems the only solution is to write your own customized version of the <code>ftplib</code>.</p>
| 0 | 2009-08-18T12:42:28Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 1,293,587 | <p>As per <a href="http://mail.python.org/pipermail/python-list/2004-October/288418.html">this</a> source.</p>
<p>Depends on the proxy, but a common method is to ftp to the proxy, then use
user at real-server as the user name, and the original password</p>
<p>EG for ftp.download.com</p>
<pre><code>ftp proxyserver (or open proxyserver from with ftp)
user anonymous at ftp.download.com
pass xxxxx
</code></pre>
<p>... so</p>
<pre><code>from ftplib import FTP
site = FTP('my_proxy')
site.set_debuglevel(1)
msg = site.login('anonymous at ftp.download.com', 'password')
site.cwd('/pub')
</code></pre>
| 6 | 2009-08-18T12:44:33Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 1,293,627 | <p>You can use the <a href="http://docs.python.org/library/urllib2.html#urllib2.ProxyHandler" rel="nofollow">ProxyHandler</a> in <code>urllib2</code>.</p>
<pre><code>ph = urllib2.ProxyHandler( { 'ftp' : proxy_server_url } )
server= urllib2.build_opener( ph )
</code></pre>
| 4 | 2009-08-18T12:52:04Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 5,581,905 | <p>I had the same problem and needed to use the <strong>ftplib</strong> module (not to rewrite all my scripts with URLlib2).</p>
<p>I have managed to write a script that installs transparent <strong>HTTP tunneling</strong> on the socket layer (used by ftplib). </p>
<p>Now, I can do <strong>FTP over HTTP</strong> transparently !</p>
<p>You can get it there:
<a href="http://code.activestate.com/recipes/577643-transparent-http-tunnel-for-python-sockets-to-be-u/" rel="nofollow">http://code.activestate.com/recipes/577643-transparent-http-tunnel-for-python-sockets-to-be-u/</a></p>
| 1 | 2011-04-07T13:31:39Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 37,144,136 | <p>Patching the builtin socket library definitely won't be an option for everyone, but my solution was to patch <code>socket.create_connection()</code> to use an HTTP proxy when the hostname matches a whitelist:</p>
<pre><code>from base64 import b64encode
from functools import wraps
import socket
_real_create_connection = socket.create_connection
_proxied_hostnames = {} # hostname: (proxy_host, proxy_port, proxy_auth)
def register_proxy (host, proxy_host, proxy_port, proxy_username=None, proxy_password=None):
proxy_auth = None
if proxy_username is not None or proxy_password is not None:
proxy_auth = b64encode('{}:{}'.format(proxy_username or '', proxy_password or ''))
_proxied_hostnames[host] = (proxy_host, proxy_port, proxy_auth)
@wraps(_real_create_connection)
def create_connection (address, *args, **kwds):
host, port = address
if host not in _proxied_hostnames:
return _real_create_connection(address, *args, **kwds)
proxy_host, proxy_port, proxy_auth = _proxied_hostnames[host]
conn = _real_create_connection((proxy_host, proxy_port), *args, **kwds)
try:
conn.send('CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n{auth_header}\r\n'.format(
host=host, port=port,
auth_header=('Proxy-Authorization: basic {}\r\n'.format(proxy_auth) if proxy_auth else '')
))
response = ''
while not response.endswith('\r\n\r\n'):
response += conn.recv(4096)
if response.split()[1] != '200':
raise socket.error('CONNECT failed: {}'.format(response.strip()))
except socket.error:
conn.close()
raise
return conn
socket.create_connection = create_connection
</code></pre>
<p>I also had to create a subclass of ftplib.FTP that ignores the <code>host</code> returned by <code>PASV</code> and <code>EPSV</code> FTP commands. Example usage:</p>
<pre><code>from ftplib import FTP
import paramiko # For SFTP
from proxied_socket import register_proxy
class FTPIgnoreHost (FTP):
def makepasv (self):
# Ignore the host returned by PASV or EPSV commands (only use the port).
return self.host, FTP.makepasv(self)[1]
register_proxy('ftp.example.com', 'proxy.example.com', 3128, 'proxy_username', 'proxy_password')
ftp_connection = FTP('ftp.example.com', 'ftp_username', 'ftp_password')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # If you don't care about security.
ssh.connect('ftp.example.com', username='sftp_username', password='sftp_password')
sftp_connection = ssh.open_sftp()
</code></pre>
| 0 | 2016-05-10T16:28:06Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Proxies in Python FTP application | 1,293,518 | <p>I'm developing an FTP client in Python ftplib. How do I add proxies support to it (most FTP apps I have seen seem to have it)? I'm especially thinking about SOCKS proxies, but also other types... FTP, HTTP (is it even possible to use HTTP proxies with FTP program?)</p>
<p>Any ideas how to do it?</p>
| 5 | 2009-08-18T12:28:03Z | 39,295,143 | <p>Here is workaround using <code>requests</code>, tested with a squid proxy that does NOT support CONNECT tunneling:</p>
<pre><code>def ftp_fetch_file_through_http_proxy(host, user, password, remote_filepath, http_proxy, output_filepath):
"""
This function let us to make a FTP RETR query through a HTTP proxy that does NOT support CONNECT tunneling.
It is equivalent to: curl -x $HTTP_PROXY --user $USER:$PASSWORD ftp://$FTP_HOST/path/to/file
It returns the 'Last-Modified' HTTP header value from the response.
More precisely, this function sends the following HTTP request to $HTTP_PROXY:
GET ftp://$USER:$PASSWORD@$FTP_HOST/path/to/file HTTP/1.1
Note that in doing so, the host in the request line does NOT match the host we send this packet to.
Python `requests` lib does not let us easily "cheat" like this.
In order to achieve what we want, we need:
- to mock urllib3.poolmanager.parse_url so that it returns a (host,port) pair indicating to send the request to the proxy
- to register a connection adapter to the 'ftp://' prefix. This is basically a HTTP adapter but it uses the FULL url of
the resource to build the request line, instead of only its relative path.
"""
url = 'ftp://{}:{}@{}/{}'.format(user, password, host, remote_filepath)
proxy_host, proxy_port = http_proxy.split(':')
def parse_url_mock(url):
return requests.packages.urllib3.util.url.parse_url(url)._replace(host=proxy_host, port=proxy_port, scheme='http')
with open(output_filepath, 'w+b') as output_file, patch('requests.packages.urllib3.poolmanager.parse_url', new=parse_url_mock):
session = requests.session()
session.mount('ftp://', FTPWrappedInFTPAdapter())
response = session.get(url)
response.raise_for_status()
output_file.write(response.content)
return response.headers['last-modified']
class FTPWrappedInFTPAdapter(requests.adapters.HTTPAdapter):
def request_url(self, request, _):
return request.url
</code></pre>
| 0 | 2016-09-02T14:44:17Z | [
"python",
"proxy",
"ftp",
"ftplib"
] |
Human readable cookie information using cookielib? | 1,293,828 | <p>Is there a way to print the cookies stored in a cookielib.CookieJar in a human-readable way?</p>
<p>I'm scraping a site and I'd like to know if the same cookies are set when I use my script as when I use the browser.</p>
| 0 | 2009-08-18T13:27:55Z | 1,294,165 | <pre><code>import urllib2
from cookielib import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict)
cj = CookieJar(policy)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://somewebsite.com")
[str(i) for i in cj]
</code></pre>
<p>Produces:</p>
<pre><code>['<Cookie JSESSIONID=BE71BFC3EE6D9799DEBD939A7487BB08 for somewebsite.com>']
</code></pre>
| 1 | 2009-08-18T14:15:11Z | [
"python",
"cookies"
] |
Sandboxing / copying a module in two separate places to prevent overwriting or monkey patching | 1,293,879 | <p>Using these four files, all in the same directory:</p>
<h3>splitter.py</h3>
<pre><code>#imagine this is a third-party library
SPLIT_CHAR = ','
class Splitter(object):
def __init__(self, s, split_char=None):
self.orig = s
if not split_char:
self.splitted = s.split(SPLIT_CHAR)
</code></pre>
<h3>a.py</h3>
<pre><code>#this person makes the mistake of re-setting the global variable
#in splitter to get different behavior, instead of just passing
#in the extra argument
import splitter
splitter.SPLIT_CHAR = '|'
def go():
s1 = splitter.Splitter("a|b|c|d")
print s1.orig
print s1.splitted
</code></pre>
<h3>b.py</h3>
<pre><code>#this person expects the default behavior (splitting commas)
from splitter import Splitter
def go():
s1 = Splitter('a,b,c,d')
print s1.orig
print s1.splitted
</code></pre>
<h3>experiment.py</h3>
<pre><code>import a
import b
a.go() #this one sets the global var in splitter
b.go() #this one expects the default behavior
</code></pre>
<p>The output of <code>experiment.py</code> will be:</p>
<pre><code>a|b|c|d
['a', 'b', 'c', 'd'] #okay... everything is fine
a,b,c,d
['a,b,c,d'] #not what the programmer expected.. should be split on commas
</code></pre>
<p>Is there a way to prevent this result? In this case, maybe <code>a.py</code> and <code>b.py</code> are written by two different coworkers, yet A's code is affecting B. It can sometimes be useful to overwrite something in a module (e.g. monkeypatching), but in this case it's producing confusing behavior.</p>
<p>Is there some way to make a copy of the module or sandbox the execution so that <code>a.py</code> can't overwrite values in <code>splitter.py</code> and end up affecting <code>b.py</code>?</p>
<p>Also, let's say instead of the simple <code>a.py</code> and <code>b.py</code>, we are running a hundred web apps under mod_python or something (sharing as much as possible to decrease memory), is there a way to prevent one rogue app from tinkering with a module and breaking all the other apps? Something like Google App Engine has this solved, of course :)</p>
| 0 | 2009-08-18T13:33:29Z | 1,293,906 | <p><strong>"Is there a way to prevent this result?"</strong></p>
<p>Yes. Find the people who monkeypatched the module and make them stop.</p>
<p>Monkeypatching doesn't require fancy code work-arounds. It requires people to simply cooperate.</p>
<p>If you write a module and some co-worker makes a mess of it, you should talk to that co-worker. It's cheaper, simpler, and more effective in the long run.</p>
| 2 | 2009-08-18T13:37:09Z | [
"python"
] |
Sandboxing / copying a module in two separate places to prevent overwriting or monkey patching | 1,293,879 | <p>Using these four files, all in the same directory:</p>
<h3>splitter.py</h3>
<pre><code>#imagine this is a third-party library
SPLIT_CHAR = ','
class Splitter(object):
def __init__(self, s, split_char=None):
self.orig = s
if not split_char:
self.splitted = s.split(SPLIT_CHAR)
</code></pre>
<h3>a.py</h3>
<pre><code>#this person makes the mistake of re-setting the global variable
#in splitter to get different behavior, instead of just passing
#in the extra argument
import splitter
splitter.SPLIT_CHAR = '|'
def go():
s1 = splitter.Splitter("a|b|c|d")
print s1.orig
print s1.splitted
</code></pre>
<h3>b.py</h3>
<pre><code>#this person expects the default behavior (splitting commas)
from splitter import Splitter
def go():
s1 = Splitter('a,b,c,d')
print s1.orig
print s1.splitted
</code></pre>
<h3>experiment.py</h3>
<pre><code>import a
import b
a.go() #this one sets the global var in splitter
b.go() #this one expects the default behavior
</code></pre>
<p>The output of <code>experiment.py</code> will be:</p>
<pre><code>a|b|c|d
['a', 'b', 'c', 'd'] #okay... everything is fine
a,b,c,d
['a,b,c,d'] #not what the programmer expected.. should be split on commas
</code></pre>
<p>Is there a way to prevent this result? In this case, maybe <code>a.py</code> and <code>b.py</code> are written by two different coworkers, yet A's code is affecting B. It can sometimes be useful to overwrite something in a module (e.g. monkeypatching), but in this case it's producing confusing behavior.</p>
<p>Is there some way to make a copy of the module or sandbox the execution so that <code>a.py</code> can't overwrite values in <code>splitter.py</code> and end up affecting <code>b.py</code>?</p>
<p>Also, let's say instead of the simple <code>a.py</code> and <code>b.py</code>, we are running a hundred web apps under mod_python or something (sharing as much as possible to decrease memory), is there a way to prevent one rogue app from tinkering with a module and breaking all the other apps? Something like Google App Engine has this solved, of course :)</p>
| 0 | 2009-08-18T13:33:29Z | 1,293,943 | <p>How about when you instantiate the <code>Splitter</code>, you set it's default split char to whatever it is you want it to be, and make a setter for it, so that people can change it?</p>
| 1 | 2009-08-18T13:42:20Z | [
"python"
] |
Sandboxing / copying a module in two separate places to prevent overwriting or monkey patching | 1,293,879 | <p>Using these four files, all in the same directory:</p>
<h3>splitter.py</h3>
<pre><code>#imagine this is a third-party library
SPLIT_CHAR = ','
class Splitter(object):
def __init__(self, s, split_char=None):
self.orig = s
if not split_char:
self.splitted = s.split(SPLIT_CHAR)
</code></pre>
<h3>a.py</h3>
<pre><code>#this person makes the mistake of re-setting the global variable
#in splitter to get different behavior, instead of just passing
#in the extra argument
import splitter
splitter.SPLIT_CHAR = '|'
def go():
s1 = splitter.Splitter("a|b|c|d")
print s1.orig
print s1.splitted
</code></pre>
<h3>b.py</h3>
<pre><code>#this person expects the default behavior (splitting commas)
from splitter import Splitter
def go():
s1 = Splitter('a,b,c,d')
print s1.orig
print s1.splitted
</code></pre>
<h3>experiment.py</h3>
<pre><code>import a
import b
a.go() #this one sets the global var in splitter
b.go() #this one expects the default behavior
</code></pre>
<p>The output of <code>experiment.py</code> will be:</p>
<pre><code>a|b|c|d
['a', 'b', 'c', 'd'] #okay... everything is fine
a,b,c,d
['a,b,c,d'] #not what the programmer expected.. should be split on commas
</code></pre>
<p>Is there a way to prevent this result? In this case, maybe <code>a.py</code> and <code>b.py</code> are written by two different coworkers, yet A's code is affecting B. It can sometimes be useful to overwrite something in a module (e.g. monkeypatching), but in this case it's producing confusing behavior.</p>
<p>Is there some way to make a copy of the module or sandbox the execution so that <code>a.py</code> can't overwrite values in <code>splitter.py</code> and end up affecting <code>b.py</code>?</p>
<p>Also, let's say instead of the simple <code>a.py</code> and <code>b.py</code>, we are running a hundred web apps under mod_python or something (sharing as much as possible to decrease memory), is there a way to prevent one rogue app from tinkering with a module and breaking all the other apps? Something like Google App Engine has this solved, of course :)</p>
| 0 | 2009-08-18T13:33:29Z | 1,295,200 | <p>Another way to prevent that is to "hint" that splitter.SPLIT_CHAR is "private" by calling it _SPLIT_CHAR. From <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8, the style guide for Python code</a>:</p>
<blockquote>
<p><code>_single_leading_underscore</code>: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an underscore.</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Use one leading underscore only for non-public methods and instance variables</p>
</blockquote>
<p>So while neither of those shout "don't mess with me," it is a hint to the next user, at least if they are familiar with Python's style.</p>
| 1 | 2009-08-18T16:59:27Z | [
"python"
] |
Best way to obtain indexed access to a Python queue, thread-safe | 1,293,966 | <p>I have a queue (from the <code>Queue</code> module), and I want to get indexed access into it. (i.e., being able to ask for item number four in the queue, without removing it from the queue.)</p>
<p>I saw that a queue uses a deque internally, and deque has indexed access. The question is, how can I use the deque without (1) messing up the queue, (2) breaking thread-safety.</p>
| 8 | 2009-08-18T13:45:32Z | 1,294,330 | <pre><code>import Queue
class IndexableQueue(Queue):
def __getitem__(self, index):
with self.mutex:
return self.queue[index]
</code></pre>
<p>It's of course crucial to release the mutex whether the indexing succeeds or raises an IndexError, and I'm using a <code>with</code> statement for that. In older Python versions, <code>try</code>/<code>finally</code> would be used to the same effect.</p>
| 9 | 2009-08-18T14:39:19Z | [
"python",
"multithreading",
"queue",
"deque"
] |
How do I install PyGTK / PyGobject on Windows with Python 2.6? | 1,294,272 | <p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p>
<pre><code>Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented <a href="http://bugs.python.org/issue3308">Python Bug 3308</a> (<code>closed: wontfix</code>).</p>
<p>Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source?</p>
| 10 | 2009-08-18T14:31:08Z | 1,294,354 | <p>I have it working fine, and it didn't give me much trouble, so we know it can be done...</p>
<p>Keep in mind you will probably need all of the following installed on your Windows machine:</p>
<ul>
<li><p>PyCairo ( <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/</a> ) </p></li>
<li><p>PyGobject ( <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win32/pygobject/</a> )</p></li>
<li><p>PyGTK ( <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/</a> )</p>
<p><em>Unofficial</em> x64 versions of the above 3 items are available <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygtk" rel="nofollow">here</a> -- However, I cannot vouch for nor recommend them!</p>
<p>and of course</p></li>
<li><p>the GTK+ Runtime ( <a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/gtk+/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win32/gtk+/</a> or <a href="http://ftp.gnome.org/pub/GNOME/binaries/win64/gtk+/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win64/gtk+/</a> )</p></li>
</ul>
<p>I suspect in your case that the PyGTK libraries are not finding your GTK+ Runtime directory where the DLLs are. You should have the environment variable GTK_BASEPATH set to the directory of your GTK+ Runtime (usually C:\GTK).</p>
<p>Please also see the <a href="http://faq.pygtk.org/index.py?req=show&file=faq21.001.htp" rel="nofollow">PyGTK-on-Windows FAQ</a></p>
<p>Now, if you're trying to compile the PyGTK'ed Python with Py2EXE, that's a bit more complicated, but it can be done as well...</p>
| 10 | 2009-08-18T14:44:11Z | [
"python",
"pygtk",
"mingw",
"pygobject"
] |
How do I install PyGTK / PyGobject on Windows with Python 2.6? | 1,294,272 | <p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p>
<pre><code>Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented <a href="http://bugs.python.org/issue3308">Python Bug 3308</a> (<code>closed: wontfix</code>).</p>
<p>Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source?</p>
| 10 | 2009-08-18T14:31:08Z | 1,992,519 | <p>u should have pygtk,pycairo,pygboject and the gtk+ runtime...</p>
<p>see this for an all in one installer
<a href="http://aruiz.typepad.com/siliconisland/2006/12/allinone_win32_.html" rel="nofollow">http://aruiz.typepad.com/siliconisland/2006/12/allinone_win32_.html</a></p>
| 0 | 2010-01-02T19:15:07Z | [
"python",
"pygtk",
"mingw",
"pygobject"
] |
How do I install PyGTK / PyGobject on Windows with Python 2.6? | 1,294,272 | <p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p>
<pre><code>Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented <a href="http://bugs.python.org/issue3308">Python Bug 3308</a> (<code>closed: wontfix</code>).</p>
<p>Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source?</p>
| 10 | 2009-08-18T14:31:08Z | 5,357,523 | <p>The PyGTK all-in-one installer has been updated recently:</p>
<p><a href="http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/" rel="nofollow">http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/</a></p>
<p>This will install PyGTK, PyGObject, PyCairo, PyGtkSourceView2, PyGooCanvas, PyRsvg, the gtk+-bundle and Glade. It is absolutely everything necessary to be able to successfully <code>import gobject</code>, <code>import gtk</code>, etc, without DLL problems.</p>
| 4 | 2011-03-18T20:31:46Z | [
"python",
"pygtk",
"mingw",
"pygobject"
] |
How do I install PyGTK / PyGobject on Windows with Python 2.6? | 1,294,272 | <p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p>
<pre><code>Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented <a href="http://bugs.python.org/issue3308">Python Bug 3308</a> (<code>closed: wontfix</code>).</p>
<p>Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source?</p>
| 10 | 2009-08-18T14:31:08Z | 9,947,516 | <p>for 64 bit Windows users see </p>
<p><a href="http://digitalpbk.blogspot.in/2012/03/installing-pygtk-pypango-and-pycairo-on.html" rel="nofollow">http://digitalpbk.blogspot.in/2012/03/installing-pygtk-pypango-and-pycairo-on.html</a> </p>
<p>Above steps will give Invalid DLL error on 64 bit.</p>
| 3 | 2012-03-30T17:15:01Z | [
"python",
"pygtk",
"mingw",
"pygobject"
] |
How do I install PyGTK / PyGobject on Windows with Python 2.6? | 1,294,272 | <p>I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute <code>import gobject</code> I get this:</p>
<pre><code>Traceback (most recent call last):
import gobject
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, in <module>
from gobject.constants import *
File "C:\Python26\lib\site-packages\gtk-2.0\gobject\constants.py", line 22, in <module>
from _gobject import type_from_name
ImportError: DLL load failed: The specified procedure could not be found.
</code></pre>
<p>This appears to be caused by the switch from building using MinGW to Microsoft Visual Studio, as documented <a href="http://bugs.python.org/issue3308">Python Bug 3308</a> (<code>closed: wontfix</code>).</p>
<p>Is there any way to install PyGTK/PyGObject in a way that will work with Python 2.6 on Windows, without having to recompile one or the other from source?</p>
| 10 | 2009-08-18T14:31:08Z | 28,122,412 | <p>Be careful about installing PyGTK bundle pack if any one planning to run PyGTK through embedded interpreter and the C/C++ code is already using GTK. PyGTK bundle pack does not add its GTK runtime to PATH.</p>
<p>In such case possibly the C code will take GTK from PATH (as probably you have already installed GTK bundle pack) and Python will use separate set of GTK runtime libraries. </p>
<p>Therefore in my case either C GUI or Python GUI used to run properly and used to conflict while running together.</p>
<p>As I use Psychopy as my base python collection, to solve this problem I have just installed PyGTK PyGTK, Pycairo, Pygobject on top of Psychopy.</p>
<p>Apart from using only one set of GTK runtime I had to initialize GTK in my C code through PyGTK (not by gtk_init (&argc, &argv) in my C code) after initializing python interpreter.</p>
| 0 | 2015-01-24T04:49:56Z | [
"python",
"pygtk",
"mingw",
"pygobject"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,398 | <p>Suppose you have multiple threads which don't <em>really</em> touch each other's data. Those should execute as independently as possible. If you have a "global lock" which you need to acquire in order to (say) call a function, that can end up as a bottleneck. You can wind up not getting much benefit from having multiple threads in the first place.</p>
<p>To put it into a real world analogy: imagine 100 developers working at a company with only a single coffee mug. Most of the developers would spend their time waiting for coffee instead of coding.</p>
<p>None of this is Python-specific - I don't know the details of what Python needed a GIL for in the first place. However, hopefully it's given you a better idea of the general concept.</p>
| 28 | 2009-08-18T14:53:04Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,402 | <p>Python's GIL is intended to serialize access to interpreter internals from different threads. On multi-core systems, it means that multiple threads can't effectively make use of multiple cores. (If the GIL didn't lead to this problem, most people wouldn't care about the GIL - it's only being raised as an issue because of the increasing prevalence of multi-core systems.) If you want to understand it in detail, you can view <a href="https://www.youtube.com/watch?v=ph374fJqFPE">this video</a> or look at <a href="http://www.dabeaz.com/python/GIL.pdf">this set of slides</a>. It might be too much information, but then you did ask for details :-)</p>
<p>Note that Python's GIL is only really an issue for CPython, the reference implementation. Jython and IronPython don't have a GIL. As a Python developer, you don't generally come across the GIL unless you're writing a C extension. C extension writers need to release the GIL when their extensions do blocking I/O, so that other threads in the Python process get a chance to run.</p>
<p><strong>Update:</strong> Updated link to video to point to Youtube, as the earlier <code>blip.tv</code> link had rotted.</p>
| 90 | 2009-08-18T14:53:17Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,408 | <p>Wikipedia has a nice description of a global interpreter lock</p>
<p><a href="http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock" rel="nofollow">http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock</a></p>
<p>That article links this nice article that discusses the GIL in Python.</p>
<p><a href="http://www.ddj.com/linux-open-source/206103078?pgno=2" rel="nofollow">http://www.ddj.com/linux-open-source/206103078?pgno=2</a></p>
| 1 | 2009-08-18T14:53:44Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,430 | <p>Whenever two threads have access to the same variable you have a problem.
In C++ for instance, the way to avoid the problem is to define some mutex lock to prevent two thread to, let's say, enter the setter of an object at the same time.</p>
<p>Multithreading is possible in python, but two threads cannot be executed at the same time
at a granularity finer than one python instruction.
The running thread is getting a global lock called GIL.</p>
<p>This means if you begin write some multithreaded code in order to take advantage of your multicore processor, your performance won't improve.
The usual workaround consists of going multiprocess.</p>
<p>Note that it is possible to release the GIL if you're inside a method you wrote in C for instance.</p>
<p>The use of a GIL is not inherent to Python but to some of its interpreter, including the most common CPython.
(#edited, see comment)</p>
<p>The GIL issue is still valid in Python 3000.</p>
| 10 | 2009-08-18T14:57:06Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,553 | <p><a href="http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-understanding-the-python-gil-82-3273690" rel="nofollow">Watch David Beazley</a> tell you everything you ever wanted to know about the GIL.</p>
| 7 | 2009-08-18T15:16:02Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 1,294,988 | <p>Here's a longish article talking about the GIL and threading in Python I wrote awhile back. It goes into a fair amount of detail on it:</p>
<p><a href="http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/" rel="nofollow">http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/</a></p>
| 3 | 2009-08-18T16:25:10Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 20,418,825 | <p>Let's first understand what the python GIL provides:</p>
<p>Any operation/instruction is executed in the interpreter. GIL ensures that interpreter is held by a single thread at <strong>a particular instant of time</strong>. And your python program with multiple threads works in a single interpreter. At any particular instant of time, this interpreter is held by a single thread. It means that only the thread which is holding the interpreter is <strong>running</strong> at <strong>any instant of time</strong>.</p>
<p>Now why is that an issue:</p>
<p>Your machine could be having multiple cores/processors. And multiple cores allow multiple threads to execute <strong>simultaneously</strong> i.e multiple threads could execute <strong>at any particular instant of time.</strong>.
But since the interpreter is held by a single thread, other threads are not doing anything even though they have access to a core. So, you are not getting any advantage provided by multiple cores because at any instant only a single core, which is the core being used by the thread currently holding the interpreter, is being used. So, your program will take as long to execute as if it were a single threaded program.</p>
<p>However, potentially blocking or long-running operations, such as I/O, image processing, and NumPy number crunching, happen outside the GIL. Taken from <a href="https://wiki.python.org/moin/GlobalInterpreterLock">here</a>. So for such operations, a multithreaded operation will still be faster than a single threaded operation despite the presence of GIL. So, GIL is not always a bottleneck.</p>
<p>Edit: GIL is an implementation detail of CPython. PyPy and Jython don't have GIL, so a truly multithreaded program should be possible in them, thought I have never used PyPy and Jython and not sure of this.</p>
| 6 | 2013-12-06T07:55:24Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 25,324,045 | <p>Here is some code demonstrating effects of GIL: <a href="https://github.com/cankav/python_gil_demonstration" rel="nofollow">https://github.com/cankav/python_gil_demonstration</a></p>
| 1 | 2014-08-15T09:19:19Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 31,306,077 | <p><strong>Why Python (CPython and others) uses the GIL</strong></p>
<p>From <a href="http://wiki.python.org/moin/GlobalInterpreterLock" rel="nofollow">http://wiki.python.org/moin/GlobalInterpreterLock</a></p>
<p>In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe.</p>
<p><strong>How to remove it from Python?</strong></p>
<p>Like Lua, maybe Python could start multiple VM, But python doesn't do that, I guess there should be some other reasons.</p>
<p>In Numpy or some other python extended library, sometimes, releasing the GIL to other threads could boost the efficiency of the whole programme.</p>
| 0 | 2015-07-09T00:18:30Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 33,493,011 | <p>I want to share an example from the book multithreading for Visual Effects. So here is a classic dead lock situation</p>
<pre><code>static void MyCallback(const Context &context){
Auto<Lock> lock(GetMyMutexFromContext(context));
...
EvalMyPythonString(str); //A function that takes the GIL
...
}
</code></pre>
<p>Now consider the events in the sequence resulting a dead-lock. </p>
<pre><code>âââââ¦âââââââââââââââââââââââââââââââââââââââââ¦âââââââââââââââââââââââââââââââââââââââ
â â Main Thread â Other Thread â
â ââââ¬âââââââââââââââââââââââââââââââââââââââââ¬âââââââââââââââââââââââââââââââââââââââ£
â 1 â Python Command acquires GIL â Work started â
â 2 â Computation requested â MyCallback runs and acquires MyMutex â
â 3 â â MyCallback now waits for GIL â
â 4 â MyCallback runs and waits for MyMutex â waiting for GIL â
âââââ©âââââââââââââââââââââââââââââââââââââââââ©âââââââââââââââââââââââââââââââââââââââ
</code></pre>
| 0 | 2015-11-03T06:50:24Z | [
"python",
"gil"
] |
What is a global interpreter lock (GIL)? | 1,294,382 | <p>What is a global interpreter lock and why is that an issue?</p>
<p>A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.</p>
| 87 | 2009-08-18T14:50:06Z | 36,942,047 | <p>I find this is the best explain of GIL. Please read.</p>
<p><a href="http://www.dabeaz.com/python/UnderstandingGIL.pdf" rel="nofollow">http://www.dabeaz.com/python/UnderstandingGIL.pdf</a></p>
| 2 | 2016-04-29T15:19:29Z | [
"python",
"gil"
] |
How to insert / retrieve a file stored as a BLOB in a MySQL db using python | 1,294,385 | <p>I want to write a python script that populates a database with some information. One of the columns in my table is a BLOB that I would like to save a file to for each entry.</p>
<p>How can I read the file (binary) and insert it into the DB using python? Likewise, how can I retrieve it and write that file back to some arbitrary location on the hard drive?</p>
| 10 | 2009-08-18T14:50:58Z | 1,294,488 | <p>You can insert and read BLOBs from a DB like every other column type. From the database API's view there is nothing special about BLOBs.</p>
| 0 | 2009-08-18T15:07:42Z | [
"python",
"mysql",
"file-io",
"blob"
] |
How to insert / retrieve a file stored as a BLOB in a MySQL db using python | 1,294,385 | <p>I want to write a python script that populates a database with some information. One of the columns in my table is a BLOB that I would like to save a file to for each entry.</p>
<p>How can I read the file (binary) and insert it into the DB using python? Likewise, how can I retrieve it and write that file back to some arbitrary location on the hard drive?</p>
| 10 | 2009-08-18T14:50:58Z | 1,294,496 | <pre><code>thedata = open('thefile', 'rb').read()
sql = "INSERT INTO sometable (theblobcolumn) VALUES (%s)"
cursor.execute(sql, (thedata,))
</code></pre>
<p>That code of course works as written only if your table has just the BLOB column and what
you want to do is INSERT, but of course you could easily tweak it to add more columns,
use UPDATE instead of INSERT, or whatever it is that you exactly need to do.</p>
<p>I'm also assuming your file is binary rather than text, etc; again, if my guesses are
incorrect it's easy for you to tweak the above code accordingly.</p>
<p>Some kind of <code>SELECT</code> on <code>cursor.execute</code>, then some kind of fetching from the cursor, is how you
retrieve BLOB data, exactly like you retrieve any other kind of data.</p>
| 12 | 2009-08-18T15:09:15Z | [
"python",
"mysql",
"file-io",
"blob"
] |
how to register more than 10 apps in Google App Engine | 1,294,618 | <p>Anyone knows any "legal" way to surpass the 10-app-limit Google imposes?
I wouldn't mind to pay, or anything, but I wasn't able to find a way to have more
than 10 apps and can't either remove one.</p>
| 13 | 2009-08-18T15:25:56Z | 1,294,678 | <p>Call or write to Google! Google's policies are very exact and very strict, because they are catering to <em>thousands</em> of developers, and thus need those standards and uniformity. But if you have a good reason for needing more than 10, and you can get a real person at the end of a telephone line, I'd think you'd have a good chance of getting the limit raised.</p>
<p>Alternatively, you could just get a friend or co-worker to register. That seems like it ought to be legal...but check the User Agreement first.</p>
| 4 | 2009-08-18T15:35:03Z | [
"python",
"google-app-engine",
"registration"
] |
how to register more than 10 apps in Google App Engine | 1,294,618 | <p>Anyone knows any "legal" way to surpass the 10-app-limit Google imposes?
I wouldn't mind to pay, or anything, but I wasn't able to find a way to have more
than 10 apps and can't either remove one.</p>
| 13 | 2009-08-18T15:25:56Z | 1,295,100 | <p>This post in the Google App Engine group "solves" the problem:
<a href="http://groups.google.com/group/google-appengine/browse%5Fthread/thread/815d0e29076da2b1/ecc21212ed9362ab#ecc21212ed9362ab">link</a></p>
| 12 | 2009-08-18T16:43:19Z | [
"python",
"google-app-engine",
"registration"
] |
Getting DOM tree of XML document | 1,294,654 | <p>Does anyone know how I would get a DOM instance (tree) of an XML file in Python. I am trying to compare two XML documents to eachother that may have elements and attributes in different order. How would I do this?</p>
| 5 | 2009-08-18T15:31:03Z | 1,294,697 | <p>Some solutions to ponder:</p>
<ul>
<li><a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">minidom</a></li>
<li><a href="http://pypi.python.org/pypi/Amara" rel="nofollow">amara</a> (xml data binding)</li>
</ul>
| 1 | 2009-08-18T15:36:42Z | [
"python",
"xml",
"dom"
] |
Getting DOM tree of XML document | 1,294,654 | <p>Does anyone know how I would get a DOM instance (tree) of an XML file in Python. I am trying to compare two XML documents to eachother that may have elements and attributes in different order. How would I do this?</p>
| 5 | 2009-08-18T15:31:03Z | 1,294,753 | <p>For comparing XML document instances, a naive compare of the parsed DOM trees will not work. You will probably need to implement your own NodeComperator that recursively compares a node and its child-nodes with some other node and its child-nodes based on your specific criteria such as:</p>
<ul>
<li>When is the order of child elements significant?</li>
<li>When is whitespace in text-content significant?</li>
<li>Are there default values for some elements and are they applied by your parser?</li>
<li>Should entity references be expanded for comparison</li>
</ul>
<p><a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">Minidom</a> is a good starting point for parsing the files and is easy to use. The actual implementation of the comparison function for your specific application however needs to be done by you.</p>
| 0 | 2009-08-18T15:45:54Z | [
"python",
"xml",
"dom"
] |
Getting DOM tree of XML document | 1,294,654 | <p>Does anyone know how I would get a DOM instance (tree) of an XML file in Python. I am trying to compare two XML documents to eachother that may have elements and attributes in different order. How would I do this?</p>
| 5 | 2009-08-18T15:31:03Z | 1,295,977 | <p>Personally, whenever possible, I'd start with <a href="http://docs.python.org/library/xml.etree.elementtree.html" rel="nofollow">elementtree</a> (preferably the C implementation that comes with Python's standard library, or the <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> implementation, but that's essentialy a matter of higher speed, only). It's not a standard-compliant DOM, but holds the same information in a more Pythonic and handier way. You can start by calling <code>xml.etree.ElementTree.parse</code>, which takes the XML source and returns an element-tree; do that on both sources, use <code>getroot</code> on each element tree to obtain its root element, then recursively compare elements starting from the root ones.</p>
<p>Children of an element form a sequence, in element tree just as in the standard DOM, meaning their order is considered important; but it's easy to make Python sets out of them (or with a little more effort "multi-sets" of some kind, if repetitions are important in your use case though order is not) for a laxer comparison. It's even easier for attributes for a given element, where uniqueness is assured and order is semantically not relevant.</p>
<p>Is there some specific reason you need a standard DOM rather than an alternative container like an element tree, or are you just using the term DOM in a general sense so that element tree would be OK?</p>
<p>In the past I've also had good results using <a href="http://www.reportlab.org/pyrxp.html" rel="nofollow">PyRXP</a>, which uses an even starker and simpler representation than ElementTree. However, it WAS years and years ago; I have no recent experience as to how PyRXP today compares with lxml or cElementTree.</p>
| 2 | 2009-08-18T19:29:48Z | [
"python",
"xml",
"dom"
] |
Python WWW macro | 1,294,862 | <p>i need something like iMacros for Python. It would be great to have something like that:</p>
<pre><code>browse_to('www.google.com')
type_in_input('search', 'query')
click_button('search')
list = get_all('<p>')
</code></pre>
<p>Do you know something like that?</p>
<p>Thanks in advance,
Etam.</p>
| 6 | 2009-08-18T16:05:29Z | 1,294,891 | <p>Use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>. Other than executing JavaScript in a page, it's pretty good.</p>
| 6 | 2009-08-18T16:10:39Z | [
"python",
"screen-scraping"
] |
Python WWW macro | 1,294,862 | <p>i need something like iMacros for Python. It would be great to have something like that:</p>
<pre><code>browse_to('www.google.com')
type_in_input('search', 'query')
click_button('search')
list = get_all('<p>')
</code></pre>
<p>Do you know something like that?</p>
<p>Thanks in advance,
Etam.</p>
| 6 | 2009-08-18T16:05:29Z | 1,295,028 | <p>Almost a direct fulfillment of the wishes in the question - <a href="http://twill.idyll.org/" rel="nofollow">twill</a>.</p>
<blockquote>
<p>twill is a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features.</p>
<p>twill supports automated Web testing and has a simple Python interface.</p>
</blockquote>
<p>(<code>pyparsing</code>, <code>mechanize</code>, and <code>BeautifulSoup</code> are included with twill for convenience.)</p>
<p>A <code>Python API</code> example:</p>
<pre><code>from twill.commands import go, showforms, formclear, fv, submit
go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()
formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()
submit('0')
</code></pre>
| 7 | 2009-08-18T16:31:31Z | [
"python",
"screen-scraping"
] |
Python WWW macro | 1,294,862 | <p>i need something like iMacros for Python. It would be great to have something like that:</p>
<pre><code>browse_to('www.google.com')
type_in_input('search', 'query')
click_button('search')
list = get_all('<p>')
</code></pre>
<p>Do you know something like that?</p>
<p>Thanks in advance,
Etam.</p>
| 6 | 2009-08-18T16:05:29Z | 1,297,568 | <p>Another thing to consider is writing your own script. It's actually not too tough once you get the hang of it, and without invoking a half dozen huge libraries it might even be faster (but I'm not sure). I use a web debugger called "Charles" to surf websites that I want to scrape. It logs all outgoing/incoming http communications, and I use the records to reverse engineer the query strings. Manipulating them in python makes for quite speedy, flexible scraping. </p>
| 0 | 2009-08-19T02:35:16Z | [
"python",
"screen-scraping"
] |
GIS: line_locate_point() in Python | 1,295,386 | <p>I'm pretty much a beginner when it comes to GIS, but I think I understand the basics - it doesn't seem to hard. But: All these acronyms and different libraries, GEOS, GDAL, PROJ, PCL, Shaply, OpenGEO, OGR, OGC, OWS and what not, each seemingly depending on any number of others, is slightly overwhelming me.</p>
<p>Here's what I would like to do: Given a number of points and a linestring, I want to determine the location on the line closest to a certain point. In other words, what PostGIS's line_locate_point() does:</p>
<p><a href="http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint" rel="nofollow">http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint</a></p>
<p>Except I want do use plain Python. Which library or libraries should I have a look at generally for doing these kinds of spatial calculations in Python, and is there one that specifically supports a line_locate_point() equivalent?</p>
| 2 | 2009-08-18T17:35:18Z | 1,298,837 | <p>For posterity:</p>
<p><a href="http://bitbucket.org/miracle2k/pyutils/changeset/156c60ec88f8/" rel="nofollow">http://bitbucket.org/miracle2k/pyutils/changeset/156c60ec88f8/</a></p>
| 2 | 2009-08-19T09:48:34Z | [
"python",
"postgresql",
"geometry",
"gis",
"geospatial"
] |
GIS: line_locate_point() in Python | 1,295,386 | <p>I'm pretty much a beginner when it comes to GIS, but I think I understand the basics - it doesn't seem to hard. But: All these acronyms and different libraries, GEOS, GDAL, PROJ, PCL, Shaply, OpenGEO, OGR, OGC, OWS and what not, each seemingly depending on any number of others, is slightly overwhelming me.</p>
<p>Here's what I would like to do: Given a number of points and a linestring, I want to determine the location on the line closest to a certain point. In other words, what PostGIS's line_locate_point() does:</p>
<p><a href="http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint" rel="nofollow">http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint</a></p>
<p>Except I want do use plain Python. Which library or libraries should I have a look at generally for doing these kinds of spatial calculations in Python, and is there one that specifically supports a line_locate_point() equivalent?</p>
| 2 | 2009-08-18T17:35:18Z | 1,299,693 | <p>In another forum I suggested reimplementing the (simple) PostGIS algorithm in Python using <a href="http://pypi.python.org/pypi/Shapely/" rel="nofollow">Shapely</a>.</p>
| 2 | 2009-08-19T12:44:57Z | [
"python",
"postgresql",
"geometry",
"gis",
"geospatial"
] |
GIS: line_locate_point() in Python | 1,295,386 | <p>I'm pretty much a beginner when it comes to GIS, but I think I understand the basics - it doesn't seem to hard. But: All these acronyms and different libraries, GEOS, GDAL, PROJ, PCL, Shaply, OpenGEO, OGR, OGC, OWS and what not, each seemingly depending on any number of others, is slightly overwhelming me.</p>
<p>Here's what I would like to do: Given a number of points and a linestring, I want to determine the location on the line closest to a certain point. In other words, what PostGIS's line_locate_point() does:</p>
<p><a href="http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint" rel="nofollow">http://postgis.refractions.net/documentation/manual-1.3/ch06.html#line%5Flocate%5Fpoint</a></p>
<p>Except I want do use plain Python. Which library or libraries should I have a look at generally for doing these kinds of spatial calculations in Python, and is there one that specifically supports a line_locate_point() equivalent?</p>
| 2 | 2009-08-18T17:35:18Z | 2,980,216 | <p>For posterity, these functions are available in Shapely 1.2</p>
| 2 | 2010-06-05T11:54:04Z | [
"python",
"postgresql",
"geometry",
"gis",
"geospatial"
] |
How to replace Python function while supporting all passed in parameters | 1,295,415 | <p>I'm looking for a way to decorate an arbitrary python function, so that an alternate function is called instead of the original, with all parameters passed as a list or dict.</p>
<p>More precisely, something like this (where f is any function, and replacement_f takes a list and a dict):</p>
<pre><code>def replace_func(f, replacement_f):
def new_f(*args, **kwargs):
replacement_f(args, kwargs)
return new_f
</code></pre>
<p>However, I cannot reference <code>replacement_f</code> inside <code>new_f</code>. And I can't use the standard trick of passing <code>replacement_f</code> to <code>new_f</code> as the default for a different parameter, because I'm using the <code>*args</code> and <code>**kwargs</code> variable argument lists.</p>
<p>The location where the original function is called cannot change, and will accept both positional and named parameters.</p>
<p>I fear that isn't very clear, but I'm happy to clarify if needed.</p>
<p>Thanks</p>
| 0 | 2009-08-18T17:39:40Z | 1,295,436 | <p>If I understand this correctly, you want to pass all arguments from one function to another.</p>
<p>Simply do:</p>
<pre><code>def replace_func(f, replacement_f):
def new_f(*args, **kwargs):
replacement_f(*args, **kwargs) # args & kwargs will be expanded
return new_f
</code></pre>
| 0 | 2009-08-18T17:43:27Z | [
"python",
"decorator",
"kwargs"
] |
How to replace Python function while supporting all passed in parameters | 1,295,415 | <p>I'm looking for a way to decorate an arbitrary python function, so that an alternate function is called instead of the original, with all parameters passed as a list or dict.</p>
<p>More precisely, something like this (where f is any function, and replacement_f takes a list and a dict):</p>
<pre><code>def replace_func(f, replacement_f):
def new_f(*args, **kwargs):
replacement_f(args, kwargs)
return new_f
</code></pre>
<p>However, I cannot reference <code>replacement_f</code> inside <code>new_f</code>. And I can't use the standard trick of passing <code>replacement_f</code> to <code>new_f</code> as the default for a different parameter, because I'm using the <code>*args</code> and <code>**kwargs</code> variable argument lists.</p>
<p>The location where the original function is called cannot change, and will accept both positional and named parameters.</p>
<p>I fear that isn't very clear, but I'm happy to clarify if needed.</p>
<p>Thanks</p>
| 0 | 2009-08-18T17:39:40Z | 1,295,443 | <p>why don't you just try:</p>
<pre><code>f = replacement_f
</code></pre>
<p><em>example</em>:</p>
<pre><code>>>> def rep(*args):
print(*args, sep=' -- ')
>>> def ori(*args):
print(args)
>>> ori('dfef', 32)
('dfef', 32)
>>> ori = rep
>>> ori('dfef', 32)
dfef -- 32
</code></pre>
| 4 | 2009-08-18T17:44:41Z | [
"python",
"decorator",
"kwargs"
] |
How to replace Python function while supporting all passed in parameters | 1,295,415 | <p>I'm looking for a way to decorate an arbitrary python function, so that an alternate function is called instead of the original, with all parameters passed as a list or dict.</p>
<p>More precisely, something like this (where f is any function, and replacement_f takes a list and a dict):</p>
<pre><code>def replace_func(f, replacement_f):
def new_f(*args, **kwargs):
replacement_f(args, kwargs)
return new_f
</code></pre>
<p>However, I cannot reference <code>replacement_f</code> inside <code>new_f</code>. And I can't use the standard trick of passing <code>replacement_f</code> to <code>new_f</code> as the default for a different parameter, because I'm using the <code>*args</code> and <code>**kwargs</code> variable argument lists.</p>
<p>The location where the original function is called cannot change, and will accept both positional and named parameters.</p>
<p>I fear that isn't very clear, but I'm happy to clarify if needed.</p>
<p>Thanks</p>
| 0 | 2009-08-18T17:39:40Z | 1,295,465 | <p>does this do what you mean? Untested</p>
<pre><code>def replace_func(f, replacement_f):
nonlocal replacement_f #<<<<<<<<<<<<<<<py3k magic
def new_f(*args, **kwargs):
replacement_f(*args, **kwargs) # args & kwargs will be expanded
replacement_f = new_f
</code></pre>
<p><a href="http://stackoverflow.com/questions/1261875/python-nonlocal-statement">http://stackoverflow.com/questions/1261875/python-nonlocal-statement</a></p>
<p>edit: its a start, im confused exactly what you want, but i think nonlocal will help</p>
| 0 | 2009-08-18T17:48:48Z | [
"python",
"decorator",
"kwargs"
] |
How to replace Python function while supporting all passed in parameters | 1,295,415 | <p>I'm looking for a way to decorate an arbitrary python function, so that an alternate function is called instead of the original, with all parameters passed as a list or dict.</p>
<p>More precisely, something like this (where f is any function, and replacement_f takes a list and a dict):</p>
<pre><code>def replace_func(f, replacement_f):
def new_f(*args, **kwargs):
replacement_f(args, kwargs)
return new_f
</code></pre>
<p>However, I cannot reference <code>replacement_f</code> inside <code>new_f</code>. And I can't use the standard trick of passing <code>replacement_f</code> to <code>new_f</code> as the default for a different parameter, because I'm using the <code>*args</code> and <code>**kwargs</code> variable argument lists.</p>
<p>The location where the original function is called cannot change, and will accept both positional and named parameters.</p>
<p>I fear that isn't very clear, but I'm happy to clarify if needed.</p>
<p>Thanks</p>
| 0 | 2009-08-18T17:39:40Z | 1,295,621 | <p>Although I think SilentGhost's answer is the best solution if it works for you, for the sake of completeness, here is the correct version of what you where trying to do:</p>
<p>To define a decorator that takes an argument, you have to introduce an additional level:</p>
<pre><code>def replace_function(repl):
def deco(f):
def inner_f(*args, **kwargs):
repl(*args, **kwargs)
return inner_f
return deco
</code></pre>
<p>Now you can use the decorator with an argument:</p>
<pre><code>@replace_function(replacement_f)
def original_function(*args, **kwargs):
....
</code></pre>
| 1 | 2009-08-18T18:17:56Z | [
"python",
"decorator",
"kwargs"
] |
HTML snippet from Python | 1,295,446 | <p>I'm new to Python and CGI, so this may be trivial. But I'd like Python to produce a block of HTML whenever a visitor loads a page.</p>
<pre><code><html>
<body>
<!-- Beautiful website with great content -->
<!-- Suddenly... -->
<h1> Here's Some Python Output </h1>
<!-- RUN PYTHON SCRIPT, display output -->
</body>
</html>
</code></pre>
<p>Using a Python script that, for simplicity, looks something like this:</p>
<pre><code>#!/usr/bin/python
print "Content-type: text/html"
print
print "<p>Hello world!</p>"
</code></pre>
<p>Most resources I was able to find demonstrate how to produce an ENTIRE webpage using a Python script. Can you invoke a Python script mid-page to produce JUST an HTML snippet? </p>
| 1 | 2009-08-18T17:44:58Z | 1,295,519 | <p>Use AJAX client-side, or templates server side. </p>
<p>A template will allow you to keep most of your page static, but use a server-side scripting language (like Python) to fill in the dynamic bits. There are lots of good posts on Python template systems on Stackoverflow. <a href="http://stackoverflow.com/questions/98245/what-is-your-single-favorite-python-templating-engine">Here's one</a></p>
<p>AJAX will allow you to update a page after it initially loads with results from a server. </p>
| 3 | 2009-08-18T17:59:37Z | [
"python",
"html",
"cgi"
] |
Running a plain python interpreter in presense of ipython with manage.py shell | 1,295,492 | <p>I have ipython installed, I want to run a plain python interpreter instead with manage.py shell.</p>
<p>So I try,</p>
<pre><code>python2.5 manage.py shell --plain
</code></pre>
<p>Which gave me an error, and text which suggest that --plain was passed to ipython</p>
<p>So I read, <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/django-admin/</a></p>
<p>which suggets </p>
<pre><code>django-admin.py shell --plain
</code></pre>
<p>Which gives me </p>
<pre><code>Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
</code></pre>
<p>Which seem the correct thing for it to do.</p>
<p>What am I mising here? [Ubuntu Jaunty, django.VERSION = (1, 2, 0, 'alpha', 0), python 2.5 and 2.6]</p>
| 1 | 2009-08-18T17:53:50Z | 1,295,585 | <p><a href="http://proteus-tech.com/blog/code-garden/bpython-django/" rel="nofollow">link to a blog post explaining the same thing for bpython</a></p>
| 0 | 2009-08-18T18:11:33Z | [
"python",
"django",
"django-manage.py"
] |
Running a plain python interpreter in presense of ipython with manage.py shell | 1,295,492 | <p>I have ipython installed, I want to run a plain python interpreter instead with manage.py shell.</p>
<p>So I try,</p>
<pre><code>python2.5 manage.py shell --plain
</code></pre>
<p>Which gave me an error, and text which suggest that --plain was passed to ipython</p>
<p>So I read, <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/django-admin/</a></p>
<p>which suggets </p>
<pre><code>django-admin.py shell --plain
</code></pre>
<p>Which gives me </p>
<pre><code>Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
</code></pre>
<p>Which seem the correct thing for it to do.</p>
<p>What am I mising here? [Ubuntu Jaunty, django.VERSION = (1, 2, 0, 'alpha', 0), python 2.5 and 2.6]</p>
| 1 | 2009-08-18T17:53:50Z | 1,299,134 | <p>If the reason you want to use python's interpretor over iPython's is because you need to paste the doc tests, you can try typing</p>
<pre><code>%doctest_mode
</code></pre>
<p>in the ipython console instead</p>
<pre><code>In [1]: %doctest_mode
*** Pasting of code with ">>>" or "..." has been enabled.
Exception reporting mode: Plain
Doctest mode is: ON
>>>
</code></pre>
| 1 | 2009-08-19T10:53:32Z | [
"python",
"django",
"django-manage.py"
] |
Evaluate a script (e.g. Python) in Java for Android platform | 1,295,720 | <p>Is it possible to evaluate a string of python code (or Perl) from Java when developing Android applications?</p>
<p>I am try to do something like evaluating a text-input script:</p>
<p>e.g. </p>
<pre><code>String script = text1.getText().toString();
String result = PythonRuntime.evaluate(script);
text2.setText(result);
</code></pre>
| 1 | 2009-08-18T18:39:27Z | 1,295,730 | <p><a href="http://www.jython.org/" rel="nofollow">Jython</a> and its derivatives should be able to do this. See also <a href="http://code.google.com/p/jythonroid/" rel="nofollow">Jythondroid</a>.</p>
| 4 | 2009-08-18T18:41:21Z | [
"java",
"python",
"android",
"scripting"
] |
Evaluate a script (e.g. Python) in Java for Android platform | 1,295,720 | <p>Is it possible to evaluate a string of python code (or Perl) from Java when developing Android applications?</p>
<p>I am try to do something like evaluating a text-input script:</p>
<p>e.g. </p>
<pre><code>String script = text1.getText().toString();
String result = PythonRuntime.evaluate(script);
text2.setText(result);
</code></pre>
| 1 | 2009-08-18T18:39:27Z | 1,295,810 | <p>In case you weren't aware of it, the <a href="http://code.google.com/p/android-scripting/" rel="nofollow">Android Scripting Environment</a> might be useful to you, though I don't think it does exactly what you're looking for.</p>
| 4 | 2009-08-18T18:55:41Z | [
"java",
"python",
"android",
"scripting"
] |
On Google AppEngine what is the best way to merge two tables? | 1,295,832 | <p>If I have two tables, Company and Sales, and I want to display both sets of data in a single list, how would I do this on Google App Engine using GQL?</p>
<p>The models are:</p>
<pre><code>
class Company(db.Model):
companyname = db.StringProperty()
companyid = db.StringProperty()
salesperson = db.StringProperty()
class Sales(db.Model):
companyid = db.StringProperty()
weeklysales = db.StringProperty()
monthlysales = db.StringProperty()
</code></pre>
<p>The views are:</p>
<pre><code>
def company(request):
companys = db.GqlQuery("SELECT * FROM Company")
sales = db.GqlQuery("SELECT * FROM Sales")
template_values = {
'companys' : companys,
'sales' : sales
}
return respond(request, 'list', template_values)
</code></pre>
<p>List html includes:</p>
<pre><code>
{%for company in companys%}
{% for sale in sales %}
{% ifequal company.companyid sales.companyid %}
{{sales.weeklysales}}
{{sales.monthlysales}}
{% endifequal %}
{% endfor %}
{{company.companyname}}
{{company.companyid}}
{{company.salesperson}}
{%endfor%}
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 0 | 2009-08-18T19:00:18Z | 1,295,986 | <p>You should use a <a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#References" rel="nofollow">ReferenceProperty</a> in your Sales model:</p>
<p><code>company = db.ReferenceProperty(Company)</code></p>
<p>An example on how to iterate through the sales for a given company:</p>
<pre><code>company = db.GqlQuery("SELECT * FROM Company").fetch(1)[0]
for sale in company.sales_set:
#Do something ...
</code></pre>
| 0 | 2009-08-18T19:31:56Z | [
"python",
"google-app-engine"
] |
On Google AppEngine what is the best way to merge two tables? | 1,295,832 | <p>If I have two tables, Company and Sales, and I want to display both sets of data in a single list, how would I do this on Google App Engine using GQL?</p>
<p>The models are:</p>
<pre><code>
class Company(db.Model):
companyname = db.StringProperty()
companyid = db.StringProperty()
salesperson = db.StringProperty()
class Sales(db.Model):
companyid = db.StringProperty()
weeklysales = db.StringProperty()
monthlysales = db.StringProperty()
</code></pre>
<p>The views are:</p>
<pre><code>
def company(request):
companys = db.GqlQuery("SELECT * FROM Company")
sales = db.GqlQuery("SELECT * FROM Sales")
template_values = {
'companys' : companys,
'sales' : sales
}
return respond(request, 'list', template_values)
</code></pre>
<p>List html includes:</p>
<pre><code>
{%for company in companys%}
{% for sale in sales %}
{% ifequal company.companyid sales.companyid %}
{{sales.weeklysales}}
{{sales.monthlysales}}
{% endifequal %}
{% endfor %}
{{company.companyname}}
{{company.companyid}}
{{company.salesperson}}
{%endfor%}
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 0 | 2009-08-18T19:00:18Z | 1,297,981 | <pre><code>{%for company in companys%}
{% for sale in sales %}
{% ifequal company.companyid sales.companyid %}
</code></pre>
<p>that code is problematic. If you have 200 companies and 1000 sales, you will be running that ifequal statement 200000 times! </p>
<p>In general, if you have more than 1000 sales or companies, this won't work at all, because you can only get 1000 items at a time from the datastore. (and if you're not planning on having more than 1000 items, app engine is probably overkill for your project)</p>
<p>I think your first goal should be to figure out how you want to break your list up into pages. Do you want to display 50 sales per page? or maybe 10 companies per page, along with all their respective sales? Once you decide on that, you can query for just the information you need. </p>
| 0 | 2009-08-19T05:45:39Z | [
"python",
"google-app-engine"
] |
On Google AppEngine what is the best way to merge two tables? | 1,295,832 | <p>If I have two tables, Company and Sales, and I want to display both sets of data in a single list, how would I do this on Google App Engine using GQL?</p>
<p>The models are:</p>
<pre><code>
class Company(db.Model):
companyname = db.StringProperty()
companyid = db.StringProperty()
salesperson = db.StringProperty()
class Sales(db.Model):
companyid = db.StringProperty()
weeklysales = db.StringProperty()
monthlysales = db.StringProperty()
</code></pre>
<p>The views are:</p>
<pre><code>
def company(request):
companys = db.GqlQuery("SELECT * FROM Company")
sales = db.GqlQuery("SELECT * FROM Sales")
template_values = {
'companys' : companys,
'sales' : sales
}
return respond(request, 'list', template_values)
</code></pre>
<p>List html includes:</p>
<pre><code>
{%for company in companys%}
{% for sale in sales %}
{% ifequal company.companyid sales.companyid %}
{{sales.weeklysales}}
{{sales.monthlysales}}
{% endifequal %}
{% endfor %}
{{company.companyname}}
{{company.companyid}}
{{company.salesperson}}
{%endfor%}
</code></pre>
<p>Any help would be greatly appreciated.</p>
| 0 | 2009-08-18T19:00:18Z | 1,300,954 | <p>You've said in a comment that there's a 1-1 relationship between sales and companies. So you could get the data in the same order:</p>
<pre><code>def company(request):
companys = db.GqlQuery("SELECT * FROM Company ORDER BY companyid").fetch(1000)
sales = db.GqlQuery("SELECT * FROM Sales ORDER BY companyid").fetch(1000)
template_values = {
'companys' : companys,
'sales' : sales
}
return respond(request, 'list', template_values)
{%for company in companys%}
{{sales[forloop.counter0].weeklysales}}
{{sales[forloop.counter0].monthlysales}}
{{company.companyname}}
{{company.companyid}}
{{company.salesperson}}
{%endfor%}
</code></pre>
<p>That's still not a great solution, though. If you're confident that the 1-1 relationship is correct, then I would just have a single entity containing all the information. If nothing else, it saves you worrying about database inconsistency where you create a company, but your attempt to create the corresponding sales data entity fails for some reason.</p>
| 1 | 2009-08-19T16:01:52Z | [
"python",
"google-app-engine"
] |
Numpy: Is there an array size limit? | 1,295,994 | <p>I'm learning to use Numpy and I wanted to see the speed difference in the summation of a list of numbers so I made this code:</p>
<pre><code>np_array = numpy.arange(1000000)
start = time.time()
sum_ = np_array.sum()
print time.time() - start, sum_
>>> 0.0 1783293664
python_list = range(1000000)
start = time.time()
sum_ = sum(python_list)
print time.time() - start, sum_
>>> 0.390000104904 499999500000
</code></pre>
<p>The python_list sum is correct.</p>
<p>If I do the same code with the summation to 1000, both print the right answer. Is there an upper limit to the length of the Numpy array or is it with the Numpy sum function?</p>
<p>Thanks for your help</p>
| 3 | 2009-08-18T19:33:20Z | 1,296,017 | <p>The standard list switched over to doing arithmetic with the long type when numbers got larger than a 32-bit int.</p>
<p>The numpy array did not switch to long, and suffered from integer overflow. The price for speed is smaller range of values allowed.</p>
<pre><code>>>> 499999500000 % 2**32
1783293664L
</code></pre>
| 9 | 2009-08-18T19:38:08Z | [
"python",
"numpy"
] |
Numpy: Is there an array size limit? | 1,295,994 | <p>I'm learning to use Numpy and I wanted to see the speed difference in the summation of a list of numbers so I made this code:</p>
<pre><code>np_array = numpy.arange(1000000)
start = time.time()
sum_ = np_array.sum()
print time.time() - start, sum_
>>> 0.0 1783293664
python_list = range(1000000)
start = time.time()
sum_ = sum(python_list)
print time.time() - start, sum_
>>> 0.390000104904 499999500000
</code></pre>
<p>The python_list sum is correct.</p>
<p>If I do the same code with the summation to 1000, both print the right answer. Is there an upper limit to the length of the Numpy array or is it with the Numpy sum function?</p>
<p>Thanks for your help</p>
| 3 | 2009-08-18T19:33:20Z | 1,296,028 | <p>Numpy is creating an array of 32-bit unsigned ints.
When it sums them, it sums them into a 32-bit value.</p>
<pre><code>if 499999500000L % (2**32) == 1783293664L:
print "Overflowed a 32-bit integer"
</code></pre>
<p>You can explicitly choose the data type at array creation time:</p>
<pre><code>a = numpy.arange(1000000, dtype=numpy.uint64)
a.sum() -> 499999500000
</code></pre>
| 9 | 2009-08-18T19:40:03Z | [
"python",
"numpy"
] |
Numpy: Is there an array size limit? | 1,295,994 | <p>I'm learning to use Numpy and I wanted to see the speed difference in the summation of a list of numbers so I made this code:</p>
<pre><code>np_array = numpy.arange(1000000)
start = time.time()
sum_ = np_array.sum()
print time.time() - start, sum_
>>> 0.0 1783293664
python_list = range(1000000)
start = time.time()
sum_ = sum(python_list)
print time.time() - start, sum_
>>> 0.390000104904 499999500000
</code></pre>
<p>The python_list sum is correct.</p>
<p>If I do the same code with the summation to 1000, both print the right answer. Is there an upper limit to the length of the Numpy array or is it with the Numpy sum function?</p>
<p>Thanks for your help</p>
| 3 | 2009-08-18T19:33:20Z | 1,296,051 | <p>Notice that <code>499999500000 % 2**32</code> equals exactly 1783293664 ... i.e., numpy is doing operations modulo 2**32, because that's the type of the numpy.array you've told it to use. </p>
<p>Make <code>np_array = numpy.arange(1000000, dtype=numpy.uint64)</code>, for example, and your sum will come out OK (although of course there are still limits, with any finite-size number type).</p>
<p>You can use <code>dtype=numpy.object</code> to tell numpy that the array holds generic Python objects; of course, performance will decay as generality increases.</p>
| 6 | 2009-08-18T19:43:12Z | [
"python",
"numpy"
] |
Tuple list from dict in Python | 1,296,042 | <p>How can I obtain a list of key-value tuples from a <a href="http://docs.python.org/2/library/stdtypes.html#dict">dict</a> in Python?</p>
| 23 | 2009-08-18T19:41:26Z | 1,296,049 | <p>For Python 2.x only (thanks Alex):</p>
<pre><code>yourdict = {}
# ...
items = yourdict.items()
</code></pre>
<p>See <a href="http://docs.python.org/library/stdtypes.html#dict.items">http://docs.python.org/library/stdtypes.html#dict.items</a> for details.</p>
<p>For Python 3.x only (taken from <a href="http://stackoverflow.com/questions/1296042/tuple-list-from-dict-in-python/1296074#1296074">Alex's answer</a>):</p>
<pre><code>yourdict = {}
# ...
items = list(yourdict.items())
</code></pre>
| 40 | 2009-08-18T19:42:48Z | [
"python",
"list",
"dictionary",
"key-value"
] |
Tuple list from dict in Python | 1,296,042 | <p>How can I obtain a list of key-value tuples from a <a href="http://docs.python.org/2/library/stdtypes.html#dict">dict</a> in Python?</p>
| 23 | 2009-08-18T19:41:26Z | 1,296,070 | <p>For a list of of tuples:</p>
<pre><code>my_dict.items()
</code></pre>
<p>If all you're doing is iterating over the items, however, it is often preferable to use <code>dict.iteritems()</code>, which is more memory efficient because it returns only one item at a time, rather than all items at once:</p>
<pre><code>for key,value in my_dict.iteritems():
#do stuff
</code></pre>
| 5 | 2009-08-18T19:45:09Z | [
"python",
"list",
"dictionary",
"key-value"
] |
Tuple list from dict in Python | 1,296,042 | <p>How can I obtain a list of key-value tuples from a <a href="http://docs.python.org/2/library/stdtypes.html#dict">dict</a> in Python?</p>
| 23 | 2009-08-18T19:41:26Z | 1,296,074 | <p>In Python <code>2.*</code>, <code>thedict.items()</code>, as in @Andrew's answer. In Python <code>3.*</code>, <code>list(thedict.items())</code> (since there <code>items</code> is just an iterable view, not a list, you need to call <code>list</code> on it explicitly if you need exactly a list).</p>
| 5 | 2009-08-18T19:45:45Z | [
"python",
"list",
"dictionary",
"key-value"
] |
Tuple list from dict in Python | 1,296,042 | <p>How can I obtain a list of key-value tuples from a <a href="http://docs.python.org/2/library/stdtypes.html#dict">dict</a> in Python?</p>
| 23 | 2009-08-18T19:41:26Z | 5,352,946 | <p>For Python > 2.5:</p>
<pre><code>a = {'1' : 10, '2' : 20 }
list(a.itervalues())
</code></pre>
| -2 | 2011-03-18T13:51:19Z | [
"python",
"list",
"dictionary",
"key-value"
] |
Tuple list from dict in Python | 1,296,042 | <p>How can I obtain a list of key-value tuples from a <a href="http://docs.python.org/2/library/stdtypes.html#dict">dict</a> in Python?</p>
| 23 | 2009-08-18T19:41:26Z | 11,231,128 | <blockquote>
<p>Converting from dict to list is made easy in Python. Three examples:</p>
<blockquote>
<blockquote>
<p>d = {'a': 'Arthur', 'b': 'Belling'}</p>
<p>d.items() [('a', 'Arthur'), ('b', 'Belling')]</p>
<p>d.keys() ['a', 'b']</p>
<p>d.values() ['Arthur', 'Belling']</p>
</blockquote>
</blockquote>
</blockquote>
<p>as seen in a previous answer <a href="http://stackoverflow.com/questions/1679384/converting-python-dictionary-to-list">Converting Python Dictionary to List</a></p>
| 2 | 2012-06-27T16:40:53Z | [
"python",
"list",
"dictionary",
"key-value"
] |
How can I read a python pickle database/file from C? | 1,296,162 | <p>I am working on integrating with several music players. At the moment my favorite is exaile.</p>
<p>In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand.</p>
<p>I know there is the cPickle python module, but I am unaware if it is callable directly from C.</p>
| 8 | 2009-08-18T20:02:51Z | 1,296,188 | <p>You can embed a Python interpreter in a C program, but I think that the easiest solution is to write a Python script that converts "pickles" in another format, e.g. an SQLite database.</p>
| 1 | 2009-08-18T20:07:27Z | [
"python",
"c"
] |
How can I read a python pickle database/file from C? | 1,296,162 | <p>I am working on integrating with several music players. At the moment my favorite is exaile.</p>
<p>In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand.</p>
<p>I know there is the cPickle python module, but I am unaware if it is callable directly from C.</p>
| 8 | 2009-08-18T20:02:51Z | 1,296,612 | <p>Like Cristian told, you can rather easily embed python code in your C code, see the example here: <a href="http://docs.python.org/extending/extending.html#calling-python-functions-from-c" rel="nofollow">http://docs.python.org/extending/extending.html#calling-python-functions-from-c</a></p>
<p>Using cPickle is dead easy as well on python you could use somehting like:</p>
<pre><code>import cPickle
f = open('dbfile', 'rb')
db = cPicle.load(f)
f.close()
# handle db integration
f = open('dbfile', 'wb')
cPickle.dump(db, f)
f.close()
</code></pre>
| 3 | 2009-08-18T21:25:52Z | [
"python",
"c"
] |
How can I read a python pickle database/file from C? | 1,296,162 | <p>I am working on integrating with several music players. At the moment my favorite is exaile.</p>
<p>In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand.</p>
<p>I know there is the cPickle python module, but I am unaware if it is callable directly from C.</p>
| 8 | 2009-08-18T20:02:51Z | 4,166,900 | <p><a href="http://www.picklingtools.com/">http://www.picklingtools.com/</a></p>
<p>There is a library called the PicklingTools which I help maintain which might be useful: it allows you to form data structures in C++ that you can then pickle/unpickle ... it is C++, not C, but that shouldn't be a problem these days (assuming you are using the gcc/g++ suite). </p>
<p>The library is a plain C++ library (there are examples of C++ and Python within the distribution showing how to use the library over sockets and files from both C++ and Python), but in general, the basics of pickling to files is available.</p>
<p>The basic idea is that the PicklingTools library gives you "python-like" data structures from C++ so that you can then serialize and deserialize to/from Python/C++. All (?) the basic types: int, long int,string, None, complex, dictionarys, lists, ordered dictionaries and tuples are supported. There are few hooks to do custom classes, but that part is a bit immature: the rest of the library is pretty stable and has been active for 8 (?) years.</p>
<p>Simple example:</p>
<pre><code>#include "chooseser.h"
int main()
{
Val a_dict = Tab("{ 'a':1, 'b':[1,2.2,'three'], 'c':None }");
cout << a_dict["b"][0]; // value of 1
// Dump to a file
DumpValToFile(a_dict, "example.p0", SERIALIZE_P0);
// .. from Python, can load the dictionary with pickle.load(file('example.p0'))
// Get the result back
Val result;
LoadValFromFile(result, "example.p0", SERIALIZE_P0);
cout << result << endl;
}
</code></pre>
<p>There is further documentation (FAQ and User's Guide) on the web site.</p>
<p>Hope this is useful:</p>
<p>Gooday,</p>
<p>Richie</p>
<p><a href="http://www.picklingtools.com/">http://www.picklingtools.com/</a></p>
| 14 | 2010-11-12T16:37:26Z | [
"python",
"c"
] |
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works | 1,296,311 | <p>I've been reading <a href="http://www.mindview.net/Books/TIPython" rel="nofollow">Thinking in python</a> by Bruce Eckel. Currently, I'm reading the <em>Pattern Concept</em> chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class). </p>
<p>This is my understanding of the code so far: </p>
<ul>
<li>All <em>Singleton</em> objects are subclasses of <em>Borg</em></li>
<li>*_shared_state* is initially an empty dictionary</li>
<li>*_shared_state* is a global variable; Any objects utilizing <em>Borg</em> will have the same *_shared_state* value</li>
</ul>
<p>My confusion so far:</p>
<ul>
<li>What's the purpose of this line: <code>self.__dict__ = self._shared_state</code> ; or the purpose of the dictionary</li>
<li>How did all the objects of <em>Singletons</em> eventually have the same <em>val</em>, even though they are all different instances of the class. </li>
<li>In overall, I don't know how <em>Borg</em> works</li>
</ul>
<p>Many Many thanks in advance!</p>
<p>-Tri</p>
<p>*Update: What is stored in *_shared_state* after each <em>Singleton</em> object creation?</p>
<pre><code>#: Alex' Martelli's Singleton in Python
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = Singleton('sausage')
print x
y = Singleton('eggs')
print y
z = Singleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
'''
</code></pre>
| 3 | 2009-08-18T20:28:46Z | 1,296,343 | <pre><code>class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
</code></pre>
<p>1) since <code>Borg._shared_state</code> is initialized at class-level (not in <code>__init__</code>) it is effectively static, e.g. shared by all instances of the class.</p>
<p>2) <code>self.__dict__</code> is a dictionary that all objects have; it contains all instance attributes. thus, </p>
<pre><code>self.a=1
assert(self.a == self.__dict__['a']) #True
</code></pre>
<p>3) Note that a Borg means 'all instances share the same state', a singleton means 'only one instance'. It's pretty much the same effect. <a href="http://stackoverflow.com/questions/1296311/bruce-eckels-code-snippet-from-design-pattern-im-confused-on-how-it-works/1297577#1297577">Alex Martelli</a> pointed out that Borg is a pythonic Monostate, so see <a href="http://stackoverflow.com/questions/887317/monostate-vs-singleton/887380">Monostate vs Singleton on SO</a>.</p>
<p>It seems that his Singleton class is more aptly named </p>
<pre><code>class ThisClassHasSingletonBehavior(Borg):
....
</code></pre>
<p>because</p>
<pre><code><__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
</code></pre>
<p>proves that x,y,z are not the same instance, even though they share the same state. So it's not REALLY a singleton, it just has the same overall effect, and is easy. AFAICT Borg is a elegant python-pattern for shared state (same state) behavior, where Singleton is an elegant cpp-pattern for same. not that this behavior is ever elegant.</p>
| 6 | 2009-08-18T20:34:56Z | [
"python"
] |
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works | 1,296,311 | <p>I've been reading <a href="http://www.mindview.net/Books/TIPython" rel="nofollow">Thinking in python</a> by Bruce Eckel. Currently, I'm reading the <em>Pattern Concept</em> chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class). </p>
<p>This is my understanding of the code so far: </p>
<ul>
<li>All <em>Singleton</em> objects are subclasses of <em>Borg</em></li>
<li>*_shared_state* is initially an empty dictionary</li>
<li>*_shared_state* is a global variable; Any objects utilizing <em>Borg</em> will have the same *_shared_state* value</li>
</ul>
<p>My confusion so far:</p>
<ul>
<li>What's the purpose of this line: <code>self.__dict__ = self._shared_state</code> ; or the purpose of the dictionary</li>
<li>How did all the objects of <em>Singletons</em> eventually have the same <em>val</em>, even though they are all different instances of the class. </li>
<li>In overall, I don't know how <em>Borg</em> works</li>
</ul>
<p>Many Many thanks in advance!</p>
<p>-Tri</p>
<p>*Update: What is stored in *_shared_state* after each <em>Singleton</em> object creation?</p>
<pre><code>#: Alex' Martelli's Singleton in Python
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = Singleton('sausage')
print x
y = Singleton('eggs')
print y
z = Singleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
'''
</code></pre>
| 3 | 2009-08-18T20:28:46Z | 1,296,490 | <p>Comparing to instances of a normal class may help you see what they're doing:</p>
<pre><code>>>> class NormalClass:
def __init__(self, arg):
self.x = arg
>>> a = NormalClass(1)
>>> b = NormalClass(2)
>>> a.x
1
>>> a.__dict__
{'x': 1}
>>> b.x
2
>>> b.__dict__
{'x': 2}
Note how the instances here each have their own unshared __dict__ where
their own x attribute is stored.
</code></pre>
<p>Editing to add: Now, let's make these normal objects share a dictionary and see what happens...</p>
<pre><code>>>> Another_Dictionary_We_Make = {}
>>> Another_Dictionary_We_Make['x'] = 1000
>>> Another_Dictionary_We_Make
{'x': 1000}
>>> a.__dict__ = Another_Dictionary_We_Make
>>> a.x
1000
>>> b.x
2
>>> b.__dict__ = Another_Dictionary_We_Make
>>> b.x
1000
>>> b.x = 777
>>> b.__dict__
{'x': 777}
>>> a.x
777
>>> a.__dict__
{'x': 777}
</code></pre>
<p>This shows making the <strong>dict</strong> be the same for both objects after they're created. The Borg/Singleton is simply causing instances to share the same dictionary by initializing them to use the same <strong>dict</strong> when they're created.</p>
| 2 | 2009-08-18T21:00:19Z | [
"python"
] |
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works | 1,296,311 | <p>I've been reading <a href="http://www.mindview.net/Books/TIPython" rel="nofollow">Thinking in python</a> by Bruce Eckel. Currently, I'm reading the <em>Pattern Concept</em> chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class). </p>
<p>This is my understanding of the code so far: </p>
<ul>
<li>All <em>Singleton</em> objects are subclasses of <em>Borg</em></li>
<li>*_shared_state* is initially an empty dictionary</li>
<li>*_shared_state* is a global variable; Any objects utilizing <em>Borg</em> will have the same *_shared_state* value</li>
</ul>
<p>My confusion so far:</p>
<ul>
<li>What's the purpose of this line: <code>self.__dict__ = self._shared_state</code> ; or the purpose of the dictionary</li>
<li>How did all the objects of <em>Singletons</em> eventually have the same <em>val</em>, even though they are all different instances of the class. </li>
<li>In overall, I don't know how <em>Borg</em> works</li>
</ul>
<p>Many Many thanks in advance!</p>
<p>-Tri</p>
<p>*Update: What is stored in *_shared_state* after each <em>Singleton</em> object creation?</p>
<pre><code>#: Alex' Martelli's Singleton in Python
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = Singleton('sausage')
print x
y = Singleton('eggs')
print y
z = Singleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
'''
</code></pre>
| 3 | 2009-08-18T20:28:46Z | 1,297,577 | <p>Good answers so far, but let me also answer directly... <code>self.__dict__</code> holds the attributes (i.e., the state) of instance <code>self</code> (unless its class does peculiar things such as defining <code>__slots__</code>;-). So by ensuring that all instances have the same <code>__dict__</code> we're ensuring they all have the same attributes, i.e., exactly the same state. So, Borg is a neat Python implementation of the general <a href="http://www.c2.com/cgi/wiki?MonostatePattern">Monostate</a> pattern, but without any of the downsides that Robert Martin identified in his <a href="http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf">essay</a> on Monostate <em>in C++</em>.</p>
<p>See also <a href="http://stackoverflow.com/questions/887317/monostate-vs-singleton/887380">this SO thread</a> for Monostate vs Singleton -- of course much of the discussion is NOT relevant to Python (obviously in Python Borg does not stand in the way of inheritance, on the contrary!, but then Singleton can be quite as transparent thanks to e.g. <code>__new__</code>, so the tradeoff are quite different...).</p>
<p>The funniest thing? In the 8+ years since I first conceived of Borg (before David Ascher, now CEO of Mozilla Messaging, suggested the cool Borg name) I've had occasion to use any kind of singleton or monostate maybe four times in all -- and three times out of the four I soon refactored it out in favor of a more flexible approach!-) (The fourth time was a subsystem that didn't prove very successful and didn't get much followup work/maintenance;-).</p>
<p>Second-funniest thing is that Guido, personally, <em>detests</em> Borg;-). Not that he has any real liking for Singleton either: he thinks in Python "singletonarity", if needed, should be done as a module (or, I'd like to add, a class instance masquerading as a module -- see e.g. my observation in section 7.2.6 of Python in a Nutshell, e.g. in <a href="http://www.hell.org.ua/Docs/oreilly/other2/python/0596001886%5Fpythonian-chp-7-sect-2.html">this</a> pirate copy;-). But, Borg appears to particularly offend his design aesthetics!-) Peculiar, since he did nominate me for PSF membership based on my <a href="http://www.aleax.it/Python/5ep.html">Five Easy Pieces</a> essay, which is basically ALL about Borg (and variants thereof, and considerations thereupon)...!-). Ah well, guess he can "hate the sin but love the sinner", hm?-)</p>
| 9 | 2009-08-19T02:37:39Z | [
"python"
] |
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works | 1,296,311 | <p>I've been reading <a href="http://www.mindview.net/Books/TIPython" rel="nofollow">Thinking in python</a> by Bruce Eckel. Currently, I'm reading the <em>Pattern Concept</em> chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inheritance, instead of privated nested class). </p>
<p>This is my understanding of the code so far: </p>
<ul>
<li>All <em>Singleton</em> objects are subclasses of <em>Borg</em></li>
<li>*_shared_state* is initially an empty dictionary</li>
<li>*_shared_state* is a global variable; Any objects utilizing <em>Borg</em> will have the same *_shared_state* value</li>
</ul>
<p>My confusion so far:</p>
<ul>
<li>What's the purpose of this line: <code>self.__dict__ = self._shared_state</code> ; or the purpose of the dictionary</li>
<li>How did all the objects of <em>Singletons</em> eventually have the same <em>val</em>, even though they are all different instances of the class. </li>
<li>In overall, I don't know how <em>Borg</em> works</li>
</ul>
<p>Many Many thanks in advance!</p>
<p>-Tri</p>
<p>*Update: What is stored in *_shared_state* after each <em>Singleton</em> object creation?</p>
<pre><code>#: Alex' Martelli's Singleton in Python
class Borg:
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
class Singleton(Borg):
def __init__(self, arg):
Borg.__init__(self)
self.val = arg
def __str__(self): return self.val
x = Singleton('sausage')
print x
y = Singleton('eggs')
print y
z = Singleton('spam')
print z
print x
print y
print ´x´
print ´y´
print ´z´
output = '''
sausage
eggs
spam
spam
spam
<__main__.Singleton instance at 0079EF2C>
<__main__.Singleton instance at 0079E10C>
<__main__.Singleton instance at 00798F9C>
'''
</code></pre>
| 3 | 2009-08-18T20:28:46Z | 31,640,691 | <p>I believe the question was this:how does <code>Borg._shared_state</code> get updated? Answer: through <code>self.__dict__</code> in every instance.
<code>self.__dict__ = self._shared_state</code> gives you access to <code>Borg._shared_state</code> through <code>self.__dict__</code> of every instance. When you change an instance attribute, you change that instance's <code>__dict__</code> and since that instance's <code>__dict__</code> is pointing to <code>Borg._shared_state</code>, you actually change <code>Borg._shared_state</code>, too.
In python, when you say <code>var1 = var2</code>, <code>var1</code> points to the value of <code>var2</code> and it has access to that value. That's why <code>var1 = a_different_value</code> will actually change the value of <code>var2</code> as well as the value of <code>var1</code>.
I am also reading the above-mentioned book (online through BitBucket). BitBucket says that development stopped a few years ago, though. I wonder why that is. Maybe the author can comment on this. Thank you Alex Martelli for this great book.</p>
| 0 | 2015-07-26T18:51:41Z | [
"python"
] |
simple python script to block nokia n73 screen | 1,296,359 | <p>i want that upon opening my N73's camera cover,the camera software keeps working as usual,but that it is blocked by a black screen covering the whole screen so that it appears that the camera is not working... I know my requirement is weired but i need this.. ;)</p>
<p>Can anyone guide me to write a python script that does exactly this... i searched a lot over net for any existing apps but couldnot find one..</p>
<p>Thanks for helping..</p>
| 1 | 2009-08-18T20:38:23Z | 1,296,689 | <p>I'm rather sceptical whether this can be achieved with PyS60. First of all, AFAIK for PyS60 program you'd need to start the interpreter environment first, autostarting when camera starts probably won't be possible.</p>
<p>Also, opening the camera cover probably does not have any callback so you won't be able to detect it from python however, you could try something like this presented in PyS60 1.4.5 doc (<a href="http://downloads.sourceforge.net/project/pys60/pys60/1.4.5/PythonForS60%5F1%5F4%5F5%5Fdoc.pdf" rel="nofollow">http://downloads.sourceforge.net/project/pys60/pys60/1.4.5/PythonForS60%5F1%5F4%5F5%5Fdoc.pdf</a>):</p>
<pre><code>>>> import appuifw
>>> import camera
>>> def cb(im):
... appuifw.app.body.blit(im)
...
>>> import graphics
>>> appuifw.app.body=appuifw.Canvas()
>>> camera.start_finder(cb)
</code></pre>
<p>Instead of blitting im you could just blit a black screen and store im. Or something. But seriously, this sounds like some very bad prank...</p>
| 0 | 2009-08-18T21:40:04Z | [
"python",
"camera",
"pys60",
"n73"
] |
Parse Gmail with Python and mark all older than date as "read" | 1,296,446 | <p>Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as unread, but I need them to appear as read.</p>
<p>I have a little experience with python, but I've only used mail and imaplib modules for sending mail, not processing accounts.</p>
<p>Is there a way to bulk process all items in an inbox, and simply mark messages older than a specified date as read?</p>
| 4 | 2009-08-18T20:52:28Z | 1,296,465 | <p>Rather than try to parse our HTML why not just use the IMAP interface? Hook it up to a standard mail client and then just sort by date and mark whichever ones you want as read.</p>
| 1 | 2009-08-18T20:55:42Z | [
"python",
"email",
"gmail",
"imap",
"pop3"
] |
Parse Gmail with Python and mark all older than date as "read" | 1,296,446 | <p>Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as unread, but I need them to appear as read.</p>
<p>I have a little experience with python, but I've only used mail and imaplib modules for sending mail, not processing accounts.</p>
<p>Is there a way to bulk process all items in an inbox, and simply mark messages older than a specified date as read?</p>
| 4 | 2009-08-18T20:52:28Z | 1,296,476 | <p>Just go to the Gmail web interface, do an advanced search by date, then select all and mark as read.</p>
| 1 | 2009-08-18T20:57:09Z | [
"python",
"email",
"gmail",
"imap",
"pop3"
] |
Parse Gmail with Python and mark all older than date as "read" | 1,296,446 | <p>Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as unread, but I need them to appear as read.</p>
<p>I have a little experience with python, but I've only used mail and imaplib modules for sending mail, not processing accounts.</p>
<p>Is there a way to bulk process all items in an inbox, and simply mark messages older than a specified date as read?</p>
| 4 | 2009-08-18T20:52:28Z | 1,296,613 | <pre><code>typ, data = M.search(None, '(BEFORE 01-Jan-2009)')
for num in data[0].split():
M.store(num, '+FLAGS', '\\Seen')
</code></pre>
<p>This is a slight modification of the code in the <a href="http://docs.python.org/library/imaplib.html" rel="nofollow">imaplib doc page</a> for the store method. I found the search criteria to use from <a href="http://tools.ietf.org/html/rfc3501.html" rel="nofollow">RFC 3501</a>. This should get you started.</p>
| 8 | 2009-08-18T21:25:53Z | [
"python",
"email",
"gmail",
"imap",
"pop3"
] |
Parse Gmail with Python and mark all older than date as "read" | 1,296,446 | <p>Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as unread, but I need them to appear as read.</p>
<p>I have a little experience with python, but I've only used mail and imaplib modules for sending mail, not processing accounts.</p>
<p>Is there a way to bulk process all items in an inbox, and simply mark messages older than a specified date as read?</p>
| 4 | 2009-08-18T20:52:28Z | 8,740,548 | <p>Based on Philip T.'s answer above and <a href="http://tools.ietf.org/html/rfc3501.html" rel="nofollow">RFC 3501</a> and <a href="http://tools.ietf.org/html/rfc2822.html" rel="nofollow">RFC 2822</a>, I built some lines of code to mark mails older than 10 days as read. A static list is used for the abbreviated month names. This is not particularly elegant, but Python's %b format string is locale dependent, which could give unpleasant surprises. All IMAP commands are UID based.</p>
<pre><code>import imaplib, datetime
myAccount = imaplib.IMAP4(<imapserver>)
myAccount.login(<imapuser>, <password>)
myAccount.select(<mailbox>)
monthListRfc2822 = ['0', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
beforeDate = datetime.datetime.today() - datetime.timedelta(days = 10)
beforeDateString = ("(BEFORE %s-%s-%s)"
% (beforeDate.strftime('%d'),
monthListRfc2822[beforeDate.month],
beforeDate.strftime('%Y')))
typ, data = myAccount.uid('SEARCH', beforeDateString)
for uid in data[0].split():
myAccount.uid('STORE', uid, '+FLAGS', '(\Seen)')
</code></pre>
<p>By the way: I do not know, why "-" had to be used as a date delimiter in the search string in my case (dovecot IMAP server). To me that seems to contradict RFC 2822. However, dates with simple whitespace as delimiter only returned IMAP errors.</p>
| 2 | 2012-01-05T09:57:47Z | [
"python",
"email",
"gmail",
"imap",
"pop3"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,296,522 | <p>This will print the directory in which the script lives (as opposed to the working directory):</p>
<pre><code>import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print "running from", dirname
print "file is", filename
</code></pre>
<p>Here's how it behaves, when I put it in <code>c:\src</code>:</p>
<pre><code>> cd c:\src
> python so-where.py
running from C:\src
file is so-where.py
> cd c:\
> python src\so-where.py
running from C:\src
file is so-where.py
</code></pre>
| 12 | 2009-08-18T21:08:20Z | [
"python"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,296,535 | <pre><code>import sys, os
file = sys.argv[0]
pathname = os.path.dirname(file)
print 'running from %s' % os.path.abspath(pathname)
print 'file is %s' % file
</code></pre>
<p>Check os.getcwd() (<a href="http://docs.python.org/library/os.html" rel="nofollow">docs</a>)</p>
| 2 | 2009-08-18T21:10:04Z | [
"python"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,296,536 | <p>The script name will (always?) be the first index of sys.argv:</p>
<pre><code>import sys
print sys.argv[0]
</code></pre>
<p>An even easier way to find the path of your running script:</p>
<pre><code>os.path.basename(sys.argv[0])
</code></pre>
| 2 | 2009-08-18T21:10:11Z | [
"python"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,296,537 | <p>The running file is always <code>__file__</code>.</p>
<p>Here's a demo script, named <code>identify.py</code></p>
<pre><code>print __file__
</code></pre>
<p>Here's the results</p>
<pre><code>MacBook-5:Projects slott$ python StackOverflow/identify.py
StackOverflow/identify.py
MacBook-5:Projects slott$ cd StackOverflow/
MacBook-5:StackOverflow slott$ python identify.py
identify.py
</code></pre>
| 1 | 2009-08-18T21:10:13Z | [
"python"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,297,407 | <p><strong><code>__file__</code> is NOT what you are looking for.</strong> Don't use accidental side-effects</p>
<p><code>sys.argv[0]</code> is <strong>always</strong> the path to the script (if in fact a script has been invoked) -- see <a href="http://docs.python.org/library/sys.html#sys.argv">http://docs.python.org/library/sys.html#sys.argv</a></p>
<p><code>__file__</code> is the path of the <em>currently executing</em> file (script or module). This is <strong>accidentally</strong> the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use <code>sys.argv[0]</code>.</p>
<p>Example:</p>
<pre><code>C:\junk\so>type \junk\so\scriptpath\script1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
C:\junk\so>type \python26\lib\site-packages\whereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
C:\junk\so>\python26\python scriptpath\script1.py
script: sys.argv[0] is 'scriptpath\\script1.py'
script: __file__ is 'scriptpath\\script1.py'
script: cwd is 'C:\\junk\\so'
show_where: sys.argv[0] is 'scriptpath\\script1.py'
show_where: __file__ is 'C:\\python26\\lib\\site-packages\\whereutils.pyc'
show_where: cwd is 'C:\\junk\\so'
</code></pre>
| 43 | 2009-08-19T01:29:19Z | [
"python"
] |
Python - Find Path to File Being Run | 1,296,501 | <p>How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this:</p>
<pre><code>Nirvana@bahamut:/tmp$ python baz.py
running from /tmp
file is baz.py
</code></pre>
| 23 | 2009-08-18T21:02:54Z | 1,299,299 | <p>I would suggest</p>
<pre><code>import os, sys
print os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]
</code></pre>
<p>This way you can safely create symbolic links to the script executable and it will still find the correct directory.</p>
| 1 | 2009-08-19T11:24:13Z | [
"python"
] |
Efficiency of using a Python list as a queue | 1,296,511 | <p>A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used <code>.append(x)</code> when needing to insert items and <code>.pop(0)</code> when needing to remove items.</p>
<p>I know that Python has <a href="http://docs.python.org/library/collections.html#collections.deque"><code>collections.deque</code></a> and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?</p>
<p>In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a <code>realloc</code> and free up some of that memory?</p>
| 34 | 2009-08-18T21:05:58Z | 1,296,523 | <p>it sounds like a bit of empirical testing might be the best thing to do here - second order issues might make one approach better in practice, even if it's not better in theory.</p>
| 2 | 2009-08-18T21:08:22Z | [
"python",
"list",
"memory-leaks"
] |
Efficiency of using a Python list as a queue | 1,296,511 | <p>A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used <code>.append(x)</code> when needing to insert items and <code>.pop(0)</code> when needing to remove items.</p>
<p>I know that Python has <a href="http://docs.python.org/library/collections.html#collections.deque"><code>collections.deque</code></a> and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?</p>
<p>In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a <code>realloc</code> and free up some of that memory?</p>
| 34 | 2009-08-18T21:05:58Z | 1,296,527 | <p>You won't run out of memory using the <code>list</code> implementation, but performance will be poor. From <a href="http://docs.python.org/library/collections.html">the docs</a>:</p>
<blockquote>
<p>Though <code>list</code> objects support similar
operations, they are optimized for
fast fixed-length operations and incur
O(n) memory movement costs for
<code>pop(0)</code> and <code>insert(0, v)</code> operations
which change both the size and
position of the underlying data
representation.</p>
</blockquote>
<p>So using a <code>deque</code> will be much faster.</p>
| 23 | 2009-08-18T21:09:05Z | [
"python",
"list",
"memory-leaks"
] |
Efficiency of using a Python list as a queue | 1,296,511 | <p>A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used <code>.append(x)</code> when needing to insert items and <code>.pop(0)</code> when needing to remove items.</p>
<p>I know that Python has <a href="http://docs.python.org/library/collections.html#collections.deque"><code>collections.deque</code></a> and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?</p>
<p>In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a <code>realloc</code> and free up some of that memory?</p>
| 34 | 2009-08-18T21:05:58Z | 1,296,531 | <p>Every <code>.pop(0)</code> takes N steps, since the list has to be reorganized. The required memory will not grow endlessly and only be as big as required for the items that are held.</p>
<p>I'd recommend using <code>deque</code> to get O(1) append and pop from front.</p>
| 4 | 2009-08-18T21:09:35Z | [
"python",
"list",
"memory-leaks"
] |
Efficiency of using a Python list as a queue | 1,296,511 | <p>A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used <code>.append(x)</code> when needing to insert items and <code>.pop(0)</code> when needing to remove items.</p>
<p>I know that Python has <a href="http://docs.python.org/library/collections.html#collections.deque"><code>collections.deque</code></a> and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?</p>
<p>In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a <code>realloc</code> and free up some of that memory?</p>
| 34 | 2009-08-18T21:05:58Z | 1,297,464 | <p>Some answers claimed a "10x" speed advantage for deque vs list-used-as-FIFO when both have 1000 entries, but that's a bit of an overbid:</p>
<pre><code>$ python -mtimeit -s'q=range(1000)' 'q.append(23); q.pop(0)'
1000000 loops, best of 3: 1.24 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(1000))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.573 usec per loop
</code></pre>
<p><code>python -mtimeit</code> is your friend -- a really useful and simple micro-benchmarking approach! With it you can of course also trivially explore performance in much-smaller cases:</p>
<pre><code>$ python -mtimeit -s'q=range(100)' 'q.append(23); q.pop(0)'
1000000 loops, best of 3: 0.972 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(100))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.576 usec per loop
</code></pre>
<p>(not very different for 12 instead of 100 items btw), and in much-larger ones:</p>
<pre><code>$ python -mtimeit -s'q=range(10000)' 'q.append(23); q.pop(0)'
100000 loops, best of 3: 5.81 usec per loop
$ python -mtimeit -s'import collections; q=collections.deque(range(10000))' 'q.append(23); q.popleft()'
1000000 loops, best of 3: 0.574 usec per loop
</code></pre>
<p>You can see that the claim of O(1) performance for deque is well founded, while a list is over twice as slow around 1,000 items, an order of magnitude around 10,000. You can also see that even in such cases you're only wasting 5 microseconds or so per append/pop pair and decide how significant that wastage is (though if that's all you're doing with that container, deque has no downside, so you might as well switch even if 5 usec more or less won't make an important difference).</p>
| 60 | 2009-08-19T02:00:10Z | [
"python",
"list",
"memory-leaks"
] |
Efficiency of using a Python list as a queue | 1,296,511 | <p>A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used <code>.append(x)</code> when needing to insert items and <code>.pop(0)</code> when needing to remove items.</p>
<p>I know that Python has <a href="http://docs.python.org/library/collections.html#collections.deque"><code>collections.deque</code></a> and I'm trying to figure out whether to spend my (limited) time to rewrite this code to use it. Assuming that we perform millions of appends and pops but never have more than a few thousand entries, will his list usage be a problem?</p>
<p>In particular, will the underlying array used by the Python list implementation continue to grow indefinitely have millions of spots even though the list only has a thousand things, or will Python eventually do a <code>realloc</code> and free up some of that memory?</p>
| 34 | 2009-08-18T21:05:58Z | 1,297,467 | <p>From Beazley's <a href="http://rads.stackoverflow.com/amzn/click/0672329786"><em>Python Essential Reference, Fourth Edition</em></a>, p. 194:</p>
<blockquote>
<p>Some library modules provide new types
that outperform the built-ins at
certain tasks. For instance,
collections.deque type provides
similar functionality to a list but
has been highly optimized for the
insertion of items at both ends. A
list, in contrast, is only efficient
when appending items at the end. If
you insert items at the front, all of
the other elements need to be shifted
in order to make room. The time
required to do this grows as the list
gets larger and larger. Just to give
you an idea of the difference, here is a timing measurement of inserting one million items at the front of a list and a deque:</p>
</blockquote>
<p>And there follows this code sample:</p>
<pre><code>>>> from timeit import timeit
>>> timeit('s.appendleft(37)', 'import collections; s = collections.deque()', number=1000000)
0.13162776274638258
>>> timeit('s.insert(0,37)', 's = []', number=1000000)
932.07849908298408
</code></pre>
<p>Timings are from my machine.</p>
<hr>
<p>2012-07-01 Update</p>
<pre><code>>>> from timeit import timeit
>>> n = 1024 * 1024
>>> while n > 1:
... print '-' * 30, n
... timeit('s.appendleft(37)', 'import collections; s = collections.deque()', number=n)
... timeit('s.insert(0,37)', 's = []', number=n)
... n >>= 1
...
------------------------------ 1048576
0.1239769458770752
799.2552740573883
------------------------------ 524288
0.06924104690551758
148.9747350215912
------------------------------ 262144
0.029170989990234375
35.077512979507446
------------------------------ 131072
0.013737916946411133
9.134140014648438
------------------------------ 65536
0.006711006164550781
1.8818109035491943
------------------------------ 32768
0.00327301025390625
0.48307204246520996
------------------------------ 16384
0.0016388893127441406
0.11021995544433594
------------------------------ 8192
0.0008249282836914062
0.028419017791748047
------------------------------ 4096
0.00044918060302734375
0.00740504264831543
------------------------------ 2048
0.00021195411682128906
0.0021741390228271484
------------------------------ 1024
0.00011205673217773438
0.0006101131439208984
------------------------------ 512
6.198883056640625e-05
0.00021386146545410156
------------------------------ 256
2.9087066650390625e-05
8.797645568847656e-05
------------------------------ 128
1.5974044799804688e-05
3.600120544433594e-05
------------------------------ 64
8.821487426757812e-06
1.9073486328125e-05
------------------------------ 32
5.0067901611328125e-06
1.0013580322265625e-05
------------------------------ 16
3.0994415283203125e-06
5.9604644775390625e-06
------------------------------ 8
3.0994415283203125e-06
5.0067901611328125e-06
------------------------------ 4
3.0994415283203125e-06
4.0531158447265625e-06
------------------------------ 2
2.1457672119140625e-06
2.86102294921875e-06
</code></pre>
| 14 | 2009-08-19T02:00:18Z | [
"python",
"list",
"memory-leaks"
] |
Does IronPython implement python standard library? | 1,296,640 | <p>I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?</p>
| 6 | 2009-08-18T21:32:14Z | 1,296,706 | <p>(As I said <a href="http://stackoverflow.com/questions/676681/iron-python-twisted/677154#677154">here</a>:)</p>
<blockquote>
<p>I've not used it myself, but you may
get some mileage out of <a href="http://www.resolversystems.com/documentation/index.php/Ironclad.html" rel="nofollow">Ironclad</a>
- it supposedly lets you use CPython from IronPython...</p>
</blockquote>
| 0 | 2009-08-18T21:43:36Z | [
"python",
"ironpython"
] |
Does IronPython implement python standard library? | 1,296,640 | <p>I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?</p>
| 6 | 2009-08-18T21:32:14Z | 1,296,734 | <p>You can use the Python standard library from IronPython just fine. Here's how:</p>
<ol>
<li>Install Python.</li>
<li>Setup an environment variable named IRONPYTHONPATH that points to the standard library directory. </li>
</ol>
<p>Next time ipy.exe is run, site.py is read and you're good to go.</p>
| 2 | 2009-08-18T21:49:21Z | [
"python",
"ironpython"
] |
Does IronPython implement python standard library? | 1,296,640 | <p>I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?</p>
| 6 | 2009-08-18T21:32:14Z | 1,296,770 | <p>The <a href="http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=22981">IronPython installer</a> includes the Python standard library. Otherwise, you can use the standard library from a compatible Python install (IPy 2.0 -> CPy 2.5, IPy 2.6 -> CPy 2.6). Either copy the Python Lib directory to the IronPython folder, or set IRONPYTHONPATH.</p>
<p>Do note that only the pure Pyton modules will be available; Python modules that require C extensions have to be re-implemented (and most of them have been).</p>
| 9 | 2009-08-18T21:55:21Z | [
"python",
"ironpython"
] |
Does IronPython implement python standard library? | 1,296,640 | <p>I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?</p>
| 6 | 2009-08-18T21:32:14Z | 1,297,357 | <p>The .msi installer for <a href="http://ironpython.codeplex.com" rel="nofollow">IronPython</a> includes all parts of the <a href="http://python.org" rel="nofollow">CPython</a> standard library that should work with IronPython. You can simply copy the standard library from a CPython install if you prefer, although you're better off getting just the modules that the IronPython developers have ensured with with IronPython - this is most of them.</p>
<p>Modules that are implemented using the CPython C API ('extension modules') will not be available. <a href="http://code.google.com/p/ironclad/" rel="nofollow">IronClad</a> is an open-source project that aims to let you seamlessly use these modules - it's not perfect yet, but (e.g.) most of the NumPy tests pass.</p>
<p>The other option for these 'extension modules' is to replace them with a pure-Python version (e.g. from <a href="http://codespeak.net/pypy/dist/pypy/doc/" rel="nofollow">PyPy</a>) or with a wrapper over a .NET class. The <a href="http://fepy.sourceforge.net/" rel="nofollow">IronPython Community Edition</a> is an IronPython distribution that includes such wrappers for many modules that are not included in the standard IronPython distribution.</p>
| 2 | 2009-08-19T01:04:37Z | [
"python",
"ironpython"
] |
Getting system status in python | 1,296,703 | <p>Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on.
I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.</p>
| 8 | 2009-08-18T21:42:51Z | 1,296,768 | <p>I don't think there is a cross-platform library for that yet (there definitely should be one though)</p>
<p>I can however provide you with one snippet I used to get the current CPU load from <code>/proc/stat</code> under Linux:</p>
<p><strong>Edit</strong>: replaced horrible undocumented code with slightly more pythonic and documented code</p>
<pre><code>import time
INTERVAL = 0.1
def getTimeList():
"""
Fetches a list of time units the cpu has spent in various modes
Detailed explanation at http://www.linuxhowtos.org/System/procstat.htm
"""
cpuStats = file("/proc/stat", "r").readline()
columns = cpuStats.replace("cpu", "").split(" ")
return map(int, filter(None, columns))
def deltaTime(interval):
"""
Returns the difference of the cpu statistics returned by getTimeList
that occurred in the given time delta
"""
timeList1 = getTimeList()
time.sleep(interval)
timeList2 = getTimeList()
return [(t2-t1) for t1, t2 in zip(timeList1, timeList2)]
def getCpuLoad():
"""
Returns the cpu load as a value from the interval [0.0, 1.0]
"""
dt = list(deltaTime(INTERVAL))
idle_time = float(dt[3])
total_time = sum(dt)
load = 1-(idle_time/total_time)
return load
while True:
print "CPU usage=%.2f%%" % (getCpuLoad()*100.0)
time.sleep(0.1)
</code></pre>
| 5 | 2009-08-18T21:55:08Z | [
"python",
"operating-system"
] |
Getting system status in python | 1,296,703 | <p>Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on.
I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.</p>
| 8 | 2009-08-18T21:42:51Z | 1,296,816 | <p>I don't know of any such library/ package that currently supports both Linux and Windows. There's <a href="http://www.i-scream.org/libstatgrab/" rel="nofollow">libstatgrab</a> which doesn't seem to be very actively developed (it already supports a decent variety of Unix platforms though) and the very active <a href="http://bitbucket.org/chrismiles/psi/wiki/Home" rel="nofollow">PSI (Python System Information)</a> which works on AIX, Linux, SunOS and Darwin. Both projects aim at having Windows support sometime in the future. Good luck.</p>
| 8 | 2009-08-18T22:03:23Z | [
"python",
"operating-system"
] |
Getting system status in python | 1,296,703 | <p>Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on.
I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.</p>
| 8 | 2009-08-18T21:42:51Z | 14,613,230 | <p><a href="https://pypi.python.org/pypi/psutil" rel="nofollow">https://pypi.python.org/pypi/psutil</a></p>
<pre><code>import psutil
psutil.get_pid_list()
psutil.virtual_memory()
psutil.cpu_times()
</code></pre>
<p>etc.</p>
| 4 | 2013-01-30T20:35:43Z | [
"python",
"operating-system"
] |
Match all urls that aren't wrapped into <a> tag | 1,296,778 | <p>I am seeking for a regular expression pattern that could match urls in HTML that aren't wrapped into 'a' tag, in order to wrap them into 'a' tag further (i.e. highlight all non-highlighted links).</p>
<p>Input is simple HTML with 'a', 'b', 'i', 'br', 'p' 'img' tags allowed. All other HTML tags shouldn't appear in the input, but tags mentioned above could appear in any combinations.</p>
<p>So pattern should omit all urls that are parts of existing 'a' tags, and match all other links that are just plain text not wrapped into 'a' tags and thus are not highlighted and are not hyperlinks yet. It would be good if pattern will match urls beginning with http://, https:// or www., and ending with .net, .com. or .org if the url isn't begin with http://, https:// or www.</p>
<p>I've tried something like '(?!<[aA][^>]+>)<a href="http://%5Ba-zA-Z0-9.%5F-%5D+" rel="nofollow">http://%5Ba-zA-Z0-9.%5F-%5D+</a>(?!)' to match more simple case than I described above, but it seems that this task is not so obvious.</p>
<p>Thanks much for any help.</p>
| 1 | 2009-08-18T21:56:33Z | 1,296,870 | <p>You could use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> or similar to exclude all urls that are already part of links. </p>
<p>Then you can match the plain text with one of the url regular expressions that's already out there (google "url regular expression", which one you want depends on how fancy you want to get).</p>
| 5 | 2009-08-18T22:15:25Z | [
"python",
"regex"
] |
Match all urls that aren't wrapped into <a> tag | 1,296,778 | <p>I am seeking for a regular expression pattern that could match urls in HTML that aren't wrapped into 'a' tag, in order to wrap them into 'a' tag further (i.e. highlight all non-highlighted links).</p>
<p>Input is simple HTML with 'a', 'b', 'i', 'br', 'p' 'img' tags allowed. All other HTML tags shouldn't appear in the input, but tags mentioned above could appear in any combinations.</p>
<p>So pattern should omit all urls that are parts of existing 'a' tags, and match all other links that are just plain text not wrapped into 'a' tags and thus are not highlighted and are not hyperlinks yet. It would be good if pattern will match urls beginning with http://, https:// or www., and ending with .net, .com. or .org if the url isn't begin with http://, https:// or www.</p>
<p>I've tried something like '(?!<[aA][^>]+>)<a href="http://%5Ba-zA-Z0-9.%5F-%5D+" rel="nofollow">http://%5Ba-zA-Z0-9.%5F-%5D+</a>(?!)' to match more simple case than I described above, but it seems that this task is not so obvious.</p>
<p>Thanks much for any help.</p>
| 1 | 2009-08-18T21:56:33Z | 1,296,897 | <p>Parsing HTML with a single regex is almost impossible by definition, since regexes don't have state.</p>
<p>Build/Use a real parser instead. Maybe <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> or <a href="http://code.google.com/p/html5lib/" rel="nofollow">html5lib</a>.</p>
<p>This code below uses BeautifulSoup to extract all links from the page:</p>
<pre><code>from BeautifulSoup import BeautifulSoup
from urllib2 import urlopen
url = 'http://stackoverflow.com/questions/1296778/'
stream = urlopen(url)
soup = BeautifulSoup(stream)
for link in soup.findAll('a'):
if link.has_key('href'):
print unicode(link.string), '->', link['href']
</code></pre>
<p>Similarly you could find all text using <code>soup.findAll(text=True)</code> and search for urls there.</p>
<p>Searching for urls is also very complex - you wouldn't believe on what's allowed on a url. A simple search shows thousands of examples, but none match exactly the specs. You should try what works better for you.</p>
| 5 | 2009-08-18T22:23:58Z | [
"python",
"regex"
] |
Match all urls that aren't wrapped into <a> tag | 1,296,778 | <p>I am seeking for a regular expression pattern that could match urls in HTML that aren't wrapped into 'a' tag, in order to wrap them into 'a' tag further (i.e. highlight all non-highlighted links).</p>
<p>Input is simple HTML with 'a', 'b', 'i', 'br', 'p' 'img' tags allowed. All other HTML tags shouldn't appear in the input, but tags mentioned above could appear in any combinations.</p>
<p>So pattern should omit all urls that are parts of existing 'a' tags, and match all other links that are just plain text not wrapped into 'a' tags and thus are not highlighted and are not hyperlinks yet. It would be good if pattern will match urls beginning with http://, https:// or www., and ending with .net, .com. or .org if the url isn't begin with http://, https:// or www.</p>
<p>I've tried something like '(?!<[aA][^>]+>)<a href="http://%5Ba-zA-Z0-9.%5F-%5D+" rel="nofollow">http://%5Ba-zA-Z0-9.%5F-%5D+</a>(?!)' to match more simple case than I described above, but it seems that this task is not so obvious.</p>
<p>Thanks much for any help.</p>
| 1 | 2009-08-18T21:56:33Z | 1,299,962 | <p>Thanks guys! Below is my solution:</p>
<pre><code>from django.utils.html import urlize # Yes, I am using Django's urlize to do all dirty work :)
def urlize_html(value):
"""
Urlizes text containing simple HTML tags.
"""
A_IMG_REGEX = r'(<[aA][^>]+>[^<]+</[aA]>|<[iI][mM][gG][^>]+>)'
a_img_re = re.compile(A_IMG_REGEX)
TAG_REGEX = r'(<[a-zA-Z]+[^>]+>|</[a-zA-Z]>)'
tag_re = re.compile(TAG_REGEX)
def process(s, p, f):
return "".join([c if p.match(c) else f(c) for c in p.split(s)])
def process_urlize(s):
return process(s, tag_re, urlize)
return process(value, a_img_re, process_urlize)
</code></pre>
| -2 | 2009-08-19T13:34:47Z | [
"python",
"regex"
] |
Django ModelChoiceField initial data not working for ForeignKey | 1,296,938 | <p>I am filling my form with initial data using the normail:</p>
<pre><code>form = somethingForm(initial = {
'title' : something.title,
'category' : something.category_id,
})
</code></pre>
<p>The title works fine, but if the category is a ModelChoiceField and a ForeignKey in the model, the initial data won't work. Nothing will be selected in the Select Box. If I change category to an IntegerField in the model it works fine. </p>
<p>I still want to use a ForeignKey for category though, so how do I fix this?</p>
| 2 | 2009-08-18T22:34:00Z | 1,297,909 | <p>You need to do this</p>
<pre><code>form = somethingForm(initial = {
'title' : something.title,
'category' : [("database value","display value")],
})
</code></pre>
<h2>Why list of tuples?</h2>
<ol>
<li><p>Because choice fields are associated with select widget ( i.e
html ===>
..............) </p></li>
<li><p>For each option we need to specify two things 1.internal value
2.display value (each tuple in the list specifies this)</p></li>
</ol>
| 0 | 2009-08-19T05:13:28Z | [
"python",
"django"
] |
Django ModelChoiceField initial data not working for ForeignKey | 1,296,938 | <p>I am filling my form with initial data using the normail:</p>
<pre><code>form = somethingForm(initial = {
'title' : something.title,
'category' : something.category_id,
})
</code></pre>
<p>The title works fine, but if the category is a ModelChoiceField and a ForeignKey in the model, the initial data won't work. Nothing will be selected in the Select Box. If I change category to an IntegerField in the model it works fine. </p>
<p>I still want to use a ForeignKey for category though, so how do I fix this?</p>
| 2 | 2009-08-18T22:34:00Z | 1,358,242 | <p>Perhaps try using an instance of a category rather than its ID?</p>
| 1 | 2009-08-31T16:36:14Z | [
"python",
"django"
] |
SQLAlchemy(Postgres) and transaction | 1,296,994 | <p>I want a record from a table(queue) to be selected, locked(no other process can edit this record) and updated at a later point in time.<br />
I assumed if I put the whole querying and updating in a transaction, no other process can edit/query the same record. But I am not quite able to achieve this.</p>
<pre><code>def move(one, two):
from settings import DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine
engine = create_engine('postgres://%s:%s@%s:%s/%s' % (DATABASE_USER, DATABASE_PASSWORD, DATABASE_HOST, DATABASE_PORT, DATABASE_NAME), echo = False)
conn = engine.connect()
tran = conn.begin()
Session = scoped_session(sessionmaker())
session = Session(bind=conn)
url = session.query(URLQueue).filter(URLQueue.status == one).first()
print "Got record: " + str(url.urlqueue_id)
time.sleep(5)
url.status = two
session.merge(url)
session.close()
tran.commit()
move('START', 'WIP')
</code></pre>
<p>If I start 2 process, they both update the same record. I am not sure if I created the connections/sessions/transactions properly. Any pointers?</p>
| 2 | 2009-08-18T22:49:57Z | 1,297,946 | <p>Either make your transaction isolation level serializable, or fetch the record for updating via query.with_lockmode('update').</p>
| 1 | 2009-08-19T05:34:50Z | [
"python",
"postgresql",
"sqlalchemy"
] |
in GTK, how do I get the original normal bg color of a widget? | 1,297,169 | <p>I do this:</p>
<pre><code> self.origbg = self.style.bg[gtk.STATE_NORMAL]
</code></pre>
<p>and later in my eventboxes I change the bgcolor to it by doing:</p>
<pre><code> self.modify_bg(gtk.STATE_NORMAL, color)
</code></pre>
<p>However, the color actually <em>changes</em>! It's not the state_normal color that I get from looking at self.style.bg . On my Windows, it's a slightly lighter tint. How do I get the real background color?</p>
| 1 | 2009-08-18T23:43:23Z | 1,310,063 | <p>Connect to the widget's "map-event" signal (which is sent when the widget is first shown in a window); this is the first time you can read the real theme colors.</p>
| 1 | 2009-08-21T04:19:22Z | [
"python",
"gtk",
"colors",
"themes"
] |
in GTK, how do I get the original normal bg color of a widget? | 1,297,169 | <p>I do this:</p>
<pre><code> self.origbg = self.style.bg[gtk.STATE_NORMAL]
</code></pre>
<p>and later in my eventboxes I change the bgcolor to it by doing:</p>
<pre><code> self.modify_bg(gtk.STATE_NORMAL, color)
</code></pre>
<p>However, the color actually <em>changes</em>! It's not the state_normal color that I get from looking at self.style.bg . On my Windows, it's a slightly lighter tint. How do I get the real background color?</p>
| 1 | 2009-08-18T23:43:23Z | 5,381,093 | <p>If you want to avoid listening for map event you should call <code>realize()</code> and then get colors. I know this is an old issue but just wanted to contribute in case people run into it like I did. :)</p>
| 3 | 2011-03-21T17:08:20Z | [
"python",
"gtk",
"colors",
"themes"
] |
in GTK, how do I get the original normal bg color of a widget? | 1,297,169 | <p>I do this:</p>
<pre><code> self.origbg = self.style.bg[gtk.STATE_NORMAL]
</code></pre>
<p>and later in my eventboxes I change the bgcolor to it by doing:</p>
<pre><code> self.modify_bg(gtk.STATE_NORMAL, color)
</code></pre>
<p>However, the color actually <em>changes</em>! It's not the state_normal color that I get from looking at self.style.bg . On my Windows, it's a slightly lighter tint. How do I get the real background color?</p>
| 1 | 2009-08-18T23:43:23Z | 39,064,643 | <p>I use this to get the default background color for an entry in GTK3</p>
<pre><code> context = entry.get_style_context()
default_background = context.get_background_color(Gtk.StateType.NORMAL)
</code></pre>
| 0 | 2016-08-21T13:19:30Z | [
"python",
"gtk",
"colors",
"themes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.