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 |
|---|---|---|---|---|---|---|---|---|---|
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 757,554
|
<p>I tried</p>
<pre><code>sed '/regexp/a\\n'
</code></pre>
<p>but it inserted two newlines. If that does not bother you, take it.</p>
<blockquote>
<p>echo -e "a\nb\nc" | sed '/^a$/a\n'<br />
a </p>
<p>b<br />
c </p>
</blockquote>
<p><strong>Edit:</strong>
Now that you state that you need to insert two lines above the matching regexp the suggested regex won't work.</p>
<p>I am not even sure if it would work at all with sed, as you need to remember past lines. Sounds like a job for a higher level language like python or perl :-)</p>
| 0
|
2009-04-16T18:55:30Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 757,943
|
<p>Here's an approach that works for Python.</p>
<pre><code>import sys
def address_change( aFile ):
address= []
for line in aFile:
if regex.match( line ):
# end of the address
print address[0]
print
print address[1:]
print line
address= []
else:
address.append( line )
address_change( sys.stdin )
</code></pre>
<p>This allows you to reformat a complete address to your heart's content. You can expand this to create define an <code>Address</code> class if your formatting is complex.</p>
| 1
|
2009-04-16T20:36:18Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 757,988
|
<pre><code>perl -ne 'END{print @x} push@x,$_; if(@x>2){splice @x,1,0,"\n" if /[[:alpha:]]\d[[:alpha:]]\s?\d[[:alpha:]]\d/;print splice @x,0,-2}'
</code></pre>
<p>If I cat your file into this, I get what you want... it's ugly, but you wanted shell (i.e., one-liner) :-) If I were to do this in full perl, I'd be able to clean it up a lot to make it approach readable. :-)</p>
| 2
|
2009-04-16T20:47:56Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 758,010
|
<p>More readable Perl, and handles multiple files sanely.</p>
<pre><code>#!/usr/bin/env perl
use constant LINES => 2;
my @buffer = ();
while (<>) {
/pattern/ and unshift @buffer, "\n";
push @buffer, $_;
print splice @buffer, 0, -LINES;
}
continue {
if (eof(ARGV)) {
print @buffer;
@buffer = ();
}
}
</code></pre>
| 7
|
2009-04-16T20:55:45Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 758,101
|
<p>Something a bit like your original approach in sed:</p>
<pre><code>sed '/regexp/i\
$H
x'
</code></pre>
<p>The basic idea is to print everything delayed by one line (<strong>x</strong>change the hold and pattern spaces - printing is implicit). That needs to be done because until we check whether the next line matches the regexp we don't know whether to <strong>i</strong>nsert a newline or not. </p>
<p>(The $H there is just a trick to make the last line print. It appends the last line into the hold buffer so that the final implicit print command outputs it too.)</p>
| 5
|
2009-04-16T21:18:18Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
Shell: insert a blank/new line two lines above pattern
| 757,532
|
<p>To add a blank line above every line that matches your regexp, you can use:</p>
<pre><code>sed '/regexp/{x;p;x;}'
</code></pre>
<p>But I want to add a blank line, not <em>one</em> line above, but <em>two</em> lines above the line which matches my regexp.</p>
<p>The pattern I'll be matching is a postal code in the address line.</p>
<p>Here is a snippet of the text's formatting:</p>
<blockquote>
<p>random info (belongs to previous business)<br>
business name<br>
business address </p>
</blockquote>
<p>For example:</p>
<blockquote>
<p>Languages Spoken: English<br>
Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
<p>I'd like to add a new line above the business name:</p>
<blockquote>
<p>Languages Spoken: English</p>
<p>Arnold's Cove, Nfld (sub To Clarenville)<br>
Nile Road, Arnolds Cove, NL, A0B1N0</p>
</blockquote>
| 6
|
2009-04-16T18:48:13Z
| 759,945
|
<p>Simple:</p>
<pre><code>sed '1{x;d};$H;/regexp/{x;s/^/\n/;b};x'
</code></pre>
<p>Describe it</p>
<pre><code>#!/bin/sed
# trick is juggling previous and current line in hold and pattern space
1 { # at firs line
x # place first line to hold space
d # skip to end and avoid printing
}
$H # append last line to hold space to force print
/regexp/ { # regexp found (in current line - pattern space)
x # swap previous and current line between hold and pattern space
s/^/\n/ # prepend line break before previous line
b # jump at end of script which cause print previous line
}
x # if regexp does not match just swap previous and current line to print previous one
</code></pre>
<p><strong>Edit</strong>: Little bit simpler version.</p>
<pre><code>sed '$H;/regexp/{x;s/^/\n/;b};x;1d'
</code></pre>
| 3
|
2009-04-17T10:41:04Z
|
[
"python",
"perl",
"text",
"sed",
"awk"
] |
django-paypal setup
| 757,809
|
<p>Has anyone setup django-paypal? Here is the link to it <a href="https://github.com/johnboxall/django-paypal">here</a>? </p>
<p>I have "myproject" setup, and my folder sturecture looks like this:</p>
<p>myproject > paypal > (stdandard and pro folders)</p>
<p>to my settins.py file I added</p>
<pre><code>INSTALLED_APPS = (
'myproject.paypal.standard',
'myproject.paypal.pro',
)
</code></pre>
<p>in my url's file for my account app I added:</p>
<pre><code>urlpatterns += patterns('myproject.account.views',
(r'^payment-url/$', 'buy_my_item'),
)
</code></pre>
<p>and in my account view I added:</p>
<pre><code>from myproject.paypal.pro.views import PayPalPro
from myproject.paypal.pro.forms import PaymentForm, ConfirmForm
def buy_my_item(request):
item = {'amt':"10.00", # amount to charge for item
'inv':"1111", # unique tracking variable paypal
'custom':"2222", # custom tracking variable for you
'cancelurl':"http://127.0.0.1:8000/", # Express checkout cancel url
'returnurl':"http://127.0.0.1:8000/"} # Express checkout return url
kw = {'item':'item', # what you're selling
'payment_template': 'pro/payment.html', # template to use for payment form
'confirm_template': ConfirmForm, # form class to use for Express checkout confirmation
'payment_form_cls': PaymentForm, # form class to use for payment
'success_url': '/success', # where to redirect after successful payment
}
ppp = PayPalPro(**kw)
return ppp(request)
</code></pre>
<p>--- EDIT ---------
Then, I added the pro and standard template folders to my projects template folder.</p>
<p>When I go to <a href="http://127.0.0.1:8000/account/payment-url/">http://127.0.0.1:8000/account/payment-url/</a> and submit the form...</p>
<p>I get a ValueError : "dictionary update sequence element #0 has length 1; 2 is required"</p>
<p>Traceback:</p>
<pre><code>File "...\accounts\views.py" in buy_my_item
655. return ppp(request)
File "...\paypal\pro\views.py" in __call__
115. return self.validate_payment_form()
File "...\paypal\pro\views.py" in validate_payment_form
133. success = form.process(self.request, self.item)
File "...\paypal\pro\forms.py" in process
</code></pre>
<ol>
<li>params.update(item)</li>
</ol>
| 14
|
2009-04-16T19:57:51Z
| 757,820
|
<p>In your code...</p>
<pre><code> 'payment_form_cls': 'payment_form_cls', # form class to use for payment
</code></pre>
<p>This must be a Form object that's used for validation.</p>
<pre><code> 'payment_form_cls': MyValidationForm, # form class to use for payment
</code></pre>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p><a href="http://github.com/johnboxall/django-paypal/tree/master">http://github.com/johnboxall/django-paypal/tree/master</a></p>
<p>Your request is supposed to include a notify-url, return-url and cancel-return. All three url's YOU provide to Paypal.</p>
<p>Paypal will send messages to these URL's.</p>
<p>Since Paypal will send messages to these URL's, YOU must put them in your urls.py. You must write view functions for these three urls'. These urls will have your paypal responses sent to them.</p>
| 6
|
2009-04-16T20:01:16Z
|
[
"python",
"django",
"paypal"
] |
django-paypal setup
| 757,809
|
<p>Has anyone setup django-paypal? Here is the link to it <a href="https://github.com/johnboxall/django-paypal">here</a>? </p>
<p>I have "myproject" setup, and my folder sturecture looks like this:</p>
<p>myproject > paypal > (stdandard and pro folders)</p>
<p>to my settins.py file I added</p>
<pre><code>INSTALLED_APPS = (
'myproject.paypal.standard',
'myproject.paypal.pro',
)
</code></pre>
<p>in my url's file for my account app I added:</p>
<pre><code>urlpatterns += patterns('myproject.account.views',
(r'^payment-url/$', 'buy_my_item'),
)
</code></pre>
<p>and in my account view I added:</p>
<pre><code>from myproject.paypal.pro.views import PayPalPro
from myproject.paypal.pro.forms import PaymentForm, ConfirmForm
def buy_my_item(request):
item = {'amt':"10.00", # amount to charge for item
'inv':"1111", # unique tracking variable paypal
'custom':"2222", # custom tracking variable for you
'cancelurl':"http://127.0.0.1:8000/", # Express checkout cancel url
'returnurl':"http://127.0.0.1:8000/"} # Express checkout return url
kw = {'item':'item', # what you're selling
'payment_template': 'pro/payment.html', # template to use for payment form
'confirm_template': ConfirmForm, # form class to use for Express checkout confirmation
'payment_form_cls': PaymentForm, # form class to use for payment
'success_url': '/success', # where to redirect after successful payment
}
ppp = PayPalPro(**kw)
return ppp(request)
</code></pre>
<p>--- EDIT ---------
Then, I added the pro and standard template folders to my projects template folder.</p>
<p>When I go to <a href="http://127.0.0.1:8000/account/payment-url/">http://127.0.0.1:8000/account/payment-url/</a> and submit the form...</p>
<p>I get a ValueError : "dictionary update sequence element #0 has length 1; 2 is required"</p>
<p>Traceback:</p>
<pre><code>File "...\accounts\views.py" in buy_my_item
655. return ppp(request)
File "...\paypal\pro\views.py" in __call__
115. return self.validate_payment_form()
File "...\paypal\pro\views.py" in validate_payment_form
133. success = form.process(self.request, self.item)
File "...\paypal\pro\forms.py" in process
</code></pre>
<ol>
<li>params.update(item)</li>
</ol>
| 14
|
2009-04-16T19:57:51Z
| 760,105
|
<p><a href="http://uswaretech.com/blog/2008/11/using-paypal-with-django/" rel="nofollow">PayPal django Integration</a> post should help you.</p>
| 1
|
2009-04-17T11:49:19Z
|
[
"python",
"django",
"paypal"
] |
Whats the easiest and fastest way to measure HD performance using Python?
| 757,816
|
<p>I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value.</p>
<p>My actual goal is to write a small utility which will adjust the postgres settings to the best configuration for the given hardware.</p>
<p>My naive approach would be to write some files and measure the time how long it would take. I would try it for several block sizes, and then I would try to access some random positions within a large file. Any other ideas?</p>
| 1
|
2009-04-16T20:00:35Z
| 757,826
|
<p>Start here: <a href="http://www.acnc.com/benchmarks.html" rel="nofollow">http://www.acnc.com/benchmarks.html</a></p>
<p>Get the source for one you like write something like it in Python.</p>
| 1
|
2009-04-16T20:03:19Z
|
[
"python",
"performance",
"postgresql"
] |
Whats the easiest and fastest way to measure HD performance using Python?
| 757,816
|
<p>I need to measure the performance of a hard disk using python. What is the best/fastest/shortest/easiest approach to do it? It doesn't have to be overly accurate, just a ballpark value.</p>
<p>My actual goal is to write a small utility which will adjust the postgres settings to the best configuration for the given hardware.</p>
<p>My naive approach would be to write some files and measure the time how long it would take. I would try it for several block sizes, and then I would try to access some random positions within a large file. Any other ideas?</p>
| 1
|
2009-04-16T20:00:35Z
| 758,057
|
<p>I would think your best bet would be using an external tool, Bonnie++ for example, and parse the program output. Even if you're not that concerned with precision there's no reason to reinvent the wheel. Why rewrite what's already there?</p>
| 2
|
2009-04-16T21:07:54Z
|
[
"python",
"performance",
"postgresql"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,973
|
<p>I think your conditional is looking for "\fad" or "fade", I think you need to move a \ outside the grouping if you want to look for "\fad" or "\fade".</p>
| 1
|
2009-04-16T20:43:41Z
|
[
"python",
"regex"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,980
|
<p>Try this:</p>
<pre><code>r"\{\\fade?\(\d{1,4},\d{1,4}\)\}"
</code></pre>
| 2
|
2009-04-16T20:45:28Z
|
[
"python",
"regex"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,981
|
<p>The bracket is part of the or branch starting with fade, so it's looking for either "{fad" or "fade(...". You need to group the fad|fade part together. Try:</p>
<pre><code>r"\{\\(?:fad|fade)\(\d{1,4},\d{1,4}\)\}"
</code></pre>
<p><strong>[Edit]</strong>
The reason you do get into the if block is because the regex <strong>is</strong> matching, but only because it detects it starts with "{\fad". However, that part of the match contains no groups. You need to match with the part that defines the groups if you want to capture them.</p>
| 4
|
2009-04-16T20:45:48Z
|
[
"python",
"regex"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,982
|
<p>Put extra parens around the choice: <code>re.search(r"{(?:\\fad|fade)\((\d{1,4}),(\d{1,4})\)}", text).groups()</code></p>
<p>Also, escaping <code>{}</code> braces isn't necessary, it just needlessly clutters your regexp.</p>
| 6
|
2009-04-16T20:45:57Z
|
[
"python",
"regex"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,985
|
<p>I don't know the python dialect of regular expressions, but wouldn't you need to 'group' the "fad|fade" somehow to make sure it isn't trying to find "fad OR fade(etc..."?</p>
| 0
|
2009-04-16T20:47:22Z
|
[
"python",
"regex"
] |
Why doesn't the regex match when I add groups?
| 757,949
|
<p>I have this regex code in python :</p>
<pre><code>if re.search(r"\{\\fad|fade\(\d{1,4},\d{1,4}\)\}", text):
print(re.search(r"\{\\fad|fade\((\d{1,4}),(\d{1,4})\)\}", text).groups())
</code></pre>
<p><code>text</code> is <code>{\fad(200,200)}Ãpisode 101 : {\i1}The Ghost{\i0}\Nv. 1.03</code> and read from a file (don't know if that helps).</p>
<p>This returns the following:</p>
<pre><code>(None, None)
</code></pre>
<p>When I change the regex in the print to <code>r"\{\\fad\((\d{1,4}),(\d{1,4})\)\}"</code>, it returns the correct values:</p>
<pre><code>(200, 200)
</code></pre>
<p>Can anyone see why the conditional <code>fad|fade</code> matches the regex in the <code>re.search</code> but doesn't return the correct values of the groups in the print?</p>
<p>Thanks.</p>
| 3
|
2009-04-16T20:38:14Z
| 757,989
|
<p>Try this instead:</p>
<pre><code>r"\{\\fade?\((\d{1,4}),(\d{1,4})\)\}"
</code></pre>
<p>The <code>e?</code> is an optional <code>e</code>.
The way you have it now matches <code>{\fad</code> or <code>fade(0000,0000)}</code></p>
| 1
|
2009-04-16T20:47:57Z
|
[
"python",
"regex"
] |
Problem with Python modules
| 758,187
|
<p>I'm uploading my first Django app to my Dreamhost server. My app uses <a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a> package and since I can't install it in the default location ( /usr/lib/python2.3/site-packages/xlwt ), I installed it on another location by:</p>
<pre><code>python setup.py install --home=$HOME
</code></pre>
<p>Then xlwt is installed here:</p>
<pre><code>/home/myuser/lib/python/xlwt/
</code></pre>
<p>After that, I add this folder to de env var PYTHONPATH</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/home/myuser/lib/python
</code></pre>
<p>... And in a python promt I can do this (without problems)</p>
<pre><code>import xlwt
</code></pre>
<p>... But if I do the same thing in my app code, I have the follow error:</p>
<pre><code>Could not import ISI.restaurante.views. Error was: No module named xlwt
</code></pre>
<p>[where ISI.restaurante.views is my code where I do the import]</p>
<p>Could u help me? Thanks!</p>
| 3
|
2009-04-16T21:48:49Z
| 758,195
|
<p>PYTHONPATH may only be set when you run from the shell, you can set path programatically from python using</p>
<pre><code>import sys
sys.path.append('/home/myuser/lib/python')
</code></pre>
| 5
|
2009-04-16T21:52:40Z
|
[
"python",
"django",
"dreamhost"
] |
Make function definition in a python file order independent
| 758,188
|
<p>I use Python CGI. I cannot call a function before it is defined.</p>
<p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p>
<p>Is there such a trick in Python as well?</p>
<p>example:</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
</code></pre>
<p>David is right, my example is wrong.
What about:</p>
<pre><code><start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
</code></pre>
<p>Can I "forward declare" the functions at the top of the script? </p>
| 22
|
2009-04-16T21:48:53Z
| 758,197
|
<p>All functions must be defined before any are used. </p>
<p>However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.</p>
<p>You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before all executable code.</p>
<p>Are you having a problem? If so, please post the code that doesn't work.</p>
<p><hr /></p>
<p>In your example, <code>print_something()</code> is out of place. </p>
<p>The rule: <strong>All functions must be defined before any code that does real work</strong></p>
<p>Therefore, put all the statements that do work <em>last</em>. </p>
| 31
|
2009-04-16T21:53:03Z
|
[
"python"
] |
Make function definition in a python file order independent
| 758,188
|
<p>I use Python CGI. I cannot call a function before it is defined.</p>
<p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p>
<p>Is there such a trick in Python as well?</p>
<p>example:</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
</code></pre>
<p>David is right, my example is wrong.
What about:</p>
<pre><code><start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
</code></pre>
<p>Can I "forward declare" the functions at the top of the script? </p>
| 22
|
2009-04-16T21:48:53Z
| 758,315
|
<p>Assuming you have some code snippet that calls your function main after it's been defined, then your example works as written. Because of how Python is interpreted, any functions that are called by the body of <code>do_something</code> do not need to be defined when the do_something function is defined.</p>
<p>The steps that Python will take while executing your code are as follows.</p>
<ol>
<li>Define the function do_something.</li>
<li>Define the function helper_function.</li>
<li>Define the function main.</li>
<li>(Given my assumption above) Call main.</li>
<li>From main, call do_something.</li>
<li>From <code>do_something</code>, call helper_function.</li>
</ol>
<p>The only time that Python cares that <code>helper_function</code> exists is when it gets to step six. You should be able to verify that Python makes it all the way to step six before raising an error when it tries to find helper_function so that it can call it.</p>
| 2
|
2009-04-16T22:35:51Z
|
[
"python"
] |
Make function definition in a python file order independent
| 758,188
|
<p>I use Python CGI. I cannot call a function before it is defined.</p>
<p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p>
<p>Is there such a trick in Python as well?</p>
<p>example:</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
</code></pre>
<p>David is right, my example is wrong.
What about:</p>
<pre><code><start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
</code></pre>
<p>Can I "forward declare" the functions at the top of the script? </p>
| 22
|
2009-04-16T21:48:53Z
| 758,590
|
<p>I've never come across a case where "forward-function-definition" is necessary.. Can you not simply move <code>print_something()</code> to inside your main function..?</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
def helper_function(hf_parameter):
....
def main()
print_something()
....
main()
</code></pre>
<p>Python doesn't care that helper_function() is defined after it's use on line 3 (in the <code>do_something</code> function)</p>
<p>I recommend using something like <a href="http://winpdb.org/" rel="nofollow">WinPDB</a> and stepping through your code. It shows nicely how Python's parser/executor(?) works</p>
| 2
|
2009-04-17T00:29:44Z
|
[
"python"
] |
Make function definition in a python file order independent
| 758,188
|
<p>I use Python CGI. I cannot call a function before it is defined.</p>
<p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p>
<p>Is there such a trick in Python as well?</p>
<p>example:</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
</code></pre>
<p>David is right, my example is wrong.
What about:</p>
<pre><code><start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
</code></pre>
<p>Can I "forward declare" the functions at the top of the script? </p>
| 22
|
2009-04-16T21:48:53Z
| 11,898,838
|
<p>An even better illustration of your point would be:</p>
<pre><code>def main():
print_something()
....
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
def helper_function(hf_parameter):
....
main()
</code></pre>
<p>In other words, you can keep your definition of <code>main()</code> at the top, for editing convenience -- avoiding frequent scrolling, if most of the time is spent editing main.</p>
| 9
|
2012-08-10T09:26:29Z
|
[
"python"
] |
Make function definition in a python file order independent
| 758,188
|
<p>I use Python CGI. I cannot call a function before it is defined.</p>
<p>In Oracle PL/SQL there was this trick of "forward declaration"; naming all the functions on top so the order of defining didn't matter no more.</p>
<p>Is there such a trick in Python as well?</p>
<p>example:</p>
<pre><code>def do_something(ds_parameter):
helper_function(ds_parameter)
....
def helper_function(hf_parameter):
....
def main():
do_something(my_value)
main()
</code></pre>
<p>David is right, my example is wrong.
What about:</p>
<pre><code><start of cgi-script>
def do_something(ds_parameter):
helper_function(ds_parameter)
....
def print_something():
do_something(my_value)
print_something()
def helper_function(hf_parameter):
....
def main()
....
main()
</code></pre>
<p>Can I "forward declare" the functions at the top of the script? </p>
| 22
|
2009-04-16T21:48:53Z
| 32,847,180
|
<pre><code>def funB(d,c):
return funA(d,c)
print funB(2,3)
def funA(x,y):
return x+y
</code></pre>
<p>The above code will return Error. But, the following code is fine ... </p>
<pre><code> def funB(d,c):
return funA(d,c)
def funA(x,y):
return x+y
print funB(2,3)
</code></pre>
<p>So, even though you must definitely define the function before any real work is done, it is possible to get away if you don't use the function explicitly. I think this is somewhat similar to prototyping in other languages.. . </p>
| 0
|
2015-09-29T14:51:31Z
|
[
"python"
] |
how to use pycurl if requested data is sometimes gzipped, sometimes not?
| 758,243
|
<p>I'm doing this to fetch some data:</p>
<pre><code>c = pycurl.Curl()
c.setopt(pycurl.ENCODING, 'gzip')
c.setopt(pycurl.URL, url)
c.setopt(pycurl.TIMEOUT, 10)
c.setopt(pycurl.FOLLOWLOCATION, True)
xml = StringIO()
c.setopt(pycurl.WRITEFUNCTION, xml.write )
c.perform()
c.close()
</code></pre>
<p>My urls are typically of this sort:</p>
<pre><code>http://host/path/to/resource-foo.xml
</code></pre>
<p>Usually I get back 302 pointing to:</p>
<pre><code>http://archive-host/path/to/resource-foo.xml.gz
</code></pre>
<p>Given that I have set FOLLOWLOCATION, and ENCODING gzip, everything works great.</p>
<p>The problem is, sometimes I have a URL which does not result in a redirect to a gzipped resource. When this happens, <code>c.perform()</code> throws this error:</p>
<pre><code>pycurl.error: (61, 'Error while processing content unencoding: invalid block type')
</code></pre>
<p>Which suggests to me that pycurl is trying to gunzip a resource that is not gzipped.</p>
<p>Is there some way I can instruct pycurl to figure out the response encoding, and gunzip or not as appropriate? I have played around with using different values for <code>ENCODING</code>, but so far no beans.</p>
<p>The pycurl docs seems to be a little lacking. :/</p>
<p>thx!</p>
| 2
|
2009-04-16T22:11:52Z
| 758,271
|
<p>If worst comes to worst, you could omit the ENCODING 'gzip', set HTTPHEADER to {'Accept-Encoding' : 'gzip'}, <a href="http://stackoverflow.com/questions/472179/how-to-read-the-header-with-pycurl">check the response headers</a> for "Content-Encoding: gzip" and if it's present, gunzip the response yourself.</p>
| 4
|
2009-04-16T22:20:21Z
|
[
"python",
"http",
"gzip",
"libcurl",
"pycurl"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 758,352
|
<p>It's pretty straightforward once you remember that there's no way to actually minimize to the <a href="http://blogs.msdn.com/oldnewthing/archive/2003/09/10/54831.aspx">system tray</a>. </p>
<p>Instead, you fake it by doing this:</p>
<ol>
<li>Catch the minimize event on your window</li>
<li>In the minimize event handler, create and show a QSystemTrayIcon</li>
<li>Also in the minimize event handler, call hide() or setVisible(false) on your window</li>
<li>Catch a click/double-click/menu item on your system tray icon</li>
<li>In your system tray icon event handler, call show() or setVisible(true) on your window, and optionally hide your tray icon.</li>
</ol>
| 26
|
2009-04-16T22:53:20Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 758,422
|
<p>Code helps, so here's something I wrote for an application, except for the closeEvent instead of the minimize event.</p>
<p>Notes:</p>
<p>"closeEvent(event)" is an overridden Qt event, so it must be put in the class that implements the window you want to hide.</p>
<p>"okayToClose()" is a function you might consider implementing (or a boolean flag you might want to store) since sometimes you actually want to exit the application instead of minimizing to systray.</p>
<p>There is also an example of how to show() your window again.</p>
<pre><code>def __init__(self):
traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self.trayIcon, QtCore.SIGNAL(traySignal), self.__icon_activated)
def closeEvent(self, event):
if self.okayToClose():
#user asked for exit
self.trayIcon.hide()
event.accept()
else:
#"minimize"
self.hide()
self.trayIcon.show() #thanks @mojo
event.ignore()
def __icon_activated(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
self.show()
</code></pre>
| 10
|
2009-04-16T23:17:59Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 1,737,709
|
<p>Just to add to the example by Chris:</p>
<p>It is crucial that you use the Qt notation when declaring the signal, ie</p>
<p><strong>correct</strong>:</p>
<pre><code>self.connect(self.icon, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.iconClicked)
</code></pre>
<p>and not the PyQt one</p>
<p><strong>incorrect</strong> and won't work:</p>
<pre><code>self.connect(self.icon, SIGNAL("activated(QSystemTrayIcon.ActivationReason)"), self.iconClicked)
</code></pre>
<p>Note the <code>::</code> in the signal string. This took me about three hours to figure out.</p>
| 6
|
2009-11-15T14:49:31Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 4,676,943
|
<p>Here's working code..Thanks <strong>Matze</strong> for <strong>Crucial</strong>, the SIGNAL took me more hours of curiosity.. but doing other things. so ta for a #! moment :-)</p>
<pre><code>def create_sys_tray(self):
self.sysTray = QtGui.QSystemTrayIcon(self)
self.sysTray.setIcon( QtGui.QIcon('../images/corp/blip_32.png') )
self.sysTray.setVisible(True)
self.connect(self.sysTray, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.on_sys_tray_activated)
self.sysTrayMenu = QtGui.QMenu(self)
act = self.sysTrayMenu.addAction("FOO")
def on_sys_tray_activated(self, reason):
print "reason-=" , reason
</code></pre>
| 4
|
2011-01-13T05:01:05Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 8,027,187
|
<p>This is the code and it does help i believe in show me the code </p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout, QSystemTrayIcon
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.icon = QSystemTrayIcon()
r = self.icon.isSystemTrayAvailable()
print r
self.icon.setIcon(QtGui.QIcon('/home/vzades/Desktop/web.png'))
self.icon.show()
# self.icon.setVisible(True)
self.setGeometry(300, 300, 250, 150)
self.setWindowIcon(QtGui.QIcon('/home/vzades/Desktop/web.png'))
self.setWindowTitle('Message box')
self.show()
self.icon.activated.connect(self.activate)
self.show()
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message', "Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
self.icon.show()
self.hide()
event.ignore()
def activate(self, reason):
print reason
if reason == 2:
self.show()
def __icon_activated(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 1
|
2011-11-06T13:11:45Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
PyQt4 Minimize to Tray
| 758,256
|
<p>Is there a way to minimize to tray in PyQt4? I've already worked with the QSystemTrayIcon class, but now I would like to minimize or "hide" my app window, and show only the tray icon.</p>
<p>Has anybody done this? Any direction would be appreciated.</p>
<p>Using Python 2.5.4 and PyQt4 on Window XP Pro</p>
| 20
|
2009-04-16T22:16:37Z
| 30,021,530
|
<p>This was an edit of vzades response, but it was rejected on a number of grounds. It does the exact same thing as their code but will also obey the minimize event (and run without syntax errors/missing icons).</p>
<pre><code>import sys
from PyQt4 import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
style = self.style()
# Set the window and tray icon to something
icon = style.standardIcon(QtGui.QStyle.SP_MediaSeekForward)
self.tray_icon = QtGui.QSystemTrayIcon()
self.tray_icon.setIcon(QtGui.QIcon(icon))
self.setWindowIcon(QtGui.QIcon(icon))
# Restore the window when the tray icon is double clicked.
self.tray_icon.activated.connect(self.restore_window)
def event(self, event):
if (event.type() == QtCore.QEvent.WindowStateChange and
self.isMinimized()):
# The window is already minimized at this point. AFAIK,
# there is no hook stop a minimize event. Instead,
# removing the Qt.Tool flag should remove the window
# from the taskbar.
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Tool)
self.tray_icon.show()
return True
else:
return super(Example, self).event(event)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(
self,
'Message',"Are you sure to quit?",
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
self.tray_icon.show()
self.hide()
event.ignore()
def restore_window(self, reason):
if reason == QtGui.QSystemTrayIcon.DoubleClick:
self.tray_icon.hide()
# self.showNormal will restore the window even if it was
# minimized.
self.showNormal()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
</code></pre>
| 2
|
2015-05-04T01:56:58Z
|
[
"python",
"pyqt4",
"system-tray",
"minimize"
] |
Program Control-Flow in Python
| 758,465
|
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p>
<pre><code>.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
</code></pre>
<p>The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like:</p>
<pre><code>if dataLine.find('007 B')==0:
numberOfSeries=int(dataLine.split()[2])
</code></pre>
<p>What I want to do though is</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Right now I am having to iterate through the entire list for each cycle</p>
<p>I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each.</p>
<p>I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.</p>
| 1
|
2009-04-16T23:41:03Z
| 758,518
|
<p>You could read the data into a dictionary. Assuming you are reading from a file-like object <code>infile</code>:</p>
<pre><code>from collections import defaultdict
data = defaultdict(list)
for line in infile:
elements = line.strip().split()
data[elements[0]].append(tuple(elements[1:]))
</code></pre>
<p>Now if you want to read the line after '007 A000000 Y', you can do so as:</p>
<pre><code># find the index of ('A000000', 'Y')
idx = data['007'].index(('A000000', 'Y'))
# get the next line
print data['007'][idx+1]
</code></pre>
| 2
|
2009-04-17T00:00:22Z
|
[
"python",
"list",
"enumerate"
] |
Program Control-Flow in Python
| 758,465
|
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p>
<pre><code>.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
</code></pre>
<p>The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like:</p>
<pre><code>if dataLine.find('007 B')==0:
numberOfSeries=int(dataLine.split()[2])
</code></pre>
<p>What I want to do though is</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Right now I am having to iterate through the entire list for each cycle</p>
<p>I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each.</p>
<p>I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.</p>
| 1
|
2009-04-16T23:41:03Z
| 758,534
|
<p>The only difficulty with using all the data in a dictionary is that a really big dictionary can become troublesome. (It's what we used to call the "Big Ole Matrix" approach.)</p>
<p>A solution to this is to construct an <em>index</em> in the Dictionary, creating a mapping of key->offset, using the <code>tell</code> method to get the file offset value. Then you can refer to the line again by seeking with the <code>seek</code> method.</p>
| 2
|
2009-04-17T00:06:13Z
|
[
"python",
"list",
"enumerate"
] |
Program Control-Flow in Python
| 758,465
|
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p>
<pre><code>.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
</code></pre>
<p>The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like:</p>
<pre><code>if dataLine.find('007 B')==0:
numberOfSeries=int(dataLine.split()[2])
</code></pre>
<p>What I want to do though is</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Right now I am having to iterate through the entire list for each cycle</p>
<p>I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each.</p>
<p>I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.</p>
| 1
|
2009-04-16T23:41:03Z
| 758,689
|
<p>You can use <code>itertools.groupby()</code> to segment your sequence into multiple sub-sequences. </p>
<pre><code>import itertools
for key, subseq in itertools.groupby(tempans, lambda s: s.partition(' ')[0]):
if key == '007':
for dataLine in subseq:
if dataLine.startswith('007 B'):
numberOfSeries = int(dataLine.split()[2])
</code></pre>
<p><hr /></p>
<p><code>itertools.dropwhile()</code> would also work if you really just want to seek up to that line,</p>
<pre><code>list(itertools.dropwhile(lambda s: s != '007 A000000 Y', tempans))
['007 A000000 Y',
'007 B000000 5',
'007 C010100 1',
'007 C020100 ACORN FUND',
'007 C030100 N',
'007 C010200 2',
'007 C020200 ACORN INTERNATIONAL',
'007 C030200 N',
'007 C010300 3',
'007 C020300 ACORN USA',
'007 C030300 N',
'007 C010400 4',
'.',
'.',
'.',
'']
</code></pre>
| 3
|
2009-04-17T01:35:02Z
|
[
"python",
"list",
"enumerate"
] |
Program Control-Flow in Python
| 758,465
|
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p>
<pre><code>.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
</code></pre>
<p>The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like:</p>
<pre><code>if dataLine.find('007 B')==0:
numberOfSeries=int(dataLine.split()[2])
</code></pre>
<p>What I want to do though is</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Right now I am having to iterate through the entire list for each cycle</p>
<p>I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each.</p>
<p>I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.</p>
| 1
|
2009-04-16T23:41:03Z
| 761,798
|
<p>Okay-while I was Googling to make sure I had covered my bases I came across a solution:</p>
<p>I find that I forget to think in Lists and Dictionaries even though I use them. Python has some powerful tools to work with these types to speed your ability to manipulate them.<br />
I need a slice so the slice references are easily obtained by</p>
<pre><code>beginPosit = tempans.index('007 A000000 Y')
endPosit = min([i for i, item in enumerate(tempans) if '008 ' in item])
</code></pre>
<p>where tempans is the datalist
now I can write</p>
<pre><code>for line in tempans[beginPosit:endPosit]:
process each line
</code></pre>
<p>I think I answered my own question. I learned alot from the other answers and appreciate them but I think this is what I needed</p>
<p>Okay I am going to further edit my answer. I have learned a lot here but some of this stuff is over my head still and I want to get some code written while I am learning more about this fantastic tool. </p>
<pre><code>from itertools import takewhile
beginPosit = tempans.index('007 A000000 Y')
new=takewhile(lambda x: '007 ' in x, tempans[beginPosit:])
</code></pre>
<p>This is based on an earlier answer to a similar question and <a href="http://stackoverflow.com/questions/337223/python-item-for-item-until-stopterm-in-item#337285">Steven Huwig's</a> answer</p>
| 0
|
2009-04-17T19:14:06Z
|
[
"python",
"list",
"enumerate"
] |
Program Control-Flow in Python
| 758,465
|
<p>I have some data that I have stored in a list and if I print out the list I see the following:</p>
<pre><code>.
.
.
007 A000000 Y
007 B000000 5
007 C010100 1
007 C020100 ACORN FUND
007 C030100 N
007 C010200 2
007 C020200 ACORN INTERNATIONAL
007 C030200 N
007 C010300 3
007 C020300 ACORN USA
007 C030300 N
007 C010400 4
.
.
.
</code></pre>
<p>The dots before and after the sequence are to represent that there is other data that is similarily structured but might or might not not be part of this seventh item (007). if the first value in the seventh item is '007 A000000 Y' then I want to create a dictionary listing of some of the data items. I can do this and have done so by just running through all of the items in my list and comparing their values to some test values for the variables. For instance a line of code like:</p>
<pre><code>if dataLine.find('007 B')==0:
numberOfSeries=int(dataLine.split()[2])
</code></pre>
<p>What I want to do though is</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Right now I am having to iterate through the entire list for each cycle</p>
<p>I want to shorten the processing because I have about 60K files that have between 500 to 5,000 lines in each.</p>
<p>I have thought about creating another reference to the list and counting the datalines until dataLine.find(''007 A000000 Y')==0. But that does not seem like it is the most elegant solution.</p>
| 1
|
2009-04-16T23:41:03Z
| 761,859
|
<p>You said you wanted to do this:</p>
<pre><code>if dataLine.find(''007 A000000 Y')==0:
READ THE NEXT LINE RIGHT HERE
</code></pre>
<p>Presumably this is within a "for dataLine in data" loop.</p>
<p>Alternatively, you could use an iterator directly instead of in a for loop:</p>
<pre><code>>>> i = iter(data)
>>> while i.next() != '007 A000000 Y': pass # find your starting line
>>> i.next() # read the next line
'007 B000000 5'
</code></pre>
<p>You also mention having 60K files to process. Are they all formatted similarly? Do they need to be processed differently? If they can all be processed the same way, you could consider chaining them together in a single flow:</p>
<pre><code>def gfind( directory, pattern="*" ):
for name in fnmatch.filter( os.listdir( directory ), pattern ):
yield os.path.join( directory, name )
def gopen( names ):
for name in names:
yield open(name, 'rb')
def gcat( files ):
for file in files:
for line in file:
yield line
data = gcat( gopen( gfind( 'C:\datafiles', '*.dat' ) ) )
</code></pre>
<p>This lets you lazily process all your files in a single iterator. Not sure if that helps your current situation but I thought it worth mentioning.</p>
| 0
|
2009-04-17T19:33:11Z
|
[
"python",
"list",
"enumerate"
] |
suggestions for a daemon that accepts zip files for processing
| 758,466
|
<p>im looking to write a daemon that:</p>
<ul>
<li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li>
<li>updates a record in the database saying something like "this job is processing"</li>
<li>reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file meta data for each file found</li>
<li>duplicates each file to s3</li>
<li>deletes the zip file</li>
<li>marks the job as "complete"</li>
<li>read next message in queue, repeat</li>
</ul>
<p>this should be running as a service, and initiated by a message queued when someone uploads a file via the web frontend. the uploader doesn't need to immediately see the results, but the upload be processed in the background fairly expediently.</p>
<p>im fluent with python, so the very first thing that comes to mind is writing a simple server with twisted to handle each request and carry out the process mentioned above. but, ive never written anything like this that would run in a multi-user context. its not going to service hundreds of uploads per minute or hour, but it'd be nice if it could handle several at a time, reasonable. i also am not terribly familiar with writing multi-threaded applications and dealing with issues like blocking. </p>
<p>how have people solved this in the past? what are some other approaches i could take?</p>
<p>thanks in advance for any help and discussion!</p>
| 2
|
2009-04-16T23:41:04Z
| 758,498
|
<p>I've used <a href="http://xph.us/software/beanstalkd/" rel="nofollow">Beanstalkd</a> as a queueing daemon to very good effect (some near-time processing and image resizing - over 2 million so far in the last few weeks). Throw a message into the queue with the zip filename (maybe from a specific directory) [I serialise a command and parameters in JSON], and when you reserve the message in your worker-client, no one else can get it, unless you allow it to time out (when it goes back to the queue to be picked up).</p>
<p>The rest is the unzipping and uploading to S3, for which there are other libraries.</p>
<p>If you want to handle several zip files at once, run as many worker processes as you want.</p>
| 1
|
2009-04-16T23:53:28Z
|
[
"python",
"django",
"zip",
"daemon"
] |
suggestions for a daemon that accepts zip files for processing
| 758,466
|
<p>im looking to write a daemon that:</p>
<ul>
<li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li>
<li>updates a record in the database saying something like "this job is processing"</li>
<li>reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file meta data for each file found</li>
<li>duplicates each file to s3</li>
<li>deletes the zip file</li>
<li>marks the job as "complete"</li>
<li>read next message in queue, repeat</li>
</ul>
<p>this should be running as a service, and initiated by a message queued when someone uploads a file via the web frontend. the uploader doesn't need to immediately see the results, but the upload be processed in the background fairly expediently.</p>
<p>im fluent with python, so the very first thing that comes to mind is writing a simple server with twisted to handle each request and carry out the process mentioned above. but, ive never written anything like this that would run in a multi-user context. its not going to service hundreds of uploads per minute or hour, but it'd be nice if it could handle several at a time, reasonable. i also am not terribly familiar with writing multi-threaded applications and dealing with issues like blocking. </p>
<p>how have people solved this in the past? what are some other approaches i could take?</p>
<p>thanks in advance for any help and discussion!</p>
| 2
|
2009-04-16T23:41:04Z
| 758,631
|
<p>I would avoid doing anything multi-threaded and instead use the queue and the database to synchronize as many worker processes as you care to start up.</p>
<p>For this application I think twisted or any framework for creating server applications is going to be overkill. </p>
<p>Keep it simple. Python script starts up, checks the queue, does some work, checks the queue again. If you want a proper background daemon you might want to just make sure you detach from the terminal as described here: <a href="http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python">http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python</a></p>
<p>Add some logging, maybe a try/except block to email out failures to you.</p>
| 1
|
2009-04-17T00:53:54Z
|
[
"python",
"django",
"zip",
"daemon"
] |
suggestions for a daemon that accepts zip files for processing
| 758,466
|
<p>im looking to write a daemon that:</p>
<ul>
<li>reads a message from a queue (sqs, rabbit-mq, whatever ...) containing a path to a zip file</li>
<li>updates a record in the database saying something like "this job is processing"</li>
<li>reads the aforementioned archive's contents and inserts a row into a database w/ information culled from file meta data for each file found</li>
<li>duplicates each file to s3</li>
<li>deletes the zip file</li>
<li>marks the job as "complete"</li>
<li>read next message in queue, repeat</li>
</ul>
<p>this should be running as a service, and initiated by a message queued when someone uploads a file via the web frontend. the uploader doesn't need to immediately see the results, but the upload be processed in the background fairly expediently.</p>
<p>im fluent with python, so the very first thing that comes to mind is writing a simple server with twisted to handle each request and carry out the process mentioned above. but, ive never written anything like this that would run in a multi-user context. its not going to service hundreds of uploads per minute or hour, but it'd be nice if it could handle several at a time, reasonable. i also am not terribly familiar with writing multi-threaded applications and dealing with issues like blocking. </p>
<p>how have people solved this in the past? what are some other approaches i could take?</p>
<p>thanks in advance for any help and discussion!</p>
| 2
|
2009-04-16T23:41:04Z
| 1,799,405
|
<p>i opted to use a combination of celery (<a href="http://ask.github.com/celery/introduction.html" rel="nofollow">http://ask.github.com/celery/introduction.html</a>), rabbitmq, and a simple django view to handle uploads. the workflow looks like this:</p>
<ol>
<li>django view accepts, stores upload</li>
<li>a celery <code>Task</code> is dispatched to process the upload. all work is done inside the <code>Task</code>.</li>
</ol>
| 1
|
2009-11-25T19:28:50Z
|
[
"python",
"django",
"zip",
"daemon"
] |
Using sphinx/miktex to generate pdf files that displays UTF8 Japanese (CJK) text in windows
| 758,693
|
<p>I have documentation in ReSt (UTF8) and I'm using <a href="http://sphinx.pocoo.org/" rel="nofollow">sphinx</a> to generate HTML and latex files.
(No issues with html conversion)</p>
<p>I then want to convert the resulting latex file to PDf. Currently I'm using <a href="http://miktex.org/" rel="nofollow">MiKTeX</a>
2.7's pdflatex.exe command to perfom this conversion. (Converting a source file without Japanese characters produces the expected pdf correctly)</p>
<p>Using the MiKTeX Package Manager I've installed the cjk related packages: cjk-fonts, miktex-cjkutils-bin-2.7, and cjk.</p>
<p>To debug I'm using the following sample:</p>
<pre><code>\documentclass{article}
\usepackage{CJK}
\begin{document}
\begin{CJK}{UTF8}{song}
\noindent Hello World!
\noindent ÎαλημÎÏα κÏÏμε
\noindent ããã«ã¡ã¯ ä¸ç
\end{CJK}
\end{document}
</code></pre>
<p>Running pdflatex.exe on this file produces the following output:</p>
<pre><code>pdflatex jutf8.tex jutf8.pdf
This is pdfTeX, Version 3.1415926-1.40.8-beta-20080627 (MiKTeX 2.7)
entering extended mode
(jutf8.tex
LaTeX2e <2005/12/01>
Babel <v3.8j> and hyphenation patterns for english, dumylang, nohyphenation, ge
rman, ngerman, german-x-2008-06-18, ngerman-x-2008-06-18, french, loaded.
! LaTeX Error: Missing \begin{document}.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.2
サソ\documentclass{article}
?
("C:\Program Files\MiKTeX 2.7\tex\latex\base\article.cls"
Document Class: article 2005/09/16 v1.4f Standard LaTeX document class
("C:\Program Files\MiKTeX 2.7\tex\latex\base\size10.clo")
Overfull \hbox (20.0pt too wide) in paragraph at lines 2--284
[]
[1{D:/Profiles/All Users/Application Data/MiKTeX/2.7/pdftex/config/pdftex.map}]
) ("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.sty"
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\mule\MULEenc.sty")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\CJK.enc")) (jutf8.aux)
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.bdg")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.enc")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\UTF8.chr")
("C:\Program Files\MiKTeX 2.7\tex\latex\cjk\UTF8\c70song.fd")Running makemf...
makemf: The cyberb source file could not be found.
Running hbf2gf...
hbf2gf (CJK ver. 4.7.0)
Couldn't find `cyberb.cfg'
maketfm: No creation rule for font cyberb03.
! Font C70/song/m/n/10/03=cyberb03 at 10.0pt not loadable: Metric (TFM) file no
t found.
<to be read again>
relax
l.12 \noindent ï¾
ï¾ï½±ï¾ï½»ï¾ï½·ï¾ï½¼ï¾ï½ï¾âï½± ï¾ï½ºï¾çÏï½¼ï¾ï½µ
</code></pre>
<p>How can I get Japanese to display properly in the resulting pdf using MiKTeX/pdflatex.exe?</p>
| 1
|
2009-04-17T01:37:32Z
| 984,015
|
<p>I would use xelatex (available in MikTeX since 2.7) instead of pdflatex and an OpenType Kanji font. The file text.tex consisting of</p>
<pre>
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Sazanami Gothic}
\begin{document}
ããã«ã¡ã¯ ä¸ç
\end{document}
</pre>
<p>compiles with "xelatex text" to a PDF with this text in Sazanami Gothic font.</p>
| 3
|
2009-06-11T22:08:26Z
|
[
"python",
"windows",
"pdflatex",
"python-sphinx",
"miktex"
] |
Python Sort Collections.DefaultDict in Descending order
| 758,792
|
<p>I have this bit of code:</p>
<pre><code> visits = defaultdict(int)
for t in tweetsSQL:
visits[t.user.from_user] += 1
</code></pre>
<p>I looked at some examples online that used the sorted method like so:</p>
<p><code>sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)</code></p>
<p>but it is giving me:</p>
<p><code>"TypeError: 'builtin_function_or_method' object is not iterable"</code></p>
<p>I am not sure why.</p>
| 8
|
2009-04-17T02:41:58Z
| 758,803
|
<p>iteritems is a method. You need parenthesis to call it: <code>visits.iteritems()</code>.</p>
<p>As it stands now, you are passing the iteritems method itself to <code>sorted</code> which is why it is complaining that it can't iterate over a function or method. </p>
| 12
|
2009-04-17T02:49:30Z
|
[
"python"
] |
Python Sort Collections.DefaultDict in Descending order
| 758,792
|
<p>I have this bit of code:</p>
<pre><code> visits = defaultdict(int)
for t in tweetsSQL:
visits[t.user.from_user] += 1
</code></pre>
<p>I looked at some examples online that used the sorted method like so:</p>
<p><code>sorted(visits.iteritems, key=operator.itemgetter(1), reverse=True)</code></p>
<p>but it is giving me:</p>
<p><code>"TypeError: 'builtin_function_or_method' object is not iterable"</code></p>
<p>I am not sure why.</p>
| 8
|
2009-04-17T02:41:58Z
| 758,847
|
<p>Personally I think one of these forms is a little more succinct as the first argument only needs to be an iterable not an iterator.</p>
<pre><code>sorted_keys = sorted(visits.keys(), reverse=True)
sorted_keys = visits.keys().sort(reverse=True)
</code></pre>
| 1
|
2009-04-17T03:08:28Z
|
[
"python"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 758,843
|
<p>Maybe try adding the keyword parameter <code>unix_socket = None</code> to <code>connect()</code>?</p>
| -1
|
2009-04-17T03:07:36Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 758,881
|
<p>Make sure that the mysql server is listening for tcp connections, which you can do with netstat -nlp (in *nix). This is the type of connection you are attempting to make, and db's normally don't listen on the network by default for security reasons. Also, try specifying --host=localhost when using the mysql command, this also try to connect via unix sockets unless you specify otherwise. If mysql is <strong>not</strong> configured to listen for tcp connections, the command will also fail. </p>
<p>Here's a relevant section from the <a href="http://dev.mysql.com/doc/refman/5.1/en/can-not-connect-to-server.html" rel="nofollow">mysql 5.1 manual</a> on unix sockets and troubleshooting connections. Note that the error described (2002) is the same one that you are getting.</p>
<p>Alternatively, check to see if the module you are using has an option to connect via unix sockets (as David Suggests).</p>
| 3
|
2009-04-17T03:19:03Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 834,431
|
<p>add <code>unix_socket='path_to_socket'</code> where <code>path_to_socket</code> should be the path of the MySQL socket, e.g. <code>/var/run/mysqld/mysqld2.sock</code></p>
| 8
|
2009-05-07T12:41:01Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 1,376,464
|
<p>As far as I can tell, the python connector can ONLY connect to mysql through a internet socket: unix sockets (the default for the command line client) is not supported.</p>
<p>In the CLI client, when you say "-h localhost", it actually interprets localhost as "Oh, localhost? I'll just connect to the unix socket instead", rather than the internet localhost socket.</p>
<p>Ie, the mysql CLI client is doing something magical, and the Python connector is doing something "consistent, but restrictive".</p>
<p>Choose your poison. (Pun not intended ;) )</p>
| -1
|
2009-09-03T23:19:53Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 3,251,205
|
<p>I had this issue where the unix socket file was some place else, python was trying to connect to a non-existing socket. Once this was corrected using the unix_socket option, it worked.</p>
| 3
|
2010-07-14T22:58:58Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 4,789,108
|
<p>Mysql uses sockets when the host is 'localhost' and tcp/ip when the host is anything else. By default Mysql will listen to both - you can disable either sockets or networking in you my.cnf file (see mysql.com for details).</p>
<p>In your case forget about the port=3000 the mysql client lib is not paying any attention to it since you are using localhost and specify the socket as in unix_socket='path_to_socket'.</p>
<p>If you decided to move this script to another machine you will need to change this connect string to use the actual host name or ip address and then you can loose the unix_socket and bring back the port. The default port for mysql is 3306 - you don't need to specify that port but you will need to specify 3000 if that is the port you are using.</p>
| 1
|
2011-01-25T01:26:52Z
|
[
"python",
"mysql",
"connection"
] |
Python: MySQLdb Connection Problems
| 758,819
|
<p>I'm having trouble with the MySQLdb module.</p>
<pre><code>db = MySQLdb.connect(
host = 'localhost',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>(I'm using a custom port)</p>
<p>the error I get is:</p>
<pre>Error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)</pre>
Which doesn't make much sense since that's the default connection set in my.conf.. it's as though it's ignoring the connection info I give..
The mysql server is definitely there:
<pre>
[root@baster ~]# mysql -uroot -p -P3000
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use testdb;
Database changed
mysql>
</pre>
<p>I tried directly from the python prompt:</p>
<pre>
>>> db = MySQLdb.connect(user='root', passwd='', port=3000, host='localhost', db='pyneoform')
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib64/python2.5/site-packages/MySQLdb/__init__.py", line 74, in Connect
return Connection(*args, **kwargs)
File "/usr/lib64/python2.5/site-packages/MySQLdb/connections.py", line 169, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
>>>
</pre>
<p>I'm confused... :(</p>
| 10
|
2009-04-17T02:55:57Z
| 6,482,408
|
<p>Changing <code>localhost</code> to <code>127.0.0.1</code> solved my problem using <code>MySQLdb</code>:</p>
<pre><code>db = MySQLdb.connect(
host = '127.0.0.1',
user = 'root',
passwd = '',
db = 'testdb',
port = 3000)
</code></pre>
<p>Using <code>127.0.0.1</code> forces the client to use TCP/IP, so that the server listening to the TCP port can pickle it up. If <code>host</code> is specified as <code>localhost</code>, a Unix socket or pipe will be used.</p>
| 36
|
2011-06-26T05:57:38Z
|
[
"python",
"mysql",
"connection"
] |
Matplotlib suddenly crashes after reinstalling Xcode?
| 758,980
|
<p>I was happy in my world of python and matplotlib with a good level of familiarity. I notied Xcode on my Mac wasn't working so I installed the latest version from Apple and it somehow broke my install of matplotlib (or numpy?)! I'm now getting </p>
<pre><code>...
/sw/lib/python2.5/site-packages/matplotlib-0.91.1-py2.5-macosx-
10.5-i386.egg/matplotlib/numerix/ma/__init__.py in <module>()
14 print "using maskedarray"
15 else:
---> 16 from numpy.core.ma import *
17 #print "using ma"
18 def getmaskorNone(obj):
ImportError: No module named ma
</code></pre>
<p>I've tried reinstalling numpy (Ver 1.3.0) and matplotlib (Ver 0.91.1) to no avail. Any ideas?</p>
| 1
|
2009-04-17T04:08:36Z
| 758,998
|
<p>You're using Python from Fink, so Xcode doesn't have anything to do with it. <code>from numpy.core.ma import *</code> works fine with Apple's bundled Python and NumPy too.</p>
| 3
|
2009-04-17T04:13:54Z
|
[
"python",
"xcode",
"numpy",
"matplotlib"
] |
How can I remove a temporary file (image) that is being displayed by CGI?
| 759,271
|
<p>I've written a python CGI script that converts files into .jpgs and displays them in a simple HTML page. I don't want to clutter up the folders with these .jpg files, so I used tempfile.NamedTemporaryFile to create a file to store the converted .jpg output. Everything works great, but i want to remove this file after the page is displayed. Currently I have delete=False set, but i can't seem to remove the file without causing a broken img link.</p>
| 2
|
2009-04-17T06:37:22Z
| 759,547
|
<p>You can't remove the file from your cgi script. Because the html page is send to the user only after your script finishes to run. And then the users browser parse the html and fetch the jpg file.</p>
<p>The simplest option is to write the temporary files to a sub directory and periodically clean that directory (living in it the last few minutes only). There are ways to improve this process but they are probably pointless.</p>
<p>A more advanced option (which is also probably pointless, depending on your scenario) is to configure the web server to run a script on the "get jpg" request. And then you can stream the jpg through your script. That way you will know when the jpg was fetched. And in this script you can call a subscript asynchronically to delete the jpg file.</p>
| 3
|
2009-04-17T08:33:55Z
|
[
"python",
"image",
"cgi"
] |
Child process detecting the parent process' death in Python
| 759,443
|
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
| 7
|
2009-04-17T07:56:42Z
| 759,455
|
<p>You might get away with reading your parent process' ID very early in your process, and then checking, but of course that is prone to race conditions. The parent that did the spawn might have died immediately, and even before your process got to execute its first instruction.</p>
<p>Unless you have a way of verifying if a given PID refers to the "expected" parent, I think it's hard to do reliably.</p>
| 1
|
2009-04-17T08:01:56Z
|
[
"python",
"subprocess"
] |
Child process detecting the parent process' death in Python
| 759,443
|
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
| 7
|
2009-04-17T07:56:42Z
| 759,458
|
<p>If your Python process is running under Linux, and the <code>prctl()</code> system call is exposed, you can use the answer <a href="http://stackoverflow.com/questions/284325/how-to-make-child-process-die-after-parent-exits">here</a>.</p>
<p>This can cause a signal to be sent to the child when the parent process dies.</p>
| 3
|
2009-04-17T08:02:38Z
|
[
"python",
"subprocess"
] |
Child process detecting the parent process' death in Python
| 759,443
|
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
| 7
|
2009-04-17T07:56:42Z
| 1,519,310
|
<p>The only reliable way I know of is to create a pipe specifically for this purpose. The child will have to repeatedly attempt to read from the pipe, preferably in a non-blocking fashion, or using select. It will get an error when the pipe does not exist anymore (presumably because of the parent's death).</p>
| 1
|
2009-10-05T10:32:39Z
|
[
"python",
"subprocess"
] |
Child process detecting the parent process' death in Python
| 759,443
|
<p>Is there a way for a child process in Python to detect if the parent process has died?</p>
| 7
|
2009-04-17T07:56:42Z
| 4,229,302
|
<p>Assuming the parent is alive when you start to do this, you can check whether it is still alive in a busy loop as such, by using <a href="http://code.google.com/p/psutil" rel="nofollow">psutil</a>:</p>
<pre><code>import psutil, os, time
me = psutil.Process(os.getpid())
while 1:
if me.parent is not None:
# still alive
time.sleep(0.1)
continue
else:
print "my parent is gone"
</code></pre>
<p>Not very nice but...</p>
| 1
|
2010-11-19T20:58:53Z
|
[
"python",
"subprocess"
] |
How do I make text wrapping match current indentation level in vim?
| 759,577
|
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p>
<p>For instance, if I set my settings so that the line:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>is displayed when wrapped as:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>then if I write a block of code like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>it wraps to something like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>I would prefer for it to be displayed as:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p><strong>Edit:</strong> after reading Don Werve's response, it seems that I am indeed looking for the <code>breakindent</code> option, but the option is still on the "Awaiting updated patches" list (see <a href="http://vimdoc.sourceforge.net/htmldoc/todo.html">Vim TODO</a>). So what I'd like to know is what is the <em>easiest way</em> to get vim working with <code>breakindent</code>? (I don't care what version of vim I have to use.)</p>
| 12
|
2009-04-17T08:41:31Z
| 759,583
|
<p>I think set textwidth=80 should do it.</p>
| -1
|
2009-04-17T08:44:05Z
|
[
"python",
"vim",
"textwrapping"
] |
How do I make text wrapping match current indentation level in vim?
| 759,577
|
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p>
<p>For instance, if I set my settings so that the line:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>is displayed when wrapped as:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>then if I write a block of code like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>it wraps to something like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>I would prefer for it to be displayed as:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p><strong>Edit:</strong> after reading Don Werve's response, it seems that I am indeed looking for the <code>breakindent</code> option, but the option is still on the "Awaiting updated patches" list (see <a href="http://vimdoc.sourceforge.net/htmldoc/todo.html">Vim TODO</a>). So what I'd like to know is what is the <em>easiest way</em> to get vim working with <code>breakindent</code>? (I don't care what version of vim I have to use.)</p>
| 12
|
2009-04-17T08:41:31Z
| 760,930
|
<p>You're looking for <code>breakindent</code></p>
<p>You may want to also refer to <a href="http://newsgroups.derkeiler.com/Archive/Comp/comp.editors/2005-07/msg00056.html" rel="nofollow">this thread</a>.</p>
| 2
|
2009-04-17T15:38:33Z
|
[
"python",
"vim",
"textwrapping"
] |
How do I make text wrapping match current indentation level in vim?
| 759,577
|
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p>
<p>For instance, if I set my settings so that the line:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>is displayed when wrapped as:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>then if I write a block of code like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>it wraps to something like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>I would prefer for it to be displayed as:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p><strong>Edit:</strong> after reading Don Werve's response, it seems that I am indeed looking for the <code>breakindent</code> option, but the option is still on the "Awaiting updated patches" list (see <a href="http://vimdoc.sourceforge.net/htmldoc/todo.html">Vim TODO</a>). So what I'd like to know is what is the <em>easiest way</em> to get vim working with <code>breakindent</code>? (I don't care what version of vim I have to use.)</p>
| 12
|
2009-04-17T08:41:31Z
| 763,031
|
<p>I recommend this vimscript:</p>
<p><a href="http://www.vim.org/scripts/script.php?script_id=974" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=974</a></p>
<p>"This indentation script for python tries to match more closely what is suggested in PEP 8 (<a href="http://www.python.org/peps/pep-0008.html" rel="nofollow">http://www.python.org/peps/pep-0008.html</a>). In particular, it handles continuation lines implied by open (parentheses), [brackets] and {braces} correctly and it indents multiline if/for/while statements differently."</p>
| 1
|
2009-04-18T06:37:56Z
|
[
"python",
"vim",
"textwrapping"
] |
How do I make text wrapping match current indentation level in vim?
| 759,577
|
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p>
<p>For instance, if I set my settings so that the line:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>is displayed when wrapped as:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>then if I write a block of code like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>it wraps to something like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>I would prefer for it to be displayed as:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p><strong>Edit:</strong> after reading Don Werve's response, it seems that I am indeed looking for the <code>breakindent</code> option, but the option is still on the "Awaiting updated patches" list (see <a href="http://vimdoc.sourceforge.net/htmldoc/todo.html">Vim TODO</a>). So what I'd like to know is what is the <em>easiest way</em> to get vim working with <code>breakindent</code>? (I don't care what version of vim I have to use.)</p>
| 12
|
2009-04-17T08:41:31Z
| 763,079
|
<p>For controlling the indentation of Python code, see <code>:h ft-python-indent</code>. This for example will make Vim indent two times the <code>shiftwidth</code> if you do a newline while there's an unclosed paren:</p>
<pre><code>let g:pyindent_open_paren = '&sw * 2'
</code></pre>
<p>However <code>&sw * 2</code> is the default, so not sure why it's not working for you. It works for me with manual newlines or with <code>textwidth</code>-induced newlines.</p>
<p>The above setting needs to be in <code>.vimrc</code> or needs to be set somehow before Vim enters Python mode. Be sure to <code>:setf python</code> or that you're otherwise in Python mode. </p>
| -1
|
2009-04-18T07:16:01Z
|
[
"python",
"vim",
"textwrapping"
] |
How do I make text wrapping match current indentation level in vim?
| 759,577
|
<p>Does anyone know of a way to get vim to wrap long lines of text such that the position of the wrapped text is based on the indentation of the current line? I don't want to reformat my code, just for it to be displayed prettily.</p>
<p>For instance, if I set my settings so that the line:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>is displayed when wrapped as:</p>
<pre><code>print 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>then if I write a block of code like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index, self.message)
</code></pre>
<p>it wraps to something like this:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p>I would prefer for it to be displayed as:</p>
<pre><code> def __repr__(self):
return 'ProcessorError(%r, %r, %r)' % (self.file, self.index,
self.message)
</code></pre>
<p><strong>Edit:</strong> after reading Don Werve's response, it seems that I am indeed looking for the <code>breakindent</code> option, but the option is still on the "Awaiting updated patches" list (see <a href="http://vimdoc.sourceforge.net/htmldoc/todo.html">Vim TODO</a>). So what I'd like to know is what is the <em>easiest way</em> to get vim working with <code>breakindent</code>? (I don't care what version of vim I have to use.)</p>
| 12
|
2009-04-17T08:41:31Z
| 1,772,003
|
<p>I asked the <a href="http://superuser.com/questions/72714/vim-line-wrap-with-indent">same question on SuperUser</a>, eventually found this question, found the patch, and <a href="https://retracile.net/blog/2009/11/20/12.00" rel="nofollow">updated the patch</a> to work with Vim 7.2.148 from Fedora 11.</p>
<p>You can use <code>yumdownloader --source vim</code> to get the source RPM. Then add a <code>Patch3312:</code> line and a <code>%patch3012 -p1</code> line to the spec file, and build the rpm.</p>
| 6
|
2009-11-20T17:21:46Z
|
[
"python",
"vim",
"textwrapping"
] |
How to use cherrypy as a web server for static files?
| 759,627
|
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p>
<pre><code>import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
</code></pre>
<p>Is it any easy way to use <code>index.html</code> instead of HelloWorld.index() method?</p>
| 13
|
2009-04-17T08:54:26Z
| 759,666
|
<p>Here is some information on serving static content with CherryPy: <a href="http://docs.cherrypy.org/stable/progguide/files/static.html" rel="nofollow">http://docs.cherrypy.org/stable/progguide/files/static.html</a></p>
<p>BTW, here is a simple way to share the current directory over HTTP with python:</p>
<pre>
$ python -m SimpleHTTPServer [port]
</pre>
| 6
|
2009-04-17T09:06:31Z
|
[
"python",
"cherrypy"
] |
How to use cherrypy as a web server for static files?
| 759,627
|
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p>
<pre><code>import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
</code></pre>
<p>Is it any easy way to use <code>index.html</code> instead of HelloWorld.index() method?</p>
| 13
|
2009-04-17T08:54:26Z
| 760,100
|
<pre><code># encode: utf-8
import cherrypy
WEB_ROOT = "c:\\webserver\\root\\"
class CServer( object ) :
@cherrypy.expose
def do_contact(self, **params):
pass
cherrypy.server.socket_port = 80
# INADDR_ANY: listen on all interfaces
cherrypy.server.socket_host = '0.0.0.0'
conf = { '/':
{ 'tools.staticdir.on' : True,
'tools.staticdir.dir' : WEB_ROOT,
'tools.staticdir.index' : 'index.html' } }
cherrypy.quickstart( CServer(), config = conf )
</code></pre>
| -1
|
2009-04-17T11:48:02Z
|
[
"python",
"cherrypy"
] |
How to use cherrypy as a web server for static files?
| 759,627
|
<p>Is it any easy way to use CherryPy as an web server that will display <code>.html</code> files in some folder? All CherryPy introductory documentation states that content is dynamically generated:</p>
<pre><code>import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
</code></pre>
<p>Is it any easy way to use <code>index.html</code> instead of HelloWorld.index() method?</p>
| 13
|
2009-04-17T08:54:26Z
| 760,115
|
<p>This simple code will serve files on current directory.</p>
<pre><code>import os
import cherrypy
PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass
cherrypy.tree.mount(Root(), '/', config={
'/': {
'tools.staticdir.on': True,
'tools.staticdir.dir': PATH,
'tools.staticdir.index': 'index.html',
},
})
cherrypy.quickstart()
</code></pre>
| 29
|
2009-04-17T11:53:00Z
|
[
"python",
"cherrypy"
] |
Performance Considerations Using Multiple Layers of Generators in Python?
| 759,729
|
<p>Are there any performance considerations for using a lot of generators chained together, as opposed to just a single generator.</p>
<p>For example:</p>
<pre><code>def A(self, items):
for item in self.AB(items):
if object.A():
yield item
def AB(self, items):
for object in self.ABC(objects):
if object.A() or object.B():
yield object
def ABC(self, objects):
for object in objects:
if object.A() or object.B() or object.C():
yield object
</code></pre>
<p>Clearly calling <code>A(objects)</code> is going to go through three different generators, but in many situations it makes the code re-use better if there are different generators to handle different filtering. Can anyone indicate that there is a significant impact on performance using this technique?</p>
| 3
|
2009-04-17T09:27:20Z
| 760,007
|
<p>There is nothing wrong with chaining generators, but in this example there is no reason for A to call self.AB, it can just loop over items to get the same result.</p>
<p>You should write your code as clearly as you can and if it's slow then use a profiler to determine where the bottleneck is. Contrived examples such as this one are too far from reality to be useful indicators of performance.</p>
| 2
|
2009-04-17T11:04:33Z
|
[
"python",
"performance",
"generator"
] |
Unexpected result from sys.getrefcount
| 759,740
|
<p>When I typed:</p>
<pre><code>>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
</code></pre>
<p>I am not getting where is <code>astrd</code> used 3 times ?</p>
| 5
|
2009-04-17T09:29:39Z
| 759,763
|
<p>From the <a href="http://docs.python.org/2/library/sys.html#sys.getrefcount" rel="nofollow">getrefcount docstring</a>:</p>
<blockquote>
<p>... The count returned is generally one higher than you might expect,
because it includes the (temporary) reference as an argument to <code>getrefcount()</code>.</p>
</blockquote>
<p>The other two references means that python internally is holding two references to the object. Maybe the locals() and globals() dictionaries count as one reference each?</p>
| 6
|
2009-04-17T09:37:41Z
|
[
"python",
"garbage-collection"
] |
Unexpected result from sys.getrefcount
| 759,740
|
<p>When I typed:</p>
<pre><code>>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
</code></pre>
<p>I am not getting where is <code>astrd</code> used 3 times ?</p>
| 5
|
2009-04-17T09:29:39Z
| 759,777
|
<p>I think it counts the references to 123, try other examples, like</p>
<pre><code>>>> import sys
>>> astrd = 1
>>> sys.getrefcount(astrd)
177
>>> astrd = 9802374987193847
>>> sys.getrefcount(astrd)
2
>>>
</code></pre>
<p>The refcount for 9802374987193847 fits codeape's answer.</p>
<p>This is probably because numbers are immutables. If you for example use a list, it will always be 2 (from a clean prompt that is).</p>
<p>Btw, I get 2 for 123 as well, perhaps your setup is somewhat different? Or it might be time related or so?</p>
| 6
|
2009-04-17T09:42:22Z
|
[
"python",
"garbage-collection"
] |
Unexpected result from sys.getrefcount
| 759,740
|
<p>When I typed:</p>
<pre><code>>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
</code></pre>
<p>I am not getting where is <code>astrd</code> used 3 times ?</p>
| 5
|
2009-04-17T09:29:39Z
| 759,780
|
<p>ints are implemented in a special way, they are cached and shared, that why you don't get 1.</p>
<p>And python, uses reference counted objects. astrd is itself a reference, so you actually get the number of references to the int '123'. Try with another (user-defined) type and you'll get 1.</p>
| 4
|
2009-04-17T09:45:05Z
|
[
"python",
"garbage-collection"
] |
Unexpected result from sys.getrefcount
| 759,740
|
<p>When I typed:</p>
<pre><code>>>> astrd = 123
>>> import sys
>>> sys.getrefcount(astrd)
3
>>>
</code></pre>
<p>I am not getting where is <code>astrd</code> used 3 times ?</p>
| 5
|
2009-04-17T09:29:39Z
| 759,782
|
<p>It's not <code>astrd</code> that is referenced three times, but the value <code>123</code>. <code>astrd</code> is simply a name for the (immutable) number 123, which can be referenced however many times. Additionally to that, small integers are usually shared:</p>
<pre><code>>>> astrd = 123
>>> sys.getrefcount(astrd)
4
>>> j = 123
>>> sys.getrefcount(astrd)
5
</code></pre>
<p>In the second assignment, no new integer is created, instead <code>j</code> is just a new name for the integer <code>123</code>.</p>
<p>However, given very large integers, this does not hold:</p>
<pre><code>>>> i = 823423442583
>>> sys.getrefcount(i)
2
>>> j = 823423442583
>>> sys.getrefcount(i)
2
</code></pre>
<p>Shared integers are an implementation detail of CPython (among others). Since small integers are instantiated very often, sharing them saves a lot of memory. This is made possible by the fact that integers are immutable in the first place.</p>
<p>For the additional reference in the second example, cf. <a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">codeape's answer</a>.</p>
| 7
|
2009-04-17T09:45:43Z
|
[
"python",
"garbage-collection"
] |
How to retrieve google appengine entities using their numerical id?
| 759,771
|
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how?
I tried using:</p>
<p>key = Key.from_path("ModelName", numericalId)
m = ModelName.get(key)</p>
<p>but the key generated wasnt correct.</p>
| 3
|
2009-04-17T09:39:55Z
| 759,801
|
<p><a href="http://code.google.com/intl/nl-NL/appengine/docs/python/datastore/creatinggettinganddeletingdata.html#Getting%5Fan%5FEntity%5FUsing%5Fa%5FKey" rel="nofollow">Getting an Entity Using a Key</a></p>
| 0
|
2009-04-17T09:55:13Z
|
[
"python",
"google-app-engine"
] |
How to retrieve google appengine entities using their numerical id?
| 759,771
|
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how?
I tried using:</p>
<p>key = Key.from_path("ModelName", numericalId)
m = ModelName.get(key)</p>
<p>but the key generated wasnt correct.</p>
| 3
|
2009-04-17T09:39:55Z
| 760,060
|
<p>Turns out I needed to do </p>
<p>key = Key.from_path( Application_ModelName, numeric_id )</p>
<p>wasn't clear till i looked at the dict() of an entity</p>
| 0
|
2009-04-17T11:27:23Z
|
[
"python",
"google-app-engine"
] |
How to retrieve google appengine entities using their numerical id?
| 759,771
|
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how?
I tried using:</p>
<p>key = Key.from_path("ModelName", numericalId)
m = ModelName.get(key)</p>
<p>but the key generated wasnt correct.</p>
| 3
|
2009-04-17T09:39:55Z
| 770,848
|
<p>You are looking for this: <a href="http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_id" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_id</a></p>
| 1
|
2009-04-21T02:38:15Z
|
[
"python",
"google-app-engine"
] |
How to retrieve google appengine entities using their numerical id?
| 759,771
|
<p>Is it possible to retrieve an entity from google appengine using their numerical IDs and if so how?
I tried using:</p>
<p>key = Key.from_path("ModelName", numericalId)
m = ModelName.get(key)</p>
<p>but the key generated wasnt correct.</p>
| 3
|
2009-04-17T09:39:55Z
| 21,352,573
|
<p>Other answers refer to the old DB API. New applications will by default use the NDB datastore, which has a slightly different API. You can still do Model.get_by_id(id, parent) to retrieve an entity by id, but the NDB also supports options to specify the app and namespace. See <a href="https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id" rel="nofollow">the documentation</a> for details.</p>
| 0
|
2014-01-25T15:40:21Z
|
[
"python",
"google-app-engine"
] |
Map raw SQL to multiple related Django models
| 759,797
|
<p>Due to performance reasons I can't use the ORM query methods of Django and I have to use raw SQL for some complex questions. I want to find a way to map the results of a SQL query to several models.</p>
<p>I know I can use the following statement to map the query results to one model, but I can't figure how to use it to be able to map to related models (like I can do by using the select_related statement in Django).</p>
<pre><code>model_instance = MyModel(**dict(zip(field_names, row_data)))
</code></pre>
<p>Is there a relatively easy way to be able to map fields of related tables that are also in the query result set? </p>
| 2
|
2009-04-17T09:52:49Z
| 760,118
|
<p>First, can you prove the ORM is stopping your performance? Sometimes performance problems are simply poor database design, or improper indexes. Usually this comes from trying to force-fit Django's ORM onto a legacy database design. Stored procedures and triggers can have adverse impact on performance -- especially when working with Django where the trigger code is expected to be in the Python model code.</p>
<p>Sometimes poor performance is an application issue. This includes needless order-by operations being done in the database.</p>
<p>The most common performance problem is an application that "over-fetches" data. Casually using the <code>.all()</code> method and creating large in-memory collections. This will crush performance. The Django query sets have to be touched as little as possible so that the query set iterator is given to the template for display.</p>
<p>Once you choose to bypass the ORM, you have to fight out the Object-Relational Impedance Mismatch problem. Again. Specifically, relational "navigation" has no concept of "related": it has to be a first-class fetch of a relational set using foreign keys. To assemble a complex in-memory object model via SQL is simply hard. Circular references make this very hard; resolving FK's into collections is hard.</p>
<p>If you're going to use raw SQL, you have two choices.</p>
<ol>
<li><p>Eschew "select related" -- it doesn't exist -- and it's painful to implement.</p></li>
<li><p>Invent your own ORM-like "select related" features. A common approach is to add stateful getters that (a) check a private cache to see if they've fetched the related object and if the object doesn't exist, (b) fetch the related object from the database and update the cache.</p></li>
</ol>
<p>In the process of inventing your own stateful getters, you'll be reinventing Django's, and you'll probably discover that it isn't the ORM layer, but a database design or an application design issue.</p>
| 1
|
2009-04-17T11:54:36Z
|
[
"python",
"sql",
"mysql",
"django",
"django-models"
] |
add request to django model method?
| 759,850
|
<p>I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?</p>
<p>One idea: Adding the request to a models method would do the trick. Is that possible?</p>
<p>Edit: I meant in templatecode: {{ lesson.get_status }}, with get_status(self, request). Is it possible? It does not work (yet).</p>
| 6
|
2009-04-17T10:11:04Z
| 759,894
|
<p>Yes, you can add a method to your model with a request paramater:</p>
<pre><code>class MyModel(models.Model):
fields....
def update_status(self, request):
make something with the request...
</code></pre>
| 0
|
2009-04-17T10:24:58Z
|
[
"python",
"django",
"django-models"
] |
add request to django model method?
| 759,850
|
<p>I'm keeping track of a user status on a model. For the model 'Lesson' I have the status 'Finished', 'Learning', 'Viewed'. In a view for a list of models I want to add the user status. What is the best way to do this?</p>
<p>One idea: Adding the request to a models method would do the trick. Is that possible?</p>
<p>Edit: I meant in templatecode: {{ lesson.get_status }}, with get_status(self, request). Is it possible? It does not work (yet).</p>
| 6
|
2009-04-17T10:11:04Z
| 760,077
|
<p>If your status is a value that changes, you have to break this into two separate parts.</p>
<ol>
<li><p>Updating the status. This must be called in a view function. The real work, however, belongs in the model. The view function calls the model method and does the save.</p></li>
<li><p>Displaying the status. This is just some string representation of the status.</p></li>
</ol>
<p>Model</p>
<pre><code>class MyStatefulModel( models.Model ):
theState = models.CharField( max_length=64 )
def changeState( self ):
if theState is None:
theState= "viewed"
elif theState is "viewed":
theState= "learning"
etc.
</code></pre>
<p>View Function</p>
<pre><code> def show( request, object_id ):
object= MyStatefulModel.objects.get( id=object_id )
object.changeState()
object.save()
render_to_response( ... )
</code></pre>
<p>Template</p>
<pre><code> <p>Your status is {{object.theState}}.</p>
</code></pre>
| 2
|
2009-04-17T11:38:56Z
|
[
"python",
"django",
"django-models"
] |
python ctypes and sysctl
| 759,892
|
<p>I have following code</p>
<pre><code>import sys
from ctypes import *
from ctypes.util import find_library
libc = cdll.LoadLibrary(find_library("c"))
CTL_KERN = 1
KERN_SHMMAX = 34
sysctl_names = {
'memory_shared_buffers' : (CTL_KERN, KERN_SHMMAX),
}
def posix_sysctl_long(name):
_mem = c_uint64(0)
_arr = c_int * 2
_name = _arr()
_name[0] = c_int(sysctl_names[name][0])
_name[1] = c_int(sysctl_names[name][1])
result = libc.sysctl(_name, byref(_mem), c_size_t(sizeof(_mem)), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value
print posix_sysctl_long('memory_shared_buffers')
</code></pre>
<p>which produces following result:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 23, in <module>
print posix_sysctl_long('memory_shared_buffers')
File "test.py", line 20, in posix_sysctl_long
raise Exception('sysctl returned with error %s' % result)
Exception: sysctl returned with error -1
</code></pre>
<p>I gues I did something wrong. What would be the correct calling convention? How would I find out what exactly went wrong?</p>
| 2
|
2009-04-17T10:24:38Z
| 760,276
|
<p>You are not providing the correct values to the sysctl function. Detailed information on the arguments of sysctl() can be found <a href="http://www.linuxjournal.com/article/2365">here</a>.</p>
<p>Here are your errors:</p>
<ul>
<li>You have forgotten the <em>nlen</em> argument (second argument)</li>
<li>The <em>oldlenp</em> argument is a pointer to the size, not directly the size</li>
</ul>
<p>Here is the correct function (with minor improvement):</p>
<pre><code>def posix_sysctl_long(name):
_mem = c_uint64(0)
_def = sysctl_names[name]
_arr = c_int * len(_def)
_name = _arr()
for i, v in enumerate(_def):
_name[i] = c_int(v)
_sz = c_size_t(sizeof(_mem))
result = libc.sysctl(_name, len(_def), byref(_mem), byref(_sz), None, c_size_t(0))
if result != 0:
raise Exception('sysctl returned with error %s' % result)
return _mem.value
</code></pre>
| 6
|
2009-04-17T12:49:11Z
|
[
"python",
"c",
"linux",
"ctypes"
] |
sys.getrefcount continuation
| 759,906
|
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p>
<p>I got the concept of reference count</p>
<p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p>
<p>This is the sample codes.These codes I developed after my yesterday's question:<a href="http://stackoverflow.com/questions/755694/delete-pyc">link text</a></p>
<p>one.py:</p>
<p>def abc():</p>
<pre><code>print "Hello"
print "123"
print '345'
</code></pre>
<p>two.py:</p>
<pre><code>import one
#reload(one)
#def defg():
one.abc()
</code></pre>
<p>three.py:</p>
<pre><code>import os,sys,gc
from time import sleep
import two
#reload(two)
#two.defg()
sleep(20)
directory = os.listdir('.')
for filename in directory:
if filename[-3:] == 'pyc':
print '- ' + filename
print sys.getrefcount(filename)
file_name = os.path.splitext (filename)[0]
del file_name # remove the local reference
del sys.modules[os.path.splitext (filename)[0]] # removes import
gc.collect() # garbage collect
#del sys.modules[filename]
#del filename
#os.remove(filename)
</code></pre>
<p>What i did in three.py is correct or not ?
Is there any unnecessary step ?If yes,why ?</p>
<p>Please help me out of this.</p>
| 0
|
2009-04-17T10:28:15Z
| 759,917
|
<p>It gets a <strong>chance</strong> to get collected on the next GC collection run.</p>
<p>See: <a href="http://docs.python.org/library/gc.html" rel="nofollow">http://docs.python.org/library/gc.html</a></p>
| 1
|
2009-04-17T10:32:41Z
|
[
"python",
"del"
] |
sys.getrefcount continuation
| 759,906
|
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p>
<p>I got the concept of reference count</p>
<p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p>
<p>This is the sample codes.These codes I developed after my yesterday's question:<a href="http://stackoverflow.com/questions/755694/delete-pyc">link text</a></p>
<p>one.py:</p>
<p>def abc():</p>
<pre><code>print "Hello"
print "123"
print '345'
</code></pre>
<p>two.py:</p>
<pre><code>import one
#reload(one)
#def defg():
one.abc()
</code></pre>
<p>three.py:</p>
<pre><code>import os,sys,gc
from time import sleep
import two
#reload(two)
#two.defg()
sleep(20)
directory = os.listdir('.')
for filename in directory:
if filename[-3:] == 'pyc':
print '- ' + filename
print sys.getrefcount(filename)
file_name = os.path.splitext (filename)[0]
del file_name # remove the local reference
del sys.modules[os.path.splitext (filename)[0]] # removes import
gc.collect() # garbage collect
#del sys.modules[filename]
#del filename
#os.remove(filename)
</code></pre>
<p>What i did in three.py is correct or not ?
Is there any unnecessary step ?If yes,why ?</p>
<p>Please help me out of this.</p>
| 0
|
2009-04-17T10:28:15Z
| 759,970
|
<p>I believe that memory is automatically freed the moment the refcount reaches zero. The GC is not involved.</p>
<p>The python GC is optional, and is only used when there are unreachable objects that has reference cycles. In fact, you can call <code>gc.disable()</code> if you are sure your program does not create reference cycles.</p>
<p>As for the original question:</p>
<ul>
<li>When you do <code>del astrd</code>, you remove the binding of astrd from the local namespace a reference to an object (whatever astrd references).</li>
<li>If this means that the refcount is zero, the memory used by the object is freed.</li>
<li>So <code>del</code> does not delete objects, it unbinds references. The deletion of objects is a side effect that occurs if unbinding a reference causes the refcount to reach zero.</li>
</ul>
<p>Note that the above is only true for CPython. Jython and IronPython uses the JVM/CLR GC mechanism, and does not use refcounting at all, I believe.</p>
<p>The handy <code>gc.get_objects</code> returns a list of all object instances tracked by the python interpreter. Example:</p>
<pre>
import gc
class test(object):
pass
def number_of_test_instances():
return len([obj for obj in gc.get_objects() if isinstance(obj, test)])
for i in range(100):
t = test()
print "Created and abandoned 100 instances, there are now", \
number_of_test_instances(), \
"instances known to the python interpreter."
# note that in normal operation, the GC would
# detect the unreachable objects and start
# collecting them right away
gc.disable()
for i in range(100):
t = test()
t.t = t
print "Created and abandoned 100 instances with circular ref, there are now", \
number_of_test_instances(), \
"instances known to the python interpreter."
gc.collect()
print "After manually doing gc.collect(), there are now", \
number_of_test_instances(), \
"instances known to the python interpreter."
</pre>
<p>Running this program gives:</p>
<pre>
Created and abandoned 100 instances, there are now 1 instances known to the python interpreter.
Created and abandoned 100 instances with circular ref, there are now 100 instances known to the python interpreter.
After manually doing gc.collect(), there are now 1 instances known to the python interpreter.
</pre>
| 5
|
2009-04-17T10:50:02Z
|
[
"python",
"del"
] |
sys.getrefcount continuation
| 759,906
|
<p><a href="http://stackoverflow.com/questions/759740/sys-getrefcount/759763#759763">link text</a></p>
<p>I got the concept of reference count</p>
<p>So when i do a "del astrd" ,reference count drops to zero and astrd gets collected by gc ?</p>
<p>This is the sample codes.These codes I developed after my yesterday's question:<a href="http://stackoverflow.com/questions/755694/delete-pyc">link text</a></p>
<p>one.py:</p>
<p>def abc():</p>
<pre><code>print "Hello"
print "123"
print '345'
</code></pre>
<p>two.py:</p>
<pre><code>import one
#reload(one)
#def defg():
one.abc()
</code></pre>
<p>three.py:</p>
<pre><code>import os,sys,gc
from time import sleep
import two
#reload(two)
#two.defg()
sleep(20)
directory = os.listdir('.')
for filename in directory:
if filename[-3:] == 'pyc':
print '- ' + filename
print sys.getrefcount(filename)
file_name = os.path.splitext (filename)[0]
del file_name # remove the local reference
del sys.modules[os.path.splitext (filename)[0]] # removes import
gc.collect() # garbage collect
#del sys.modules[filename]
#del filename
#os.remove(filename)
</code></pre>
<p>What i did in three.py is correct or not ?
Is there any unnecessary step ?If yes,why ?</p>
<p>Please help me out of this.</p>
| 0
|
2009-04-17T10:28:15Z
| 761,032
|
<p>Could you give some background as to what you are doing?
There's rarely any reason for explicitly using <code>del</code> on variables other than to clean up a namespace of things you don't want to expose. I'm not sure why you are calling <code>del file_name</code> or running <code>gc.collect()</code>. (<code>del sys.modules[filename]</code> is fine - that's a different use of del)</p>
<p>For objects when the exact time they get finalised doesn't matter (eg strings like file_name), you may as well let the variable drop out of scope - when your function finishes, it will be collected, and it won't cause any harm till then. Manually calling <code>del</code> for such variables just clutters up your code.</p>
<p>For objects which need to be finalised immediately (eg. an open file, or a held lock), you shouldn't be relying on the garbage collector anyway - it is not guaranteed to immediately collect such objects. It happens to do so in the standard C python implementation, but not in Jython or IronPython, and is so not guaranteed. Instead, you should explicitly clean up such objects by calling <code>close</code> or using the new <code>with</code> construct.</p>
<p>The only other reason might be that you have a very large amount of memory allocated, and want to signal you are done with it before the variable that refers to it goes out of scope naturally.</p>
<p>Your example doesn't seem to fit either of these circumstances however, so I'm not sure why you're manually invoking the garbage collector at all.</p>
| 0
|
2009-04-17T16:04:25Z
|
[
"python",
"del"
] |
Investigating python process to see what's eating CPU
| 760,039
|
<p>I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?</p>
<p><strong>Update:</strong></p>
<ul>
<li>configured access log which shows that there are no requests going on, webapp is just idling </li>
<li>no point to plug in paste.profile in middleware chain since there are no requests, activity must be happening either in webapp's worker threads or paster web server</li>
<li>running paster like this: "python -m cProfile -o outfile /usr/bin/paster serve dev.ini" and inspecting results shows that most time is spent in "posix.waitpid". Paster runs webapp in subprocess, subprocess activity is not picked up by profiler</li>
<li>looking into ;hacking PasteScript "serve" command so that subprocesses would get profiled</li>
</ul>
<p><strong>Another update:</strong></p>
<p>After much tinkering, sticking profiler in various places and getting familiar with PasteScript insides, I discovered that the constant CPU load goes away if application is started without "--reload" parameter (this flag tells paster to restart itself if code changes, handy in development), which is fine in production environment.</p>
| 6
|
2009-04-17T11:17:34Z
| 760,048
|
<p><a href="http://docs.python.org/library/profile.html#instant-user-s-manual">Profiling</a> might help you learn a bit of what it's doing. If your sort the output by "time" you will see which functions are chowing up cpu time, which should give you some good hints.</p>
| 7
|
2009-04-17T11:22:27Z
|
[
"python",
"multithreading",
"debugging",
"monitoring",
"pylons"
] |
Investigating python process to see what's eating CPU
| 760,039
|
<p>I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?</p>
<p><strong>Update:</strong></p>
<ul>
<li>configured access log which shows that there are no requests going on, webapp is just idling </li>
<li>no point to plug in paste.profile in middleware chain since there are no requests, activity must be happening either in webapp's worker threads or paster web server</li>
<li>running paster like this: "python -m cProfile -o outfile /usr/bin/paster serve dev.ini" and inspecting results shows that most time is spent in "posix.waitpid". Paster runs webapp in subprocess, subprocess activity is not picked up by profiler</li>
<li>looking into ;hacking PasteScript "serve" command so that subprocesses would get profiled</li>
</ul>
<p><strong>Another update:</strong></p>
<p>After much tinkering, sticking profiler in various places and getting familiar with PasteScript insides, I discovered that the constant CPU load goes away if application is started without "--reload" parameter (this flag tells paster to restart itself if code changes, handy in development), which is fine in production environment.</p>
| 6
|
2009-04-17T11:17:34Z
| 784,432
|
<p>As you noted, in --reload mode, Paste sweeps the filesystem every second to see if any of the files loaded have changed. If they have, then Paste reloads the process. You can also manually tell Paste to monitor non-Python code modules for changes if desired.</p>
<p>You can change the reload interval with the --reload-interval option, this will reduce the CPU usage when using --reload as it will sweep less often.</p>
| 5
|
2009-04-24T03:45:38Z
|
[
"python",
"multithreading",
"debugging",
"monitoring",
"pylons"
] |
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label
| 760,310
|
<p>I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. </p>
<p>Are there any properties I can modify about a device that will not cause it to behave/look differently to the user?</p>
<p>Running Ubuntu Jaunty.</p>
| 1
|
2009-04-17T12:58:48Z
| 760,744
|
<p>You cannot modify this property, but the tuple (vendor_id, product_id, serial_number) is unique to each device, so you can use this as mark that is already there.
You can enumerate the devices on the USB bus using lsusb or usblib.</p>
| 1
|
2009-04-17T14:59:41Z
|
[
"python",
"hardware",
"mount",
"dbus",
"hal"
] |
How to mark a device in a way that can be retrived by HAL but does not require mounting or changing the label
| 760,310
|
<p>I'm trying to find a way to mark a USB flash device in a way that I can programmaticly test for without mounting it or changing the label. </p>
<p>Are there any properties I can modify about a device that will not cause it to behave/look differently to the user?</p>
<p>Running Ubuntu Jaunty.</p>
| 1
|
2009-04-17T12:58:48Z
| 760,814
|
<p>Changing the VID/PID might make your device non-usable without custom drivers. HAL isn't supposed to auto-mount your flash drives for you. </p>
<p>That being said, you could always sneak something into the boot sector and/or the beginning part of the drive. There are a lot of spare bytes in there that can be used for custom purposes - both nefarious and otherwise.</p>
| 0
|
2009-04-17T15:12:10Z
|
[
"python",
"hardware",
"mount",
"dbus",
"hal"
] |
Self updating py2exe/py2app application
| 760,383
|
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p>
<p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p>
<p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</p>
<ul>
<li>check for new versions on an http server</li>
<li>download the patches needed to update to the last version</li>
<li>apply the patches list and restart the application</li>
</ul>
<p>I have some questions:</p>
<ul>
<li>what is the preferred way to update a windows application since open files are locked and can't be overwritten ?</li>
<li>how do I prepare and apply the patches ? perhaps using <a href="http://www.daemonology.net/bsdiff/">bsdiff/pspatch</a> ?</li>
</ul>
<p><strong>[update]</strong></p>
<p>I made a simple class to make patches with <a href="http://www.daemonology.net/bsdiff/">bsdiff</a>, which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.</p>
<p>The code is available in the 'update' package of <a href="http://pypi.python.org/pypi/pyflu">pyflu</a>, a small library of Python code.</p>
| 12
|
2009-04-17T13:22:58Z
| 760,490
|
<p>I don't know about patches, but on OS X the "standard" for this with cocoa apps is <a href="http://sparkle.andymatuschak.org/" rel="nofollow">Sparkle</a>. Basically it does "appcasting". It downloads the full app each time. It might be worth looking at it for inspiration.</p>
<p>I imagine on OS X you can probably just download the actual part of your app bundle that contains your specific code (not the libs etc that get packaged in) and that'd be fairly small and easy to replace in the bundle.</p>
<p>On Windows, you'd probably be able to do a similar trick by not bundling your app into one exe - thus letting you change the one file that has actually changed.</p>
<p>I'd imagine your actual Python code would be much less than 40Mb, so that's probably the way to go.</p>
<p>As for replacing the running app, well first you need to find it's location, so you could use <code>sys.executable</code> to get you a starting point, then you could probably fork a child process to, kill the parent process and have the child doing the actual replacement?</p>
<p>I'm currently playing around with a small wxPython app and wondering about exactly this problem. I'd love to hear about what you come up with.</p>
<p>Also how big is you app when compressed? If it compresses well then maybe you can still afford to send the whole thing.</p>
| 3
|
2009-04-17T13:47:47Z
|
[
"python",
"deployment",
"patch",
"py2exe"
] |
Self updating py2exe/py2app application
| 760,383
|
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p>
<p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p>
<p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</p>
<ul>
<li>check for new versions on an http server</li>
<li>download the patches needed to update to the last version</li>
<li>apply the patches list and restart the application</li>
</ul>
<p>I have some questions:</p>
<ul>
<li>what is the preferred way to update a windows application since open files are locked and can't be overwritten ?</li>
<li>how do I prepare and apply the patches ? perhaps using <a href="http://www.daemonology.net/bsdiff/">bsdiff/pspatch</a> ?</li>
</ul>
<p><strong>[update]</strong></p>
<p>I made a simple class to make patches with <a href="http://www.daemonology.net/bsdiff/">bsdiff</a>, which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.</p>
<p>The code is available in the 'update' package of <a href="http://pypi.python.org/pypi/pyflu">pyflu</a>, a small library of Python code.</p>
| 12
|
2009-04-17T13:22:58Z
| 760,494
|
<p>I don't believe py2exe supports patched updates. However, if you do not bundle the entire package into a single EXE (<a href="http://www.py2exe.org/index.cgi/SingleFileExecutable" rel="nofollow">py2exe website example</a> - bottom of page), <strong>you can get away with smaller updates by just replacing certain files</strong>, like the EXE file, for example. This can reduce the size of your updates significantly.</p>
<p>You can write a separate <strong>updater app</strong>, which can be downloaded/ran from inside your application. This app may be different for every update, as the files that need to be updated may change.</p>
<p>Once the application launches the updater, it will need to close itself so the files can be overwritten. Once the updater is complete, you can have it reopen the application before closing itself.</p>
| 4
|
2009-04-17T13:48:34Z
|
[
"python",
"deployment",
"patch",
"py2exe"
] |
Self updating py2exe/py2app application
| 760,383
|
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p>
<p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p>
<p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</p>
<ul>
<li>check for new versions on an http server</li>
<li>download the patches needed to update to the last version</li>
<li>apply the patches list and restart the application</li>
</ul>
<p>I have some questions:</p>
<ul>
<li>what is the preferred way to update a windows application since open files are locked and can't be overwritten ?</li>
<li>how do I prepare and apply the patches ? perhaps using <a href="http://www.daemonology.net/bsdiff/">bsdiff/pspatch</a> ?</li>
</ul>
<p><strong>[update]</strong></p>
<p>I made a simple class to make patches with <a href="http://www.daemonology.net/bsdiff/">bsdiff</a>, which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.</p>
<p>The code is available in the 'update' package of <a href="http://pypi.python.org/pypi/pyflu">pyflu</a>, a small library of Python code.</p>
| 12
|
2009-04-17T13:22:58Z
| 760,788
|
<p>Since py2exe puts all of the compiled modules of your app into a ZIP file, you could try to update this file by creating a script that updates it from a given set of files.
Then replace the remaining files that have changed (which should be few, if any).</p>
| 1
|
2009-04-17T15:06:33Z
|
[
"python",
"deployment",
"patch",
"py2exe"
] |
Self updating py2exe/py2app application
| 760,383
|
<p>I maintain a cross platform application, based on PyQt that runs on linux mac and windows.</p>
<p>The windows and mac versions are distributed using py2exe and py2app, which produces quite large bundles (~40 MB).</p>
<p>I would like to add an "auto update" functionality, based on patches to limit downloads size:</p>
<ul>
<li>check for new versions on an http server</li>
<li>download the patches needed to update to the last version</li>
<li>apply the patches list and restart the application</li>
</ul>
<p>I have some questions:</p>
<ul>
<li>what is the preferred way to update a windows application since open files are locked and can't be overwritten ?</li>
<li>how do I prepare and apply the patches ? perhaps using <a href="http://www.daemonology.net/bsdiff/">bsdiff/pspatch</a> ?</li>
</ul>
<p><strong>[update]</strong></p>
<p>I made a simple class to make patches with <a href="http://www.daemonology.net/bsdiff/">bsdiff</a>, which is very efficient as advertised on their site : a diff on two py2exe versions of my app (~75 MB uncompressed) produces a 44 kB patch ! Small enough for me, I will stick to this format.</p>
<p>The code is available in the 'update' package of <a href="http://pypi.python.org/pypi/pyflu">pyflu</a>, a small library of Python code.</p>
| 12
|
2009-04-17T13:22:58Z
| 17,540,301
|
<p>This is 4 years old now, but what about <a href="https://pypi.python.org/pypi/esky" rel="nofollow">Esky</a>?</p>
| 2
|
2013-07-09T05:02:48Z
|
[
"python",
"deployment",
"patch",
"py2exe"
] |
Generator function getting executed twice?
| 760,647
|
<p>I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails.</p>
<p>Can anyone point me in the right direction?</p>
<p>Script:</p>
<pre><code>
import os
import sys
import Image
class ThumbnailGenerator:
def __init__(self, width, height, image_path, thumb_path):
self.width = width
self.height = height
self.image_path = image_path
self.thumb_path = "%s%s%s" % (self.image_path, os.sep, thumb_path)
def __call__(self):
self.__create_thumbnail_dir()
for filename, image in self.__generate_image_list():
try:
thumbnail = "%s%s%s" % (self.thumb_path, os.sep, filename)
image.thumbnail((self.width, self.height))
image.save(thumbnail, 'JPEG')
print "Thumbnail gemaakt voor: %s" % filename
except IOError:
print "Fout: thumbnail kon niet gemaakt worden voor: %s" % filename
def __generate_image_list(self):
for dirpath, dirnames, filenames in os.walk(self.image_path):
count = 0
for filename in filenames:
try:
image = Image.open(filename)
print '=========', count, filename
count += 1
yield (filename, image)
except IOError:
pass
def __create_thumbnail_dir(self):
try:
os.mkdir(self.thumb_path)
except OSError as exception:
print "Fout: %s" % exception
if __name__ == '__main__':
try:
thumbnail_generator = ThumbnailGenerator(80, 80, '.', 'thumbs')
thumbnail_generator()
except KeyboardInterrupt:
print 'Programma gestopt'
</code></pre>
<p>The output of the script at this moment (with some test images) is:</p>
<pre>
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
</pre>
<p>While it should be:</p>
<pre>
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
</pre>
<p>As you can see the generator function is returning the list twice (I verified it and it gets called only once).</p>
<p>@heikogerlach:
os.walk cannot find the thumbnails as I'm walking the filenames of the current directory and the thumbnails get written to a sub-folder of the current directory called 'thumb'. The list is generated before writing the thumbnails to the 'thumb' dir and I verified (using WinPDB) that the thumbnails are not included in the list.</p>
<p>@S.Lott:
Thanks for the advice. os.path.join fixed the problem.</p>
| 1
|
2009-04-17T14:35:51Z
| 760,680
|
<p>Your thumbnails are in a subdirectory of <code>self.image_path</code> and have the same name as the original image. Can you check if walk finds the thumnails as you create them? Just print the path of the image together with the name.</p>
| 0
|
2009-04-17T14:46:26Z
|
[
"python",
"generator"
] |
Generator function getting executed twice?
| 760,647
|
<p>I'm using a python generator function to provide me with a list of images in the current directory. However I see the function is giving out the entire list twice instead of one time and I have no idea why. I'm using the Python PIL library to create batch thumbnails.</p>
<p>Can anyone point me in the right direction?</p>
<p>Script:</p>
<pre><code>
import os
import sys
import Image
class ThumbnailGenerator:
def __init__(self, width, height, image_path, thumb_path):
self.width = width
self.height = height
self.image_path = image_path
self.thumb_path = "%s%s%s" % (self.image_path, os.sep, thumb_path)
def __call__(self):
self.__create_thumbnail_dir()
for filename, image in self.__generate_image_list():
try:
thumbnail = "%s%s%s" % (self.thumb_path, os.sep, filename)
image.thumbnail((self.width, self.height))
image.save(thumbnail, 'JPEG')
print "Thumbnail gemaakt voor: %s" % filename
except IOError:
print "Fout: thumbnail kon niet gemaakt worden voor: %s" % filename
def __generate_image_list(self):
for dirpath, dirnames, filenames in os.walk(self.image_path):
count = 0
for filename in filenames:
try:
image = Image.open(filename)
print '=========', count, filename
count += 1
yield (filename, image)
except IOError:
pass
def __create_thumbnail_dir(self):
try:
os.mkdir(self.thumb_path)
except OSError as exception:
print "Fout: %s" % exception
if __name__ == '__main__':
try:
thumbnail_generator = ThumbnailGenerator(80, 80, '.', 'thumbs')
thumbnail_generator()
except KeyboardInterrupt:
print 'Programma gestopt'
</code></pre>
<p>The output of the script at this moment (with some test images) is:</p>
<pre>
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
</pre>
<p>While it should be:</p>
<pre>
========= 0 124415main_image_feature_380a_ys_full.jpg
Thumbnail gemaakt voor: 124415main_image_feature_380a_ys_full.jpg
========= 1 60130main_image_feature_182_jwfull.jpg
Thumbnail gemaakt voor: 60130main_image_feature_182_jwfull.jpg
========= 2 assetImage.jpg
Thumbnail gemaakt voor: assetImage.jpg
========= 3 devcon-c1-image.gif
Fout: thumbnail kon niet gemaakt worden voor: devcon-c1-image.gif
========= 4 image-646313.jpg
Thumbnail gemaakt voor: image-646313.jpg
========= 5 Image-Schloss_Nymphenburg_Munich_CC.jpg
Thumbnail gemaakt voor: Image-Schloss_Nymphenburg_Munich_CC.jpg
========= 6 image1w.jpg
Thumbnail gemaakt voor: image1w.jpg
========= 7 New%20Image.jpg
Thumbnail gemaakt voor: New%20Image.jpg
========= 8 samsung-gx20-image.jpg
Thumbnail gemaakt voor: samsung-gx20-image.jpg
========= 9 samsung-image.jpg
Thumbnail gemaakt voor: samsung-image.jpg
</pre>
<p>As you can see the generator function is returning the list twice (I verified it and it gets called only once).</p>
<p>@heikogerlach:
os.walk cannot find the thumbnails as I'm walking the filenames of the current directory and the thumbnails get written to a sub-folder of the current directory called 'thumb'. The list is generated before writing the thumbnails to the 'thumb' dir and I verified (using WinPDB) that the thumbnails are not included in the list.</p>
<p>@S.Lott:
Thanks for the advice. os.path.join fixed the problem.</p>
| 1
|
2009-04-17T14:35:51Z
| 760,709
|
<p>In your debugging, print the full path. I think you're walking the <code>thumbs</code> subdirectory after you walk the <code>.</code> directory.</p>
<p>Also. </p>
<pre><code>class ThumbnailGenerator( object ):
</code></pre>
<p>Usually works out better in the long run.</p>
<p>Please do NOT use <code>__</code> in front of your method names (generate_image_list and create_thumbnail_dir).</p>
<p>Do not use <code>"%s%s%s" % (self.image_path, os.sep, thumb_path)</code> to make path names, use <code>os.path.join</code>.</p>
| 3
|
2009-04-17T14:51:34Z
|
[
"python",
"generator"
] |
Use value of variable in lambda expression
| 760,688
|
<pre><code>a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
</code></pre>
<p>In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)</p>
<p>How can I tell lambda to pick up the value of i instead of the variable i itself.</p>
| 3
|
2009-04-17T14:47:48Z
| 760,732
|
<p>Ugly, but one way:</p>
<pre><code>for i in range(4)
b.append(lambda x, copy=i: x**copy)
</code></pre>
<p>You might prefer</p>
<pre><code>def raiser(power):
return lambda x: x**power
for i in range(4)
b.append(raiser(i))
</code></pre>
<p>(All code untested.)</p>
| 5
|
2009-04-17T14:56:57Z
|
[
"python",
"lambda"
] |
Use value of variable in lambda expression
| 760,688
|
<pre><code>a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
</code></pre>
<p>In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)</p>
<p>How can I tell lambda to pick up the value of i instead of the variable i itself.</p>
| 3
|
2009-04-17T14:47:48Z
| 760,750
|
<pre><code>b=[]
f=(lambda p:(lambda x:x**p))
for i in range(4):
b.append(f(i))
for g in b:
print g(2)
</code></pre>
| 2
|
2009-04-17T15:00:27Z
|
[
"python",
"lambda"
] |
Use value of variable in lambda expression
| 760,688
|
<pre><code>a = [] a.append(lambda x:x**0)
a.append(lambda x:x**1)
a[0](2), a[1](2), a[2](2)... spits out 1, 2, 4, ...
b=[]
for i in range(4)
b.append(lambda x:x**i)
b[0](2), b[1](2), b[2](2)... spits out 8, 8, 8, ...
</code></pre>
<p>In the for loop, the i is being passed to lambda as a variable, so when I call it, the last value of i is used instead of the code running as it does with a[]. (ie b[0] should use x^1, b[1] should use x^2, ...)</p>
<p>How can I tell lambda to pick up the value of i instead of the variable i itself.</p>
| 3
|
2009-04-17T14:47:48Z
| 760,878
|
<p>Define a factory</p>
<pre><code>def power_function_factory(value):
def new_power_function(base):
return base ** value
return new_power_function
b = []
for i in range(4):
b.append(power_function_factory(i))
</code></pre>
<p>or </p>
<pre><code>b = [power_function_factory(i) for i in range(4)]
</code></pre>
| 2
|
2009-04-17T15:26:41Z
|
[
"python",
"lambda"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,828
|
<p>One solution, although I challenge someone to do better ;-)</p>
<pre><code>a = 'abcdef'
b = [[a[i-1], a[i]] for i in range(1, len(a), 2)]
for x, y in b:
print "%s%s\n" % (x, y)
</code></pre>
| 0
|
2009-04-17T15:13:39Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,829
|
<p>I am sure someone is going to come up with some more "Pythonic" but how about:</p>
<pre><code>for y in range(0, len(x), 2):
print "%s%s" % (x[y], x[y+1])
</code></pre>
<p>Note that this would only work if you know that <code>len(x) % 2 == 0;</code></p>
| 7
|
2009-04-17T15:13:44Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,830
|
<p>you can create the following generator</p>
<pre><code>def chunks(seq, size):
a = range(0, len(seq), size)
b = range(size, len(seq) + 1, size)
for i, j in zip(a, b):
yield seq[i:j]
</code></pre>
<p>and use it like this:</p>
<pre><code>for i in chunks('abcdef', 2):
print(i)
</code></pre>
| 3
|
2009-04-17T15:14:36Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,857
|
<p>A generator function would be neat:</p>
<pre><code>def batch_gen(data, batch_size):
for i in range(0, len(data), batch_size):
yield data[i:i+batch_size]
</code></pre>
<p>Example use:</p>
<pre><code>a = "abcdef"
for i in batch_gen(a, 2): print i
</code></pre>
<p>prints:</p>
<pre><code>ab
cd
ef
</code></pre>
| 39
|
2009-04-17T15:20:36Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,887
|
<p>Don't forget about the zip() function:</p>
<pre><code>a = 'abcdef'
for x,y in zip(a[::2], a[1::2]):
print '%s%s' % (x,y)
</code></pre>
| 10
|
2009-04-17T15:28:48Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 760,899
|
<p>but the more general way would be (inspired by <a href="http://stackoverflow.com/questions/756550/multiple-tuple-to-two-pair-tuple-in-python/756602#756602">this answer</a>):</p>
<pre><code>for i in zip(*(seq[i::size] for i in range(size))):
print(i) # tuple of individual values
</code></pre>
| 6
|
2009-04-17T15:30:53Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 761,125
|
<p>I've got an alternative approach, that works for iterables that don't have a known length. </p>
<pre><code>
def groupsgen(seq, size):
it = iter(seq)
while True:
values = ()
for n in xrange(size):
values += (it.next(),)
yield values
</code></pre>
<p>It works by iterating over the sequence (or other iterator) in groups of size, collecting the values in a tuple. At the end of each group, it yield the tuple.</p>
<p>When the iterator runs out of values, it produces a StopIteration exception which is then propagated up, indicating that groupsgen is out of values.</p>
<p>It assumes that the values come in sets of size (sets of 2, 3, etc). If not, any values left over are just discarded.</p>
| 13
|
2009-04-17T16:24:48Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 782,173
|
<p>How about itertools?</p>
<pre><code>from itertools import islice, groupby
def chunks_islice(seq, size):
while True:
aux = list(islice(seq, 0, size))
if not aux: break
yield "".join(aux)
def chunks_groupby(seq, size):
for k, chunk in groupby(enumerate(seq), lambda x: x[0] / size):
yield "".join([i[1] for i in chunk])
</code></pre>
| 0
|
2009-04-23T15:10:44Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 782,321
|
<pre><code>>>> a = "abcdef"
>>> size = 2
>>> [a[x:x+size] for x in range(0, len(a), size)]
['ab', 'cd', 'ef']
</code></pre>
<p>..or, not as a list comprehension:</p>
<pre><code>a = "abcdef"
size = 2
output = []
for x in range(0, len(a), size):
output.append(a[x:x+size])
</code></pre>
<p>Or, as a generator, which would be best if used multiple times (for a one-use thing, the list comprehension is probably "best"):</p>
<pre><code>def chunker(thelist, segsize):
for x in range(0, len(thelist), segsize):
yield thelist[x:x+segsize]
</code></pre>
<p>..and it's usage:</p>
<pre><code>>>> for seg in chunker(a, 2):
... print seg
...
ab
cd
ef
</code></pre>
| 4
|
2009-04-23T15:41:37Z
|
[
"iteration",
"python"
] |
Iterate over a python sequence in multiples of n?
| 760,753
|
<p>How do I process the elements of a sequence in batches, idiomatically?</p>
<p>For example, with the sequence "abcdef" and a batch size of 2, I would like to do something like the following:</p>
<pre><code>for x, y in "abcdef":
print "%s%s\n" % (x, y)
ab
cd
ef
</code></pre>
<p>Of course, this doesn't work because it is expecting a single element from the list which itself contains 2 elements.</p>
<p>What is a nice, short, clean, pythonic way to process the next n elements of a list in a batch, or sub-strings of length n from a larger string (two similar problems)?</p>
| 17
|
2009-04-17T15:01:35Z
| 787,130
|
<p>And then there's always the <a href="http://docs.python.org/library/itertools.html">documentation</a>.</p>
<pre><code>def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
try:
b.next()
except StopIteration:
pass
return izip(a, b)
def grouper(n, iterable, padvalue=None):
"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
</code></pre>
<p>Note: these produce tuples instead of substrings, when given a string sequence as input.</p>
| 6
|
2009-04-24T18:59:15Z
|
[
"iteration",
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.