title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
16,368,876
<p>naturally <code>netstat</code> (<code>netstat -an | grep 5000</code> does the trick on linux). Will grab the port</p> <p>However I found this other question with the same error. </p> <p><a href="http://stackoverflow.com/questions/4465959/python-errno-98-address-already-in-use/4466035#4466035">Python [Errno 98] Address already in use</a></p> <pre><code>sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) </code></pre> <p>Essentially Python takes too long to open the socket. </p>
0
2013-05-03T23:17:04Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Pylons: address already in use when trying to serve
1,071,071
<p>I'm running pylons and I did this: paster server development.ini It's running on :5000</p> <p>But when I try to run the command again: paster serve development.ini</p> <p>I get this message: socket.error: [Errno 98] Address already in use</p> <p>Any ideas?</p>
3
2009-07-01T20:03:07Z
30,009,931
<p>I tried all the upvoted answers exists here but no one works for me. But this below command does the trick.</p> <pre><code>sudo kill $(sudo lsof -t -i:5000) </code></pre> <p>This would kill the process which listens on the port <code>5000</code>.</p>
0
2015-05-03T03:31:37Z
[ "python", "nginx", "pylons", "paste", "paster" ]
Deploying Pylons with Nginx reverse proxy?
1,071,088
<p>Is there a tutorial on how to deploy Pylons with Nginx?</p> <p>I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini</p> <p>However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons serving to do other stuff on my server, pylons goes down.</p> <p>There must be a different method of deployment.</p> <p>PS - I've done all this: <a href="http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments" rel="nofollow">http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments</a></p> <p>I just have no clue what to do with the Pylons app other than paster serve. Not sure if tehre is a different method.</p>
1
2009-07-01T20:06:12Z
1,071,185
<p>Run Pylons in daemon mode.</p> <pre><code>paster serve development.ini --daemon </code></pre>
5
2009-07-01T20:21:43Z
[ "python", "nginx", "pylons", "paster" ]
Deploying Pylons with Nginx reverse proxy?
1,071,088
<p>Is there a tutorial on how to deploy Pylons with Nginx?</p> <p>I've been able to start nginx and then serve pylons to :8080 with paster serve development.ini</p> <p>However, I can't seem to do other stuff as pylons locks me into that serve mode. If I try to CTRL+Z out of pylons serving to do other stuff on my server, pylons goes down.</p> <p>There must be a different method of deployment.</p> <p>PS - I've done all this: <a href="http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments" rel="nofollow">http://wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX?showComments=true#comments</a></p> <p>I just have no clue what to do with the Pylons app other than paster serve. Not sure if tehre is a different method.</p>
1
2009-07-01T20:06:12Z
2,016,256
<p>Running Pylons with nginx tutorial found here: wiki.pylonshq.com/display/pylonscookbook/Running+Pylons+with+NGINX</p> <p>Pylons on Nginx with Memcached and SSI: <a href="http://www.reshetseret.com/app/blog/?p=3" rel="nofollow">http://www.reshetseret.com/app/blog/?p=3</a></p> <p>UPDATE: link is broken, here is google cached version: <a href="http://webcache.googleusercontent.com/search?q=cache:http://www.reshetseret.com/app/blog/" rel="nofollow">http://webcache.googleusercontent.com/search?q=cache:http://www.reshetseret.com/app/blog/</a></p>
2
2010-01-06T21:09:32Z
[ "python", "nginx", "pylons", "paster" ]
Call Google Translate from Python
1,071,110
<p>I want to execute <a href="http://code.google.com/apis/ajaxlanguage/documentation/translate.html" rel="nofollow">this script (view source)</a> that uses Google Translate AJAX API from python, and be able to pass arguments and get the answer back. I don't care about the HTML.</p> <p>I understand I need to embed a Javascript interpreter of some sort. Does this mean I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?</p>
4
2009-07-01T20:10:21Z
1,071,150
<p>You can use the RESTful API instead. It's designed for environments that are not Javascript.</p> <p><a href="http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje" rel="nofollow">http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje</a></p> <p>That should be easy to use from Python.</p>
3
2009-07-01T20:18:17Z
[ "python", "ajax" ]
Call Google Translate from Python
1,071,110
<p>I want to execute <a href="http://code.google.com/apis/ajaxlanguage/documentation/translate.html" rel="nofollow">this script (view source)</a> that uses Google Translate AJAX API from python, and be able to pass arguments and get the answer back. I don't care about the HTML.</p> <p>I understand I need to embed a Javascript interpreter of some sort. Does this mean I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?</p>
4
2009-07-01T20:10:21Z
1,071,161
<p>You can use <a href="http://googletranslate.sourceforge.net/" rel="nofollow">google-api-translate-python</a> to talk to google api.</p> <p><strong>EDIT:</strong> It wasn't clear where the sources are, found them <a href="https://googletranslate.svn.sourceforge.net/svnroot/googletranslate/src/trunk/" rel="nofollow">here</a>.</p>
3
2009-07-01T20:19:39Z
[ "python", "ajax" ]
Call Google Translate from Python
1,071,110
<p>I want to execute <a href="http://code.google.com/apis/ajaxlanguage/documentation/translate.html" rel="nofollow">this script (view source)</a> that uses Google Translate AJAX API from python, and be able to pass arguments and get the answer back. I don't care about the HTML.</p> <p>I understand I need to embed a Javascript interpreter of some sort. Does this mean I need to have a browser instance and manipulate it? What is the cleanest way to access this API from python?</p>
4
2009-07-01T20:10:21Z
18,106,223
<p>Had to do this recently, and since I had to translate long strings, I couldn't use URL parameters, but rather use a data payload. Thought this is the best place to share this solution.<br> The trick basically is to use Python's excellent Requests module post, but since google require a GET request, use the 'X-HTTP-Method-Override' header to override the request method to GET.<br> (plainly using requests.get messes up the data payload) </p> <p>the code:</p> <pre><code>import requests def translate_es_to_en(text): url = "https://www.googleapis.com/language/translate/v2" data = { 'key': '&lt;your-server-google-api-key&gt;' 'source': 'es', 'target': 'en', 'q': text } headers = {'X-HTTP-Method-Override': 'GET'} response = requests.post(url, data=data, headers=headers) return response.json() </code></pre> <p>Hope this helps anyone still tackling this</p>
1
2013-08-07T14:33:35Z
[ "python", "ajax" ]
Detect URLs in a string and wrap with "<a href..." tag
1,071,191
<p>I am looking to write something that seems like it should be easy enough, but for whatever reason I'm having a tough time getting my head around it.</p> <p>I am looking to write a python function that, when passed a string, will pass that string back with HTML encoding around URLs.</p> <pre><code>unencoded_string = "This is a link - http://google.com" def encode_string_with_links(unencoded_string): # some sort of regex magic occurs return encoded_string print encoded_string 'This is a link - &lt;a href="http://google.com"&gt;http://google.com&lt;/a&gt;' </code></pre> <p>Thank you!</p>
6
2009-07-01T20:22:25Z
1,071,240
<p>Googled solutions:</p> <pre><code>#---------- find_urls.py----------# # Functions to identify and extract URLs and email addresses import re def fix_urls(text): pat_url = re.compile( r''' (?x)( # verbose identify URLs within text (http|ftp|gopher) # make sure we find a resource type :// # ...needs to be followed by colon-slash-slash (\w+[:.]?){2,} # at least two domain groups, e.g. (gnosis.)(cx) (/?| # could be just the domain name (maybe w/ slash) [^ \n\r"]+ # or stuff then space, newline, tab, quote [\w/]) # resource name ends in alphanumeric or slash (?=[\s\.,&gt;)'"\]]) # assert: followed by white or clause ending ) # end of match group ''') pat_email = re.compile(r''' (?xm) # verbose identify URLs in text (and multiline) (?=^.{11} # Mail header matcher (?&lt;!Message-ID:| # rule out Message-ID's as best possible In-Reply-To)) # ...and also In-Reply-To (.*?)( # must grab to email to allow prior lookbehind ([A-Za-z0-9-]+\.)? # maybe an initial part: DAVID.mertz@gnosis.cx [A-Za-z0-9-]+ # definitely some local user: MERTZ@gnosis.cx @ # ...needs an at sign in the middle (\w+\.?){2,} # at least two domain groups, e.g. (gnosis.)(cx) (?=[\s\.,&gt;)'"\]]) # assert: followed by white or clause ending ) # end of match group ''') for url in re.findall(pat_url, text): text = text.replace(url[0], '&lt;a href="%(url)s"&gt;%(url)s&lt;/a&gt;' % {"url" : url[0]}) for email in re.findall(pat_email, text): text = your_string.replace(email[1], '&lt;a href="mailto:%(email)s"&gt;%(email)s&lt;/a&gt;' % {"email" : email[1]}) return text if __name__ == '__main__': print fix_urls("test http://google.com asdasdasd some more text") </code></pre> <p><strong>EDIT:</strong> Adjusted to your needs</p>
5
2009-07-01T20:31:17Z
[ "python", "html", "regex" ]
Detect URLs in a string and wrap with "<a href..." tag
1,071,191
<p>I am looking to write something that seems like it should be easy enough, but for whatever reason I'm having a tough time getting my head around it.</p> <p>I am looking to write a python function that, when passed a string, will pass that string back with HTML encoding around URLs.</p> <pre><code>unencoded_string = "This is a link - http://google.com" def encode_string_with_links(unencoded_string): # some sort of regex magic occurs return encoded_string print encoded_string 'This is a link - &lt;a href="http://google.com"&gt;http://google.com&lt;/a&gt;' </code></pre> <p>Thank you!</p>
6
2009-07-01T20:22:25Z
1,071,294
<p>The "regex magic" you need is just <code>sub</code> (which does a substitution):</p> <pre><code>def encode_string_with_links(unencoded_string): return URL_REGEX.sub(r'&lt;a href="\1"&gt;\1&lt;/a&gt;', unencoded_string) </code></pre> <p><code>URL_REGEX</code> could be something like:</p> <pre><code>URL_REGEX = re.compile(r'''((?:mailto:|ftp://|http://)[^ &lt;&gt;'"{}|\\^`[\]]*)''') </code></pre> <p>This is a pretty loose regex for URLs: it allows mailto, http and ftp schemes, and after that pretty much just keeps going until it runs into an "unsafe" character (except percent, which you want to allow for escapes). You could make it more strict if you need to. For example, you could require that percents are followed by a valid hex escape, or only allow one pound sign (for the fragment) or enforce the order between query parameters and fragments. This should be enough to get you started, though.</p>
7
2009-07-01T20:42:08Z
[ "python", "html", "regex" ]
Why does list comprehension using a zip object results in an empty list?
1,071,201
<pre><code>f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") for pair in myZip : print ( k(pair) ) print ("\n\nOutput # 2: [ k(pair) for pair in myZip ] ...") print ( [ k(pair) for pair in myZip ] ) # script output is ... # Output # 1: for pair in myZip: k(pair) ... # 2 # 9 # 3125 # # Output # 2: [ k(pair) for pair in myZip ] ... # [] </code></pre>
6
2009-07-01T20:24:37Z
1,071,239
<p>Works perfectly in Python 2.6 but fails in Python 3.0 because <code>zip</code> returns a generator-style object and the first loop exhausts it. Make a list instead:</p> <pre><code>myZip = list( zip ( funcTriple, (1, 3, 5) ) ) </code></pre> <p>and it works in Python 3.0</p>
17
2009-07-01T20:31:16Z
[ "python", "zip", "list-comprehension" ]
Form Initialization with ToscaWidgets
1,071,277
<p><strong>Question:</strong></p> <p>How do I prefill a CheckBoxTable from ToscaWidgets with values.</p> <p><strong>Background:</strong></p> <p>I've looked everywhere and I can't seem to figure out how to initialize a particular form field with ToscaWidgets. Most form fields seem to respond just fine to initialization, like if I create a form with a single TextField in it when I render the form in the template and pass in fieldValue=x where fieldValue is the name of the TextField and x is some string the TextField will be filled with x. My problem is with all multiple select field, in particular CheckBoxTable. No matter what I pass in it will not initialize the multiple select. Here is an example of what I'm talking about, it's a user edit page with a CheckBoxTable for groups so you can select several or no groups out of a list of several groups fetched from the databse:</p> <p><strong>What I have:</strong></p> <p>My widget is:</p> <pre><code>from tw import forms class UserForm(forms.TableForm): show_errors = True submit_text = "Create User" clientOptions = [(-1, "Select a Client")] groupOptions = [(-1, "Select a Group")] fields = [forms.TextField('name', label_text='User Name', validator=String(not_empty=True), size=40), forms.Spacer(), forms.SingleSelectField('clientID', label_text='Client Name', validator=Int(min=0), options=clientOptions), forms.Spacer(), forms.CheckBoxTable('groups', lable_text='Groups', validator=Set(), options=groupOptions, num_cols=3), forms.Spacer(), forms.PasswordField('password', label_text="Password", validator=String(not_empty=True, min=6), size=40), forms.PasswordField('passwordAgain', label_text="Repeat Password", validator=String(not_empty=True, min=6), size=40), forms.HiddenField('id')] editUserForm = UserForm("createUserForm", action='alterUser', submit_text="Edit User") </code></pre> <p>In my controller I have:</p> <pre><code>result = model.DBSession.query(model.User).filter_by(id=kw['id']).first() tmpl_context.form = editUserForm clientOptions=model.DBSession.query(model.Client.id, model.Client.name) groupOptions=model.DBSession.query(model.Group.id, model.Group.name) formChildArgs = dict(clientID=dict(options=clientOptions), groups=dict(options=groupOptions)) userAttributes=dict(id=result.id, name=result.name, groups=[g.id for g in result.groups], clientID=result.clientID, password=result.password, passwordAgain=result.password) return dict(verb="Edit", modelName = "User", modelAttributes=userAttributes, formChildArgs=formChildArgs, page='editUser') </code></pre> <p>and in my template (Mako) I have:</p> <pre><code>${tmpl_context.form(modelAttributes, child_args=formChildArgs) | n} </code></pre> <p><strong>What I've tried:</strong></p> <p>In my userAttributs dictionary I've tried:</p> <pre><code>groups=[g.id for g in result.groups] groups=[g.name for g in result.groups] groups=[(g.id, g.name) for g in result.groups] groups=[[g.id, g.name) for g in result.groups] groups=result.groups </code></pre> <p><strong>What I get:</strong></p> <p>The result of all of this code is a User edit form with data pre-filled with the user data except for the CheckBoxTable. The CheckBoxTable has all of the groups in my database displaying and empty, what I need for for them to be displaying but have the groups the user is apart of checked. I thought the code in the model attributes would do this, since that's what it does for every other field, but there must be some fundamental thing I'm missing about CheckBoxTable instantiation.</p> <p><strong>Specs:</strong></p> <p>I'm using Turbogears 2 with ToscaWidgets 0.9.7 forms and Mako for templating.</p>
3
2009-07-01T20:39:06Z
1,073,935
<p>set them via the value param. </p> <pre><code>import tw.forms f = tw.forms.TableForm(fields=[tw.forms.CheckBoxTable("name",options=(("foo"),("bar")))]) f(value={"name":{"foo":True,"bar":False}}) &gt;&gt;&gt; u'&lt;form xmlns="http://www.w3.org/1999/xhtml" action="" method="post" class="tableform"&gt;\n &lt;table border="0" cellspacing="0" cellpadding="2"&gt;\n&lt;tr id="name.container" class="even" title=""&gt;\n &lt;td class="labelcol"&gt;\n &lt;label id="name.label" for="name" class="fieldlabel"&gt;Name&lt;/label&gt;\n &lt;/td&gt;\n &lt;td class="fieldcol"&gt;\n &lt;table id="name" class="checkboxtable"&gt;\n &lt;tbody&gt;\n &lt;tr&gt;\n &lt;td&gt;\n &lt;input id="name_0" value="foo" name="name" type="checkbox" checked="checked" /&gt;\n &lt;label for="name_0"&gt;foo&lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;&lt;tr&gt;\n &lt;td&gt;\n &lt;input id="name_1" value="bar" name="name" type="checkbox" /&gt;\n &lt;label for="name_1"&gt;bar&lt;/label&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/tbody&gt;\n&lt;/table&gt;\n &lt;/td&gt;\n &lt;/tr&gt;&lt;tr id="submit.container" class="odd" title=""&gt;\n &lt;td class="labelcol"&gt;\n &lt;/td&gt;\n &lt;td class="fieldcol"&gt;\n &lt;input type="submit" class="submitbutton" value="Submit" /&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n&lt;/form&gt;' </code></pre>
1
2009-07-02T11:52:58Z
[ "python", "forms", "turbogears", "mako", "toscawidgets" ]
Does anyone know of source code for a web based study group?
1,071,433
<p>I'm looking for source code for a web based study group. I'd prefer something in Python or C#. I have searched google but I'm finding mostly existing study groups on particular topics and not software to host an online study group. </p> <p>Can anyone help out?</p> <p><hr /></p> <p>Edit: Ah, I was unfamiliar with the buzzwords "Learning Management System" or "Virtual Learning Environment". Moodle is indeed the type of thing I was looking for, even if it is written in the horrible php "language".</p> <p>Thanks.</p>
2
2009-07-01T21:15:27Z
1,071,455
<p>I am not quite sure what you mean by "host an online study group".</p> <p>If it is about people collaborate to learn something, I think <a href="http://moodle.org/" rel="nofollow">moodle</a> is what you are looking for.</p> <p>Here is the <a href="http://en.wikipedia.org/wiki/Moodle" rel="nofollow">wikipedia lemma for moodle:</a></p> <blockquote> <p>Moodle is a free and open source e-learning software platform, also known as a Course Management System, Learning Management System, or Virtual Learning Environment. It has a significant user base with 49,256 registered sites with 28,177,443 users in 2,571,855 courses (as of February, 2009).</p> </blockquote> <p>Here is how the <a href="http://moodle.org/" rel="nofollow">moodle people</a> describe it themselves:</p> <blockquote> <p>Moodle is an Open Source Course Management System (CMS), also known as a Learning Management System (LMS) or a Virtual Learning Environment (VLE). It has become very popular among educators around the world as a tool for creating online dynamic web sites for their students.</p> </blockquote> <p>It is not written in Python or C#, but PHP and released under GPL. You can install it on your webserver or use free moodle hosting like <a href="http://www.e-socrates.org/" rel="nofollow">e-socrates</a>.</p>
4
2009-07-01T21:20:27Z
[ "c#", "python" ]
Does anyone know of source code for a web based study group?
1,071,433
<p>I'm looking for source code for a web based study group. I'd prefer something in Python or C#. I have searched google but I'm finding mostly existing study groups on particular topics and not software to host an online study group. </p> <p>Can anyone help out?</p> <p><hr /></p> <p>Edit: Ah, I was unfamiliar with the buzzwords "Learning Management System" or "Virtual Learning Environment". Moodle is indeed the type of thing I was looking for, even if it is written in the horrible php "language".</p> <p>Thanks.</p>
2
2009-07-01T21:15:27Z
1,075,093
<p>There seems to be work on a django based course MS - <a href="http://peach3.nl/trac" rel="nofollow">http://peach3.nl/trac</a> . However, the source is not available yet :(</p> <p>I am interested in developping such an app (free open-source) in django (which I am learning), so if anybody else wants to help email me (a web designer would help a lot).</p> <p>Rado</p>
0
2009-07-02T15:34:02Z
[ "c#", "python" ]
python class variable not visible in __init__?
1,071,469
<p>This code produces an error message, which I found surprising:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() </code></pre> <p>Can anyone provide enlightenment?</p>
5
2009-07-01T21:25:34Z
1,071,485
<p>The class body is executed before the class its self is defined, so default argument values can't reference the class. Just making <code>custom</code> the default (without class qualification) should work.</p>
3
2009-07-01T21:29:34Z
[ "python" ]
python class variable not visible in __init__?
1,071,469
<p>This code produces an error message, which I found surprising:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() </code></pre> <p>Can anyone provide enlightenment?</p>
5
2009-07-01T21:25:34Z
1,071,491
<p>It's <code>Foo</code> that isn't visible, because you're in the middle of building it. But since you're in the same scope as <code>custom</code>, you can just say <code>custom</code> rather than <code>Foo.custom</code>:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, mycustom=custom): self._custom = mycustom </code></pre> <p>But note that changing <code>Foo.custom</code> later on won't affect the value of <code>custom</code> that subsequently-created <code>Foo</code>s see:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, mycustom=custom): self._custom = mycustom one = Foo() Foo.custom = 2 two = Foo() print (two._custom) # Prints 1 </code></pre> <p>By using a sentinel default value instead, you can get what you want:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, mycustom=None): if mycustom is None: self._custom = Foo.custom else: self._custom = mycustom one = Foo() Foo.custom = 2 two = Foo() print (two._custom) # Prints 2 </code></pre>
11
2009-07-01T21:30:21Z
[ "python" ]
python class variable not visible in __init__?
1,071,469
<p>This code produces an error message, which I found surprising:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() </code></pre> <p>Can anyone provide enlightenment?</p>
5
2009-07-01T21:25:34Z
1,071,494
<p>I get the following error:</p> <pre><code>Traceback (most recent call last): Line 1, in &lt;module&gt; class Foo(object): Line 3, in Foo def __init__(self, custom=Foo.custom): NameError: name 'Foo' is not defined </code></pre> <p>This is because the name <code>Foo</code> is in the process of being defined as the <code>__init__</code> function is defined, and is not fully available at that time.</p> <p>The solution is to avoid using the name <code>Foo</code> in the function definition (I also renamed the <code>custom</code> paramter to <code>acustom</code> to distinguish it from <code>Foo.custom</code>):</p> <pre><code>class Foo(object): custom = 1 def __init__(self, acustom=custom): self._custom = acustom x = Foo() print x._custom </code></pre>
2
2009-07-01T21:30:47Z
[ "python" ]
python class variable not visible in __init__?
1,071,469
<p>This code produces an error message, which I found surprising:</p> <pre><code>class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() </code></pre> <p>Can anyone provide enlightenment?</p>
5
2009-07-01T21:25:34Z
1,071,498
<p>What we do instead is the following</p> <pre><code>class Foo( object ): custom = 1 def __init__( self, arg=None ) self._custom = self.custom if arg is None else arg </code></pre> <p>This bypasses the confusing issue of whether or not the name <code>Foo</code> has been defined yet.</p>
6
2009-07-01T21:32:27Z
[ "python" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
1,071,694
<p>If you set up the table correctly, then you just need to do:</p> <pre><code>translated_chars = ebcdic.translate(EBCDIC_TO_LATIN1) </code></pre> <p>where <code>ebcdic</code> contains EBCDIC characters and <code>EBCDIC_TO_LATIN1</code> is a 256-char string which maps each EBCDIC character to its Latin-1 equivalent. The characters in <code>EBCDIC_TO_LATIN1</code> are the actual binary values rather than their hex representations. For example, if you are using code page 500, the first 16 bytes of <code>EBCDIC_TO_LATIN1</code> would be</p> <pre><code>'\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' </code></pre> <p>using <a href="http://www.tachyonsoft.com/cp00500.htm" rel="nofollow">this reference</a>.</p>
1
2009-07-01T22:36:43Z
[ "python", "ebcdic" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
1,071,735
<p>EBCDIC 500, aka Code Page 500, is amongst Pythons encodings, although you link to cp1047, which doesn't. Which one are you using, really? Anyway this works for cp500 (or any other encoding that you have).</p> <pre><code>from __future__ import with_statement import sys from contextlib import nested BUFFER_SIZE = 16384 with nested(open(sys.argv[1], 'rb'), open(sys.argv[2], 'wb')) as (infile, outfile): while True: buffer = infile.read(BUFFER_SIZE) if not buffer: break outfile.write(buffer.decode('cp500').encode('latin1')) </code></pre> <p>This way you shouldn't need to keep track of the mappings yourself.</p>
3
2009-07-01T22:54:54Z
[ "python", "ebcdic" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
1,072,049
<p>Assuming cp500 contains all of your "additional propietary characters", a more concise version based on Lennart's answer using the <code>codecs</code> module:</p> <pre><code>import sys, codecs BUFFER_SIZE = 64*1024 ebd_file = codecs.open(sys.argv[1], 'r', 'cp500') latin1_file = codecs.open(sys.argv[2], 'w', 'latin1') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(buffer) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre>
-2
2009-07-02T01:03:26Z
[ "python", "ebcdic" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
1,072,347
<p>Answer 1:</p> <p>Yet another silly question: What gave you the impression that recode produced only ASCII as output? AFAICT it will transcode ANY of its repertoire of charsets to ANY of its repertoire, AND its repertoire includes IBM cp500 and cp1047, and OF COURSE latin1. Reading the comments, you will note that Lennaert and I have discovered that there aren't any "proprietary" codes in those two IBM character sets. So you may well be able to use recode after all, once you are certain what charset you've actually got.</p> <p>Answer 2:</p> <p>If you really need/want to transcode IBM cp1047 via Python, you might like to firstly get the mapping from an authoritative source, processing it via script with some checks:</p> <pre><code>URL = "http://source.icu-project.org/repos/icu/data/trunk/charset/data/ucm/glibc-IBM1047-2.1.2.ucm" """ Sample lines: &lt;U0000&gt; \x00 |0 &lt;U0001&gt; \x01 |0 &lt;U0002&gt; \x02 |0 &lt;U0003&gt; \x03 |0 &lt;U0004&gt; \x37 |0 &lt;U0005&gt; \x2D |0 """ import urllib, re text = urllib.urlopen(URL).read() regex = r"&lt;U([0-9a-fA-F]{4,4})&gt;\s+\\x([0-9a-fA-F]{2,2})\s" results = re.findall(regex, text) wlist = [None] * 256 for result in results: unum, inum = [int(x, 16) for x in result] assert wlist[inum] is None assert 0 &lt;= unum &lt;= 255 wlist[inum] = chr(unum) assert not any(x is None for x in wlist) print repr(''.join(wlist)) </code></pre> <p>Then carefully copy/paste the output into your transcoding script for use with Vinay's buffer.translate(the_mapping) idea, with a buffer size perhaps a bit larger than 16KB and certainly a bit smaller than 2GB :-)</p>
0
2009-07-02T03:39:20Z
[ "python", "ebcdic" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
1,075,257
<p>No crystal ball, no info from OP, so had a bit of a rummage in the EPO website. Found freely downloadable weekly patent info files, still available in cp500/SGML even though website says this to be replaced by utf8/XML in 2006 :-). Got the 2009 week 27 file. Is a zip containing 2 files s350927[ab].bin. "bin" means "not XML". Got the spec! Looks possible that "proprietary codes" are actually <strong>BINARY</strong> fields. Each record has a fixed 252-byte header. First 5 bytes are record length in EBCDIC e.g. hex F0F2F2F0F8 -> 2208 bytes. Last 2 bytes of the fixed header are the BINARY length (redundant) of the following variable part. In the middle are several text fields, two 2-byte binary fields, and one 4-byte binary field. The binary fields are serial numbers within groups, but all I saw are 1. The variable part is SGML.</p> <p>Example (last record from s350927b.bin):</p> <pre><code>Record number: 7266 pprint of header text and binary slices: ['EPB102055619 TXT00000001', 1, ' 20090701200927 08013627.8 EP20090528NN ', 1, 1, ' T *lots of spaces snipped*'] Edited version of the rather long SGML: &lt;PATDOC FILE="08013627.8" CY=EP DNUM=2055619 KIND=B1 DATE=20090701 STATUS=N&gt; *snip* &lt;B541&gt;DE&lt;B542&gt;Windschutzeinheit für ein Motorrad &lt;B541&gt;EN&lt;B542&gt;Windshield unit for saddle-ride type vehicle &lt;B541&gt;FR&lt;B542&gt;Unité pare-brise pour motocyclette&lt;/B540&gt; *snip* &lt;/PATDOC&gt; </code></pre> <p>There are no header or trailer records, just this one record format.</p> <p>So: if the OP's annual files are anything like this, we might be able to help him out. </p> <p><strong>Update</strong>: Above was the "2 a.m. in my timezone" version. Here's a bit more info: </p> <p>OP said: "at the beginning of each file there are a few digits in ASCII that tell you about the length of the file." ... translate that to "at the beginning of each <em>record</em> there are <em>five</em> digits in <em>EBCDIC</em> that tell you <em>exactly</em> the length of the <em>record</em>" and we have a (very fuzzy) match! </p> <p>Here is the URL of the documentation page: <a href="http://docs.epoline.org/ebd/info.htm" rel="nofollow">http://docs.epoline.org/ebd/info.htm</a><br /> The FIRST file mentioned is the spec. </p> <p>Here is the URL of the download-weekly-data page: <a href="http://ebd2.epoline.org/jsp/ebdst35.jsp" rel="nofollow">http://ebd2.epoline.org/jsp/ebdst35.jsp</a> </p> <p>An observation: The data that I looked at is in the ST.35 series. There is also available for download ST.32 which appears to be a parallel version containing only the SGML content (in "reduced cp437/850", one tag per line). This indicates that the fields in the fixed-length header of the ST.35 records may not be very interesting, and can thus be skipped over, which would greatly simplify the transcoding task. </p> <p>For what it's worth, here is my (investigatory, written after midnight) code:<br /> [<strong>Update 2</strong>: tidied up the code a little; no functionality changes]</p> <pre><code>from pprint import pprint as pp import sys from struct import unpack HDRSZ = 252 T = '&gt;s' # text H = '&gt;H' # binary 2 bytes I = '&gt;I' # binary 4 bytes hdr_defn = [ 6, T, 38, H, 40, T, 94, I, 98, H, 100, T, 251, H, # length of following SGML text HDRSZ + 1 ] # above positions as per spec, reduce to allow for counting from 1 for i in xrange(0, len(hdr_defn), 2): hdr_defn[i] -= 1 def records(fname, output_encoding='latin1', debug=False): xlator=''.join(chr(i).decode('cp500').encode(output_encoding, 'replace') for i in range(256)) # print repr(xlator) def xlate(ebcdic): return ebcdic.translate(xlator) # return ebcdic.decode('cp500') # use this if unicode output desired f = open(fname, 'rb') recnum = -1 while True: # get header buff = f.read(HDRSZ) if not buff: return # EOF recnum += 1 if debug: print "\nrecnum", recnum assert len(buff) == HDRSZ recsz = int(xlate(buff[:5])) if debug: print "recsz", recsz # split remainder of header into text and binary pieces fields = [] for i in xrange(0, len(hdr_defn) - 2, 2): ty = hdr_defn[i + 1] piece = buff[hdr_defn[i]:hdr_defn[i+2]] if ty == T: fields.append(xlate(piece)) else: fields.append(unpack(ty, piece)[0]) if debug: pp(fields) sgmlsz = fields.pop() if debug: print "sgmlsz: %d; expected: %d - %d = %d" % (sgmlsz, recsz, HDRSZ, recsz - HDRSZ) assert sgmlsz == recsz - HDRSZ # get sgml part sgml = f.read(sgmlsz) assert len(sgml) == sgmlsz sgml = xlate(sgml) if debug: print "sgml", sgml yield recnum, fields, sgml if __name__ == "__main__": maxrecs = int(sys.argv[1]) # dumping out the last `maxrecs` records in the file fname = sys.argv[2] keep = [None] * maxrecs for recnum, fields, sgml in records(fname): # do something useful here keep[recnum % maxrecs] = (recnum, fields, sgml) keep.sort() for k in keep: if k: recnum, fields, sgml = k print print recnum pp(fields) print sgml </code></pre>
0
2009-07-02T16:07:48Z
[ "python", "ebcdic" ]
Is this a sensible approach for an EBCDIC (CP500) to Latin-1 converter?
1,071,667
<p>I have to convert a number of large files (up to 2GB) of EBCDIC 500 encoded files to Latin-1. Since I could only find EBCDIC to ASCII converters (dd, recode) and the files contain some additional proprietary character codes, I thought I'd write my own converter.</p> <p>I have the <a href="http://www.tachyonsoft.com/cp01047.htm" rel="nofollow">character mapping</a> so I'm interested in the technical aspects.</p> <p>This is my approach so far:</p> <pre><code># char mapping lookup table EBCDIC_TO_LATIN1 = { 0xC1:'41', # A 0xC2:'42', # B # and so on... } BUFFER_SIZE = 1024 * 64 ebd_file = file(sys.argv[1], 'rb') latin1_file = file(sys.argv[2], 'wb') buffer = ebd_file.read(BUFFER_SIZE) while buffer: latin1_file.write(ebd2latin1(buffer)) buffer = ebd_file.read(BUFFER_SIZE) ebd_file.close() latin1_file.close() </code></pre> <p>This is the function that does the converting:</p> <pre><code>def ebd2latin1(ebcdic): result = [] for ch in ebcdic: result.append(EBCDIC_TO_LATIN1[ord(ch)]) return ''.join(result).decode('hex') </code></pre> <p>The question is whether or not this is a sensible approach from an engineering standpoint. Does it have some serious design issues? Is the buffer size OK? And so on...</p> <p>As for the "proprietary characters" that some don't believe in: Each file contains a year's worth of patent documents in SGML format. The patent office has been using EBCDIC until they switched to Unicode in 2005. So there are thousands of documents <em>within</em> each file. They are separated by some hex values that are not part of any IBM specification. They were added by the patent office. Also, at the beginning of each file there are a few digits in ASCII that tell you about the length of the file. I don't really need that information but if I want to process the file so I have to deal with them.</p> <p>Also:</p> <pre><code>$ recode IBM500/CR-LF..Latin1 file.ebc recode: file.ebc failed: Ambiguous output in step `CR-LF..data' </code></pre> <p>Thanks for the help so far.</p>
-1
2009-07-01T22:27:56Z
37,647,699
<p>While this might not help the original poster anymore, some time ago I released a package for Python 2.6+ and 3.2+ that adds most of the western 8 bit mainframe codecs including CP1047 (French) and CP1141 (German): <a href="https://pypi.python.org/pypi/ebcdic" rel="nofollow">https://pypi.python.org/pypi/ebcdic</a>. Simply <code>import ebcdic</code> to add the codecs and then use <code>open(..., encoding='cp1047')</code> to read or write files.</p>
0
2016-06-05T23:13:49Z
[ "python", "ebcdic" ]
I need a Python class that keep tracks of how many times it is instantiated
1,071,935
<p>I need a class that works like this:</p> <pre><code>&gt;&gt;&gt; a=Foo() &gt;&gt;&gt; b=Foo() &gt;&gt;&gt; c=Foo() &gt;&gt;&gt; c.i 3 </code></pre> <p>Here is my try:</p> <pre><code>class Foo(object): i = 0 def __init__(self): Foo.i += 1 </code></pre> <p>It works as required, but I wonder if there is a more pythonic way to do it.</p>
4
2009-07-02T00:12:36Z
1,071,939
<p>Nope. That's pretty good.</p> <p>From The Zen of Python: "Simple is better than complex."</p> <p>That works fine and is clear on what you're doing, don't complicate it. Maybe name it <code>counter</code> or something, but other than that you're good to go as far as pythonic goes.</p>
11
2009-07-02T00:14:04Z
[ "python", "class", "instances" ]
I need a Python class that keep tracks of how many times it is instantiated
1,071,935
<p>I need a class that works like this:</p> <pre><code>&gt;&gt;&gt; a=Foo() &gt;&gt;&gt; b=Foo() &gt;&gt;&gt; c=Foo() &gt;&gt;&gt; c.i 3 </code></pre> <p>Here is my try:</p> <pre><code>class Foo(object): i = 0 def __init__(self): Foo.i += 1 </code></pre> <p>It works as required, but I wonder if there is a more pythonic way to do it.</p>
4
2009-07-02T00:12:36Z
1,072,061
<p>Abuse of decorators and metaclasses.</p> <pre><code>def counting(cls): class MetaClass(getattr(cls, '__class__', type)): __counter = 0 def __new__(meta, name, bases, attrs): old_init = attrs.get('__init__') def __init__(*args, **kwargs): MetaClass.__counter += 1 if old_init: return old_init(*args, **kwargs) @classmethod def get_counter(cls): return MetaClass.__counter new_attrs = dict(attrs) new_attrs.update({'__init__': __init__, 'get_counter': get_counter}) return super(MetaClass, meta).__new__(meta, name, bases, new_attrs) return MetaClass(cls.__name__, cls.__bases__, cls.__dict__) @counting class Foo(object): pass class Bar(Foo): pass print Foo.get_counter() # ==&gt; 0 print Foo().get_counter() # ==&gt; 1 print Bar.get_counter() # ==&gt; 1 print Bar().get_counter() # ==&gt; 2 print Foo.get_counter() # ==&gt; 2 print Foo().get_counter() # ==&gt; 3 </code></pre> <p>You can tell it's Pythonic by the frequent use of double underscored names. (Kidding, kidding...)</p>
5
2009-07-02T01:48:41Z
[ "python", "class", "instances" ]
I need a Python class that keep tracks of how many times it is instantiated
1,071,935
<p>I need a class that works like this:</p> <pre><code>&gt;&gt;&gt; a=Foo() &gt;&gt;&gt; b=Foo() &gt;&gt;&gt; c=Foo() &gt;&gt;&gt; c.i 3 </code></pre> <p>Here is my try:</p> <pre><code>class Foo(object): i = 0 def __init__(self): Foo.i += 1 </code></pre> <p>It works as required, but I wonder if there is a more pythonic way to do it.</p>
4
2009-07-02T00:12:36Z
1,074,252
<p>If you want to worry about thread safety (so that the class variable can be modified from multiple threads that are instantiating <code>Foo</code>s), the above answer is in correct. I asked this question about thread safety <a href="http://stackoverflow.com/questions/1072821/is-modifying-a-class-variable-in-python-threadsafe">here</a>. In summary, you would have to do something like this:</p> <pre><code>from __future__ import with_statement # for python 2.5 import threading class Foo(object): lock = threading.Lock() instance_count = 0 def __init__(self): with Foo.lock: Foo.instance_count += 1 </code></pre> <p>Now <code>Foo</code> may be instantiated from multiple threads.</p>
4
2009-07-02T13:10:47Z
[ "python", "class", "instances" ]
How do I satisfy a 3rd-party shared library reference to stat when I'm creating a shared library shim rather than an executable?
1,072,068
<p>I am the new maintainer for an in-house Python system that uses a set of 3rd-party shared C libraries via a shared library shim that is created using a combination of swig and a setup.py script. This has been working well until recently.</p> <p>The 3rd-party shared C libraries were updated for new functionality and now I get the following run-time error, after a clean build, when I try to run our main Python program (which imports the generated shared library shim):</p> <p>-sh-3.00$ python ams.py</p> <pre><code>ImportError: /usr/lib/libz4lnx.so: undefined symbol: stat </code></pre> <p>I found a discussion thread from 1999 that explains that the problem is that stat is not present in libc.so.6, but rather in libc_nonshared.a, and provides a solution: Link against the c library, by adding -lc to your build command line.</p> <pre><code>http://www.redhat.com/archives/pam-list/1999-February/msg00082.html </code></pre> <p>I've added 'c' to the list of libraries in the setup.py script, but this doesn't change my results. I suspect that this is because I am creating a shared library shim rather than an executable.</p> <p>How can I satisfy the 3rd-party shared library's reference to stat, given my build environment?</p> <p>My build system is:</p> <p>-sh-3.00$ lsb_release -a</p> <pre><code>LSB Version: :core-3.0-ia32:core-3.0-noarch:graphics-3.0-ia32:graphics-3.0-noarch Distributor ID: CentOS Description: CentOS release 4.6 (Final) Release: 4.6 Codename: Final </code></pre> <p>My gcc version is:</p> <p>-sh-3.00$ gcc --version</p> <pre><code>gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-10) </code></pre> <p>My Python version is:</p> <p>-sh-3.00$ python -V</p> <pre><code>Python 2.3.4 </code></pre>
1
2009-07-02T01:58:55Z
1,094,520
<p>The solution was to create to a new Centos 5.3 VM and re-build and/or re-install components as needed.</p>
1
2009-07-07T20:00:40Z
[ "python", "c", "swig" ]
How do I satisfy a 3rd-party shared library reference to stat when I'm creating a shared library shim rather than an executable?
1,072,068
<p>I am the new maintainer for an in-house Python system that uses a set of 3rd-party shared C libraries via a shared library shim that is created using a combination of swig and a setup.py script. This has been working well until recently.</p> <p>The 3rd-party shared C libraries were updated for new functionality and now I get the following run-time error, after a clean build, when I try to run our main Python program (which imports the generated shared library shim):</p> <p>-sh-3.00$ python ams.py</p> <pre><code>ImportError: /usr/lib/libz4lnx.so: undefined symbol: stat </code></pre> <p>I found a discussion thread from 1999 that explains that the problem is that stat is not present in libc.so.6, but rather in libc_nonshared.a, and provides a solution: Link against the c library, by adding -lc to your build command line.</p> <pre><code>http://www.redhat.com/archives/pam-list/1999-February/msg00082.html </code></pre> <p>I've added 'c' to the list of libraries in the setup.py script, but this doesn't change my results. I suspect that this is because I am creating a shared library shim rather than an executable.</p> <p>How can I satisfy the 3rd-party shared library's reference to stat, given my build environment?</p> <p>My build system is:</p> <p>-sh-3.00$ lsb_release -a</p> <pre><code>LSB Version: :core-3.0-ia32:core-3.0-noarch:graphics-3.0-ia32:graphics-3.0-noarch Distributor ID: CentOS Description: CentOS release 4.6 (Final) Release: 4.6 Codename: Final </code></pre> <p>My gcc version is:</p> <p>-sh-3.00$ gcc --version</p> <pre><code>gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-10) </code></pre> <p>My Python version is:</p> <p>-sh-3.00$ python -V</p> <pre><code>Python 2.3.4 </code></pre>
1
2009-07-02T01:58:55Z
1,122,516
<p>As it turns out, while moving to Centos 5.3 was probably a good thing in the long run, the actual problem turns out to have been the way that libz4lnx was built on the DVD that I was originally using. In the process of moving to Centos 5.3, I also moved to a newer build of the libz4lnx library. Today, while testing something else, I used the library from the original DVD and got the exact same undefined symbol error when running the Python program. Switching back to the newest DVD (some two months newer) solved the problem again.</p>
1
2009-07-13T22:47:46Z
[ "python", "c", "swig" ]
Is this a correct way to return JSON in Python/GAE for parsing in JavaScript?
1,072,281
<p>I am making an API for some AJAX related things in my web app on GAE in Python. After setting the content-type to 'application/json' and accessing my url directly-</p> <pre><code>http://mysite.com/api?method=theMethod&amp;param=firstParam </code></pre> <p>-I am being prompted with a 'save file' dialog box instead of seeing the JSON object displayed. The file contains the JSON object when opened in notepad.</p> <p>Is this a correct way to return JSON from Python using GAE to be parsed in JavaScript?</p> <pre><code>from django.utils import simplejson self.response.headers['Content-Type'] = 'application/json' jsonData = {"foo" : "bar"} self.response.out.write(simplejson.dumps(jsonData)) </code></pre> <p>I have noticed that when using another API from somewhere else such as Flickr, my browser displays the JSON object rather than asking for me to save the file. This behavior is what encouraged me to investigate my implementation. My only thought is that this is related to a JSONP implementation.</p> <p>Judging from <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="nofollow">rfc4627</a>, I should be using 'application/json'.</p>
2
2009-07-02T03:15:11Z
1,072,291
<p>I think the Flickr API returns the json as type 'text/plain' which then will be displayed as text. You might try 'text/json' as a halfway point. Being easily viewed might outweigh being correct in your case.</p> <p>Also consider that should any client require the content type to be 'application/json' and refuse to work with 'text/plain' that client should specifically request the type it wants without '<em>/</em>'. This then could be a case you look for when preparing the content type of your response, and you could document your service accordingly.</p> <p>See Request:</p> <pre><code>http://www.flickr.com/services/rest/?method=flickr.test.echo&amp;format=json&amp;api_key=cecc9218c59188ebc6150eff9cd908dc </code></pre> <p>Request Headers</p> <pre><code>Accept:application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Referer:http://www.flickr.com/services/api/response.json.html User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_5_7; en-us) AppleWebKit/530.18 (KHTML, like Gecko) Version/4.0.1 Safari/530.18 </code></pre> <p>Response Headers</p> <pre><code>Connection:close Content-Encoding:gzip Content-Length:134 Content-Type:text/plain; charset=utf-8 Date:Thu, 02 Jul 2009 03:19:34 GMT P3p:policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV" Vary:Accept-Encoding </code></pre> <p>Content</p> <pre><code>jsonFlickrApi({"method":{"_content":"flickr.test.echo"}, "format":{"_content":"json"}, "api_key":{"_content":"cecc9218c59188ebc6150eff9cd908dc"}, "stat":"ok"}) </code></pre>
1
2009-07-02T03:18:10Z
[ "python", "ajax", "json", "api", "google-app-engine" ]
Is this a correct way to return JSON in Python/GAE for parsing in JavaScript?
1,072,281
<p>I am making an API for some AJAX related things in my web app on GAE in Python. After setting the content-type to 'application/json' and accessing my url directly-</p> <pre><code>http://mysite.com/api?method=theMethod&amp;param=firstParam </code></pre> <p>-I am being prompted with a 'save file' dialog box instead of seeing the JSON object displayed. The file contains the JSON object when opened in notepad.</p> <p>Is this a correct way to return JSON from Python using GAE to be parsed in JavaScript?</p> <pre><code>from django.utils import simplejson self.response.headers['Content-Type'] = 'application/json' jsonData = {"foo" : "bar"} self.response.out.write(simplejson.dumps(jsonData)) </code></pre> <p>I have noticed that when using another API from somewhere else such as Flickr, my browser displays the JSON object rather than asking for me to save the file. This behavior is what encouraged me to investigate my implementation. My only thought is that this is related to a JSONP implementation.</p> <p>Judging from <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="nofollow">rfc4627</a>, I should be using 'application/json'.</p>
2
2009-07-02T03:15:11Z
1,072,395
<p>This is the right way, mime type for json is application/json not text/json and NEVER text/html. <a href="http://tools.ietf.org/html/rfc4627" rel="nofollow">http://tools.ietf.org/html/rfc4627</a> starts with "The application/json Media Type for JavaScript Object Notation (JSON)"</p> <p>read <a href="http://simonwillison.net/2009/Feb/6/json/" rel="nofollow">this</a> for more details/options</p>
4
2009-07-02T03:55:53Z
[ "python", "ajax", "json", "api", "google-app-engine" ]
Use SQLite's backup API from Python/SQLAlchemy
1,072,444
<p>I'm using an SQLite database from python (with <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>). For performance reasons, I'd like to populate an in-memory database in the application, and then back up that database to disk.</p> <p>SQLite has a <a href="http://www.sqlite.org/backup.html" rel="nofollow">backup API</a>, which seems would do this transparently.</p> <p>The <a href="http://code.google.com/p/apsw/" rel="nofollow">APSW</a> documentation says that it <a href="http://apsw.googlecode.com/svn/publish/backup.html" rel="nofollow">wraps the backup API</a>, but I'd like to access this functionality from Python's standard sqlite3 module, or in the best case from SQLAlchemy. Is this possible?</p>
4
2009-07-02T04:12:51Z
1,073,589
<p>When I do the following</p> <pre><code>import sqlite3 dir(sqlite3) </code></pre> <p>I see none of the <a href="http://www.sqlite.org/c3ref/backup%5Ffinish.html" rel="nofollow">backup API</a> methods.</p> <p>Therefore, the answer is no; you cannot access the API from the sqlite3 module. It appears that no one implemented it.</p>
1
2009-07-02T10:18:07Z
[ "python", "sqlite", "sqlalchemy" ]
Use SQLite's backup API from Python/SQLAlchemy
1,072,444
<p>I'm using an SQLite database from python (with <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>). For performance reasons, I'd like to populate an in-memory database in the application, and then back up that database to disk.</p> <p>SQLite has a <a href="http://www.sqlite.org/backup.html" rel="nofollow">backup API</a>, which seems would do this transparently.</p> <p>The <a href="http://code.google.com/p/apsw/" rel="nofollow">APSW</a> documentation says that it <a href="http://apsw.googlecode.com/svn/publish/backup.html" rel="nofollow">wraps the backup API</a>, but I'd like to access this functionality from Python's standard sqlite3 module, or in the best case from SQLAlchemy. Is this possible?</p>
4
2009-07-02T04:12:51Z
1,077,925
<p>the APSW dialect can be added to SQLAlchemy pretty easily as well. It would be very easy to achieve in 0.6, which allows multiple kinds of DBAPI adapters to make use of a common dialect for the database in use.</p>
3
2009-07-03T05:54:32Z
[ "python", "sqlite", "sqlalchemy" ]
Use SQLite's backup API from Python/SQLAlchemy
1,072,444
<p>I'm using an SQLite database from python (with <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>). For performance reasons, I'd like to populate an in-memory database in the application, and then back up that database to disk.</p> <p>SQLite has a <a href="http://www.sqlite.org/backup.html" rel="nofollow">backup API</a>, which seems would do this transparently.</p> <p>The <a href="http://code.google.com/p/apsw/" rel="nofollow">APSW</a> documentation says that it <a href="http://apsw.googlecode.com/svn/publish/backup.html" rel="nofollow">wraps the backup API</a>, but I'd like to access this functionality from Python's standard sqlite3 module, or in the best case from SQLAlchemy. Is this possible?</p>
4
2009-07-02T04:12:51Z
3,426,144
<p>If pysqlite and apsw are linked against the same sqlite library then pysqlite can accept apsw connections. See:</p> <p><a href="http://docs.pysqlite.googlecode.com/hg/sqlite3.html#combining-apsw-and-pysqlite" rel="nofollow">http://docs.pysqlite.googlecode.com/hg/sqlite3.html#combining-apsw-and-pysqlite</a></p> <p>I will try to do work on this (and other) approaches to getting apsw to work with SQLAlchemy as they are a very useful combination.</p>
3
2010-08-06T17:21:03Z
[ "python", "sqlite", "sqlalchemy" ]
Use SQLite's backup API from Python/SQLAlchemy
1,072,444
<p>I'm using an SQLite database from python (with <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>). For performance reasons, I'd like to populate an in-memory database in the application, and then back up that database to disk.</p> <p>SQLite has a <a href="http://www.sqlite.org/backup.html" rel="nofollow">backup API</a>, which seems would do this transparently.</p> <p>The <a href="http://code.google.com/p/apsw/" rel="nofollow">APSW</a> documentation says that it <a href="http://apsw.googlecode.com/svn/publish/backup.html" rel="nofollow">wraps the backup API</a>, but I'd like to access this functionality from Python's standard sqlite3 module, or in the best case from SQLAlchemy. Is this possible?</p>
4
2009-07-02T04:12:51Z
18,189,301
<p>The <a href="https://github.com/husio/python-sqlite3-backup" rel="nofollow">python-sqlite3-backup</a> module claims to solve this problem.</p>
1
2013-08-12T14:16:09Z
[ "python", "sqlite", "sqlalchemy" ]
Updating one aspect of a Pygame surface
1,072,639
<p>I have an application written in python that's basically an etch-a-sketch, you move pixels around with WASD and arrow keys and it leaves a trail. However, I want to add a counter for the amount of pixels on the screen. How do I have the counter update without updating the entire surface and pwning the pixel drawings?</p>
0
2009-07-02T05:24:19Z
1,073,207
<p>Use <a href="http://www.pygame.org/docs/ref/surface.html" rel="nofollow">Surface</a>.blit(source, dest, area=None, special_flags = 0): return Rect</p> <p><em>dest</em> can be a pair of coordinates representing the upper left corner of the source.</p> <p>You probably want to erase the your old counter value, before you blit the new one. For this you can capture the background before you blit your counter value for the first time. Then blit that image everytime before you update the counter value. </p> <p>In addition you should make the background of surface that your blitting transparent. Assuming you have black font on white background, you could use:</p> <pre><code>source.set_colorkey((255,255,255)) </code></pre>
0
2009-07-02T08:43:49Z
[ "python", "pygame" ]
Python Language Question: attributes of object() vs Function
1,072,649
<p>In python, it is illegal to create new attribute for an object instance like this</p> <pre><code>&gt;&gt;&gt; a = object() &gt;&gt;&gt; a.hhh = 1 </code></pre> <p>throws </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'hhh' </code></pre> <p>However, for a function object, it is OK.</p> <pre><code>&gt;&gt;&gt; def f(): ... return 1 ... &gt;&gt;&gt; f.hhh = 1 </code></pre> <p>What is the rationale behind this difference?</p>
17
2009-07-02T05:27:25Z
1,072,669
<p>The reason function objects support arbitrary attributes is that, before we added that feature, several frameworks (e.g. parser generator ones) were abusing function docstrings (and other attribute of function objects) to stash away per-function information that was crucial to them -- the need for such association of arbitrary named attributes to function objects being proven by example, supporting them directly in the language rather than punting and letting (e.g.) docstrings be abused, was pretty obvious.</p> <p>To support arbitrary instance attributes a type must supply every one of its instances with a <code>__dict__</code> -- that's no big deal for functions (which are never tiny objects anyway), but it might well be for other objects <em>intended</em> to be tiny. By making the <code>object</code> type as light as we could, and also supplying <code>__slots__</code> to allow avoiding per-instance <code>__dict__</code> in subtypes of <code>object</code>, we supported small, specialized "value" types to the best of our ability.</p>
22
2009-07-02T05:33:52Z
[ "python", "function", "object" ]
Python Language Question: attributes of object() vs Function
1,072,649
<p>In python, it is illegal to create new attribute for an object instance like this</p> <pre><code>&gt;&gt;&gt; a = object() &gt;&gt;&gt; a.hhh = 1 </code></pre> <p>throws </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'hhh' </code></pre> <p>However, for a function object, it is OK.</p> <pre><code>&gt;&gt;&gt; def f(): ... return 1 ... &gt;&gt;&gt; f.hhh = 1 </code></pre> <p>What is the rationale behind this difference?</p>
17
2009-07-02T05:27:25Z
1,072,763
<p>Alex Martelli posted an awesome answer to your question. For anyone who is looking for a good way to accomplish arbitrary attributes on an empty object, do this:</p> <pre><code>class myobject(object): pass o = myobject() o.anything = 123 </code></pre> <p>Or more efficient (and better documented) if you know the attributes:</p> <pre><code>class myobject(object): __slots__ = ('anything', 'anythingelse') o = myobject() o.anything = 123 o.anythingelse = 456 </code></pre>
7
2009-07-02T06:15:15Z
[ "python", "function", "object" ]
Python Language Question: attributes of object() vs Function
1,072,649
<p>In python, it is illegal to create new attribute for an object instance like this</p> <pre><code>&gt;&gt;&gt; a = object() &gt;&gt;&gt; a.hhh = 1 </code></pre> <p>throws </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'hhh' </code></pre> <p>However, for a function object, it is OK.</p> <pre><code>&gt;&gt;&gt; def f(): ... return 1 ... &gt;&gt;&gt; f.hhh = 1 </code></pre> <p>What is the rationale behind this difference?</p>
17
2009-07-02T05:27:25Z
1,073,573
<p>The rationale is that an instance of <code>object()</code> is a degenerate special case. It "is" an object but it isn't designed to be useful by itself.</p> <p>Think of <code>object</code> as a temporary hack, bridging old-style types and classes. In Python 3.0 it will fade into obscurity because it will no longer be used as part of </p> <pre><code>class Foo( object ): pass f = Foo() f.randomAttribute = 3.1415926 </code></pre>
1
2009-07-02T10:11:02Z
[ "python", "function", "object" ]
Python Language Question: attributes of object() vs Function
1,072,649
<p>In python, it is illegal to create new attribute for an object instance like this</p> <pre><code>&gt;&gt;&gt; a = object() &gt;&gt;&gt; a.hhh = 1 </code></pre> <p>throws </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has no attribute 'hhh' </code></pre> <p>However, for a function object, it is OK.</p> <pre><code>&gt;&gt;&gt; def f(): ... return 1 ... &gt;&gt;&gt; f.hhh = 1 </code></pre> <p>What is the rationale behind this difference?</p>
17
2009-07-02T05:27:25Z
20,256,311
<p>Here's another alternative, as short as I could make it:</p> <pre><code>&gt;&gt;&gt; dummy = type('', (), {})() &gt;&gt;&gt; dummy.foo = 5 &gt;&gt;&gt; dummy.foo 5 </code></pre>
0
2013-11-28T01:43:52Z
[ "python", "function", "object" ]
Playing MMS streams within Python
1,072,652
<p>I'm writing a XM desktop application (I plan on releasing the source on github when I'm finished if anyone is interested) Anyway, the one part I know very little about is how to play media within Python (I'm using PyQt for the frontend). Basically, I have a mms:// url that I need to play. I was wondering if there is a library that could accomplish this or something, really I just need someone to point me in the right direction. </p> <p>I know its possible, because SMplayer (Python implementation of MPlayer that uses Qt) works with MMS, I may have to take a peak at they're source if worse comes to worse.</p>
1
2009-07-02T05:28:34Z
1,072,688
<p>You can have a look at </p> <ol> <li><a href="http://pymedia.org/" rel="nofollow">PyMedia</a></li> <li><a href="http://www.pygame.org/" rel="nofollow">PyGame</a></li> <li><a href="http://www.wxpython.org/" rel="nofollow">wxPython</a></li> </ol> <p><a href="http://www.daniweb.com/code/snippet467.html#" rel="nofollow">Here is a code snippet</a> of doing a similar thing with wxPython.</p> <p>All of these can play media files.</p>
2
2009-07-02T05:43:18Z
[ "python", "streaming", "pyqt", "audio-streaming", "mms" ]
Updating part of a surface in python, or transparent surfaces
1,072,734
<p>I have an application written in python that's basically an etch-a-sketch, you move pixels around with WASD and arrow keys and it leaves a trail. However, I want to add a counter for the amount of pixels on the screen. How do I have the counter update without updating the entire surface and pwning the pixel drawings?</p> <p>Alternatively, can I make a surface that's completely transparent except for the text so you can see the drawing surface underneath?</p>
1
2009-07-02T06:03:39Z
1,072,808
<p>What you need is pygame.font module</p> <pre><code>#define a font surface spamSurface = pygame.font.SysFont('Arial', 20) #then, in your infinite cycle... eggsPixels = spamSurface.render(str(pixelsOnScreen), True, (255, 255, 255)) hamDisplay.blit(eggsPixels, (10, 10)) </code></pre> <p>Where <code>spamSurface</code> is a new font surface, <code>eggsPixels</code> is the value that <code>spamSurface</code> will render (display/show) and <code>hamDisplay</code> is your main surface display.</p>
0
2009-07-02T06:35:37Z
[ "python", "pygame" ]
Updating part of a surface in python, or transparent surfaces
1,072,734
<p>I have an application written in python that's basically an etch-a-sketch, you move pixels around with WASD and arrow keys and it leaves a trail. However, I want to add a counter for the amount of pixels on the screen. How do I have the counter update without updating the entire surface and pwning the pixel drawings?</p> <p>Alternatively, can I make a surface that's completely transparent except for the text so you can see the drawing surface underneath?</p>
1
2009-07-02T06:03:39Z
1,117,885
<p>To solve this problem, you want to have a separate surface for your Etch-a-Sketch pixels, so that they do not get clobbered when you go to refresh the screen. Unfortunately, with Rigo's scheme, the font will continue to render on top of itself, which will get messy for more than two pixel count changes.</p> <p>So, here's some sample rendering code:</p> <pre><code># Fill background screen.fill((0xcc, 0xcc, 0xcc)) # Blit Etch-a-Sketch surface (with the drawing) # etch_surf should be the same size as the screen screen.blit(etch_surf, (0, 0)) # Render the pixel count arial = pygame.font.SysFont('Arial', 20) counter_surf = arial.render(str(pixel_count), True, (0, 0, 0)) screen.blit(counter_surf, (16, 16)) # Refresh entire screen pygame.display.update() </code></pre> <p>Now, admittedly, updating the entire screen is rather inefficient. For this, you have two options: only refresh the screen when the drawing changes or track the location of drawing changes and refresh individual locations (see the <a href="http://www.pygame.org/docs/ref/display.html#pygame.display.update" rel="nofollow" title="pygame.display.update">update documentation</a>). If you choose the second option, you will have to refresh the text and where it was previously; I would recommend having a <a href="http://www.pygame.org/docs/ref/display.html#pygame.display.update" rel="nofollow" title="pygame.display.update">Sprite</a> manage this.</p>
1
2009-07-13T06:00:04Z
[ "python", "pygame" ]
How can I deal with No module named edit.editor?
1,072,736
<p>I am trying to follow the <a href="http://wingware.com/doc/scripting/example" rel="nofollow">WingIDE tutorial</a> on creating scripts in the IDE. </p> <p>This following example scripts always throws an error:</p> <pre><code>import wingapi def test_script(test_str): app = wingapi.gApplication v = "Product info is: " + str(app.GetProductInfo()) v += "\nAnd you typed: %s" % test_str wingapi.gApplication.ShowMessageDialog("Test Message", v) </code></pre> <p>Traceback (most recent call last): File "C:\Wing-pi\Scripts\test.py", line 1, in import wingapi File "C:\Program Files\Development\Wing IDE 3.1\bin\wingapi.py", line 18, in import edit.editor ImportError: No module named edit.editor Process terminated with an exit code of 1</p> <p>I am launching the script in the Wing IDE as suggested by someone, but I keep getting the same result. </p>
0
2009-07-02T06:03:45Z
1,078,574
<p>Answer is based on email from Stephan Deibel from the Wingware company that develops Wind IDE.</p> <blockquote> <p>Scripts are not launched in Wing's debugger. If you're editing them within Wing, they get reloaded as soon as you save and you should be able to use Command By Name in the edit menu to type test-script, which will execute the above script. This is described in more detail on the page you found the example:</p> </blockquote> <p>You <strong>cannot run the script in debug mode</strong> unless you have the Wing sources. You can launch the script fine from within the Wing IDE.</p>
1
2009-07-03T09:29:52Z
[ "python", "wing-ide" ]
Is modifying a class variable in python threadsafe?
1,072,821
<p>I was reading <a href="http://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated">this question</a> (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)...</p> <p>So, if I have a class that counts how many instances were created:</p> <pre><code>class Foo(object): instance_count = 0 def __init__(self): Foo.instance_count += 1 </code></pre> <p>My question is, if I create Foo objects in multiple threads, is instance_count going to be correct? Are class variables safe to modify from multiple threads?</p>
13
2009-07-02T06:38:59Z
1,072,851
<p>I would say it is thread-safe, at least on CPython implementation. The GIL will make all your "threads" to run sequentially so they will not be able to mess with your reference count.</p>
-2
2009-07-02T06:48:03Z
[ "python", "multithreading" ]
Is modifying a class variable in python threadsafe?
1,072,821
<p>I was reading <a href="http://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated">this question</a> (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)...</p> <p>So, if I have a class that counts how many instances were created:</p> <pre><code>class Foo(object): instance_count = 0 def __init__(self): Foo.instance_count += 1 </code></pre> <p>My question is, if I create Foo objects in multiple threads, is instance_count going to be correct? Are class variables safe to modify from multiple threads?</p>
13
2009-07-02T06:38:59Z
1,073,230
<p>It's not threadsafe even on CPython. Try this to see for yourself:</p> <pre><code>import threading class Foo(object): instance_count = 0 def inc_by(n): for i in xrange(n): Foo.instance_count += 1 threads = [threading.Thread(target=inc_by, args=(100000,)) for thread_nr in xrange(100)] for thread in threads: thread.start() for thread in threads: thread.join() print(Foo.instance_count) # Expected 10M for threadsafe ops, I get around 5M </code></pre> <p>The reason is that while INPLACE_ADD is atomic under GIL, the attribute is still loaded and store (see <em>dis.dis(Foo.__init__)</em>). Use a lock to serialize the access to the class variable:</p> <pre><code>Foo.lock = threading.Lock() def interlocked_inc(n): for i in xrange(n): with Foo.lock: Foo.instance_count += 1 threads = [threading.Thread(target=interlocked_inc, args=(100000,)) for thread_nr in xrange(100)] for thread in threads: thread.start() for thread in threads: thread.join() print(Foo.instance_count) </code></pre>
20
2009-07-02T08:48:52Z
[ "python", "multithreading" ]
Is modifying a class variable in python threadsafe?
1,072,821
<p>I was reading <a href="http://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated">this question</a> (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)...</p> <p>So, if I have a class that counts how many instances were created:</p> <pre><code>class Foo(object): instance_count = 0 def __init__(self): Foo.instance_count += 1 </code></pre> <p>My question is, if I create Foo objects in multiple threads, is instance_count going to be correct? Are class variables safe to modify from multiple threads?</p>
13
2009-07-02T06:38:59Z
1,074,035
<p>No it is not thread safe. I've faced a similar problem a few days ago and I choosed to implement the lock thanks to a decorator. The benefit is that it makes the code readable:</p> <pre> def threadsafe_function(fn): """decorator making sure that the decorated function is thread safe""" lock = threading.Lock() def new(*args, **kwargs): lock.acquire() try: r = fn(*args, **kwargs) except Exception as e: raise e finally: lock.release() return r return new class X: var = 0 @threadsafe_function def inc_var(self): X.var += 1 return X.var </pre>
7
2009-07-02T12:17:09Z
[ "python", "multithreading" ]
How to convert XSD to Python Class
1,072,853
<p>I just want to know if there is a program that can convert an XSD file to a Python class as <strong>JAXB</strong> does for Java?</p>
29
2009-07-02T06:49:23Z
1,072,989
<p><a href="http://pythonhosted.org/generateDS/">generateDS</a> : I think this is the good tool I need </p> <p>Edit : Actually, generateDS does very well the job !! It generates the Python class with all methods (setters and getters, export to XML, import from XML). It works very well !</p>
24
2009-07-02T07:35:15Z
[ "python", "xml", "data-binding", "xsd", "xsd2code" ]
How to convert XSD to Python Class
1,072,853
<p>I just want to know if there is a program that can convert an XSD file to a Python class as <strong>JAXB</strong> does for Java?</p>
29
2009-07-02T06:49:23Z
1,073,556
<p>Look at <a href="http://pypi.python.org/pypi/rsl.xsd/0.2.3" rel="nofollow">http://pypi.python.org/pypi/rsl.xsd/0.2.3</a></p> <p>Also, you might want <a href="http://pyxsd.org/" rel="nofollow">http://pyxsd.org/</a> it works very nicely.</p>
1
2009-07-02T10:06:33Z
[ "python", "xml", "data-binding", "xsd", "xsd2code" ]
How to convert XSD to Python Class
1,072,853
<p>I just want to know if there is a program that can convert an XSD file to a Python class as <strong>JAXB</strong> does for Java?</p>
29
2009-07-02T06:49:23Z
10,815,021
<p>PyXB: <a href="http://pyxb.sourceforge.net/">http://pyxb.sourceforge.net/</a></p>
8
2012-05-30T11:06:22Z
[ "python", "xml", "data-binding", "xsd", "xsd2code" ]
date is added in background while adding time in datastore GAE
1,072,877
<p>3.Why does "jan 1st 1970" gets added in the startime field in datastore when I am doing the below statements?</p> <pre><code> (hour,min) = self.request.get('starttime').split(":") #if either of them is null or empty string then int will throw exception if hour and min : datastoremodel.starttime = datetime.time(int(hour), int(min)) </code></pre> <p>Although when I retrieve it only time comes through? I wonder what date is doing in datastore? Any clues?</p>
0
2009-07-02T06:55:19Z
1,073,053
<p>google app engine <a href="http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#TimeProperty" rel="nofollow">doc</a> says</p> <pre><code>class TimeProperty(verbose_name=None, auto_now=False, auto_now_add=False, ...) A time property, without a date. Takes a Python standard library datetime.time value. See DateTimeProperty for more information. Value type: datetime.time. This is converted to a datetime.datetime internally. </code></pre> <p>so to convert time to a date , start of <a href="http://en.wikipedia.org/wiki/Unix%5Ftime" rel="nofollow">epoch time "jan 1st 1970"</a> is added</p>
2
2009-07-02T07:53:29Z
[ "python", "google-app-engine", "datetime" ]
Printing python modulus operator as it is over command line
1,072,951
<p>I want to print modulus operator as it is over the command line: E.g this is how the output should look like:<br/> 1%2<br/> 2%4</p> <p>or<br/> 30%<br/> 40%</p> <p>I am using the print statement like this:<br/></p> <blockquote> <p>print 'computing %s % %s' % (num1, num2)</p> </blockquote> <p>Its throwing the default error:</p> <blockquote> <p>TypeError: not all arguments converted during string formatting</p> </blockquote> <p>For now I am using:</p> <blockquote> <p>print 'computing 1'+'%'+'2'</p> </blockquote> <p>which prints:</p> <blockquote> <p>computing 1%2</p> </blockquote> <p>But tell me how to get this done using the first approach(:print 'computing %s % %s' % (num1,num2))</p>
3
2009-07-02T07:21:52Z
1,072,959
<pre><code>print 'computing %s %% %s' % (num1, num2) </code></pre>
1
2009-07-02T07:24:10Z
[ "python", "operators", "modulo" ]
Printing python modulus operator as it is over command line
1,072,951
<p>I want to print modulus operator as it is over the command line: E.g this is how the output should look like:<br/> 1%2<br/> 2%4</p> <p>or<br/> 30%<br/> 40%</p> <p>I am using the print statement like this:<br/></p> <blockquote> <p>print 'computing %s % %s' % (num1, num2)</p> </blockquote> <p>Its throwing the default error:</p> <blockquote> <p>TypeError: not all arguments converted during string formatting</p> </blockquote> <p>For now I am using:</p> <blockquote> <p>print 'computing 1'+'%'+'2'</p> </blockquote> <p>which prints:</p> <blockquote> <p>computing 1%2</p> </blockquote> <p>But tell me how to get this done using the first approach(:print 'computing %s % %s' % (num1,num2))</p>
3
2009-07-02T07:21:52Z
1,072,963
<p>Escape the % sign with another % sign, like this:</p> <pre><code>print 'computing %s %% %s' % (num1, num2) </code></pre>
7
2009-07-02T07:25:29Z
[ "python", "operators", "modulo" ]
Calculate score in a pyramid score system
1,072,977
<p>I am trying to calculate gamescores for a bunch over users and I haven't really got it yet. It is a pyramid game where you can invite people, and the people you invite is placed beneth you in the relations tree.</p> <p>So if i invite X and X invites Y i get kickback from both of them. Let's say 10%^steps...</p> <p>So from X i get 10% of his score and 1% from Y, and X get 10% from Y.</p> <p>So to calculate this i was thinking that each "player" had a function that calculated his total score. This function had to be recursive and "know" how far in the tree it was so that it would kick back the right values.</p> <pre><code>def get_score(player): if children: score = player.points for child in children: score += child.points*math.pow(.1, get_ancestors(child)) score += get_score(child) return score else: return player.points </code></pre> <p>But this doesnt work proper, it gives what i believe is the right values in some levels but not in others. So think my function is broken. Anybody got an idea on how to solve this?</p>
1
2009-07-02T07:30:07Z
1,073,002
<p>I doubt these two lines</p> <pre><code>score += child.points*math.pow(.1, get_ancestors(child)) score += get_score(child) </code></pre> <p>this is a simple recursive structure so i think something like below will suffice</p> <pre><code>score += get_score(child)*.1 </code></pre> <p>and recursive beauty will take care of itself</p> <p>you also do not need 'if children:' check so does it help</p> <pre><code>def get_score(player): score = player.points for child in children: score += get_score(child)*.1 return score </code></pre>
2
2009-07-02T07:39:13Z
[ "python", "recursion" ]
Calculate score in a pyramid score system
1,072,977
<p>I am trying to calculate gamescores for a bunch over users and I haven't really got it yet. It is a pyramid game where you can invite people, and the people you invite is placed beneth you in the relations tree.</p> <p>So if i invite X and X invites Y i get kickback from both of them. Let's say 10%^steps...</p> <p>So from X i get 10% of his score and 1% from Y, and X get 10% from Y.</p> <p>So to calculate this i was thinking that each "player" had a function that calculated his total score. This function had to be recursive and "know" how far in the tree it was so that it would kick back the right values.</p> <pre><code>def get_score(player): if children: score = player.points for child in children: score += child.points*math.pow(.1, get_ancestors(child)) score += get_score(child) return score else: return player.points </code></pre> <p>But this doesnt work proper, it gives what i believe is the right values in some levels but not in others. So think my function is broken. Anybody got an idea on how to solve this?</p>
1
2009-07-02T07:30:07Z
1,073,062
<p>This can have very different implementations, depending on the way the score must be calculating :</p> <ul> <li><p>Do you need to propagate the result of each gain, in real time ? In that case , you start from the bottom of the pyramid and give the feedback until the top.</p></li> <li><p>Can you afford the result to be calculated at the end of the game for everybody ? In that cas you can just set a method on each player and only call the one at the top.</p></li> </ul> <p><strong>E.G for the second option</strong></p> <p>You used a functional approach. While this is valid, I am more into OO so I'll go this way :</p> <pre><code>class Player(object) : def __init__(self) : self.score = 0; self.children = [] def updateScore(self) : self.score = self.score + sum(((children.score * 10 / 100) for children in self.children)) class Pyramid(object) : def __init__(self) : self.top_child = Player() def updateScore(self, player = None) : if player == None : player = self.top_child for child in player.children : self.updateScore(child) child.updateScore() </code></pre> <p>You may want to use itertools to make it less CPU and memory intensive. </p>
0
2009-07-02T07:56:31Z
[ "python", "recursion" ]
Is generator.next() visible in python 3.0?
1,073,396
<p>I have a generator that generates a series, for example:</p> <pre><code>def triangleNums(): '''generate series of triangle numbers''' tn = 0 counter = 1 while(True): tn = tn + counter yield tn counter = counter + 1 </code></pre> <p>in python 2.6 I am able to make the following calls:</p> <pre><code>g = triangleNums() # get the generator g.next() # get next val </code></pre> <p>however in 3.0 if I execute the same two lines of code I'm getting the following error:</p> <pre><code>AttributeError: 'generator' object has no attribute 'next' </code></pre> <p>but, the loop iterator syntax does work in 3.0</p> <pre><code>for n in triangleNums(): if not exitCond: doSomething... </code></pre> <p>I've not been able to find anything yet that explains this difference in behavior for 3.0.</p>
82
2009-07-02T09:29:44Z
1,073,407
<p>Try:</p> <pre><code>next(g) </code></pre> <p>Check out <a href="http://www.diveinto.org/python3/porting-code-to-python-3-with-2to3.html#next">this neat table</a> that shows the differences in syntax between 2 and 3 when it comes to this.</p>
49
2009-07-02T09:31:19Z
[ "python", "python-3.x", "iteration" ]
Is generator.next() visible in python 3.0?
1,073,396
<p>I have a generator that generates a series, for example:</p> <pre><code>def triangleNums(): '''generate series of triangle numbers''' tn = 0 counter = 1 while(True): tn = tn + counter yield tn counter = counter + 1 </code></pre> <p>in python 2.6 I am able to make the following calls:</p> <pre><code>g = triangleNums() # get the generator g.next() # get next val </code></pre> <p>however in 3.0 if I execute the same two lines of code I'm getting the following error:</p> <pre><code>AttributeError: 'generator' object has no attribute 'next' </code></pre> <p>but, the loop iterator syntax does work in 3.0</p> <pre><code>for n in triangleNums(): if not exitCond: doSomething... </code></pre> <p>I've not been able to find anything yet that explains this difference in behavior for 3.0.</p>
82
2009-07-02T09:29:44Z
1,073,582
<p>Correct, <code>g.next()</code> has been renamed to <code>g.__next__()</code>. The reason for this is to have consistence. Special methods like <code>__init__()</code> and <code>__del__</code> all have double underscores (or "dunder" as it is getting popular to call them now), and .next() is one of the few exceptions to that rule. Python 3.0 fixes that. [*]</p> <p>But instead of calling <code>g.__next__()</code>, as Paolo says, use <code>next(g)</code>.</p> <p>[*] There are more special attributes who has gotten this fix, like function attributes. No longer <code>func_name</code>, it's now <code>__name__</code>, etc.</p>
143
2009-07-02T10:15:53Z
[ "python", "python-3.x", "iteration" ]
Is generator.next() visible in python 3.0?
1,073,396
<p>I have a generator that generates a series, for example:</p> <pre><code>def triangleNums(): '''generate series of triangle numbers''' tn = 0 counter = 1 while(True): tn = tn + counter yield tn counter = counter + 1 </code></pre> <p>in python 2.6 I am able to make the following calls:</p> <pre><code>g = triangleNums() # get the generator g.next() # get next val </code></pre> <p>however in 3.0 if I execute the same two lines of code I'm getting the following error:</p> <pre><code>AttributeError: 'generator' object has no attribute 'next' </code></pre> <p>but, the loop iterator syntax does work in 3.0</p> <pre><code>for n in triangleNums(): if not exitCond: doSomething... </code></pre> <p>I've not been able to find anything yet that explains this difference in behavior for 3.0.</p>
82
2009-07-02T09:29:44Z
32,636,158
<p>If your code must run under Python2 and Python3, use the 2to3 <a href="https://pythonhosted.org/six/#six.next" rel="nofollow">six</a> library like this:</p> <pre><code>import six six.next(g) # on PY2K: 'g.next()' and onPY3K: 'next(g)' </code></pre>
4
2015-09-17T17:09:59Z
[ "python", "python-3.x", "iteration" ]
PyQt clipboard doesn't copy to system clipboard
1,073,550
<p>The following snippet of code doesn't seem to affect the system clipboard at all:</p> <pre><code>clipboard = QtGui.QApplication.clipboard() clipboard.setText(text) </code></pre> <p>According to the Qt documentation, this is how you copy text to clipboard, </p> <p>Why isn't it working?</p> <p>Googling turned <a href="http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17328.html">this</a> up.</p> <p>It suggests adding this after the above code:</p> <pre><code>event = QtCore.QEvent(QtCore.QEvent.Clipboard) app.sendEvent(clipboard, event) </code></pre> <p>But this one behaves odd: it only copies the text to the clipboard after the program exits. Plus, some people in that link reported that this doesn't work with linux.</p> <h3>UPDATE:</h3> <p>Nevermind, I was doing something wrong else where, instead of binding the copy slot to the copy button, I connected it to the "quit" button.</p>
7
2009-07-02T10:04:20Z
1,073,788
<p>I know you are not using Windows, but maybe this will give you some ideas... I used this in a PyQt program to copy URLs to the clipboard:</p> <pre><code>import win32clipboard s = 'copy this to the clipboard' try: win32clipboard.OpenClipboard() win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(s) win32clipboard.CloseClipboard() except: print 'Could not copy clipboard data.' </code></pre>
4
2009-07-02T11:16:23Z
[ "python", "qt", "pyqt", "clipboard" ]
PyQt clipboard doesn't copy to system clipboard
1,073,550
<p>The following snippet of code doesn't seem to affect the system clipboard at all:</p> <pre><code>clipboard = QtGui.QApplication.clipboard() clipboard.setText(text) </code></pre> <p>According to the Qt documentation, this is how you copy text to clipboard, </p> <p>Why isn't it working?</p> <p>Googling turned <a href="http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17328.html">this</a> up.</p> <p>It suggests adding this after the above code:</p> <pre><code>event = QtCore.QEvent(QtCore.QEvent.Clipboard) app.sendEvent(clipboard, event) </code></pre> <p>But this one behaves odd: it only copies the text to the clipboard after the program exits. Plus, some people in that link reported that this doesn't work with linux.</p> <h3>UPDATE:</h3> <p>Nevermind, I was doing something wrong else where, instead of binding the copy slot to the copy button, I connected it to the "quit" button.</p>
7
2009-07-02T10:04:20Z
1,073,838
<p>You might try <a href="http://library.gnome.org/devel/pygtk/stable/class-gtkclipboard.html" rel="nofollow">gtk.Clipboard</a> from <a href="http://www.pygtk.org/about.html" rel="nofollow">PyGTK</a>. I believe it is multi-platform.</p> <p>This might be part of the reason you're having trouble with PyQt's <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qapplication.html#clipboard" rel="nofollow">QClipboard</a> object:</p> <blockquote> <p><strong>QClipboard QApplication.clipboard ()</strong></p> <p>Returns a pointer to the application global clipboard.</p> <p>Note: The QApplication object should already be constructed before accessing the clipboard.</p> </blockquote> <p><strike>It's pointing to the <em>application</em> clipboard, not the system clipboard. You'll probably have to use something other than the QClipboard object to achieve your end.</strike></p> <p><strong>Edit:</strong></p> <p>The above conclusion from the cited documentation is incorrect. According to the actual <a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qclipboard.html" rel="nofollow">PyQt documentation of the QClipboard</a> object:</p> <blockquote> <p>The QClipboard class provides access to the window system clipboard.</p> </blockquote>
0
2009-07-02T11:30:43Z
[ "python", "qt", "pyqt", "clipboard" ]
PyQt clipboard doesn't copy to system clipboard
1,073,550
<p>The following snippet of code doesn't seem to affect the system clipboard at all:</p> <pre><code>clipboard = QtGui.QApplication.clipboard() clipboard.setText(text) </code></pre> <p>According to the Qt documentation, this is how you copy text to clipboard, </p> <p>Why isn't it working?</p> <p>Googling turned <a href="http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg17328.html">this</a> up.</p> <p>It suggests adding this after the above code:</p> <pre><code>event = QtCore.QEvent(QtCore.QEvent.Clipboard) app.sendEvent(clipboard, event) </code></pre> <p>But this one behaves odd: it only copies the text to the clipboard after the program exits. Plus, some people in that link reported that this doesn't work with linux.</p> <h3>UPDATE:</h3> <p>Nevermind, I was doing something wrong else where, instead of binding the copy slot to the copy button, I connected it to the "quit" button.</p>
7
2009-07-02T10:04:20Z
23,119,741
<p>You may need to specify the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qclipboard.html#Mode-enum" rel="nofollow">mode</a>.</p> <p>This code worked for me on windows:</p> <pre><code> cb = QtGui.QApplication.clipboard() cb.clear(mode=cb.Clipboard ) cb.setText("Clipboard Text", mode=cb.Clipboard) </code></pre>
3
2014-04-16T20:43:15Z
[ "python", "qt", "pyqt", "clipboard" ]
Why does SCons VariantDir() not put output in the given directory?
1,074,062
<p>I'm thinking about using <a href="http://www.scons.org/">SCons</a> for a new project. It looks really good, though I'm finding <code>VariantDir</code> quite confusing.</p> <p>I have a simple project with a handful of C source files in one directory, and I want to build in "normal" and in "profile" mode -- with two different sets of options to gcc. I want the outputs to go in the normal/ and profile/ directories, respectively.</p> <p>For testing, I've cut back to just a single source file, t.c, which has a <code>main()</code> in it. My <code>SConstruct</code> file is in the same directory, and looks like this:</p> <pre><code>normal = DefaultEnvironment(tools=['mingw'], CCFLAGS = '-O2') normal.VariantDir('release', '.', duplicate=0) normal.Program('t', ['t.c']) #profile = normal.Clone(CCFLAGS='-O2 -pg', LINKFLAGS = '-pg') #profile.VariantDir('profile', '.', duplicate=0) #profile.Program('t', ['t.c']) </code></pre> <p>When I run scons, I'm expecting it to put t.o and t.exe into release/, but it puts them in the current directory. And I can't run it at all with the 3 profile lines uncommented -- if I do, I get this error:</p> <p><strong>scons: *** Two environments with different actions were specified for the same target: t.o</strong></p> <p>Basically, I'm unsure why my VariantDir() calls aren't telling scons to put the output in the specified output directory, <code>release</code>.</p> <p>(I've read a fair bit in the docs and newsgroups, but nothing that answers this question. The closest I've come is <a href="http://scons.org/wiki/SimultaneousVariantBuilds">this page</a>, which describes a similar thing, but it involves a separate src/ directory and two separate scons files, and importing/exporting variables between them. That doesn't seem pleasant.)</p>
7
2009-07-02T12:26:40Z
1,074,587
<p>Yes, VariantDir is confusing in scons. Although not well advertised, you can put both SConstruct and SConscript in the same directory, using the current directory as the source directory</p> <pre><code># SConstruct SConscript('SConscript', build_dir='build', src='.') </code></pre> <p>and</p> <pre><code># SConscript Program('main.c') </code></pre> <p>I have never found a way to avoid using two files while keeping my sanity trying to understand variant dir :)</p>
7
2009-07-02T14:10:23Z
[ "python", "c", "makefile", "scons" ]
Why does SCons VariantDir() not put output in the given directory?
1,074,062
<p>I'm thinking about using <a href="http://www.scons.org/">SCons</a> for a new project. It looks really good, though I'm finding <code>VariantDir</code> quite confusing.</p> <p>I have a simple project with a handful of C source files in one directory, and I want to build in "normal" and in "profile" mode -- with two different sets of options to gcc. I want the outputs to go in the normal/ and profile/ directories, respectively.</p> <p>For testing, I've cut back to just a single source file, t.c, which has a <code>main()</code> in it. My <code>SConstruct</code> file is in the same directory, and looks like this:</p> <pre><code>normal = DefaultEnvironment(tools=['mingw'], CCFLAGS = '-O2') normal.VariantDir('release', '.', duplicate=0) normal.Program('t', ['t.c']) #profile = normal.Clone(CCFLAGS='-O2 -pg', LINKFLAGS = '-pg') #profile.VariantDir('profile', '.', duplicate=0) #profile.Program('t', ['t.c']) </code></pre> <p>When I run scons, I'm expecting it to put t.o and t.exe into release/, but it puts them in the current directory. And I can't run it at all with the 3 profile lines uncommented -- if I do, I get this error:</p> <p><strong>scons: *** Two environments with different actions were specified for the same target: t.o</strong></p> <p>Basically, I'm unsure why my VariantDir() calls aren't telling scons to put the output in the specified output directory, <code>release</code>.</p> <p>(I've read a fair bit in the docs and newsgroups, but nothing that answers this question. The closest I've come is <a href="http://scons.org/wiki/SimultaneousVariantBuilds">this page</a>, which describes a similar thing, but it involves a separate src/ directory and two separate scons files, and importing/exporting variables between them. That doesn't seem pleasant.)</p>
7
2009-07-02T12:26:40Z
1,181,212
<p>I was able to separate binaries in a build directory using this call:</p> <pre><code># SConstruct SConscript('SConscript', variant_dir='build', src_dir='..', duplicate=0) </code></pre> <p>If you want to put binaries into a directory two levels below, do this:</p> <pre><code># SConstruct SConscript('SConscript', variant_dir='build/release', src_dir='../..', duplicate=0) </code></pre> <p>Basically, provide the <code>src_dir</code> parameter as a path from your build directory back to your source directory.</p>
6
2009-07-25T04:39:19Z
[ "python", "c", "makefile", "scons" ]
Why does SCons VariantDir() not put output in the given directory?
1,074,062
<p>I'm thinking about using <a href="http://www.scons.org/">SCons</a> for a new project. It looks really good, though I'm finding <code>VariantDir</code> quite confusing.</p> <p>I have a simple project with a handful of C source files in one directory, and I want to build in "normal" and in "profile" mode -- with two different sets of options to gcc. I want the outputs to go in the normal/ and profile/ directories, respectively.</p> <p>For testing, I've cut back to just a single source file, t.c, which has a <code>main()</code> in it. My <code>SConstruct</code> file is in the same directory, and looks like this:</p> <pre><code>normal = DefaultEnvironment(tools=['mingw'], CCFLAGS = '-O2') normal.VariantDir('release', '.', duplicate=0) normal.Program('t', ['t.c']) #profile = normal.Clone(CCFLAGS='-O2 -pg', LINKFLAGS = '-pg') #profile.VariantDir('profile', '.', duplicate=0) #profile.Program('t', ['t.c']) </code></pre> <p>When I run scons, I'm expecting it to put t.o and t.exe into release/, but it puts them in the current directory. And I can't run it at all with the 3 profile lines uncommented -- if I do, I get this error:</p> <p><strong>scons: *** Two environments with different actions were specified for the same target: t.o</strong></p> <p>Basically, I'm unsure why my VariantDir() calls aren't telling scons to put the output in the specified output directory, <code>release</code>.</p> <p>(I've read a fair bit in the docs and newsgroups, but nothing that answers this question. The closest I've come is <a href="http://scons.org/wiki/SimultaneousVariantBuilds">this page</a>, which describes a similar thing, but it involves a separate src/ directory and two separate scons files, and importing/exporting variables between them. That doesn't seem pleasant.)</p>
7
2009-07-02T12:26:40Z
24,505,810
<p>As <a href="http://www.scons.org/wiki/VariantDir%28%29" rel="nofollow">http://www.scons.org/wiki/VariantDir%28%29</a> said, </p> <blockquote> <p>Note that when you're not using an SConscript file in the src subdirectory, you must actually specify that the program must be built from the build/hello.c file that SCons will duplicate in the build subdirectory. </p> </blockquote> <pre><code>VariantDir('release','.',duplicate=0) env=Environment() env.Program('release/t',['release/t.c']) </code></pre> <p>when I run it with <code>scons</code> on Linux.</p> <pre><code>scons -u . scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... scons: building associated VariantDir targets: release gcc -o release/t.o -c t.c gcc -o release/t release/t.o scons: done building targets. </code></pre> <p>I guess it would also work on Win32</p>
2
2014-07-01T08:36:15Z
[ "python", "c", "makefile", "scons" ]
Pyinstaller traceback
1,074,144
<pre><code>Traceback (most recent call last): File "&lt;string&gt;", line 137, in &lt;module&gt; File C:\Python26\buildSVG_Resizer\out1.pyz/encodings", line 100, in search_function TypeError: importHook() got an unexpected keyword argument 'level' </code></pre> <p>The imports in my .py file are:</p> <pre><code>import xml.etree.ElementTree as ET import os, stat import tkFileDialog </code></pre> <p>My script parses SVG's (xml) in a directory and then replaces values if they are out of range. This script runs fine through the console.</p> <p>I can post the whole script if that will help. </p> <p>Thanks for anything.</p>
0
2009-07-02T12:47:17Z
1,074,750
<p><code>importHook</code> in <code>iu.py</code> (top level of pyinstaller) does accept a <code>level=</code> named argument, so the message is quite perplexing and suggests a bad installation.</p> <p>What output do you get from cd'ing to pyinstaller's top directory and doing:</p> <pre><code>svn log -r HEAD </code></pre> <p>? Should currently be </p> <pre><code>r685 | giovannibajo | 2009-06-30 05:19:59 -0700 (Tue, 30 Jun 2009) | 3 lines Preliminar support for creating a bundle on Mac OSX. Yet to be integrated into Makespec.py. </code></pre> <p>If you get something older, <code>svn up</code> to make sure you have the current version, and try packaging your project again (from the start, since, if you've used some defective version, there might have been incorrect intermediate files generated).</p>
1
2009-07-02T14:33:51Z
[ "python" ]
Serve a dynamically generated image with Django
1,074,200
<p>How do I serve a dynamically generated image in Django? </p> <p>I have an html tag</p> <pre><code>&lt;html&gt; ... &lt;img src="images/dynamic_chart.png" /&gt; ... &lt;/html&gt; </code></pre> <p>linked up to this request handler, which creates an in-memory image</p> <pre><code>def chart(request): img = Image.new("RGB", (300,300), "#FFFFFF") data = [(i,randint(100,200)) for i in range(0,300,10)] draw = ImageDraw.Draw(img) draw.polygon(data, fill="#000000") # now what? return HttpResponse(output) </code></pre> <p>I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution.</p>
23
2009-07-02T12:59:55Z
1,074,270
<p>I'm relatively new to Django myself. I haven't been able to find anything in Django itself, but I have stumbled upon a project on Google Code that may be of some help to you:</p> <p><a href="http://code.google.com/p/django-dynamic-media-serve/" rel="nofollow">django-dynamic-media-serve</a></p>
3
2009-07-02T13:13:36Z
[ "python", "ajax", "django", "image" ]
Serve a dynamically generated image with Django
1,074,200
<p>How do I serve a dynamically generated image in Django? </p> <p>I have an html tag</p> <pre><code>&lt;html&gt; ... &lt;img src="images/dynamic_chart.png" /&gt; ... &lt;/html&gt; </code></pre> <p>linked up to this request handler, which creates an in-memory image</p> <pre><code>def chart(request): img = Image.new("RGB", (300,300), "#FFFFFF") data = [(i,randint(100,200)) for i in range(0,300,10)] draw = ImageDraw.Draw(img) draw.polygon(data, fill="#000000") # now what? return HttpResponse(output) </code></pre> <p>I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution.</p>
23
2009-07-02T12:59:55Z
1,074,277
<p>I assume you're using PIL (Python Imaging Library). You need to replace your last line with (for example, if you want to serve a PNG image):</p> <pre><code>response = HttpResponse(mimetype="image/png") img.save(response, "PNG") return response </code></pre> <p>See <a href="http://effbot.org/zone/django-pil.htm">here</a> for more information.</p>
22
2009-07-02T13:15:02Z
[ "python", "ajax", "django", "image" ]
restore registry from file
1,074,467
<p>I am trying to migrate microsoft office settings from one system to other system by backing up office registry and restoring it on the destination machine using Python.I am able to do the saving part,but on trying to restore the existing settings in destination machine to overwrite existing office settings,i am getting an error. This is the code for restoring :-</p> <pre><code>import os, sys import _winreg import win32api import win32con import win32security priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), priv_flags) backup_privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege") restore_privilege_id = win32security.LookupPrivilegeValue (None, "SeRestorePrivilege") win32security.AdjustTokenPrivileges ( hToken, 0, [ (backup_privilege_id, win32security.SE_PRIVILEGE_ENABLED), (restore_privilege_id, win32security.SE_PRIVILEGE_ENABLED) ] ) result = _winreg.LoadKey (_winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Office",ur"Office.registry") print "Restored Office Settings" </code></pre> <p>here "office.registry" is the backed up hive HKEY_CURRENT_USER\Software\Microsoft\Office</p> <p>I am getting WindowsError: [Errno 5] Access is denied.</p> <p>Please help me to identify my mistake</p>
1
2009-07-02T13:53:02Z
1,614,364
<p>The registry system has a built-in method for updating registry keys by creating and importing a .reg text file. I suggest that you try to write your changes to a .reg file and import that.</p> <p>Also, you don't mention what Windows version you are using. In the newer versions, the permission system is rather more complex than it used to be.</p>
1
2009-10-23T15:52:02Z
[ "python", "registry" ]
Generating an image thumbnail that is <10KB and did not lose proportions
1,075,037
<p>Notice how for every image that google indexes it has a small <a href="http://images.google.com/images?q=jeff+atwood" rel="nofollow">thumbnail</a>. These thumbnails are:</p> <ol> <li>Less than 10KB in size.</li> <li>The proportions of the width / height are the same as the ones in the original image.</li> </ol> <p>I would like to write a function (in python) that would take an image and create a thumbnail with these to properties. </p> <p>EDIT: So there are 3 answers right now and all of them are half right.</p> <p>I need a function that not only resizes the image proportionally, but also makes sure the file size is smaller than 10KB. How do I do that?</p>
1
2009-07-02T15:22:30Z
1,075,079
<p>Did you read the <a href="http://www.pythonware.com/library/pil/handbook/image.htm" rel="nofollow">PIL documentation</a>? There is an image.thumbnail method.</p>
1
2009-07-02T15:30:37Z
[ "python", "image-processing", "python-imaging-library" ]
Generating an image thumbnail that is <10KB and did not lose proportions
1,075,037
<p>Notice how for every image that google indexes it has a small <a href="http://images.google.com/images?q=jeff+atwood" rel="nofollow">thumbnail</a>. These thumbnails are:</p> <ol> <li>Less than 10KB in size.</li> <li>The proportions of the width / height are the same as the ones in the original image.</li> </ol> <p>I would like to write a function (in python) that would take an image and create a thumbnail with these to properties. </p> <p>EDIT: So there are 3 answers right now and all of them are half right.</p> <p>I need a function that not only resizes the image proportionally, but also makes sure the file size is smaller than 10KB. How do I do that?</p>
1
2009-07-02T15:22:30Z
1,075,089
<p>In <a href="http://mail.python.org/pipermail/python-list/2005-August/338139.html" rel="nofollow">this short post</a>, Mike Fletcher and the effbot show (and discuss detailed variation) an excellent approach for the task you want to do.</p> <p><strong>Edit</strong>: as for the 10K requirement, it's hard (to say the least;-) to predict how well an image will compress, depending on the image's format, since today's compression algorithms are so subtle. If you want your thumbnail to be just about as large (in pixels) as feasible while respecting a &lt;10K requirement, you may have to use a "trial and error" approach making successively more refined guesses about the scaling factor, until you reach an acceptable result.</p> <p>For example, here's a "binary search" approach to getting the correct size (there may well be better strategies!), with ample print statements &amp;c to explain what's going on...:</p> <pre><code>import Image import cStringIO import math import os import stat # try no more than 10 times, then give up MAX_TRIES = 10 def getThumbnail(filename, max_bytes=(10*1024)): '''Get a thumbnail image of filename, &lt;max_bytes''' original_size = os.stat(filename)[stat.ST_SIZE] print "Original file size: %.1f KB" % (original_size/1024.) image = Image.open(filename) image.load() print "Original image size: %dx%d pixels" % image.size min_bytes = int(0.9 * max_bytes) largest_side = max(image.size) smallest_side = 16 for attempt in range(MAX_TRIES): try_side = (largest_side + smallest_side) / 2 print "Attempt #%d of %d" % (attempt+1, MAX_TRIES) print "Side must be within [%d:%d], now trying %d" % ( smallest_side, largest_side, try_side) thumb = image.copy() thumb.thumbnail((try_side,try_side), Image.ANTIALIAS) afile = cStringIO.StringIO() thumb.save(afile, "PNG") resulting_size = len(afile.getvalue()) afile.close() print "Reduced file size: %.1f KB" % (resulting_size/1024.) print "Reduced image size: %dx%d pixels" % thumb.size if min_bytes &lt;= resulting_size &lt;= max_bytes: print "Success!" return thumb elif resulting_size &gt; max_bytes: print "Too large (&gt;%d), reducing more" % max_bytes largest_side = try_side else: print "Too small (&lt;%d), reducing less" % min_bytes smallest_side = try_side print "too many attempts, returning what I've got!" return thumb def main(): thumb = getThumbnail("pyth.png") print "Reduced image size: %dx%d pixels" % thumb.size print "Saving to thumb.png" thumb.save("thumb.png") thumb_size = os.stat("thumb.png")[stat.ST_SIZE] print "Reduced file size: %.1f KB" % (thumb_size/1024.) print "Done, bye!" if __name__ == '__main__': main() </code></pre>
3
2009-07-02T15:32:59Z
[ "python", "image-processing", "python-imaging-library" ]
Generating an image thumbnail that is <10KB and did not lose proportions
1,075,037
<p>Notice how for every image that google indexes it has a small <a href="http://images.google.com/images?q=jeff+atwood" rel="nofollow">thumbnail</a>. These thumbnails are:</p> <ol> <li>Less than 10KB in size.</li> <li>The proportions of the width / height are the same as the ones in the original image.</li> </ol> <p>I would like to write a function (in python) that would take an image and create a thumbnail with these to properties. </p> <p>EDIT: So there are 3 answers right now and all of them are half right.</p> <p>I need a function that not only resizes the image proportionally, but also makes sure the file size is smaller than 10KB. How do I do that?</p>
1
2009-07-02T15:22:30Z
1,075,277
<p>Use PIL, see sample code here to resize keeping aspect ratio</p> <p><a href="http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio">http://stackoverflow.com/questions/273946/how-do-i-resize-an-image-using-pil-and-maintain-its-aspect-ratio</a></p> <p>see how to do similar thing on a dir</p> <p><a href="http://stackoverflow.com/questions/1048658/resize-images-in-directory/1048793#1048793">http://stackoverflow.com/questions/1048658/resize-images-in-directory/1048793#1048793</a></p> <p>So above links describe how to resize images using PIL, now coming to your question of max size of 10KB, that can be achieved easily e.g.</p> <p>Suppose size required is 100x100, and we use JPEG compression, 100% JPEG quality takes abt 9 bits per pixel(see <a href="http://en.wikipedia.org/wiki/JPEG" rel="nofollow">http://en.wikipedia.org/wiki/JPEG</a>), that means size of 100x100 image would be 100x100x9/(1024x8) = 11KB, so at quality=100 you are almost achieving your goal, but if you still want 10KB only you can set quality=90, and in general you can pass quality as param to resize function and reduce quality by 10% if image size is above 10KB but I think that is not needed, at 90% quality all JPEG images would be &lt; 10KB.</p> <p>Also note that without compression also image size is just 30KB for RGB image, and if you reduce size to 60x60 pixels image size would be only 10KB without any compression i.e you can use bmp images and if you want lesses sizer but lossless compression you can choose PNG.</p> <p>So in conclusion your target of 10KB is very easy to achieve.</p>
1
2009-07-02T16:11:54Z
[ "python", "image-processing", "python-imaging-library" ]
How do I find the memory address of a Python / Django model object?
1,075,106
<p>An ordinary object, I can use </p> <pre><code>o.__repr__() </code></pre> <p>to see something like </p> <pre><code>'&lt;__main__.A object at 0x9d78fec&gt;' </code></pre> <p>But, say, a Django User just returns </p> <pre><code>&lt;User:bob&gt; </code></pre> <p>How can I see the actual address of one of these, or compare whether two such model-objects are actually the same object or not?</p>
0
2009-07-02T15:35:53Z
1,075,130
<p>Use the id() function for that. Or equivalently just compare "obj1 is obj2".</p>
1
2009-07-02T15:40:15Z
[ "python", "django", "django-models" ]
How do I find the memory address of a Python / Django model object?
1,075,106
<p>An ordinary object, I can use </p> <pre><code>o.__repr__() </code></pre> <p>to see something like </p> <pre><code>'&lt;__main__.A object at 0x9d78fec&gt;' </code></pre> <p>But, say, a Django User just returns </p> <pre><code>&lt;User:bob&gt; </code></pre> <p>How can I see the actual address of one of these, or compare whether two such model-objects are actually the same object or not?</p>
0
2009-07-02T15:35:53Z
1,075,131
<p><code>id()</code> will return the identity of the object (generally implemented as the address), which is guaranteed unique for two objects which exist at the same point in time. However the obvious way to check whether two objects are identical is to use the operator explicitely designed for this: <code>is</code></p> <p>ie.</p> <pre><code> if obj1 is obj2: # Objects are identical. </code></pre>
7
2009-07-02T15:40:20Z
[ "python", "django", "django-models" ]
How do I find the memory address of a Python / Django model object?
1,075,106
<p>An ordinary object, I can use </p> <pre><code>o.__repr__() </code></pre> <p>to see something like </p> <pre><code>'&lt;__main__.A object at 0x9d78fec&gt;' </code></pre> <p>But, say, a Django User just returns </p> <pre><code>&lt;User:bob&gt; </code></pre> <p>How can I see the actual address of one of these, or compare whether two such model-objects are actually the same object or not?</p>
0
2009-07-02T15:35:53Z
1,075,148
<p>You can get the id of any object:</p> <pre><code>a = object() print hex(id(a)) </code></pre> <p>Although for CPython, this is the address of the object, this is not guaranteed I believe (and may be different on other implementations like iron python). Same id means same object, though.</p>
2
2009-07-02T15:44:13Z
[ "python", "django", "django-models" ]
How to debug SCons scripts using eclipse and pydev?
1,075,304
<p>I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?</p>
3
2009-07-02T16:16:07Z
1,075,694
<p>I'm not an Eclipse expert, but since you didn't get any other answer...</p> <p>If you make the SCons source a part of the Eclipse project, and run the whole command from within Eclipse it should work like any Eclipse debugging. SCons is written in Python, there is no reason it shouldn't be debuggable in Eclipse just like anything else.</p>
2
2009-07-02T17:33:35Z
[ "python", "eclipse", "pydev", "scons" ]
How to debug SCons scripts using eclipse and pydev?
1,075,304
<p>I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?</p>
3
2009-07-02T16:16:07Z
1,077,102
<p>You are right. Since the SCons is python based, the SCons scripts are debuggable via EClipse PyDev. For this, you need to do the following in the debug configuration... <li>1. Under the main tab, set the main module to the SCons file which will be available under the python/scripts directory if you have installed SCons. If you have not run the install of SCons you can point to this file under the SCons directory. <li> 2. Under the arguments tab, set the working directory to the root of your project.</p> <p>Now set the breakpoint either on SConstruct or SConcript and run in debug mode. That's all!! With this approach you can not only debug your product code but also the build scripts that builds your product :-) Happy Debugging!!!!</p>
5
2009-07-02T22:58:13Z
[ "python", "eclipse", "pydev", "scons" ]
How to debug SCons scripts using eclipse and pydev?
1,075,304
<p>I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?</p>
3
2009-07-02T16:16:07Z
6,202,513
<p>if you are using SCons for C/C++ development and Eclipse CDT check out <a href="http://sconsolidator.com" rel="nofollow">http://sconsolidator.com</a> (within the next weeks), we will release our SCons Eclipse plug-in for free public use shortly. It also contains an "interactive mode" that allows SCons builds to run more quickly (no startup time) and also to debug SCons in a console. However, the tip with using PyDev still applies (can be installed alongside with CDT in the same Eclipse instance.</p>
1
2011-06-01T14:07:25Z
[ "python", "eclipse", "pydev", "scons" ]
How to debug SCons scripts using eclipse and pydev?
1,075,304
<p>I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?</p>
3
2009-07-02T16:16:07Z
15,386,322
<p>On MAC to debug scons through pydev follow Lennart's answer but with one simply addition.</p> <p>Using Finder (or terminal) browse to where scons is installed. You can find this with the "which" command.</p> <p>e.g. which scons -> /usr/local/bin/scons</p> <p>Make a copy of the scons file and call it scons.py.</p> <p>Now when you create the Debug Configuration in Eclipse use scons.py as the "Main Module".</p> <p>PS: To add a scons project to Eclipse I found it easier to use a "Linked Folder" pointing at /usr/local/bin/. i.e. Because I was getting a read-only error when trying to add the directory itself.</p>
1
2013-03-13T13:12:11Z
[ "python", "eclipse", "pydev", "scons" ]
How to debug SCons scripts using eclipse and pydev?
1,075,304
<p>I'm a newbie to SCons and also using pydev. Can someone help me with instructions on how to debug scons scripts using Eclipse and pydev? Is it even possible considering the fact that SCons is a seperate app and not an extension to python?</p>
3
2009-07-02T16:16:07Z
32,887,089
<p>I've since gain more experience with SCons / Python and I'd recommend using python's pdb module. To use it simply add the following code to your SCons/Python files.</p> <p>import pdb; pdb.set_trace()</p> <p>When the file is run from the command line a breakpoint will be hit at this line. I also moved away from Eclipse. A lightweight editor will be just as good for Python development. I use Sublime.</p>
0
2015-10-01T11:59:25Z
[ "python", "eclipse", "pydev", "scons" ]
CherryPy interferes with Twisted shutting down on Windows
1,075,351
<p>I've got an application that runs Twisted by starting the reactor with <code>reactor.run()</code> in my main thread after starting some other threads, including the CherryPy web server. Here's a program that shuts down cleanly when Ctrl+C is pressed on Linux but not on Windows:</p> <pre><code>from threading import Thread from signal import signal, SIGINT import cherrypy from twisted.internet import reactor from twisted.web.client import getPage def stop(signum, frame): cherrypy.engine.exit() reactor.callFromThread(reactor.stop) signal(SIGINT, stop) class Root: @cherrypy.expose def index(self): reactor.callFromThread(kickoff) return "Hello World!" cherrypy.server.socket_host = "0.0.0.0" Thread(target=cherrypy.quickstart, args=[Root()]).start() def print_page(html): print(html) def kickoff(): getPage("http://acpstats/account/login").addCallback(print_page) reactor.run() </code></pre> <p>I believe that CherryPy is the culprit here, because here's a different program that I wrote without CherryPy that does shutdown cleanly on both Linux and Windows when Ctrl+C is pressed:</p> <pre><code>from time import sleep from threading import Thread from signal import signal, SIGINT from twisted.internet import reactor from twisted.web.client import getPage keep_going = True def stop(signum, frame): global keep_going keep_going = False reactor.callFromThread(reactor.stop) signal(SIGINT, stop) def print_page(html): print(html) def kickoff(): getPage("http://acpstats/account/login").addCallback(print_page) def periodic_downloader(): while keep_going: reactor.callFromThread(kickoff) sleep(5) Thread(target=periodic_downloader).start() reactor.run() </code></pre> <p>Does anyone have any idea what the problem is? Here's my conundrum:</p> <ul> <li>On Linux everything works</li> <li>On Windows, I can call functions from signal handlers using <code>reactor.callFromThread</code> when CherryPy is not running</li> <li>When CherryPy is running, no function that I call using <code>reactor.callFromThread</code> from a signal handler will ever execute (I've verified that the signal handler itself does get called)</li> </ul> <p>What can I do about this? How can I shut down Twisted on Windows from a signal handler while running CherryPy? Is this a bug, or have I simply missed some important part of the documentation for either of these two projects?</p>
7
2009-07-02T16:25:05Z
1,080,010
<p>CherryPy handles signals by default when you call quickstart. In your case, you should probably just unroll quickstart, which is only a few lines, and pick and choose. Here's basically what quickstart does in trunk:</p> <pre><code>if config: cherrypy.config.update(config) tree.mount(root, script_name, config) if hasattr(engine, "signal_handler"): engine.signal_handler.subscribe() if hasattr(engine, "console_control_handler"): engine.console_control_handler.subscribe() engine.start() engine.block() </code></pre> <p>In your case, you don't need the signal handlers, so you can omit those. You also don't need to call engine.block if you're not starting CherryPy from the main thread. Engine.block() is just a way to make the main thread not terminate immediately, but instead wait around for process termination (this is so autoreload works reliably; some platforms have issues calling execv from any thread but the main thread).</p> <p>If you remove the block() call, you don't even need the Thread() around quickstart. So, replace your line:</p> <pre><code>Thread(target=cherrypy.quickstart, args=[Root()]).start() </code></pre> <p>with:</p> <pre><code>cherrypy.tree.mount(Root()) cherrypy.engine.start() </code></pre>
14
2009-07-03T16:14:12Z
[ "python", "windows", "linux", "twisted", "cherrypy" ]
Does python have hooks into EXT3
1,075,391
<p>We have several cron jobs that ftp proxy logs to a centralized server. These files can be rather large and take some time to transfer. Part of the requirement of this project is to provide a logging mechanism in which we log the success or failure of these transfers. This is simple enough.</p> <p>My question is, is there a way to check if a file is currently being written to? My first solution was to just check the file size twice within a given timeframe and check the file size. But a co-worker said that there may be able to hook into the EXT3 file system via python and check the attributes to see if the file is currently being appended to. My Google-Fu came up empty. </p> <p>Is there a module for EXT3 or something else that would allow me to check the state of a file? The server is running Fedora Core 9 with EXT3 file system.</p>
4
2009-07-02T16:32:54Z
1,075,459
<p>no need for ext3-specific hooks; just check <code>lsof</code>, or more exactly, <code>/proc/&lt;pid&gt;/fd/*</code> and <code>/proc/&lt;pid&gt;/fdinfo/*</code> (that's where <code>lsof</code> gets it's info, AFAICT). There you can check if the file is open, if it's writeable, and the 'cursor' position.</p> <p>That's not the whole picture; but any more is done in processpace by stdlib on the writing process, as most writes are buffered and the kernel only sees bigger chunks of data, so any 'ext3-aware' monitor wouldn't get that either.</p>
7
2009-07-02T16:45:20Z
[ "python", "linux", "ext3" ]
Does python have hooks into EXT3
1,075,391
<p>We have several cron jobs that ftp proxy logs to a centralized server. These files can be rather large and take some time to transfer. Part of the requirement of this project is to provide a logging mechanism in which we log the success or failure of these transfers. This is simple enough.</p> <p>My question is, is there a way to check if a file is currently being written to? My first solution was to just check the file size twice within a given timeframe and check the file size. But a co-worker said that there may be able to hook into the EXT3 file system via python and check the attributes to see if the file is currently being appended to. My Google-Fu came up empty. </p> <p>Is there a module for EXT3 or something else that would allow me to check the state of a file? The server is running Fedora Core 9 with EXT3 file system.</p>
4
2009-07-02T16:32:54Z
1,075,518
<p>There's no ext3 hooks to check what you'd want directly. </p> <ul> <li>I suppose you could dig through the source code of <a href="http://linux.die.net/man/1/fuser" rel="nofollow" title="fuser">Fuser</a> linux command, replicate the part that finds which process owns a file, and watch that resource. When noone longer has the file opened, it's done transferring.</li> </ul> <p>Another approach:</p> <ul> <li>Your cron jobs should tell that they're finished.</li> </ul> <p>We have our cron jobs that transport files just write an empty <em>filename.finished</em> after it's transferred the <em>filename</em>. Another approach is to transfer them to a temporary filename, e.g. <em>filename.part</em> and then rename it to <em>filename</em> Renaming is atomic. In both cases you check repeatedly until the presence of <em>filename</em> or <em>filename.finished</em></p>
1
2009-07-02T16:55:34Z
[ "python", "linux", "ext3" ]
Share objects with file handle attribute between processes
1,075,443
<p>I have a question about shared resource with file handle between processes. Here is my test code:</p> <pre><code>from multiprocessing import Process,Lock,freeze_support,Queue import tempfile #from cStringIO import StringIO class File(): def __init__(self): self.temp = tempfile.TemporaryFile() #print self.temp def read(self): print "reading!!!" s = "huanghao is a good boy !!" print &gt;&gt; self.temp,s self.temp.seek(0,0) f_content = self.temp.read() print f_content class MyProcess(Process): def __init__(self,queue,*args,**kwargs): Process.__init__(self,*args,**kwargs) self.queue = queue def run(self): print "ready to get the file object" self.queue.get().read() print "file object got" file.read() if __name__ == "__main__": freeze_support() queue = Queue() file = File() queue.put(file) print "file just put" p = MyProcess(queue) p.start() </code></pre> <p>Then I get a <code>KeyError</code> like below:</p> <pre><code>file just put ready to get the file object Process MyProcess-1: Traceback (most recent call last): File "D:\Python26\lib\multiprocessing\process.py", line 231, in _bootstrap self.run() File "E:\tmp\mpt.py", line 35, in run self.queue.get().read() File "D:\Python26\lib\multiprocessing\queues.py", line 91, in get res = self._recv() File "D:\Python26\lib\tempfile.py", line 375, in __getattr__ file = self.__dict__['file'] KeyError: 'file' </code></pre> <p>I think when I put the <code>File()</code> object into queue , the object got serialized, and file handle can not be serialized, so, i got the <code>KeyError</code>:</p> <p>Anyone have any idea about that? if I want to share objects with file handle attribute, what should I do?</p>
5
2009-07-02T16:42:46Z
1,077,599
<p>I have to object (at length, won't just fit in a commentl;-) to @Mark's repeated assertion that file handles just can't be "passed around between running processes" -- this is simply not true in real, modern operating systems, such as, oh, say, Unix (free BSD variants, MacOSX, and Linux, included -- hmmm, I wonder what OS's are left out of this list...?-) -- <a href="http://www.myelin.co.nz/post/2003/12/2/">sendmsg</a> of course can do it (on a "Unix socket", by using the <code>SCM_RIGHTS</code> flag).</p> <p>Now the poor, valuable <code>multiprocessing</code> is fully right to not exploit this feature (even assuming there might be black magic to implement it on Windows too) -- most developers would no doubt misuse it anyway (having multiple processes access the same open file concurrently and running into race conditions). The only proper way to use it is for a process which has exclusive rights to open certain files to pass the opened file handles to another process which runs with reduced privileges -- and then never use that handle itself again. No way to enforce that in the <code>multiprocessing</code> module, anyway.</p> <p>Back to @Andy's original question, unless he's going to work on Linux only (AND with local processes only, too) and willing to play dirty tricks with the /proc filesystem, he's going to have to define his application-level needs more sharply and serialize <code>file</code> objects accordingly. Most files have a path (or can be made to have one: path-less files are pretty rare, actually non-existent on Windows I believe) and thus can be serialized via it -- many others are small enough to serialize by sending their content over -- etc, etc.</p>
6
2009-07-03T02:55:17Z
[ "python", "multiprocessing" ]
Simplifying Data with a for loop (Python)
1,075,631
<p>I was trying to simplify the code:</p> <pre><code> header = [] header.append(header1) header.append(header2) header.append(header3) header.append(header4) header.append(header5) header.append(header6) </code></pre> <p>where:</p> <pre><code> header1 = str(input.headerOut1) header2 = str(input.headerOut2) header3 = str(input.headerOut3) header4 = str(input.headerOut4) header5 = str(input.headerOut5) header6 = str(input.headerOut6) </code></pre> <p>I had wanted to use a for loop, like:</p> <pre><code> headerList = [] for i in range(6) headerList.append(header+i) </code></pre> <p>however, python won't recognize that header+i represents the string header1. Is there any way to simplify this code or get the for loop to work? Thank you so much!</p>
0
2009-07-02T17:18:53Z
1,075,642
<p>Put the headers in an array and loop through it.</p>
2
2009-07-02T17:21:30Z
[ "python", "string", "loops", "for-loop", "simplify" ]
Simplifying Data with a for loop (Python)
1,075,631
<p>I was trying to simplify the code:</p> <pre><code> header = [] header.append(header1) header.append(header2) header.append(header3) header.append(header4) header.append(header5) header.append(header6) </code></pre> <p>where:</p> <pre><code> header1 = str(input.headerOut1) header2 = str(input.headerOut2) header3 = str(input.headerOut3) header4 = str(input.headerOut4) header5 = str(input.headerOut5) header6 = str(input.headerOut6) </code></pre> <p>I had wanted to use a for loop, like:</p> <pre><code> headerList = [] for i in range(6) headerList.append(header+i) </code></pre> <p>however, python won't recognize that header+i represents the string header1. Is there any way to simplify this code or get the for loop to work? Thank you so much!</p>
0
2009-07-02T17:18:53Z
1,075,654
<p>You can use <a href="http://docs.python.org/library/functions.html#locals" rel="nofollow"><code>locals</code></a> to get the the local scope as a dict:</p> <pre><code>headerList = [] for i in xrange(1, 7): headerList.append(locals()['header%s' % (i,)]) </code></pre> <p>If possible, though, you should just use the <code>input</code> variable directly, as some of the other answers suggested.</p>
2
2009-07-02T17:22:49Z
[ "python", "string", "loops", "for-loop", "simplify" ]
Simplifying Data with a for loop (Python)
1,075,631
<p>I was trying to simplify the code:</p> <pre><code> header = [] header.append(header1) header.append(header2) header.append(header3) header.append(header4) header.append(header5) header.append(header6) </code></pre> <p>where:</p> <pre><code> header1 = str(input.headerOut1) header2 = str(input.headerOut2) header3 = str(input.headerOut3) header4 = str(input.headerOut4) header5 = str(input.headerOut5) header6 = str(input.headerOut6) </code></pre> <p>I had wanted to use a for loop, like:</p> <pre><code> headerList = [] for i in range(6) headerList.append(header+i) </code></pre> <p>however, python won't recognize that header+i represents the string header1. Is there any way to simplify this code or get the for loop to work? Thank you so much!</p>
0
2009-07-02T17:18:53Z
1,075,658
<pre><code>header = [str(getattr(input, "headerOut%d" % x)) for x in range(1,7)] </code></pre>
5
2009-07-02T17:24:40Z
[ "python", "string", "loops", "for-loop", "simplify" ]
Simplifying Data with a for loop (Python)
1,075,631
<p>I was trying to simplify the code:</p> <pre><code> header = [] header.append(header1) header.append(header2) header.append(header3) header.append(header4) header.append(header5) header.append(header6) </code></pre> <p>where:</p> <pre><code> header1 = str(input.headerOut1) header2 = str(input.headerOut2) header3 = str(input.headerOut3) header4 = str(input.headerOut4) header5 = str(input.headerOut5) header6 = str(input.headerOut6) </code></pre> <p>I had wanted to use a for loop, like:</p> <pre><code> headerList = [] for i in range(6) headerList.append(header+i) </code></pre> <p>however, python won't recognize that header+i represents the string header1. Is there any way to simplify this code or get the for loop to work? Thank you so much!</p>
0
2009-07-02T17:18:53Z
1,075,659
<p>You should really structure your data as a list or a dictionary, like this:</p> <pre><code>input.headerOut[1] input.headerOut[2] # etc. </code></pre> <p>which would make this a lot easier, and more Pythonic. But you can do what you want using <code>getattr</code>:</p> <pre><code>headerList = [] for i in range(1, 7): header = str(getattr(input, 'headerOut%d' % i)) headerList.append(header) </code></pre>
9
2009-07-02T17:24:58Z
[ "python", "string", "loops", "for-loop", "simplify" ]
Using the AND and NOT Operator in Python
1,075,652
<p>Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if <code>self.a</code>, <code>self.b</code>, and <code>self.c</code> are greater than 0, which would mean that I have Angle, Angle, Angle. </p> <p>Below you will see the code that checks for A and B, however when I use just <code>self.a != 0</code> then it works fine. I believe I'm not using <code>&amp;</code> correctly. Any ideas? Here is how I am calling it: <code>print myTri.detType()</code></p> <pre><code>class Triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f def detType(self): #Triangle Type AAA if self.a != 0 &amp; self.b != 0: return self.a #If self.a &gt; 10: #return AAA #Triangle Type AAS #elif self.a = 0: #return AAS #Triangle Type ASA #Triangle Type SAS #Triangle Type SSS #else: #return unknown </code></pre>
36
2009-07-02T17:22:44Z
1,075,667
<p>Use the keyword "and", not &amp;. &amp; is a bit operator.</p> <p>Be careful with this... just so you know, in Java and C++, the "&amp;" operator is ALSO a bit operator. The correct way to do a boolean comparison in those languages is "&amp;&amp;". Similarly "|" is a bit operator, and "||" is a boolean operator. In python "and", and "or" are used for boolean comparisons.</p>
15
2009-07-02T17:27:17Z
[ "python", "operators" ]
Using the AND and NOT Operator in Python
1,075,652
<p>Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if <code>self.a</code>, <code>self.b</code>, and <code>self.c</code> are greater than 0, which would mean that I have Angle, Angle, Angle. </p> <p>Below you will see the code that checks for A and B, however when I use just <code>self.a != 0</code> then it works fine. I believe I'm not using <code>&amp;</code> correctly. Any ideas? Here is how I am calling it: <code>print myTri.detType()</code></p> <pre><code>class Triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f def detType(self): #Triangle Type AAA if self.a != 0 &amp; self.b != 0: return self.a #If self.a &gt; 10: #return AAA #Triangle Type AAS #elif self.a = 0: #return AAS #Triangle Type ASA #Triangle Type SAS #Triangle Type SSS #else: #return unknown </code></pre>
36
2009-07-02T17:22:44Z
1,075,673
<p>It's called "and" and "or" in Python.</p>
6
2009-07-02T17:27:34Z
[ "python", "operators" ]
Using the AND and NOT Operator in Python
1,075,652
<p>Here is my custom class that I have that represents a triangle. I'm trying to write code that checks to see if <code>self.a</code>, <code>self.b</code>, and <code>self.c</code> are greater than 0, which would mean that I have Angle, Angle, Angle. </p> <p>Below you will see the code that checks for A and B, however when I use just <code>self.a != 0</code> then it works fine. I believe I'm not using <code>&amp;</code> correctly. Any ideas? Here is how I am calling it: <code>print myTri.detType()</code></p> <pre><code>class Triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f def detType(self): #Triangle Type AAA if self.a != 0 &amp; self.b != 0: return self.a #If self.a &gt; 10: #return AAA #Triangle Type AAS #elif self.a = 0: #return AAS #Triangle Type ASA #Triangle Type SAS #Triangle Type SSS #else: #return unknown </code></pre>
36
2009-07-02T17:22:44Z
1,075,700
<p>You should write :</p> <pre><code>if (self.a != 0) and (self.b != 0) : </code></pre> <p>"<code>&amp;</code>" is the bit wise operator and does not suit for boolean operations. The equivalent of "<code>&amp;&amp;</code>" is "and" in Python.</p> <p>A shorter way to check what you want is to use the "in" operator :</p> <pre><code>if 0 not in (self.a, self.b) : </code></pre> <p>You can check if anything is part of a an iterable with "in", it works for :</p> <ul> <li>Tuples. I.E : <code>"foo" in ("foo", 1, c, etc)</code> will return true</li> <li>Lists. I.E : <code>"foo" in ["foo", 1, c, etc]</code> will return true</li> <li>Strings. I.E : <code>"a" in "ago"</code> will return true</li> <li>Dict. I.E : <code>"foo" in {"foo" : "bar"}</code> will return true</li> </ul> <p><strong>As an answer to the comments :</strong></p> <p>Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.</p> <p>For the triangle check, it's easier to read :</p> <pre><code>0 not in (self.a, self.b, self.c) </code></pre> <p>Than </p> <pre><code>(self.a != 0) and (self.b != 0) and (self.c != 0) </code></pre> <p>It's easier to refactor too.</p> <p>Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.</p>
70
2009-07-02T17:34:31Z
[ "python", "operators" ]
Django template can't see CSS files
1,075,753
<p>I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:</p> <pre><code>MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' </code></pre> <p>I've got the CSS files in /mysite/media/css/ and the template code contains:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/css/site_base.css" /&gt;` </code></pre> <p>then, in the url.py file I have:</p> <pre><code># DEVELOPMENT ONLY (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>but the development server serves the plain html (without styles). What am I doing wrong? </p> <p>-- </p> <p>OK - I got it working based on what you folks have said. The answer is:</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media </code></pre> <p>site_base.html:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /&gt; </code></pre> <p>urls.py</p> <pre><code>from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>And voila! It works.</p>
20
2009-07-02T17:45:34Z
1,075,769
<p>in the "development only" block in your urls.py you need to change</p> <pre><code>(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>to...</p> <pre><code>(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), </code></pre>
13
2009-07-02T17:49:13Z
[ "python", "css", "django", "django-templates" ]
Django template can't see CSS files
1,075,753
<p>I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:</p> <pre><code>MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' </code></pre> <p>I've got the CSS files in /mysite/media/css/ and the template code contains:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/css/site_base.css" /&gt;` </code></pre> <p>then, in the url.py file I have:</p> <pre><code># DEVELOPMENT ONLY (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>but the development server serves the plain html (without styles). What am I doing wrong? </p> <p>-- </p> <p>OK - I got it working based on what you folks have said. The answer is:</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media </code></pre> <p>site_base.html:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /&gt; </code></pre> <p>urls.py</p> <pre><code>from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>And voila! It works.</p>
20
2009-07-02T17:45:34Z
1,075,780
<p>I had a similar problem when I was trying to get jQuery to work. My fix was to add an alias to my Apache httpd.conf file that pointed to the folder containing the .js. You could do the same with your CSS folder.</p>
0
2009-07-02T17:50:33Z
[ "python", "css", "django", "django-templates" ]
Django template can't see CSS files
1,075,753
<p>I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:</p> <pre><code>MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' </code></pre> <p>I've got the CSS files in /mysite/media/css/ and the template code contains:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/css/site_base.css" /&gt;` </code></pre> <p>then, in the url.py file I have:</p> <pre><code># DEVELOPMENT ONLY (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>but the development server serves the plain html (without styles). What am I doing wrong? </p> <p>-- </p> <p>OK - I got it working based on what you folks have said. The answer is:</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media </code></pre> <p>site_base.html:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /&gt; </code></pre> <p>urls.py</p> <pre><code>from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>And voila! It works.</p>
20
2009-07-02T17:45:34Z
1,075,782
<p>On the dev server, I like to cheat and put the following in my urls.py</p> <pre><code>if settings.DEBUG: urlpatterns += patterns('', (r'^includes/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/path/to/static/files'}), ) </code></pre> <p>That way anything in the project under the "/includes" folder is server by the dev server. You could just change that to "/media".</p>
2
2009-07-02T17:51:11Z
[ "python", "css", "django", "django-templates" ]
Django template can't see CSS files
1,075,753
<p>I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:</p> <pre><code>MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' </code></pre> <p>I've got the CSS files in /mysite/media/css/ and the template code contains:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/css/site_base.css" /&gt;` </code></pre> <p>then, in the url.py file I have:</p> <pre><code># DEVELOPMENT ONLY (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>but the development server serves the plain html (without styles). What am I doing wrong? </p> <p>-- </p> <p>OK - I got it working based on what you folks have said. The answer is:</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media </code></pre> <p>site_base.html:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /&gt; </code></pre> <p>urls.py</p> <pre><code>from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>And voila! It works.</p>
20
2009-07-02T17:45:34Z
1,075,800
<p><code>ADMIN_MEDIA_PREFIX</code> is set to <code>\media\</code> by default, and is probably 'stealing' the path. Change that setting, or use a different one for non-admin media - eg <code>site_media</code> or <code>assets</code>.</p>
5
2009-07-02T17:55:10Z
[ "python", "css", "django", "django-templates" ]
Django template can't see CSS files
1,075,753
<p>I'm building a django app and I can't get the templates to see the CSS files... My settings.py file looks like:</p> <pre><code>MEDIA_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'media') MEDIA_URL = '/media/' </code></pre> <p>I've got the CSS files in /mysite/media/css/ and the template code contains:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/media/css/site_base.css" /&gt;` </code></pre> <p>then, in the url.py file I have:</p> <pre><code># DEVELOPMENT ONLY (r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': '/media'}), </code></pre> <p>but the development server serves the plain html (without styles). What am I doing wrong? </p> <p>-- </p> <p>OK - I got it working based on what you folks have said. The answer is:</p> <p>settings.py:</p> <pre><code>MEDIA_ROOT = 'd://web//mysite//media//' #absolute path to media MEDIA_URL = '/mymedia/' #because admin already using /media </code></pre> <p>site_base.html:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="/mymedia/css/site_base.css" /&gt; </code></pre> <p>urls.py</p> <pre><code>from mysite import settings if settings.DEBUG: urlpatterns += patterns('', (r'^mymedia/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>And voila! It works.</p>
20
2009-07-02T17:45:34Z
3,375,105
<p>It also worked for me, thanks guys !!</p> <p>settings.py</p> <pre><code>MEDIA_ROOT = '/home/pi/ewspaces/ws-classic/xima/media' MEDIA_URL = '/statics/' </code></pre> <p>urls.py</p> <pre><code>if settings.DEBUG: urlpatterns += patterns('', (r'^statics/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), ) </code></pre> <p>inside templates:</p> <pre><code>&lt;link type="text/css" href="/statics/css/base/jquery.ui.all.css" rel="stylesheet" /&gt; </code></pre>
1
2010-07-30T20:21:48Z
[ "python", "css", "django", "django-templates" ]
Working with foreign symbols in python
1,075,866
<p>I'm parsing a JSON feed in Python and it contains this character, causing it not to validate. </p> <p>Is there a way to handle these symbols? Can they be converted or is they're a tidy way to remove them? </p> <p>I don't even know what this symbol is called or what causes them, otherwise I would research it myself.</p> <p>EDIT: Stackover Flow is stripping the character so here: <a href="http://files.getdropbox.com/u/194177/symbol.jpg" rel="nofollow">http://files.getdropbox.com/u/194177/symbol.jpg</a></p> <p>It's that [?] symbol in "Classic 80s"</p>
0
2009-07-02T18:10:35Z
1,075,949
<p>That probably means the text you have is in some sort of encoding, and you need to figure out what encoding, and convert it to Unicode with a thetext.decode('encoding') call.</p> <p>I not sure, but it could possibly be the [?] character, meaning that the display you have there also doesn't know how to display it. That would probably mean that the data you have is incorrect, and that there is a character in there that doesn't exist in the encoding that you are supposed to use. To handle that you call the decode like this: thetext.decode('encoding', 'ignore'). There are other options than ignore, like "replace", "xmlcharrefreplace" and more.</p>
1
2009-07-02T18:26:31Z
[ "python", "parsing", "utf-8", "ascii", "symbols" ]
Working with foreign symbols in python
1,075,866
<p>I'm parsing a JSON feed in Python and it contains this character, causing it not to validate. </p> <p>Is there a way to handle these symbols? Can they be converted or is they're a tidy way to remove them? </p> <p>I don't even know what this symbol is called or what causes them, otherwise I would research it myself.</p> <p>EDIT: Stackover Flow is stripping the character so here: <a href="http://files.getdropbox.com/u/194177/symbol.jpg" rel="nofollow">http://files.getdropbox.com/u/194177/symbol.jpg</a></p> <p>It's that [?] symbol in "Classic 80s"</p>
0
2009-07-02T18:10:35Z
1,396,803
<p>JSON must be encoded in one of UTF-8, UTF-16, or UTF-32. If a JSON file contains bytes which are illegal in its current encoding, it is garbage.</p> <p>If you don't know which encoding it's using, you can try parsing using my <a href="http://pypi.python.org/pypi/jsonlib" rel="nofollow">jsonlib</a> library, which includes an encoding-detector. JSON parsed using <code>jsonlib</code> will be provided to the programmer as Unicode strings, so you don't have to worry about encoding at all.</p>
0
2009-09-08T23:06:49Z
[ "python", "parsing", "utf-8", "ascii", "symbols" ]
I want to parse a PAC file to get some Proxy information... just not in Explorer
1,075,899
<p>Follow on from <a href="http://stackoverflow.com/questions/1068212/programitcally-detect-system-proxy-settings-on-windows-xp-with-python/1068303#1068303">this question</a>:</p> <p>I am working on a Python 2.4 app which will run on Windows XP. It needs to be able to download various resources from HTTP and it's got to work in all of our office locations which use "PAC" files to automatically select http proxies.</p> <p>Thanks to somebody who responded to my previous question I managed to find a technique to execute Javascript from within Python, it's really easy:</p> <pre><code>js = win32com.client.Dispatch('MSScriptControl.ScriptControl') js.Language = 'JavaScript' js.AddCode('function foo(a,b) {return a;}' ) result = js.Run( "foo", "hello" ) </code></pre> <p>But here comes the problem:</p> <p>The PAC file references a number of functions such as <strong>shExpMatch</strong> and <strong>isPlainHostName</strong> - these are presumably provided for free by Microsoft Internet Explorer. If I simply run the PAC file in Widnows Scripting using the recipe above it will fail because these functions are not missing.</p> <p>So what I need is a way to set up the environment exactly the same way that IE does. The obvious way is to somehow import the functions in the same way that IE does.</p> <p>I found that Firefox contains a single JS file which includes these functions, I suppose I could try to run Firefox's JS on Microsoft's scripting-host, but that sounds like a risky idea. What I really want is to make the javascript environment 100% Microsoft standard without anything that can make my life harder.</p> <p>Any suggestions?</p> <p>PS. You can see an <a href="http://en.wikipedia.org/wiki/Proxy%5Fauto-config" rel="nofollow">example of a PAC file on Wikipedia</a>. Unfortunately I cannot publish ours... that would violate company security. </p>
0
2009-07-02T18:16:35Z
1,076,135
<p>Are you able to download the PAC file from the remote host? I am asking because usually urllib in python uses static information for the proxy, retrieved from the registry.<br /> However, if you are able to get that file, then I think you could be able to get also another file - and then your idea of using FF version could kick in.</p>
1
2009-07-02T19:05:29Z
[ "javascript", "python", "windows", "internet-explorer" ]
.class file from jython with pydev
1,075,905
<p>My first attempt at jython is a java/jython project I'm writing in eclipse with pydev.</p> <p>I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I set each folder as a buildpath for the project. I guess I'm letting you know all this so hopefully you can tell me wether or not I set the project up correctly.</p> <p>But the real question is: <strong>how do I get my jython code made into a class file so the java code can use it?</strong> The preferred method would be that eclipse/pydev would do this for me automatically, but I can't figure it out. Something mentioned in the jython users guide implies that it's possible but I can't find info on it anywhere.</p> <p>EDIT: I did find some information <a href="http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1" rel="nofollow">here</a> and <a href="http://www.jython.org/archive/22/jythonc.html#what-is-jythonc" rel="nofollow">here</a>, but things are not going too smooth.</p> <p>I've been following the guide in the second link pretty closely but I can't figure out how to get jythonc to make a constructor for my python class.</p>
3
2009-07-02T18:17:59Z
1,563,692
<p>Following the "Accessing Jython from Java Without Using jythonc" tutorial it became possible to use the jython modules inside java code. The only tricky point is that the *.py modules do not get compiled to *.class files. So it turns out to be exotic scripting inside java. The performance may of course degrade vs jythonc'ed py modules, but as I got from the jython community pages they are not going to support jythonc (and in fact have already dropped it in jython2.5.1).</p> <p>So if you decide to follow non-jythonc approach, the above tutorial is perfect. I had to modify the JythonFactory.java code a bit:</p> <pre><code>String objectDef = "=" + javaClassName + "(your_constructor_params here)"; try { Class JavaInterface = Class.forName(interfaceName); System.out.println("JavaInterface=" + JavaInterface); javaInt = interpreter.get("instance name of a jython class from jython main function").__tojava__(JavaInterface); } catch (ClassNotFoundException ex) { ex.printStackTrace(); // Add logging here } </code></pre>
0
2009-10-14T00:29:15Z
[ "java", "python", "eclipse", "jython", "pydev" ]
.class file from jython with pydev
1,075,905
<p>My first attempt at jython is a java/jython project I'm writing in eclipse with pydev.</p> <p>I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And I set each folder as a buildpath for the project. I guess I'm letting you know all this so hopefully you can tell me wether or not I set the project up correctly.</p> <p>But the real question is: <strong>how do I get my jython code made into a class file so the java code can use it?</strong> The preferred method would be that eclipse/pydev would do this for me automatically, but I can't figure it out. Something mentioned in the jython users guide implies that it's possible but I can't find info on it anywhere.</p> <p>EDIT: I did find some information <a href="http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1" rel="nofollow">here</a> and <a href="http://www.jython.org/archive/22/jythonc.html#what-is-jythonc" rel="nofollow">here</a>, but things are not going too smooth.</p> <p>I've been following the guide in the second link pretty closely but I can't figure out how to get jythonc to make a constructor for my python class.</p>
3
2009-07-02T18:17:59Z
3,206,809
<p>Jythonc doesn't exist anymore, it has been forked off to another project called <a href="http://github.com/groves/clamp/">Clamp</a>, but with that said...</p> <blockquote> <p>...you can pre-compile your python scripts to .class files using:</p> <p>jython [jython home]/Lib/compileall.py [the directory where you keep your python code]</p> </blockquote> <p>Source - <a href="http://wiki.python.org/jython/JythonMonthly/Newsletters/March2009"><em>Jython Newsletter, March 2009</em></a></p> <p>When I fed it a folder with Python <strong>2.7</strong> code (knowing it would fail in Jython <strong>2.5</strong>) it did output a .class file, even though it doesn't function. Try that with your Jython scripts. If it works, please let us know, because I'll be where you are soon enough.</p> <p>Once you're that far, it isn't hard to convert your command line statement to an External Tool in PyDev that can be called as needed.</p>
5
2010-07-08T18:35:00Z
[ "java", "python", "eclipse", "jython", "pydev" ]
Extending Python with C/C++
1,076,300
<p>Can anyone please give me tips on the tools or sofware to use to extend Python with C/C++? Thanks.</p>
4
2009-07-02T19:42:30Z
1,076,318
<p>We use SWIG to wrap our C/C++ libraries for use in Python. It works quite well.</p> <p><a href="http://www.swig.org/">http://www.swig.org/</a></p>
8
2009-07-02T19:45:43Z
[ "c++", "python", "c" ]