title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Simple recursive descent in PyParsing | 1,345,039 | <p>I've tried taking <a href="http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725">this code</a> and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version:</p>
<pre><code>op = oneOf( '+ - / *')
lparen, rparen = Literal('('), Literal(')')
expr = Forward()
expr << ( Word(nums) | ( expr + op + expr ) | ( lparen + expr + rparen) )
</code></pre>
<p>I've played around with a number of different modifications of this simple setup. Usually, trying something like:</p>
<pre><code>print(expr.parseString('1+2'))
</code></pre>
<p>Will return <code>['1']</code>. While I get caught in deep recursion with something like:</p>
<pre><code>print(expr.parseString('(1+2)'))
</code></pre>
<p>What am I missing with respect to simple recursion that I can't parse arbitrarily arithmetic expressions, such as <code>1+(2 * 3-(4*(5+6)-(7))...</code>?</p>
| 17 | 2009-08-28T04:38:13Z | 1,350,314 | <p>Wow, I guess pyparsing is really on the map! Thanks Alex and John for stepping in on this question. You are both on the mark with your responses. But let me add a comment or two:</p>
<ol>
<li><p>If we suppress the opening and closing parenthesis symbols, and group the parenthesized expression using Group, pyparsing will a structured result that is closer to an AST. </p>
<pre><code>from pyparsing import Literal,Word,ZeroOrMore,Forward,nums,oneOf,Group
def Syntax():
op = oneOf( '+ - / *')
lpar = Literal( '(' ).suppress()
rpar = Literal( ')' ).suppress()
num = Word(nums)
expr = Forward()
atom = num | Group( lpar + expr + rpar )
expr << atom + ZeroOrMore( op + expr )
return expr
if __name__ == "__main__":
expr = Syntax()
def test(s):
results = expr.parseString( s )
print s,'->', results
<pre><code>test( "(9 + 3)" )
test( "(9 + 3) * (4 / 5)" )
</code></pre>
</code></pre>
<p>Giving:</p>
<pre><code>(9 + 3) -> [['9', '+', '3']]
(9 + 3) * (4 / 5) -> [['9', '+', '3'], '*', ['4', '/', '5']]
</code></pre>
<p>Otherwise, pyparsing is just tokenizing, and you have to walk the list of parsed tokens to find the nested expressions.</p></li>
<li><p>Since op is defined as just oneOf("+ - * /"), there is no precedence of operations. There are examples on the pyparsing wiki of the manual way to define this (fourFn.py), or the more recent approach using the operatorPrecedence helper (simpleArith.py). Again, this has pyparsing adding more value than just tokenizing.</p></li>
</ol>
<p>To the OP, please check out those examples, I think they will help move you forward on your project.</p>
<p>-- Paul</p>
| 21 | 2009-08-29T03:02:04Z | [
"python",
"pyparsing",
"recursive-descent"
] |
Simple recursive descent in PyParsing | 1,345,039 | <p>I've tried taking <a href="http://stackoverflow.com/questions/634432/need-help-on-making-the-recursive-parser-using-pyparsing/634725#634725">this code</a> and converting it to something for a project I'm working on for programming language processing, but I'm running into an issue with a simplified version:</p>
<pre><code>op = oneOf( '+ - / *')
lparen, rparen = Literal('('), Literal(')')
expr = Forward()
expr << ( Word(nums) | ( expr + op + expr ) | ( lparen + expr + rparen) )
</code></pre>
<p>I've played around with a number of different modifications of this simple setup. Usually, trying something like:</p>
<pre><code>print(expr.parseString('1+2'))
</code></pre>
<p>Will return <code>['1']</code>. While I get caught in deep recursion with something like:</p>
<pre><code>print(expr.parseString('(1+2)'))
</code></pre>
<p>What am I missing with respect to simple recursion that I can't parse arbitrarily arithmetic expressions, such as <code>1+(2 * 3-(4*(5+6)-(7))...</code>?</p>
| 17 | 2009-08-28T04:38:13Z | 21,996,158 | <p>Use <code>operatorPrecedence</code> to build expressions, for example as in the example at <a href="http://pyparsing.wikispaces.com/file/view/simpleArith.py/30268305/simpleArith.py" rel="nofollow">http://pyparsing.wikispaces.com/file/view/simpleArith.py/30268305/simpleArith.py</a>. It'll build the correct expressions, and take care of operator precedence while at it:</p>
<pre><code>num = Word(nums)
plusop = oneOf( '+ -')
multop = oneOf('/ *')
expr = operatorPrecedence(num,
[(multop, 2, opAssoc.LEFT),(plusop, 2, opAssoc.LEFT)])
</code></pre>
<p>example:</p>
<pre><code>>> print parsetime.expr.parseString("1+(2 * 3-(4*(5+6)-(7)))")
[['1', '+', [['2', '*', '3'], '-', [['4', '*', ['5', '+', '6']], '-', '7']]]]
</code></pre>
| 0 | 2014-02-24T18:38:33Z | [
"python",
"pyparsing",
"recursive-descent"
] |
How to set timeout detection on a RabbitMQ server? | 1,345,239 | <p>I am trying out <a href="http://www.rabbitmq.com/">RabbitMQ</a> with <a href="http://barryp.org/software/py-amqplib/">this</a> python binding.</p>
<p>One thing I noticed is that if I kill a consumer uncleanly (emulating a crashed program), the server will think that this consumer is still there for a long time. The result of this is that every other message will be ignored.</p>
<p>For example if you kill a consumer 1 time and reconnect, then 1/2 messages will be ignored. If you kill another consumer, then 2/3 messages will be ignored. If you kill a 3rd, then 3/4 messages will be ignored and so on.</p>
<p>I've tried turning on acknowledgments, but it doesn't seem to be helping. The only solution I have found is to manually stop the server and reset it. </p>
<p>Is there a better way?</p>
<p><strong>How to recreate this scenario</strong></p>
<ul>
<li><p>Run rabbitmq.</p></li>
<li><p>Unarchive <a href="http://barryp.org/static/software/download/py-amqplib/0.6/amqplib-0.6.tgz">this library</a>.</p></li>
<li><p>Download the consumer and publisher <a href="http://blogs.digitar.com/jjww/code-samples/">here</a>.
Run amqp_consumer.py twice. Run amqp_publisher.py, feeding in some data and observe that it works as expected. Messages are received round robin style.</p></li>
<li><p>Kill one of the consumer processes with kill -9 or task manager.</p></li>
<li><p>Now when you publish a message, 50% of the messages will be lost.</p></li>
</ul>
| 16 | 2009-08-28T05:55:14Z | 1,378,968 | <p>Please provide a few more specifics regarding the components you've declared. Usually (and independent of the the client implementation) a queue with the properties</p>
<ul>
<li>exclusive and</li>
<li>auto-delete</li>
</ul>
<p>should get removed as soon as the connection between the declaring client and the broker breaks up. This won't help you with shared queues, though. Please detail a bit what exactly you are trying to model.</p>
| 2 | 2009-09-04T12:37:25Z | [
"python",
"message-queue",
"rabbitmq",
"amqp"
] |
How to set timeout detection on a RabbitMQ server? | 1,345,239 | <p>I am trying out <a href="http://www.rabbitmq.com/">RabbitMQ</a> with <a href="http://barryp.org/software/py-amqplib/">this</a> python binding.</p>
<p>One thing I noticed is that if I kill a consumer uncleanly (emulating a crashed program), the server will think that this consumer is still there for a long time. The result of this is that every other message will be ignored.</p>
<p>For example if you kill a consumer 1 time and reconnect, then 1/2 messages will be ignored. If you kill another consumer, then 2/3 messages will be ignored. If you kill a 3rd, then 3/4 messages will be ignored and so on.</p>
<p>I've tried turning on acknowledgments, but it doesn't seem to be helping. The only solution I have found is to manually stop the server and reset it. </p>
<p>Is there a better way?</p>
<p><strong>How to recreate this scenario</strong></p>
<ul>
<li><p>Run rabbitmq.</p></li>
<li><p>Unarchive <a href="http://barryp.org/static/software/download/py-amqplib/0.6/amqplib-0.6.tgz">this library</a>.</p></li>
<li><p>Download the consumer and publisher <a href="http://blogs.digitar.com/jjww/code-samples/">here</a>.
Run amqp_consumer.py twice. Run amqp_publisher.py, feeding in some data and observe that it works as expected. Messages are received round robin style.</p></li>
<li><p>Kill one of the consumer processes with kill -9 or task manager.</p></li>
<li><p>Now when you publish a message, 50% of the messages will be lost.</p></li>
</ul>
| 16 | 2009-08-28T05:55:14Z | 1,384,438 | <p>RabbitMQ doesn't have a timeout on acknowledgements from the client that a message has been processed: see <a href="http://lists.rabbitmq.com/pipermail/rabbitmq-discuss/2009-March/003158.html">this post</a> (the whole thread might be of interest). Some salient points from the post:</p>
<blockquote>
<p>The AMQP ack model for subscriptions
and "pull" are identical. In both
cases the message is kept on the
server but is unavailable to other
consumers until it either has been
ack'ed (and gets removed), nack'ed
(with basic.reject; though RabbitMQ
does not implement that) or the
channel/connection is closed (at which
point the message becomes available
to other consumers).</p>
</blockquote>
<p>and (my emphases)</p>
<blockquote>
<p>There is no timeout on waiting for
acks. Usually that is not a problem
<strong>since the common cases of a missing
ack - network or client failure -
will result in the connection getting
dropped</strong> (and thus trigger the
behaviour described above). Still,
a timeout could be useful to, say,
deal with <strong>alive but unresponsive
consumers</strong>. That has come up in
discussion before. Is there a specific
use case you have in mind that
requires such functionality?</p>
</blockquote>
<p>The problem might well be occurring because in a client pull model, it's harder for the server to detect a broken connection (as opposed to an alive but unresponsive consumer), particularly as the server seems happy to wait forever for an ack.</p>
<p><strong>Update:</strong> On Linux, you can attach signal handlers for SIGTERM and/or SIGKILL and/or SIGINT and hopefully close down the connection in an orderly way from the client. On Windows, I believe closing from Task Manager invokes the Win32 <code>TerminateProcess</code> API, about which MSDN says:</p>
<blockquote>
<p>If a process is terminated by
<code>TerminateProcess</code>, all threads of the
process are terminated immediately
with no chance to run additional code.
This means that the thread does not
execute code in termination handler
blocks. In addition, no attached DLLs
are notified that the process is
detaching.</p>
</blockquote>
<p>This means it might be difficult to catch termination and close down in an orderly way.</p>
<p>It might be worth pursuing on the RabbitMQ list with your own use case for an ack timeout.</p>
| 5 | 2009-09-05T22:46:53Z | [
"python",
"message-queue",
"rabbitmq",
"amqp"
] |
How to set timeout detection on a RabbitMQ server? | 1,345,239 | <p>I am trying out <a href="http://www.rabbitmq.com/">RabbitMQ</a> with <a href="http://barryp.org/software/py-amqplib/">this</a> python binding.</p>
<p>One thing I noticed is that if I kill a consumer uncleanly (emulating a crashed program), the server will think that this consumer is still there for a long time. The result of this is that every other message will be ignored.</p>
<p>For example if you kill a consumer 1 time and reconnect, then 1/2 messages will be ignored. If you kill another consumer, then 2/3 messages will be ignored. If you kill a 3rd, then 3/4 messages will be ignored and so on.</p>
<p>I've tried turning on acknowledgments, but it doesn't seem to be helping. The only solution I have found is to manually stop the server and reset it. </p>
<p>Is there a better way?</p>
<p><strong>How to recreate this scenario</strong></p>
<ul>
<li><p>Run rabbitmq.</p></li>
<li><p>Unarchive <a href="http://barryp.org/static/software/download/py-amqplib/0.6/amqplib-0.6.tgz">this library</a>.</p></li>
<li><p>Download the consumer and publisher <a href="http://blogs.digitar.com/jjww/code-samples/">here</a>.
Run amqp_consumer.py twice. Run amqp_publisher.py, feeding in some data and observe that it works as expected. Messages are received round robin style.</p></li>
<li><p>Kill one of the consumer processes with kill -9 or task manager.</p></li>
<li><p>Now when you publish a message, 50% of the messages will be lost.</p></li>
</ul>
| 16 | 2009-08-28T05:55:14Z | 1,385,416 | <p>I don't see <code>amqp_consumer.py</code> or <code>amqp_producer.py</code> in the tarball, so reproducing the fault is tricky.</p>
<p>RabbitMQ terminates connections, releasing their unacknowledged messages for redelivery to other clients, whenever it is told by the operating system that a socket has closed. Your symptoms are very strange, in that even a <code>kill -9</code> ought to cause the TCP socket to be cleaned up properly.</p>
<p>Some people have noticed problems with sockets surviving longer than they should when running with a firewall or NAT device between the AMQP clients and the server. Could that be an issue here, or are you running everything on localhost? Also, what operating system are you running the various components of the system on?</p>
<p><strong>ETA:</strong> From your comment below, I am guessing that while you are running the server on Linux, you may be running the clients on Windows. If this is the case, then it could be that the Windows TCP driver is not closing the sockets correctly, which is different from the kill-9 behaviour on Unix. (On Unix, the kernel will properly close the TCP connections on any killed process.)</p>
<p>If that's the case, then the <strong>bad news</strong> is that RabbitMQ can only release resources when the socket is closed, so if the client operating system doesn't do that, there's nothing it can do. This is the same as almost every other TCP-based service out there.</p>
<p>The <strong>good news</strong>, though, is that AMQP supports a "heartbeat" option for exactly these cases, where the networking fabric is untrustworthy. You could try enabling heartbeats. When they're enabled, if the server doesn't receive any traffic within a configurable interval, it decides that the connection must be dead.</p>
<p>The <strong>bad news</strong>, however, is that I don't think py-amqplib supports heartbeats at the moment. Worth a try, though!</p>
| 11 | 2009-09-06T11:14:32Z | [
"python",
"message-queue",
"rabbitmq",
"amqp"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 1,345,291 | <blockquote>
<p><a href="http://docs.python.org/library/functions.html#map" rel="nofollow">map</a>(<a href="http://docs.python.org/library/functions.html#int" rel="nofollow">int</a>, ["1", "2", "3"]) </p>
</blockquote>
<p>gives</p>
<pre><code>[1, 2, 3]
</code></pre>
| 16 | 2009-08-28T06:13:32Z | [
"python"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 1,345,294 | <p>Try this method:</p>
<pre><code>>>> int('5')
5
</code></pre>
| 2 | 2009-08-28T06:14:26Z | [
"python"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 1,345,298 | <p>Like this:</p>
<pre><code>map(int, ['1', '2', '3'])
</code></pre>
| 2 | 2009-08-28T06:15:23Z | [
"python"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 1,345,299 | <p>As Long as the strings are of the form '1' rather than 'one' then you can use the int() function. </p>
<p>Some sample code would be</p>
<pre><code>strList = ['1','2','3']
numList = [int(x) for x in strList]
</code></pre>
<p>Or without the list comprehension</p>
<pre><code>strList = ['1','2','3']
numList = []
for x in strList:
numList.append(int(x))
</code></pre>
<p>Both examples iterate through the list on strings and apply the int() function to the value.</p>
| 5 | 2009-08-28T06:15:31Z | [
"python"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 1,345,303 | <p>Use <a href="http://docs.python.org/library/functions.html#int"><code>int()</code></a> and a <a href="http://docs.python.org/tutorial/datastructures.html">list comprehensions</a>: </p>
<pre><code>>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]
</code></pre>
| 10 | 2009-08-28T06:16:47Z | [
"python"
] |
How can I convert a list of strings into numeric values? | 1,345,287 | <p>How can I convert a list of strings (each of which represents a number, i.e. <code>[â1â, â2â, â3â]</code>) into numeric values.</p>
| 0 | 2009-08-28T06:11:04Z | 8,378,198 | <pre><code>a=['1','2','3']
map(lambda x: int(x),a)
> [1, 2, 3]
</code></pre>
| 0 | 2011-12-04T20:00:59Z | [
"python"
] |
How to efficiently determine if webpage comes from a website | 1,345,341 | <p>I have some unknown webpages and I want to determine which websites they come from. I have example webpages from each website and I assume each website has a distinctive template.
I do not need complete certainty, and don't want to use too much resources matching each webpage. So crawling each website for the webpage is out of the question.</p>
<p>I imagine the best way is to compare the tree structure of each webpage's DOM. Are there any libraries that will do this?</p>
<p>Ideally I am after a Python based solution, but if there is an algorithm I can understand and implement then I would be interested in that too.</p>
<p>Thanks</p>
| 1 | 2009-08-28T06:31:49Z | 1,345,621 | <p>A quick and dirty way you can try is to split html source in html tags, then compare the resultant collections of strings. You should end up with collection of tags and content, say:</p>
<pre><code>item[n] ="<p>"
item[n+2] ="This is some content"
item[n+2] ="</p>"
</code></pre>
<p>I think a regex can do this in about every language.</p>
<p>Some content, other than tags, would be the same (menus and so on). I think a numeric comparison of occurrences should be enough. You can improve by giving kinda "points" when you have same tag/content in the same position. Probably a "combo" of a decent number of collection items can give you certainty.</p>
| 0 | 2009-08-28T08:02:54Z | [
"python",
"dom",
"website",
"webpage"
] |
How to efficiently determine if webpage comes from a website | 1,345,341 | <p>I have some unknown webpages and I want to determine which websites they come from. I have example webpages from each website and I assume each website has a distinctive template.
I do not need complete certainty, and don't want to use too much resources matching each webpage. So crawling each website for the webpage is out of the question.</p>
<p>I imagine the best way is to compare the tree structure of each webpage's DOM. Are there any libraries that will do this?</p>
<p>Ideally I am after a Python based solution, but if there is an algorithm I can understand and implement then I would be interested in that too.</p>
<p>Thanks</p>
| 1 | 2009-08-28T06:31:49Z | 1,346,017 | <p>You could do this via Bayes classification. Feed a few pages from each site into the classifier first, then future pages can be tested against them to see how closely they match.</p>
<p>Bayes classifier library available here: <a href="http://www.divmod.org/trac/wiki/DivmodReverend" rel="nofollow">reverend</a> (LGPL)</p>
<p>Simplified example:</p>
<pre><code># initialisation
from reverend.thomas import Bayes
guesser = Bayes()
guesser.train('site one', site_one_page_one_data)
guesser.train('site one', site_one_page_two_data)
# ...etc...
guesser.train('site two', site_two_page_one_data)
guesser.train('site two', site_two_page_two_data)
# ...etc...
guesser.save()
# run time
guesser.load()
results = guesser.guess(page_I_want_to_classify)
</code></pre>
<p>For better results, tokenise the HTML first. But that might not be necessary.</p>
| 4 | 2009-08-28T09:50:36Z | [
"python",
"dom",
"website",
"webpage"
] |
command line arg parsing through introspection | 1,345,448 | <p>I'm developing a management script that does a fairly large amount of work via a plethora of command-line options. The first few iterations of the script have used optparse to collect user input and then just run down the page, testing the value of each option in the appropriate order, and doing the action if necessary. This has resulted in a jungle of code that's really hard to read and maintain.</p>
<p>I'm looking for something better.</p>
<p>My hope is to have a system where I can write functions in more or less normal python fashion, and then when the script is run, have options (and help text) generated from my functions, parsed, and executed in the appropriate order. Additionally, I'd REALLY like to be able to build django-style sub-command interfaces, where <code>myscript.py install</code> works completely separately from <code>myscript.py remove</code> (separate options, help, etc.)</p>
<p>I've found <a href="http://github.com/simonw/optfunc/tree/master" rel="nofollow">simon willison's optfunc</a> and it does a lot of this, but seems to just miss the mark â I want to write each OPTION as a function, rather than try to compress the whole option set into a huge string of options. </p>
<p>I imagine an architecture involving a set of classes for major functions, and each defined method of the class corresponding to a particular option in the command line. This structure provides the advantage of having each option reside near the functional code it modifies, easing maintenance. The thing I don't know quite how to deal with is the ordering of the commands, since the ordering of class methods is not deterministic.</p>
<p>Before I go reinventing the wheel: Are there any other existing bits of code that behave similarly? Other things that would be easy to modify? Asking the question has clarified my own thinking on what would be nice, but feedback on why this is a terrible idea, or how it should work would be welcome.</p>
| 4 | 2009-08-28T06:58:04Z | 1,346,134 | <p>Don't waste time on "introspection". </p>
<p>Each "Command" or "Option" is an object with two sets of method functions or attributes.</p>
<ol>
<li><p>Provide setup information to optparse.</p></li>
<li><p>Actually do the work.</p></li>
</ol>
<p>Here's the superclass for all commands</p>
<pre><code>class Command( object ):
name= "name"
def setup_opts( self, parser ):
"""Add any options to the parser that this command needs."""
pass
def execute( self, context, options, args ):
"""Execute the command in some application context with some options and args."""
raise NotImplemented
</code></pre>
<p>You create sublcasses for <code>Install</code> and <code>Remove</code> and every other command you need.</p>
<p>Your overall application looks something like this.</p>
<pre><code>commands = [
Install(),
Remove(),
]
def main():
parser= optparse.OptionParser()
for c in commands:
c.setup_opts( parser )
options, args = parser.parse()
command= None
for c in commands:
if c.name.startswith(args[0].lower()):
command= c
break
if command:
status= command.execute( context, options, args[1:] )
else:
logger.error( "Command %r is unknown", args[0] )
status= 2
sys.exit( status )
</code></pre>
| 3 | 2009-08-28T10:19:58Z | [
"python",
"command-line",
"parsing"
] |
command line arg parsing through introspection | 1,345,448 | <p>I'm developing a management script that does a fairly large amount of work via a plethora of command-line options. The first few iterations of the script have used optparse to collect user input and then just run down the page, testing the value of each option in the appropriate order, and doing the action if necessary. This has resulted in a jungle of code that's really hard to read and maintain.</p>
<p>I'm looking for something better.</p>
<p>My hope is to have a system where I can write functions in more or less normal python fashion, and then when the script is run, have options (and help text) generated from my functions, parsed, and executed in the appropriate order. Additionally, I'd REALLY like to be able to build django-style sub-command interfaces, where <code>myscript.py install</code> works completely separately from <code>myscript.py remove</code> (separate options, help, etc.)</p>
<p>I've found <a href="http://github.com/simonw/optfunc/tree/master" rel="nofollow">simon willison's optfunc</a> and it does a lot of this, but seems to just miss the mark â I want to write each OPTION as a function, rather than try to compress the whole option set into a huge string of options. </p>
<p>I imagine an architecture involving a set of classes for major functions, and each defined method of the class corresponding to a particular option in the command line. This structure provides the advantage of having each option reside near the functional code it modifies, easing maintenance. The thing I don't know quite how to deal with is the ordering of the commands, since the ordering of class methods is not deterministic.</p>
<p>Before I go reinventing the wheel: Are there any other existing bits of code that behave similarly? Other things that would be easy to modify? Asking the question has clarified my own thinking on what would be nice, but feedback on why this is a terrible idea, or how it should work would be welcome.</p>
| 4 | 2009-08-28T06:58:04Z | 1,346,756 | <p>The WSGI library werkzeug provides <strong><a href="http://werkzeug.pocoo.org/documentation/dev/script.html" rel="nofollow">Management Script Utilities</a></strong> which may do what you want, or at least give you a hint how to do the introspection yourself.</p>
<pre><code>from werkzeug import script
# actions go here
def action_test():
"sample with no args"
pass
def action_foo(name=2, value="test"):
"do some foo"
pass
if __name__ == '__main__':
script.run()
</code></pre>
<p>Which will generate the following help message:</p>
<pre><code>$ python /tmp/test.py --help
usage: test.py <action> [<options>]
test.py --help
actions:
foo:
do some foo
--name integer 2
--value string test
test:
sample with no args
</code></pre>
<p>An action is a function in the same module starting with "action_" which takes a number of arguments where every argument has a default. The type of the default value specifies the type of the argument.</p>
<p>Arguments can then be passed by position or using --name=value from the shell.</p>
| 0 | 2009-08-28T12:37:48Z | [
"python",
"command-line",
"parsing"
] |
How to quickly (easy to script) preview 3D vectors / lines? | 1,345,485 | <p>I am busy reading 3D building models from a tool and thus generating a bunch of <code>Line(p1, p2)</code> objects, each consisting of two <code>Point(x, y, z)</code> objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).</p>
<p>The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.</p>
<p>What format / tool would you use to view the data?</p>
<p>(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)</p>
<p>I did check the mathplot library, but that seems to only plot functions...</p>
<p><strong>EDIT:</strong> I eventually did go the X3D route and wrote a <a href="http://darenatwork.blogspot.com/2010/02/how-to-create-3d-wireframe-with-x3d.html" rel="nofollow">little blog post on how to do it</a>. Here is a sample X3D wireframe file for a 1x1x1 cube:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
</code></pre>
| 2 | 2009-08-28T07:08:40Z | 1,345,557 | <p>I'm not a 3D-programming expert but there is a simple trick you can do.<br>
If you <em>imagine</em> that the <code>z</code> axis is vertical to your screen then you can project a 3D point <code>(x, y, z)</code> like this: <code>(zoom_factor*(x/z), zoom_factor*(y/z))</code></p>
| 1 | 2009-08-28T07:35:26Z | [
".net",
"python",
"3d",
"ironpython"
] |
How to quickly (easy to script) preview 3D vectors / lines? | 1,345,485 | <p>I am busy reading 3D building models from a tool and thus generating a bunch of <code>Line(p1, p2)</code> objects, each consisting of two <code>Point(x, y, z)</code> objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).</p>
<p>The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.</p>
<p>What format / tool would you use to view the data?</p>
<p>(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)</p>
<p>I did check the mathplot library, but that seems to only plot functions...</p>
<p><strong>EDIT:</strong> I eventually did go the X3D route and wrote a <a href="http://darenatwork.blogspot.com/2010/02/how-to-create-3d-wireframe-with-x3d.html" rel="nofollow">little blog post on how to do it</a>. Here is a sample X3D wireframe file for a 1x1x1 cube:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
</code></pre>
| 2 | 2009-08-28T07:08:40Z | 1,347,584 | <p>You might try the <a href="http://pyqwt.sourceforge.net/" rel="nofollow">PyQwt3D</a> package. If that doesn't work, here's a <a href="http://www.vrplumber.com/py3d.py" rel="nofollow">list of other python packages</a> that might be useful.</p>
| 1 | 2009-08-28T15:03:35Z | [
".net",
"python",
"3d",
"ironpython"
] |
How to quickly (easy to script) preview 3D vectors / lines? | 1,345,485 | <p>I am busy reading 3D building models from a tool and thus generating a bunch of <code>Line(p1, p2)</code> objects, each consisting of two <code>Point(x, y, z)</code> objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).</p>
<p>The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.</p>
<p>What format / tool would you use to view the data?</p>
<p>(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)</p>
<p>I did check the mathplot library, but that seems to only plot functions...</p>
<p><strong>EDIT:</strong> I eventually did go the X3D route and wrote a <a href="http://darenatwork.blogspot.com/2010/02/how-to-create-3d-wireframe-with-x3d.html" rel="nofollow">little blog post on how to do it</a>. Here is a sample X3D wireframe file for a 1x1x1 cube:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
</code></pre>
| 2 | 2009-08-28T07:08:40Z | 1,362,062 | <p>For using the writing to file approach you could investigate <a href="http://en.wikipedia.org/wiki/X3D" rel="nofollow">X3D</a>, which is the successor to VRML. Also see <a href="http://en.wikipedia.org/wiki/List%5Fof%5Fvector%5Fgraphics%5Fmarkup%5Flanguages" rel="nofollow">this list of vector graphics markup languages</a> </p>
| 1 | 2009-09-01T11:50:17Z | [
".net",
"python",
"3d",
"ironpython"
] |
How to quickly (easy to script) preview 3D vectors / lines? | 1,345,485 | <p>I am busy reading 3D building models from a tool and thus generating a bunch of <code>Line(p1, p2)</code> objects, each consisting of two <code>Point(x, y, z)</code> objects. I would like to display these things in a simple 3D viewer, kind of like SVG (which, as I understand, only supports 2D).</p>
<p>The reading is done in Python, specifically IronPython. I could use either a .NET viewer library or write out a text/xml/whatnot file with the data to be displayed by manually opening the result in the appropriate program.</p>
<p>What format / tool would you use to view the data?</p>
<p>(At the moment, this is only for debugging purposes, so it doesn't have to be top-notch. Just a wire-frame will do!)</p>
<p>I did check the mathplot library, but that seems to only plot functions...</p>
<p><strong>EDIT:</strong> I eventually did go the X3D route and wrote a <a href="http://darenatwork.blogspot.com/2010/02/how-to-create-3d-wireframe-with-x3d.html" rel="nofollow">little blog post on how to do it</a>. Here is a sample X3D wireframe file for a 1x1x1 cube:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
"http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
<Scene>
<Transform>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 0
1 1 0
0 1 0
0 0 0
1 0 0"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="1 0 1
1 1 1
0 1 1
0 0 1
1 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 0 1
1 0 1
1 0 0
0 0 0
0 0 1"
/>
</LineSet>
</Shape>
<Shape>
<LineSet vertexCount="5">
<Coordinate point="0 1 1
1 1 1
1 1 0
0 1 0
0 1 1"
/>
</LineSet>
</Shape>
</Transform>
</Scene>
</X3D>
</code></pre>
| 2 | 2009-08-28T07:08:40Z | 2,335,105 | <p>You could look at POV-Ray. It's a ray tracer that has its own text based scene description language. IIRC, there is a python module which will generate the scene files, if not, it wouldn't be difficult to do by hand. Displaying line segments at low resolution should render fairly quickly.</p>
<p>Check here: <a href="http://code.activestate.com/recipes/205451/" rel="nofollow">http://code.activestate.com/recipes/205451/</a></p>
<p>Also, python is the scripting language for Blender.</p>
| 1 | 2010-02-25T15:21:24Z | [
".net",
"python",
"3d",
"ironpython"
] |
Determine if an executable (or library) is 32 -or 64-bits (on Windows) | 1,345,632 | <p>I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits.</p>
<p>Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?</p>
| 5 | 2009-08-28T08:05:38Z | 1,345,697 | <p>The Windows API for this is <a href="http://msdn.microsoft.com/en-us/library/aa364819%28VS.85%29.aspx"><code>GetBinaryType</code></a>. You can call this from Python using <a href="http://sourceforge.net/projects/pywin32/files/">pywin32</a>:</p>
<pre><code>import win32file
type=GetBinaryType("myfile.exe")
if type==win32file.SCS_32BIT_BINARY:
print "32 bit"
# And so on
</code></pre>
<p>If you want to do this without pywin32, you'll have to read the <a href="http://en.wikipedia.org/wiki/Portable%5Fexecutable">PE header</a> yourself. Here's <a href="http://www.neowin.net/forum/index.php?showtopic=732648&st=0&p=590544108&#entry590544108">an example</a> in C#, and here's a quick port to Python:</p>
<pre><code>import struct
IMAGE_FILE_MACHINE_I386=332
IMAGE_FILE_MACHINE_IA64=512
IMAGE_FILE_MACHINE_AMD64=34404
f=open("c:\windows\explorer.exe", "rb")
s=f.read(2)
if s!="MZ":
print "Not an EXE file"
else:
f.seek(60)
s=f.read(4)
header_offset=struct.unpack("<L", s)[0]
f.seek(header_offset+4)
s=f.read(2)
machine=struct.unpack("<H", s)[0]
if machine==IMAGE_FILE_MACHINE_I386:
print "IA-32 (32-bit x86)"
elif machine==IMAGE_FILE_MACHINE_IA64:
print "IA-64 (Itanium)"
elif machine==IMAGE_FILE_MACHINE_AMD64:
print "AMD64 (64-bit x86)"
else:
print "Unknown architecture"
f.close()
</code></pre>
| 17 | 2009-08-28T08:27:12Z | [
"python",
"windows",
"dll",
"64bit",
"executable"
] |
Determine if an executable (or library) is 32 -or 64-bits (on Windows) | 1,345,632 | <p>I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits.</p>
<p>Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?</p>
| 5 | 2009-08-28T08:05:38Z | 1,351,790 | <p>If you're running Python 2.5 or later on Windows, you could also use the Windows API without pywin32 by using ctypes.</p>
<pre><code>from ctypes import windll, POINTER
from ctypes.wintypes import LPWSTR, DWORD, BOOL
SCS_32BIT_BINARY = 0 # A 32-bit Windows-based application
SCS_64BIT_BINARY = 6 # A 64-bit Windows-based application
SCS_DOS_BINARY = 1 # An MS-DOS-based application
SCS_OS216_BINARY = 5 # A 16-bit OS/2-based application
SCS_PIF_BINARY = 3 # A PIF file that executes an MS-DOS-based application
SCS_POSIX_BINARY = 4 # A POSIX-based application
SCS_WOW_BINARY = 2 # A 16-bit Windows-based application
_GetBinaryType = windll.kernel32.GetBinaryTypeW
_GetBinaryType.argtypes = (LPWSTR, POINTER(DWORD))
_GetBinaryType.restype = BOOL
def GetBinaryType(filepath):
res = DWORD()
handle_nonzero_success(_GetBinaryType(filepath, res))
return res
</code></pre>
<p>Then use GetBinaryType just like you would with win32file.GetBinaryType.</p>
<p>Note, you would have to implement handle_nonzero_success, which basically throws an exception if the return value is 0.</p>
| 4 | 2009-08-29T16:08:37Z | [
"python",
"windows",
"dll",
"64bit",
"executable"
] |
Determine if an executable (or library) is 32 -or 64-bits (on Windows) | 1,345,632 | <p>I am trying to find out if a given executable (or library) is compiled for 32-bits or 64-bits from Python. I am running Vista 64-bits and would like to determine if a certain application in a directory is compiled for 32-bits or 64-bits.</p>
<p>Is there a simple way to do this using only the standard Python libraries (currently using 2.5.4)?</p>
| 5 | 2009-08-28T08:05:38Z | 39,762,731 | <p>I was able to use Martin B's answer successfully in a Python 3.5 program after making this adjustment:</p>
<pre><code>s=f.read(2).decode(encoding="utf-8", errors="strict")
</code></pre>
<p>Originally it worked just fine with my program in Python 2.7, but after making other necessary changes, I discovered I was getting b'MZ', and decoding it appears to fix this.</p>
| 0 | 2016-09-29T06:16:46Z | [
"python",
"windows",
"dll",
"64bit",
"executable"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 1,345,847 | <p>Just subtract one from the other. You get a <code>timedelta</code> object with the difference.</p>
<pre><code>>>> import datetime
>>> d1 = datetime.datetime.now()
>>> d2 = datetime.datetime.now() # after a 5-second or so pause
>>> d2 - d1
datetime.timedelta(0, 5, 203000)
</code></pre>
<p>You can convert <code>dd.days</code>, <code>dd.seconds</code> and <code>dd.microseconds</code> to minutes.</p>
| 15 | 2009-08-28T09:06:47Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 1,345,852 | <pre><code>>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 86400 + c.seconds, 60)
(0, 8) # 0 minutes, 8 seconds
</code></pre>
| 129 | 2009-08-28T09:08:13Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 12,654,426 | <p>New at Python 2.7 is the <code>timedelta</code> instance method <code>.total_seconds()</code>. From the Python docs, this is equivalent to <code>(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6</code>.</p>
<p>Reference: <a href="http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds">http://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds</a></p>
<pre><code>>>> import datetime
>>> time1 = datetime.datetime.now()
>>> time2 = datetime.datetime.now() # waited a few minutes before pressing enter
>>> elapsedTime = time2 - time1
>>> elapsedTime
datetime.timedelta(0, 125, 749430)
>>> divmod(elapsedTime.total_seconds(), 60)
(2.0, 5.749430000000004) # divmod returns quotient and remainder
# 2 minutes, 5.74943 seconds
</code></pre>
| 71 | 2012-09-29T16:35:40Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 16,755,333 | <p>This is how I get the number of hours that elapsed between two datetime.datetime objects:</p>
<pre><code>before = datetime.datetime.now()
after = datetime.datetime.now()
hours = math.floor(((after - before).seconds) / 3600)
</code></pre>
| 6 | 2013-05-26T01:11:21Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 22,768,924 | <p>Use divmod:</p>
<pre><code>now = int(time.time()) # epoch seconds
then = now - 90000 # some time in the past
d = divmod(now-then,86400) # days
h = divmod(d[1],3600) # hours
m = divmod(h[1],60) # minutes
s = m[1] # seconds
print '%d days, %d hours, %d minutes, %d seconds' % (d[0],h[0],m[0],s)
</code></pre>
| 8 | 2014-03-31T18:05:09Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 26,586,568 | <p>This is my approach using <a href="https://docs.python.org/2/library/time.html#time.mktime" rel="nofollow">mktime</a>.</p>
<pre><code>from datetime import datetime, timedelta
from time import mktime
yesterday = datetime.now() - timedelta(days=1)
today = datetime.now()
difference_in_seconds = abs(mktime(yesterday.timetuple()) - mktime(today.timetuple()))
difference_in_minutes = difference_in_seconds / 60
</code></pre>
| 1 | 2014-10-27T11:28:24Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 26,586,909 | <p>If <code>a</code>, <code>b</code> are datetime objects then to find the time difference between them in Python 3:</p>
<pre><code>from datetime import timedelta
time_difference = a - b
time_difference_in_minutes = time_difference / timedelta(minutes=1)
</code></pre>
<p>On earlier Python versions:</p>
<pre><code>time_difference_in_minutes = time_difference.total_seconds() / 60
</code></pre>
<p>If <code>a</code>, <code>b</code> are naive datetime objects such as returned by <code>datetime.now()</code> then the result may be wrong if the objects represent local time with different UTC offsets e.g., around DST transitions or for past/future dates. More details: <a href="http://stackoverflow.com/a/26313848/4279">Find if 24 hrs have passed between datetimes - Python</a>.</p>
<p>To get reliable results, use UTC time or timezone-aware datetime objects.</p>
| 6 | 2014-10-27T11:49:16Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 32,527,383 | <p>To just find the number of days: timedelta has a 'days' attribute. You can simply query that.</p>
<pre><code>>>>from datetime import datetime, timedelta
>>>d1 = datetime(2015, 9, 12, 13, 9, 45)
>>>d2 = datetime(2015, 8, 29, 21, 10, 12)
>>>d3 = d1- d2
>>>print d3
13 days, 15:59:33
>>>print d3.days
13
</code></pre>
| 1 | 2015-09-11T15:49:20Z | [
"python",
"datetime"
] |
How do I find the time difference between two datetime objects in python? | 1,345,827 | <p>How do I tell the time difference in minutes between two <code>datetime</code> objects?</p>
| 117 | 2009-08-28T09:03:15Z | 37,492,704 | <p>Just thought it might be useful to mention formatting as well in regards to timedelta. strptime() parses a string representing a time according to a format.</p>
<pre><code>import datetime
from datetime import timedelta
datetimeFormat = '%Y/%m/%d %H:%M:%S.%f'
time1 = '2016/03/16 10:01:28.585'
time2 = '2016/03/16 09:56:28.067'
timedelta = datetime.datetime.strptime(time1, datetimeFormat) - datetime.datetime.strptime(time2,datetimeFormat)
</code></pre>
<p>This will output:
0:05:00.518000</p>
| 2 | 2016-05-27T21:46:44Z | [
"python",
"datetime"
] |
What's the most Pythonic way of determining endianness? | 1,346,034 | <p>I'm trying to find the best way of working out whether the machine my code is running on is big-endian or little-endian. I have a solution that works (although I haven't tested it on a big-endian machine) but it seems a bit clunky:</p>
<pre><code>import struct
little_endian = (struct.pack('@h', 1) == struct.pack('<h', 1))
</code></pre>
<p>This is just comparing a 'native' two-byte pack to a little-endian pack. Is there a prettier way?</p>
| 26 | 2009-08-28T09:55:21Z | 1,346,039 | <p>The answer is in the <a href="http://docs.python.org/library/sys.html">sys module</a>:</p>
<pre><code>>>> import sys
>>> sys.byteorder
'little'
</code></pre>
<p>Of course depending on your machine it may return <code>'big'</code>. Your method should certainly work too though.</p>
| 57 | 2009-08-28T09:56:17Z | [
"python",
"endianness",
"little-endian",
"big-endian"
] |
Threads in python | 1,346,098 | <p>I am beginar in python script. I want read msaccess database records and write into XML file.
Access database table have more than 20000 records.</p>
<p>Now i am able to do but , it is taking 4 to 5 minutes. So i implement threading concept. But threading also taking more than 5 to 6 minutes. Because each thread open datasource reading records from tables and close datasource.</p>
<p>I don't know how to solve the problems.</p>
<h1>CODE:</h1>
<pre><code>class ConfigDataHandler(Thread):
def __init__(self, dev):
Thread.__init__(self)
self.dev = dev
def run(self):
db_source_path = r'D:\sampleDB.mdb'
db_source = win32com.client.Dispatch(r'ADODB.Connection')
db_source.ConnectionString = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;
DATA SOURCE=' + db_source_path + ';'
db_source.Open()
query = """ SELECT * from table"""
source_rs = win32com.client.Dispatch(r'ADODB.Recordset')
source_rs.Open(query, db_source, 3, 1)
while not source_rs.EOF :
f_units.append(source_rs.fields("Name").Value))
source_rs.MoveNext()
source_rs.Close()
db_source.Close()
out = render(f_units)
open("D:/test.xml", "w").write(out)
d_list = get_dev_list()
for d in d_list:
current = ConfigDataHandler(d)
current.start()
</code></pre>
| 0 | 2009-08-28T10:12:44Z | 1,346,176 | <p>As mentioned please paste your code snippet. First - threads have a synchronisation overhead which is causing multi-threads to run slower.</p>
<p>Second - the msaccess/JET database is very slow and not really suited to multi-threaded use. You might like to consider SQL Server instead - SQL Server Express is free.</p>
<p>Third - it is probably the database slowing down the processing. What indexes do you have? What queries are you making? What does "explain" say?</p>
| 5 | 2009-08-28T10:30:30Z | [
"python",
"multithreading"
] |
Threads in python | 1,346,098 | <p>I am beginar in python script. I want read msaccess database records and write into XML file.
Access database table have more than 20000 records.</p>
<p>Now i am able to do but , it is taking 4 to 5 minutes. So i implement threading concept. But threading also taking more than 5 to 6 minutes. Because each thread open datasource reading records from tables and close datasource.</p>
<p>I don't know how to solve the problems.</p>
<h1>CODE:</h1>
<pre><code>class ConfigDataHandler(Thread):
def __init__(self, dev):
Thread.__init__(self)
self.dev = dev
def run(self):
db_source_path = r'D:\sampleDB.mdb'
db_source = win32com.client.Dispatch(r'ADODB.Connection')
db_source.ConnectionString = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;
DATA SOURCE=' + db_source_path + ';'
db_source.Open()
query = """ SELECT * from table"""
source_rs = win32com.client.Dispatch(r'ADODB.Recordset')
source_rs.Open(query, db_source, 3, 1)
while not source_rs.EOF :
f_units.append(source_rs.fields("Name").Value))
source_rs.MoveNext()
source_rs.Close()
db_source.Close()
out = render(f_units)
open("D:/test.xml", "w").write(out)
d_list = get_dev_list()
for d in d_list:
current = ConfigDataHandler(d)
current.start()
</code></pre>
| 0 | 2009-08-28T10:12:44Z | 1,349,343 | <ol>
<li><p>Undo the threading stuff.</p></li>
<li><p>Run the <a href="http://docs.python.org/library/profile.html" rel="nofollow">profiler</a> on the original unthreaded code.</p></li>
<li><p>Replace the AODB business with ordinary ODBC.</p></li>
<li><p>Run the new code through the profiler.</p></li>
<li><p>Post your results for further discussion.</p></li>
</ol>
| 0 | 2009-08-28T21:03:20Z | [
"python",
"multithreading"
] |
Py2App Can't find standard modules | 1,346,297 | <p>I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file). How do I fix this?</p>
| 2 | 2009-08-28T10:57:31Z | 1,346,359 | <p>use zip -y ... to create the file whilst preserving symlinks.</p>
| 0 | 2009-08-28T11:12:43Z | [
"python",
"osx",
"py2app"
] |
Py2App Can't find standard modules | 1,346,297 | <p>I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file). How do I fix this?</p>
| 2 | 2009-08-28T10:57:31Z | 1,349,783 | <p>You probably need to give it your full PYTHONPATH.</p>
<p>Depends on your os. Here's how to find out:</p>
<p>import os [or any other std module]
os.<strong>file</strong>()</p>
| 0 | 2009-08-28T22:55:31Z | [
"python",
"osx",
"py2app"
] |
Py2App Can't find standard modules | 1,346,297 | <p>I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file). How do I fix this?</p>
| 2 | 2009-08-28T10:57:31Z | 2,043,314 | <p>This is caused by building a <strong>semi-standalone</strong> version that contains symlinks to the natively installed files and as you say, the links are lost when zipping/unzipping unless the "<strong>-y</strong>" option is used.</p>
<p>An alternate solution is to build for <strong>standalone</strong> instead, which puts (public domain) files inside the application and so survives zipping/unzipping etc. better. It also means the app is more resilient to changes in the underlying OS. The downside is that it is bigger, of course, and is more complicated to get it set up.</p>
<p>To build a stand alone version, you need to install the python.org version which can be repackaged.
An explanation of how to do this is <a href="http://aralbalkan.com/1675" rel="nofollow">here</a>, but read the comments as there have been some changes since the blog post was written.</p>
| 4 | 2010-01-11T16:50:49Z | [
"python",
"osx",
"py2app"
] |
How to find out whether computer is connected to internet? | 1,346,575 | <p>How to find out whether computer is connected to internet in python?</p>
| 9 | 2009-08-28T11:59:50Z | 1,346,598 | <p>Try</p>
<pre><code>import urllib
file = urllib.urlopen("http://stackoverflow.com/")
html = file.read()
</code></pre>
<p>and see if that works, or if it throws an exception. Even if you don't use the exact code, you should get the idea.</p>
| 7 | 2009-08-28T12:06:11Z | [
"python",
"internet-connection"
] |
How to find out whether computer is connected to internet? | 1,346,575 | <p>How to find out whether computer is connected to internet in python?</p>
| 9 | 2009-08-28T11:59:50Z | 1,346,623 | <p>If you have <a href="http://docs.python.org/library/urllib2.html#urllib2.urlopen">python2.6</a> you can set a timeout. Otherwise the connection might block for a long time.</p>
<pre><code>try:
urllib2.urlopen("http://example.com", timeout=2)
except urllib2.URLError:
# There is no connection
</code></pre>
| 16 | 2009-08-28T12:11:23Z | [
"python",
"internet-connection"
] |
JavaFX or RIA desktop app (on dvd) also available on the web? | 1,346,723 | <p>Is it possible to develop an application easily available on the web that also can be distributed on DVD (installer or started from the dvd)?</p>
<p>For the moment, we use static html (frameset!) pages (generated by xml files), with one difference: pdf's are only on the DVD version, the web version only shows a preview of these files.</p>
<p>Can this be done with JavaFX, OpenLaszlo or are there better options?
(for example: turbogears, and using tg2exe for DVD version)</p>
| 1 | 2009-08-28T12:30:40Z | 1,347,338 | <p>I think if you design it correctly to begin with, a JavaFX app can be interchanged between web-app and desktop-app relatively easily. However, I've only done this with very simple apps (specifically, Tic-Tac-Toe!), so I'm sure there might exist some caveats that I am unaware of (thus the "design it correctly" catch-all). ;)</p>
<p>Why don't you just provide the PDFs in your current web version, rather than redeveloping everything? I'm not aware of any browsers that don't support in-browser PDF reading anymore.</p>
| 0 | 2009-08-28T14:26:11Z | [
"java",
"python",
"web-applications",
"javafx",
"turbogears"
] |
JavaFX or RIA desktop app (on dvd) also available on the web? | 1,346,723 | <p>Is it possible to develop an application easily available on the web that also can be distributed on DVD (installer or started from the dvd)?</p>
<p>For the moment, we use static html (frameset!) pages (generated by xml files), with one difference: pdf's are only on the DVD version, the web version only shows a preview of these files.</p>
<p>Can this be done with JavaFX, OpenLaszlo or are there better options?
(for example: turbogears, and using tg2exe for DVD version)</p>
| 1 | 2009-08-28T12:30:40Z | 1,357,063 | <p>Yes JavaFX or Flash applications can be used to develop applications that run in different contexts. </p>
<p>However, it's not clear from your question why these would be preferable over your current solution. </p>
<p>If the information your sharing is primarily text and you're using DVD because your audience is primarily located in area with bad Internet connectivity, then you're current approach probably makes more sense. JavaFX or Flash might be more fun to write for developers but maybe doesn't serve your audience. </p>
<p>I would suggest that if you are shipping DVD and are looking for ways to make the DVD more useful than as a PDF delivery system would be to add video to the DVDs. And then maybe it would make more sense to use JavaFX or Flash to drive the UI. </p>
| 0 | 2009-08-31T11:45:34Z | [
"java",
"python",
"web-applications",
"javafx",
"turbogears"
] |
JavaFX or RIA desktop app (on dvd) also available on the web? | 1,346,723 | <p>Is it possible to develop an application easily available on the web that also can be distributed on DVD (installer or started from the dvd)?</p>
<p>For the moment, we use static html (frameset!) pages (generated by xml files), with one difference: pdf's are only on the DVD version, the web version only shows a preview of these files.</p>
<p>Can this be done with JavaFX, OpenLaszlo or are there better options?
(for example: turbogears, and using tg2exe for DVD version)</p>
| 1 | 2009-08-28T12:30:40Z | 1,371,752 | <p>Yes, it is possible. If you use JavaFX you will be allowed use multiple deployments. For example, NetBeans 6.7.1 with JavaFX creates several possible deployments from one project. Then you can publish this application on web, DVD, etc. You will need to slightly customize standalone deployment for DVD to be able e.g. start it as autorun if necessary. JavaFX is good choice. </p>
| 0 | 2009-09-03T06:47:17Z | [
"java",
"python",
"web-applications",
"javafx",
"turbogears"
] |
JavaFX or RIA desktop app (on dvd) also available on the web? | 1,346,723 | <p>Is it possible to develop an application easily available on the web that also can be distributed on DVD (installer or started from the dvd)?</p>
<p>For the moment, we use static html (frameset!) pages (generated by xml files), with one difference: pdf's are only on the DVD version, the web version only shows a preview of these files.</p>
<p>Can this be done with JavaFX, OpenLaszlo or are there better options?
(for example: turbogears, and using tg2exe for DVD version)</p>
| 1 | 2009-08-28T12:30:40Z | 1,508,000 | <p>This seems like a job for flex, however I know better little about it to give a better answer.</p>
| 0 | 2009-10-02T06:29:42Z | [
"java",
"python",
"web-applications",
"javafx",
"turbogears"
] |
Use QAction without adding to menu (or toolbar) | 1,346,964 | <p>I'm trying to develop an application with a very modular approach to commands and thought it would be nice, sind I'm using pyqt, to use QAction's to bind shortcuts to the commands.<br />
However, it seems that actions shortcuts only works when the action is visible in a menu or toolbar. Does anyone know a way to get this action to work without it being visible?<br />
Below some example code that shows what I'm trying.<br />
Thanks,</p>
<p>André</p>
<pre><code>from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class TesteMW(QMainWindow):
def __init__(self, *args):
QMainWindow.__init__(self, *args)
self.create_action()
def create_action(self):
self.na = QAction(self)
self.na.setText('Teste')
self.na.setShortcut('Ctrl+W')
self.connect(self.na, SIGNAL('triggered()'), self.action_callback)
# uncomment the next line for the action to work
# self.menuBar().addMenu("Teste").addAction(self.na)
def action_callback(self):
print 'action called!'
app = QApplication(sys.argv)
mw = TesteMW()
mw.show()
app.exec_()
</code></pre>
| 3 | 2009-08-28T13:27:47Z | 1,347,104 | <p>You need to add your action to a widget before it will be processed. From the QT documentation for QAction:</p>
<blockquote>
<p>Actions are added to widgets using
QWidget::addAction() or
QGraphicsWidget::addAction(). Note
that an action must be added to a
widget before it can be used; this is
also true when the shortcut should be
global (i.e., Qt::ApplicationShortcut
as Qt::ShortcutContext).</p>
</blockquote>
<p>This does not mean that they will be visible as a menu item or whatever - just that they will be processes as part of the widgets event loop.</p>
| 5 | 2009-08-28T13:49:27Z | [
"python",
"qt",
"pyqt"
] |
creating class instances from a list | 1,346,969 | <p>Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.</p>
<pre><code>class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
</code></pre>
<p>I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.</p>
| 2 | 2009-08-28T13:28:35Z | 1,347,012 | <p>you're probably looking for <a href="http://docs.python.org/3.1/library/functions.html#getattr" rel="nofollow"><code>getattr</code></a>.</p>
| 0 | 2009-08-28T13:35:58Z | [
"python"
] |
creating class instances from a list | 1,346,969 | <p>Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.</p>
<pre><code>class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
</code></pre>
<p>I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.</p>
| 2 | 2009-08-28T13:28:35Z | 1,347,032 | <p>You could use a dict, like:</p>
<pre><code>classes = {"foo" : foo, "bar" : bar}
</code></pre>
<p>then you could do:</p>
<pre><code>myvar = classes[somestring]()
</code></pre>
<p>this way you'll have to initialize and keep the dict, but will have control on which classes can be created.</p>
| 2 | 2009-08-28T13:37:57Z | [
"python"
] |
creating class instances from a list | 1,346,969 | <p>Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.</p>
<pre><code>class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
</code></pre>
<p>I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.</p>
| 2 | 2009-08-28T13:28:35Z | 1,347,045 | <p>The getattr approach seems right, a bit more detail:</p>
<pre><code>def forname(modname, classname):
''' Returns a class of "classname" from module "modname". '''
module = __import__(modname)
classobj = getattr(module, classname)
return classobj
</code></pre>
<p>From <a href="http://www.bensnider.com/2008/02/27/dynamically-import-and-instantiate-python-classes/" rel="nofollow">a blog post by Ben Snider</a>.</p>
| 2 | 2009-08-28T13:40:05Z | [
"python"
] |
creating class instances from a list | 1,346,969 | <p>Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.</p>
<pre><code>class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
</code></pre>
<p>I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.</p>
| 2 | 2009-08-28T13:28:35Z | 1,347,071 | <p>If it a list of classes in a string form you can:</p>
<pre><code>classes = ['foo', 'bar']
for class in classes:
obj = eval(class)
</code></pre>
<p>and to create an instance you simply do this:</p>
<pre><code>instance = obj(arg1, arg2, arg3)
</code></pre>
| 1 | 2009-08-28T13:43:39Z | [
"python"
] |
creating class instances from a list | 1,346,969 | <p>Using python.....I have a list that contain names. I want to use each item in the list to create instances of a class. I can't use these items in their current condition (they're strings). Does anyone know how to do this in a loop.</p>
<pre><code>class trap(movevariables):
def __init__(self):
movevariables.__init__(self)
if self.X==0:
self.X=input('Move Distance(mm) ')
if self.Vmax==0:
self.Vmax=input('Max Velocity? (mm/s) ')
if self.A==0:
percentg=input('Acceleration as decimal percent of g' )
self.A=percentg*9806.65
self.Xmin=((self.Vmax**2)/(2*self.A))
self.calc()
def calc(self):
if (self.X/2)>self.Xmin:
self.ta=2*((self.Vmax)/self.A) # to reach maximum velocity, the move is a symetrical trapezoid and the (acceleration time*2) is used
self.halfta=self.ta/2. # to calculate the total amount of time consumed by acceleration and deceleration
self.xa=.5*self.A*(self.halfta)**2
else: # If the move is not a trap, MaxV is not reached and the acceleration time is set to zero for subsequent calculations
self.ta=0
if (self.X/2)<self.Xmin:
self.tva=(self.X/self.A)**.5
self.halftva=self.tva/2
self.Vtriang=self.A*self.halftva
else:
self.tva=0
if (self.X/2)>self.Xmin:
self.tvc=(self.X-2*self.Xmin)/(self.Vmax) # calculate the Constant velocity time if you DO get to it
else:
self.tvc=0
self.t=(self.ta+self.tva+self.tvc)
print self
</code></pre>
<p>I'm a mechanical engineer. The trap class describes a motion profile that is common throughout the design of our machinery. There are many independent axes (trap classes) in our equipment so I need to distinguish between them by creating unique instances. The trap class inherits from movevariables many getter/setter functions structured as properties. In this way I can edit the variables by using the instance names. I'm thinking that I can initialize many machine axes at once by looping through the list instead of typing each one.</p>
| 2 | 2009-08-28T13:28:35Z | 1,347,576 | <p><strong>EDIT</strong></p>
<p>If you want to create several instances of the class trap, here is what to do:</p>
<pre><code>namelist=['lane1', 'lane2']
traps = dict((name, trap()) for name in namelist)
</code></pre>
<p>That will create a dictionary that maps each name to the instance.</p>
<p>Then to access each instance by name you do:</p>
<pre><code>traps['lane1'].Vmax
</code></pre>
| 1 | 2009-08-28T15:02:16Z | [
"python"
] |
Improving Python list slicing | 1,347,085 | <p>I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:</p>
<pre><code>for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
</code></pre>
<p>But I've got: <code>TypeError</code>. Instead following code with intermediate variable is used:</p>
<pre><code> for i in range(l, 0, -1):
sub = src[0:i-1]
sub.append(src[-1])
yield " ".join(sub)
</code></pre>
<p>Correct me please if I'm wrong</p>
| 0 | 2009-08-28T13:45:49Z | 1,347,101 | <p>The general reasoning is that the return type in <code>None</code> to indicate the <code>list</code> is being modified in-place.</p>
| 1 | 2009-08-28T13:49:10Z | [
"python",
"list"
] |
Improving Python list slicing | 1,347,085 | <p>I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:</p>
<pre><code>for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
</code></pre>
<p>But I've got: <code>TypeError</code>. Instead following code with intermediate variable is used:</p>
<pre><code> for i in range(l, 0, -1):
sub = src[0:i-1]
sub.append(src[-1])
yield " ".join(sub)
</code></pre>
<p>Correct me please if I'm wrong</p>
| 0 | 2009-08-28T13:45:49Z | 1,347,117 | <pre><code>for i in range(l-1, 0, -1):
yield ' '.join(src[:i] + src[-1:])
</code></pre>
<p>will do.</p>
<p>Extend/append methods modify list in place and therefore don't return the list.</p>
| 0 | 2009-08-28T13:50:37Z | [
"python",
"list"
] |
Improving Python list slicing | 1,347,085 | <p>I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:</p>
<pre><code>for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
</code></pre>
<p>But I've got: <code>TypeError</code>. Instead following code with intermediate variable is used:</p>
<pre><code> for i in range(l, 0, -1):
sub = src[0:i-1]
sub.append(src[-1])
yield " ".join(sub)
</code></pre>
<p>Correct me please if I'm wrong</p>
| 0 | 2009-08-28T13:45:49Z | 1,347,128 | <p>Hm, maybe replace:</p>
<pre><code>src[0:i-1].append(src[-1])
</code></pre>
<p>with:</p>
<pre><code>src[0:i-1] + src[-1:] #note the trailing ":", we want a list not an element
</code></pre>
| 7 | 2009-08-28T13:51:20Z | [
"python",
"list"
] |
Improving Python list slicing | 1,347,085 | <p>I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:</p>
<pre><code>for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
</code></pre>
<p>But I've got: <code>TypeError</code>. Instead following code with intermediate variable is used:</p>
<pre><code> for i in range(l, 0, -1):
sub = src[0:i-1]
sub.append(src[-1])
yield " ".join(sub)
</code></pre>
<p>Correct me please if I'm wrong</p>
| 0 | 2009-08-28T13:45:49Z | 1,347,288 | <p>To operate on the list and then return it, you can use the <code>or</code> construction:</p>
<pre><code>def append_and_return(li, x):
"""silly example"""
return (li.append(x) or li)
</code></pre>
<p>Here it is so that <code>X or Y</code> evaluates X, if X is true, returns X, else evaluates and returns Y. X needs to be always negative.</p>
<p>However, if you are only acting on a temporary list, the concatenation operation already suggested is just as good or better.</p>
<p>Edit: It is not worthless</p>
<pre><code>>>> li = [1, 2, 3]
>>> newli = append_and_return(li, 10)
>>> li
[1, 2, 3, 10]
>>> newli is li
True
</code></pre>
| -1 | 2009-08-28T14:18:09Z | [
"python",
"list"
] |
Improving Python list slicing | 1,347,085 | <p>I've wondered why extend/append methods of Python don't return a reference to result list.
To build string of all combination of list with last element, I would like to write simple:</p>
<pre><code>for i in range(l, 0, -1):
yield " ".join(src[0:i-1].append(src[-1]))
</code></pre>
<p>But I've got: <code>TypeError</code>. Instead following code with intermediate variable is used:</p>
<pre><code> for i in range(l, 0, -1):
sub = src[0:i-1]
sub.append(src[-1])
yield " ".join(sub)
</code></pre>
<p>Correct me please if I'm wrong</p>
| 0 | 2009-08-28T13:45:49Z | 1,347,857 | <p>The reason mutating methods in Python do NOT return a reference to the object they've mutated can be found in the <a href="http://en.wikipedia.org/wiki/Command-query%5Fseparation" rel="nofollow">Command-Query Separation</a> principle (CQS for short). Python does not apply CQS as thoroughly as Meyer's Eiffel language does (since -- as per the Zen of Python, aka <code>import this</code>, "practicality beats purity"): for example, <code>somelist.pop()</code> does return the just-popped element (still NOT the container that was just mutated;-), while in Eiffel popping a stack has no return value (in the common case in which you need to pop and use the top element, your first use a "query" to peek at the top, and later a "command" to make the top go away).</p>
<p>The deep motivation of CQS is not really "mutators should return nothing useful": rather, it's "queries should have no side effect". Keeping the distinction (be it rigidly or "as more of a guideline than a rule") is supposed to help you keep it in mind, and it does work to some extent (catching some accidental errors) though it can feel inconvenient at times if you're used to smoothly flowing "expressions and statements are the same thing" languages.</p>
<p>Another aspect of CQS (broadly speaking...) in Python is the distinction between statements and expressions. Again, that's not rigidly applied -- an expression can be used wherever a statement can, which does occasionally hide errors, e.g. when somebody forgets that to call a function they need <code>foo()</code>, NOT just <code>foo</code>;-). But, for example (and drastically different from C, Perl, etc), you can't easily assign something while at the same testing it (<code>if(a=foo())...</code>), which is occasionally inconvenient but does catch other kinds of accidental errors.</p>
| 8 | 2009-08-28T15:47:02Z | [
"python",
"list"
] |
Moving to Python 2.6.x | 1,347,168 | <p>My stuff is developed and running on Python 2.5.2</p>
<p>I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).</p>
<p>So, I'll do the intermediate step and go to 2.6.2. </p>
<p>My question: If an external module runs on 2.5.2, but doesn't explicitly state that it works with 2.6.x, can I assume it'll be fine? Or not?</p>
| 2 | 2009-08-28T13:56:09Z | 1,347,191 | <p>Most likely they will work just fine. Some things might cause DeprecationWarnings, for example sha module, but they can be ignored safely. This is my gut feeling, of course you can hit some specific thing causing problems. Anyway, a quick look over these should tell pretty fast whether your code needs work or not:</p>
<ul>
<li><a href="http://docs.python.org/whatsnew/2.6.html#new-improved-and-deprecated-modules" rel="nofollow">Improved and deprecated modules</a></li>
<li><a href="http://docs.python.org/whatsnew/2.6.html#porting-to-python-2-6" rel="nofollow">Porting to Python 2.6</a></li>
</ul>
| 8 | 2009-08-28T14:00:20Z | [
"python",
"python-2.6"
] |
Moving to Python 2.6.x | 1,347,168 | <p>My stuff is developed and running on Python 2.5.2</p>
<p>I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).</p>
<p>So, I'll do the intermediate step and go to 2.6.2. </p>
<p>My question: If an external module runs on 2.5.2, but doesn't explicitly state that it works with 2.6.x, can I assume it'll be fine? Or not?</p>
| 2 | 2009-08-28T13:56:09Z | 1,347,199 | <p>You can't assume that. However, you should be able to easily test if it works or not.</p>
<p>Also, do not bother trying to move to 3.x for another year or two. 2.6 has many of 3.0's features back-ported to it already, so the transition won't be that bad, once you do make it.</p>
| 2 | 2009-08-28T14:01:47Z | [
"python",
"python-2.6"
] |
Moving to Python 2.6.x | 1,347,168 | <p>My stuff is developed and running on Python 2.5.2</p>
<p>I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).</p>
<p>So, I'll do the intermediate step and go to 2.6.2. </p>
<p>My question: If an external module runs on 2.5.2, but doesn't explicitly state that it works with 2.6.x, can I assume it'll be fine? Or not?</p>
| 2 | 2009-08-28T13:56:09Z | 1,347,458 | <p>It is probably worth reading the <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">What's New</a> section of the 2.6 documentation. While 2.6 is designed to be backwards compatible, there are a few changes that could catch code, particular code that is doing something odd (example: <code>hasattr()</code> used to swallow all errors, now it swallows all but <code>SystemExit</code> and <code>KeyboardInterrupt</code>; not something that most people would notice, but there may be odd code where it would make a difference).</p>
<p>Also, that code indicates changes you can make going forward that will make it easier to move to 3.x when your packages are read (such as distinguishing between str and bytes even though they are synonyms in 2.6).</p>
| 1 | 2009-08-28T14:44:03Z | [
"python",
"python-2.6"
] |
Moving to Python 2.6.x | 1,347,168 | <p>My stuff is developed and running on Python 2.5.2</p>
<p>I want to move some code to 3.x, but that isn't feasible because so many of the external packages I use are not there yet. (Like numpy for instance).</p>
<p>So, I'll do the intermediate step and go to 2.6.2. </p>
<p>My question: If an external module runs on 2.5.2, but doesn't explicitly state that it works with 2.6.x, can I assume it'll be fine? Or not?</p>
| 2 | 2009-08-28T13:56:09Z | 1,347,750 | <p>The main issue will come with any C-coded extensions you may be using: depending on your system, but especially on Windows, such extensions, compiled for 2.5, are likely to not work at all (or at least not quietly and reliably) with 2.6. That's not particularly different from, e.g., migrating from 2.4 to 2.5 in the past.</p>
<p>The simplest solution (IMHO) is to get the sources for any such extensions and reinstall them. On most platforms, and for most extensions, <code>python setup.py install</code> (possibly with a <code>sudo</code> or logged in as administrator, depending on your installation) will work -- you may need to download and install proper "developer" packages, again depending on what system exactly you're using and what you have already installed (for example, on Mac OS X you need to install XCode -- or at least the gcc subset thereof, but it's simplest to install it all -- which in turn requires you to sign up for free at Apple Developer Connection and download the large XCode package).</p>
<p>I'm not sure how hassle-free this approach is on Windows at this time -- i.e., whether you can use free-as-in-beer compilers such as mingw or Microsoft's "express" edition of VS, or have to shell out $$ to MS to get the right compiler. However, most developers of third party extensions do go out on their way to supply ready Windows binaries, exactly because having the users recompile is (or at least used to be) a hassle on Windows, and 2.6 is already widely supported by third-party extension maintainers (since after all it IS just about a simple recompile for them, too;-), so you may be in luck and find all the precompiled binaries you need already available for the extensions you use.</p>
| 3 | 2009-08-28T15:28:33Z | [
"python",
"python-2.6"
] |
ctype question char** | 1,347,280 | <p>I'm trying to figure out why this works after lots and lots of messing about with </p>
<p>obo.librar_version is a c function which requires char ** as the input and does a strcpy
to passed in char.</p>
<pre><code>from ctypes import *
_OBO_C_DLL = 'obo.dll'
STRING = c_char_p
OBO_VERSION = _stdcall_libraries[_OBO_C_DLL].OBO_VERSION
OBO_VERSION.restype = c_int
OBO_VERSION.argtypes = [POINTER(STRING)]
def library_version():
s = create_string_buffer('\000' * 32)
t = cast(s, c_char_p)
res = obo.library_version(byref(t))
if res != 0:
raise Error("OBO error %r" % res)
return t.value, s.raw, s.value
library_version()
</code></pre>
<p>The above code returns</p>
<pre><code>('OBO Version 1.0.1', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '')
</code></pre>
<p>What I don't understand is why 's' does not have any value? Anyone have any ideas? Thx</p>
| 1 | 2009-08-28T14:16:56Z | 1,347,415 | <p>When you cast <code>s</code> to <code>c_char_p</code> you store a new object in <code>t</code>, not a reference. So when you pass <code>t</code> to your function by reference, <code>s</code> doesn't get updated.</p>
<p><strong>UPDATE:</strong></p>
<p>You are indeed correct: </p>
<blockquote>
<p>cast takes two parameters, a ctypes
object that is or can be converted to
a pointer of some kind, and a ctypes
pointer type. It returns an instance
of the second argument, which
references the same memory block as
the first argument.</p>
</blockquote>
<p>In order to get a reference to your string buffer, you need to use the following for your cast:</p>
<pre><code>t = cast(s, POINTER(c_char*33))
</code></pre>
<p>I have no idea why <code>c_char_p</code> doesn't create a reference where this does, but there you go.</p>
| 1 | 2009-08-28T14:36:42Z | [
"python",
"ctypes"
] |
ctype question char** | 1,347,280 | <p>I'm trying to figure out why this works after lots and lots of messing about with </p>
<p>obo.librar_version is a c function which requires char ** as the input and does a strcpy
to passed in char.</p>
<pre><code>from ctypes import *
_OBO_C_DLL = 'obo.dll'
STRING = c_char_p
OBO_VERSION = _stdcall_libraries[_OBO_C_DLL].OBO_VERSION
OBO_VERSION.restype = c_int
OBO_VERSION.argtypes = [POINTER(STRING)]
def library_version():
s = create_string_buffer('\000' * 32)
t = cast(s, c_char_p)
res = obo.library_version(byref(t))
if res != 0:
raise Error("OBO error %r" % res)
return t.value, s.raw, s.value
library_version()
</code></pre>
<p>The above code returns</p>
<pre><code>('OBO Version 1.0.1', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', '')
</code></pre>
<p>What I don't understand is why 's' does not have any value? Anyone have any ideas? Thx</p>
| 1 | 2009-08-28T14:16:56Z | 1,348,923 | <p>Because library_version requires a char**, they don't want you to allocate the characters (as you're doing with create_string_buffer. Instead, they just want you to pass in a reference to a pointer so they can return the address of where to find the version string.</p>
<p>So all you need to do is allocate the pointer, and then pass in a reference to that pointer.</p>
<p>The following code should work, although I don't have obo.dll (or know of a suitable replacement) to test it.</p>
<pre><code>from ctypes import *
_OBO_C_DLL = 'obo.dll'
STRING = c_char_p
_stdcall_libraries = dict()
_stdcall_libraries[_OBO_C_DLL] = WinDLL(_OBO_C_DLL)
OBO_VERSION = _stdcall_libraries[_OBO_C_DLL].OBO_VERSION
OBO_VERSION.restype = c_int
OBO_VERSION.argtypes = [POINTER(STRING)]
def library_version():
s_res = c_char_p()
res = OBO_VERSION(byref(s_res))
if res != 0:
raise Error("OBO error %r" % res)
return s_res.value
library_version()
</code></pre>
<p>[Edit]</p>
<p>I've gone a step further and written my own DLL that implements a possible implementation of OBO_VERSION that does not require an allocated character buffer, and is not subject to any memory leaks.</p>
<pre><code>int OBO_VERSION(char **pp_version)
{
static char result[] = "Version 2.0";
*pp_version = result;
return 0; // success
}
</code></pre>
<p>As you can see, OBO_VERSION simply sets the value of *pp_version to a pointer to a null-terminated character array. This is likely how the real OBO_VERSION works. I've tested this against my originally suggested technique above, and it works as prescribed.</p>
| 0 | 2009-08-28T19:33:53Z | [
"python",
"ctypes"
] |
Python version shipping with Mac OS X Snow Leopard? | 1,347,376 | <p>I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")</p>
<p>Thanks!</p>
| 10 | 2009-08-28T14:30:28Z | 1,347,397 | <p>Python 2.6.1</p>
<p>(according to the web)</p>
<p>Really good to know :)</p>
| 3 | 2009-08-28T14:33:05Z | [
"python",
"osx",
"osx-snow-leopard"
] |
Python version shipping with Mac OS X Snow Leopard? | 1,347,376 | <p>I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")</p>
<p>Thanks!</p>
| 10 | 2009-08-28T14:30:28Z | 1,348,251 | <pre><code>bot:nasuni jesse$ python
Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
<p>Probably the biggest reason I went and upgraded this morning, it's not 2.6.2, but it's close enough.</p>
| 5 | 2009-08-28T16:54:08Z | [
"python",
"osx",
"osx-snow-leopard"
] |
Python version shipping with Mac OS X Snow Leopard? | 1,347,376 | <p>I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")</p>
<p>Thanks!</p>
| 10 | 2009-08-28T14:30:28Z | 1,350,316 | <p>It ships with both python 2.6.1 and 2.5.4.</p>
<blockquote>
<p>$ python2.5</p>
<p>Python 2.5.4 (r254:67916, Jul 7 2009, 23:51:24)</p>
<p>$ python</p>
<p>Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) </p>
</blockquote>
| 12 | 2009-08-29T03:03:07Z | [
"python",
"osx",
"osx-snow-leopard"
] |
Python version shipping with Mac OS X Snow Leopard? | 1,347,376 | <p>I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")</p>
<p>Thanks!</p>
| 10 | 2009-08-28T14:30:28Z | 1,352,207 | <p>You can get an installer for 2.6.2 from python.org, no reason to go without.</p>
| 1 | 2009-08-29T19:38:57Z | [
"python",
"osx",
"osx-snow-leopard"
] |
Python version shipping with Mac OS X Snow Leopard? | 1,347,376 | <p>I would appreciate it if somebody running the final version of Snow Leopard could post what version of Python is included with the OS (on a Terminal, just type "python --version")</p>
<p>Thanks!</p>
| 10 | 2009-08-28T14:30:28Z | 1,363,299 | <p><a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html" rel="nofollow">http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html</a></p>
| 3 | 2009-09-01T16:01:35Z | [
"python",
"osx",
"osx-snow-leopard"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,347,472 | <p>Using python:</p>
<pre><code>totals = [ int(i)+int(j) for i, j in zip ( open(fname1), open(fname2) ) ]
</code></pre>
| 11 | 2009-08-28T14:46:28Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,347,520 | <p>You can avoid the intermediate steps by just using a command that do the counts and the comparison at the same time:</p>
<pre><code>find . -type f -exec perl -nle 'END { print $ARGV if $h{"{"} != $h{"}"} } $h{$_}++ for /([}{])/g' {}\;
</code></pre>
<p>This calls the Perl program once per file, the Perl program counts the number of each type curly brace and prints the name of the file if they counts don't match.</p>
<p>You must be careful with the <code>/([}{]])/</code> section, <code>find</code> will think it needs to do the replacement on <code>{}</code> if you say <code>/([{}]])/</code>.</p>
<p>WARNING: this code will have false positives and negatives if you are trying to run it against source code. Consider the following cases:</p>
<p>balanced, but curlies in strings:</p>
<pre><code>if ($s eq '{') {
print "I saw a {\n"
}
</code></pre>
<p>unbalanced, but curlies in strings:</p>
<pre><code>while (1) {
print "}";
</code></pre>
<p>You can expand the Perl command by using <a href="http://perldoc.perl.org/B/Deparse.html" rel="nofollow">B::Deparse</a>:</p>
<p>perl -MO=Deparse -nle 'END { print $ARGV if $h{"{"} != $h{"}"} } $h{$_}++ for /([}{])/g'</p>
<p>Which results in:</p>
<pre><code>BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
chomp $_;
sub END {
print $ARGV if $h{'{'} != $h{'}'};
}
;
++$h{$_} foreach (/([}{])/g);
}
</code></pre>
<p>We can now look at each piece of the program:</p>
<pre><code>BEGIN { $/ = "\n"; $\ = "\n"; }
</code></pre>
<p>This is caused by the <code>-l</code> option. It sets both the input and output record separators to "\n". This means anything read in will be broken into records based "\n" and any print statement will have "\n" appended to it.</p>
<pre><code>LINE: while (defined($_ = <ARGV>)) {
}
</code></pre>
<p>This is created by the <code>-n</code> option. It loops over every file passed in via the commandline (or STDIN if no files are passed) reading each line of those files. This also happens to set <code>$ARGV</code> to the last file read by <code><ARGV></code>.</p>
<pre><code>chomp $_;
</code></pre>
<p>This removes whatever is in the <code>$/</code> variable from the line that was just read (<code>$_</code>), it does nothing useful here. It was caused by the <code>-l</code> option.</p>
<pre><code>sub END {
print $ARGV if $h{'{'} != $h{'}'};
}
</code></pre>
<p>This is an END block, this code will run at the end of the program. It prints <code>$ARGV</code> (the name of the file last read from, see above) if the values stored in <code>%h</code> associated with the keys <code>'{'</code> and <code>'}'</code> are equal.</p>
<pre><code>++$h{$_} foreach (/([}{])/g);
</code></pre>
<p>This needs to be broken down further:</p>
<pre><code>/
( #begin capture
[}{] #match any of the '}' or '{' characters
) #end capture
/gx
</code></pre>
<p>Is a regex that returns a list of '{' and '}' characters that are in the string being matched. Since no string was specified the <code>$_</code> variable (which holds the line last read from the file, see above) will be matched against. That list is fed into the <code>foreach</code> statement which then runs the statement it is in front of for each item (hence the name) in the list. It also sets <code>$_</code> (as you can see <code>$_</code> is a popular variable in Perl) to be the item from the list.</p>
<pre><code>++h{$_}
</code></pre>
<p>This line increments the value in $h that is associated with <code>$_</code> (which will be either '{' or '}', see above) by one.</p>
| 3 | 2009-08-28T14:53:38Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,347,521 | <p>If c1 and c2 are youre files, you can do this:</p>
<pre><code>$ paste c1 c2 | awk '{print $1 + $2}'
</code></pre>
<p>Or (without AWK):</p>
<pre><code>$ paste c1 c2 | while read i j; do echo $(($i+$j)); done
</code></pre>
| 11 | 2009-08-28T14:53:43Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,347,604 | <p>In Python (or Perl, Awk, &c) you can reasonably do it in a single stand-alone "pass" -- I'm not sure what you mean by "too many curly brackets", but you can surely count curly use per file. For example (unless you have to worry about multi-GB files), the 10 files using most curly braces:</p>
<pre><code>import heapq
import os
import re
curliest = dict()
for path, dirs, files in os.walk('.'):
for afile in files:
fn = os.path.join(path, afile)
with open(fn) as f:
data = f.read()
braces = data.count('{') + data.count('}')
curliest[fn] = bracs
top10 = heapq.nlargest(10, curlies, curliest.get)
top10.sort(key=curliest.get)
for fn in top10:
print '%6d %s' % (curliest[fn], fn)
</code></pre>
| 1 | 2009-08-28T15:06:39Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,347,751 | <p><strong>Reply to Lutz'n answer</strong></p>
<p>My problem was finally solved by this commnad</p>
<pre><code>paste -d: /tmp/1 /tmp/2 | awk -F: '{ print $1 "\t" $2 - $4 }'
</code></pre>
| 0 | 2009-08-28T15:29:00Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Summing up two columns the Unix way | 1,347,457 | <h1># To fix the symptom</h1>
<p><strong>How can you sum up the following columns effectively?</strong></p>
<p><em>Column 1</em></p>
<pre><code>1
3
3
...
</code></pre>
<p><em>Column 2</em></p>
<pre><code>2323
343
232
...
</code></pre>
<p>This should give me</p>
<p><em>Expected result</em></p>
<pre><code>2324
346
235
...
</code></pre>
<p>I have the columns in two files.</p>
<p><hr /></p>
<h1># Initial situation</h1>
<p>I use sometimes too many curly brackets such that I have used one more this { than this } in my files.
I am trying to find where I have used the one unnecessary curly bracket.
I have used the following steps in getting the data</p>
<p><strong>Find commands</strong></p>
<pre><code> find . * -exec grep '{' {} + > /tmp/1
find . * -exec grep '}' {} + > /tmp/2
</code></pre>
<p><strong>AWK commands</strong> </p>
<pre><code> awk -F: '{ print $2 }' /tmp/1 > /tmp/11
awk -F: '{ print $2 }' /tmp/2 > /tmp/22
</code></pre>
<p>The column are in the files /tmp/11 and /tmp/22.</p>
<p>I repeat a lot of similar commands in my procedure.
This suggests me that this is not the right way.</p>
<p>Please, suggests me any way such as Python, Perl or any Unix tool which can decrease the number of steps.</p>
| 1 | 2009-08-28T14:43:59Z | 1,353,960 | <p>your problem can be solved with just 1 awk command...</p>
<pre><code>awk '{getline i<"file1";print i+$0}' file2
</code></pre>
| 0 | 2009-08-30T14:12:44Z | [
"python",
"perl",
"unix",
"awk",
"brackets"
] |
Documenting class attribute | 1,347,566 | <p>Following sample is taken from "Dive into python" book.</p>
<pre><code>class MP3FileInfo(FileInfo):
"store ID3v1.0 MP3 tags"
tagDataMap = ...
</code></pre>
<p>This sample shows documenting the MP3FileInfo, but how can I add help to MP3FileInfo. tagDataMap</p>
| 5 | 2009-08-28T15:00:53Z | 1,347,582 | <p>Change it into a property method.</p>
| 1 | 2009-08-28T15:03:11Z | [
"python",
"class",
"attributes",
"self-documenting"
] |
Documenting class attribute | 1,347,566 | <p>Following sample is taken from "Dive into python" book.</p>
<pre><code>class MP3FileInfo(FileInfo):
"store ID3v1.0 MP3 tags"
tagDataMap = ...
</code></pre>
<p>This sample shows documenting the MP3FileInfo, but how can I add help to MP3FileInfo. tagDataMap</p>
| 5 | 2009-08-28T15:00:53Z | 1,347,591 | <p>The <a href="http://www.python.org/dev/peps/pep-0224/" rel="nofollow">PEP 224</a> on attribute docstrings was rejected (long time ago), so this is a problem for me as well, sometimes I don't know to choose a class attribute or an instance property -- the second can have a docstring.</p>
| 4 | 2009-08-28T15:04:17Z | [
"python",
"class",
"attributes",
"self-documenting"
] |
Documenting class attribute | 1,347,566 | <p>Following sample is taken from "Dive into python" book.</p>
<pre><code>class MP3FileInfo(FileInfo):
"store ID3v1.0 MP3 tags"
tagDataMap = ...
</code></pre>
<p>This sample shows documenting the MP3FileInfo, but how can I add help to MP3FileInfo. tagDataMap</p>
| 5 | 2009-08-28T15:00:53Z | 1,347,896 | <p>Do it like this:</p>
<pre><code>class MP3FileInfo(FileInfo):
"""Store ID3v1.0 MP3 tags."""
@property
def tagDataMap(self):
"""This function computes map of tags.
The amount of work necessary to compute is quite large, therefore
we memoize the result.
"""
...
</code></pre>
<p>Note though you really shouldn't make a separate docstring if the attribute has only a one-line description. Instead, use </p>
<pre><code>class MP3FileInfo(FileInfo):
"""Store ID3v1.0 MP3 tags.
Here are the attributes:
tagDataMap -- contains a map of tags
"""
tagDataMap = ...
</code></pre>
| 0 | 2009-08-28T15:53:27Z | [
"python",
"class",
"attributes",
"self-documenting"
] |
Generate test coverage information from pyunit unittests? | 1,347,727 | <p>I have some pyunit unit tests for a simple command line programme I'm writing. Is it possible for me to generate test coverage numbers? I want to see what lines aren't being covered by my tests.</p>
| 2 | 2009-08-28T15:24:56Z | 1,347,755 | <p>I regularly use Ned Batchelder's <a href="http://nedbatchelder.com/code/modules/coverage.html">coverage.py</a> tool for exactly this purpose.</p>
| 7 | 2009-08-28T15:30:19Z | [
"python",
"unit-testing",
"testing",
"code-coverage",
"pyunit"
] |
Generate test coverage information from pyunit unittests? | 1,347,727 | <p>I have some pyunit unit tests for a simple command line programme I'm writing. Is it possible for me to generate test coverage numbers? I want to see what lines aren't being covered by my tests.</p>
| 2 | 2009-08-28T15:24:56Z | 1,347,783 | <p>If you run your tests with <a href="http://code.google.com/p/testoob/" rel="nofollow">testoob</a> you can get a coverage report with <code>--coverage</code>. Can install with easy_install. No changes to your tests necessary:</p>
<pre><code>testoob alltests.py --coverage
</code></pre>
| 1 | 2009-08-28T15:35:06Z | [
"python",
"unit-testing",
"testing",
"code-coverage",
"pyunit"
] |
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | 1,347,791 | <p>I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p>
| 63 | 2009-08-28T15:36:39Z | 1,347,854 | <p>The problem is with the string</p>
<pre><code>"C:\Users\Eric\Desktop\beeline.txt"
</code></pre>
<p>Here, <code>\U</code> starts an eight-character Unicode escape, such as '\U00014321`. In your code, the escape is followed by the character 's', which is invalid.</p>
<p>You either need to duplicate all backslashes, or prefix the string with <code>r</code> (to produce a raw string).</p>
| 146 | 2009-08-28T15:46:24Z | [
"python",
"unicode",
"python-3.x"
] |
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | 1,347,791 | <p>I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p>
| 63 | 2009-08-28T15:36:39Z | 19,255,661 | <p>I had this same error in python 3.2.</p>
<p>I have script for email sending and:</p>
<pre><code>csv.reader(open('work_dir\uslugi1.csv', newline='', encoding='utf-8'))
</code></pre>
<p>when I remove first char in file <code>uslugi1.csv</code> works fine.</p>
| 1 | 2013-10-08T18:38:37Z | [
"python",
"unicode",
"python-3.x"
] |
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | 1,347,791 | <p>I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p>
| 63 | 2009-08-28T15:36:39Z | 28,392,894 | <p>You may use</p>
<pre><code>fileName=r"C:\Users\XYZ\ABC\def.txt"
open(fileName, encoding="utf8")
</code></pre>
| 0 | 2015-02-08T10:26:32Z | [
"python",
"unicode",
"python-3.x"
] |
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | 1,347,791 | <p>I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p>
| 63 | 2009-08-28T15:36:39Z | 29,014,683 | <p>Typical error on Windows because the default user directory is <code>C:\user\<your_user></code>, so when you want to use this path as an string parameter into a Python function, you get a Unicode error, just because the <code>\u</code> is a Unicode escape. Any character not numeric after this produces an error.</p>
<p>To solve it, just double the backslashes: <code>C:\\\user\\\<\your_user>...</code></p>
| 3 | 2015-03-12T16:04:47Z | [
"python",
"unicode",
"python-3.x"
] |
"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3 | 1,347,791 | <p>I am using python 3.1, on a windows 7 machines. Russian is the default system language, and utf-8 is the default encoding.</p>
<p>Looking at the answer to a <a href="http://stackoverflow.com/questions/778096/problem-opening-a-text-document-unicode-error">previous question</a>, I have attempting using the "codecs" module to give me a little luck. Here's a few examples:</p>
<pre><code>>>> g = codecs.open("C:\Users\Eric\Desktop\beeline.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#39>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#40>, line 1)
>>> g = codecs.open("C:\Python31\Notes.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: malformed \N character escape (<pyshell#41>, line 1)
>>> g = codecs.open("C:\Users\Eric\Desktop\Site.txt", "r", encoding="utf-8")
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape (<pyshell#44>, line 1)
</code></pre>
<p>My last idea was, I thought it might have been the fact that windows "translates" a few folders, such as the "users" folder, into Russian (though typing "users" is still the correct path), so I tried it in the Python31 folder. Still, no luck. Any ideas?</p>
| 63 | 2009-08-28T15:36:39Z | 33,494,617 | <p>Or you could replace '\' with '/' in the path.</p>
| -3 | 2015-11-03T08:38:58Z | [
"python",
"unicode",
"python-3.x"
] |
Confusion about the Python path in Python shell vs FCGI server: Why are they different? | 1,347,851 | <p>I'm trying to deploy my Django app into production on a shared server.</p>
<p>It seems I'm having problems with the Python path because I'm getting the error from the server:
No module named products.models</p>
<p>However, when I go to the root of the app and run the shell the modules load fine.</p>
<pre><code>'>>> from products.models import Answer
'>>> import sys
'>>> sys.path
['/home/SecretUserAcct/django-projects/review_app', ...]
</code></pre>
<p>The path above does point to the root of the Django app.</p>
<p>I'm guessing this is an issue with the Python path, but I'm not sure what is going wrong.</p>
<p>Here is the fcgi file:
$ cat ~/public_html/django.fcgi </p>
<pre><code>#!/usr/local/bin/python2.6
import sys
import os
# Insert PYTHONPATH values here, including the path to your application
#sys.path.insert(0, '<path_to_your_app_directory>')
sys.path.insert(0, '/home/SecretUserAcct/django-projects/')
# Provide the location of your application's settings file.
os.environ['DJANGO_SETTINGS_MODULE'] = 'review_app.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method = "threaded", daemonize = "false", maxchildren=3, minspare=0, maxspare=1)
</code></pre>
<p>What understanding am I missing here?</p>
| 1 | 2009-08-28T15:45:50Z | 1,347,922 | <p>I'm somewhat confused -- if what you have in the path in the working case is:</p>
<pre><code>'/home/SecretUserAcct/django-projects/review_app'
</code></pre>
<p>i.e., including the app, why are you instead, in the second non-working case, inserting</p>
<pre><code>'/home/SecretUserAcct/django-projects/'
</code></pre>
<p>i.e., WITHOUT the app? Surely you'll need different forms of import depending on what you chose to put on your sys.path, no?</p>
| 0 | 2009-08-28T15:56:59Z | [
"python",
"django"
] |
Confusion about the Python path in Python shell vs FCGI server: Why are they different? | 1,347,851 | <p>I'm trying to deploy my Django app into production on a shared server.</p>
<p>It seems I'm having problems with the Python path because I'm getting the error from the server:
No module named products.models</p>
<p>However, when I go to the root of the app and run the shell the modules load fine.</p>
<pre><code>'>>> from products.models import Answer
'>>> import sys
'>>> sys.path
['/home/SecretUserAcct/django-projects/review_app', ...]
</code></pre>
<p>The path above does point to the root of the Django app.</p>
<p>I'm guessing this is an issue with the Python path, but I'm not sure what is going wrong.</p>
<p>Here is the fcgi file:
$ cat ~/public_html/django.fcgi </p>
<pre><code>#!/usr/local/bin/python2.6
import sys
import os
# Insert PYTHONPATH values here, including the path to your application
#sys.path.insert(0, '<path_to_your_app_directory>')
sys.path.insert(0, '/home/SecretUserAcct/django-projects/')
# Provide the location of your application's settings file.
os.environ['DJANGO_SETTINGS_MODULE'] = 'review_app.settings'
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method = "threaded", daemonize = "false", maxchildren=3, minspare=0, maxspare=1)
</code></pre>
<p>What understanding am I missing here?</p>
| 1 | 2009-08-28T15:45:50Z | 1,348,523 | <p>The Django dev server and manage.py shell put the current directory (the directory you ran manage.py from) on your python path for you. When running in production mode, you'll need to adjust your path accordingly if you have code that relies on that feature.</p>
| 0 | 2009-08-28T17:59:40Z | [
"python",
"django"
] |
How do I create a file in python without overwriting an existing file | 1,348,026 | <p>Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a race condition exists.</p>
<p>How can I keep python from overwriting an existing file, if one is created between the time of the check and the time of the open in the other thread.</p>
<p>I can minimize the chance by randomizing the suffixes, but the chance is already minimized based on parts of the pathname. I want to eliminate that chance with a function that can be told, create this file ONLY if it doesn't exist.</p>
<p>I can use win32 functions to do this, but I want this to work cross platform because it will be hosted on linux in the end.</p>
| 20 | 2009-08-28T16:14:03Z | 1,348,057 | <p>If you are concerned about a race condition, you can <a href="http://docs.python.org/library/tempfile.html">create a temporary file</a> and then rename it.</p>
<pre><code>>>> import os
>>> import tempfile
>>> f = tempfile.NamedTemporaryFile(delete=False)
>>> f.name
'c:\\users\\hughdb~1\\appdata\\local\\temp\\tmpsmdl53'
>>> f.write("Hello world")
>>> f.close()
>>> os.rename(f.name, r'C:\foo.txt')
>>> if os.path.exists(r'C:\foo.txt') :
... print 'File exists'
...
File exists
</code></pre>
<p>Alternatively, you can create the files using a <a href="http://docs.python.org/library/uuid.html">uuid</a> in the name. <a href="http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python">Stackoverflow</a> item on this.</p>
<pre><code>>>> import uuid
>>> str(uuid.uuid1())
'64362370-93ef-11de-bf06-0023ae0b04b8'
</code></pre>
| 6 | 2009-08-28T16:18:51Z | [
"python",
"multithreading"
] |
How do I create a file in python without overwriting an existing file | 1,348,026 | <p>Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a race condition exists.</p>
<p>How can I keep python from overwriting an existing file, if one is created between the time of the check and the time of the open in the other thread.</p>
<p>I can minimize the chance by randomizing the suffixes, but the chance is already minimized based on parts of the pathname. I want to eliminate that chance with a function that can be told, create this file ONLY if it doesn't exist.</p>
<p>I can use win32 functions to do this, but I want this to work cross platform because it will be hosted on linux in the end.</p>
| 20 | 2009-08-28T16:14:03Z | 1,348,073 | <p>Use <a href="https://docs.python.org/2/library/os.html#os.open"><code>os.open()</code></a> with <code>os.O_CREAT</code> and <code>os.O_EXCL</code> to create the file. That will fail if the file already exists:</p>
<pre><code>>>> fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 17] File exists: 'x'
</code></pre>
<p>Once you've created a new file, use <a href="https://docs.python.org/2/library/os.html#os.fdopen"><code>os.fdopen()</code></a> to turn the handle into a standard Python file object:</p>
<pre><code>>>> fd = os.open("y", os.O_WRONLY | os.O_CREAT | os.O_EXCL)
>>> f = os.fdopen(fd, "w") # f is now a standard Python file object
</code></pre>
<p><strong>Edit:</strong> From Python 3.3, the builtin <a href="http://docs.python.org/release/3.3.0/library/functions.html?highlight=open#open"><code>open()</code></a> has an <code>x</code> mode that means "open for exclusive creation, failing if the file already exists".</p>
| 36 | 2009-08-28T16:21:33Z | [
"python",
"multithreading"
] |
How do I create a file in python without overwriting an existing file | 1,348,026 | <p>Currently I have a loop that tries to find an unused filename by adding suffixes to a filename string. Once it fails to find a file, it uses the name that failed to open a new file wit that name. Problem is this code is used in a website and there could be multiple attempts to do the same thing at the same time, so a race condition exists.</p>
<p>How can I keep python from overwriting an existing file, if one is created between the time of the check and the time of the open in the other thread.</p>
<p>I can minimize the chance by randomizing the suffixes, but the chance is already minimized based on parts of the pathname. I want to eliminate that chance with a function that can be told, create this file ONLY if it doesn't exist.</p>
<p>I can use win32 functions to do this, but I want this to work cross platform because it will be hosted on linux in the end.</p>
| 20 | 2009-08-28T16:14:03Z | 1,348,441 | <p>If you have an <code>id</code> associated with each thread / process that tries to create the file, you could put that id in the suffix somewhere, thereby guaranteeing that no two processes can use the same file name.</p>
<p>This eliminates the race condition between the processes.</p>
| 0 | 2009-08-28T17:42:28Z | [
"python",
"multithreading"
] |
passing ctrl+z to pexpect | 1,348,283 | <p>How do I pass a certain key combination to a spawned/child process using the pexpect module? I'm using telnet and have to pass Ctrl+Z to a remote server.</p>
<p>Tnx</p>
| 2 | 2009-08-28T17:01:48Z | 1,348,298 | <p>use <a href="http://pexpect.sourceforge.net/pexpect.html#spawn-sendcontrol">sendcontrol()</a></p>
<p>for example:</p>
<pre><code>p = pexpect.spawn(your_cmd_here)
p.sendcontrol('z')
</code></pre>
| 7 | 2009-08-28T17:07:36Z | [
"python",
"pexpect"
] |
Gracefully-degrading pickling in Python | 1,348,315 | <p>(You may read <a href="http://stackoverflow.com/questions/1336908/python-alternatives-to-pickling-a-module">this</a> question for some background)</p>
<p>I would like to have a gracefully-degrading way to pickle objects in Python.</p>
<p>When pickling an object, let's call it the main object, sometimes the Pickler raises an exception because it can't pickle a certain sub-object of the main object. For example, an error I've been getting a lot is "canât pickle module objects." That is because I am referencing a module from the main object.</p>
<p>I know I can write up a little something to replace that module with a facade that would contain the module's attributes, but that would have its own issues(1).</p>
<p>So what I would like is a pickling function that automatically replaces modules (and any other hard-to-pickle objects) with facades that contain their attributes. That may not produce a perfect pickling, but in many cases it would be sufficient.</p>
<p>Is there anything like this? Does anyone have an idea how to approach this?</p>
<p><hr /></p>
<p>(1) One issue would be that the module may be referencing other modules from within it.</p>
| 6 | 2009-08-28T17:13:40Z | 1,348,822 | <p>How about the following, which is a wrapper you can use to wrap some modules (maybe any module) in something that's pickle-able. You could then subclass the Pickler object to check if the target object is a module, and if so, wrap it. Does this accomplish what you desire?</p>
<pre><code>class PickleableModuleWrapper(object):
def __init__(self, module):
# make a copy of the module's namespace in this instance
self.__dict__ = dict(module.__dict__)
# remove anything that's going to give us trouble during pickling
self.remove_unpickleable_attributes()
def remove_unpickleable_attributes(self):
for name, value in self.__dict__.items():
try:
pickle.dumps(value)
except Exception:
del self.__dict__[name]
import pickle
p = pickle.dumps(PickleableModuleWrapper(pickle))
wrapped_mod = pickle.loads(p)
</code></pre>
| 0 | 2009-08-28T19:13:53Z | [
"python",
"pickle",
"graceful-degradation"
] |
Gracefully-degrading pickling in Python | 1,348,315 | <p>(You may read <a href="http://stackoverflow.com/questions/1336908/python-alternatives-to-pickling-a-module">this</a> question for some background)</p>
<p>I would like to have a gracefully-degrading way to pickle objects in Python.</p>
<p>When pickling an object, let's call it the main object, sometimes the Pickler raises an exception because it can't pickle a certain sub-object of the main object. For example, an error I've been getting a lot is "canât pickle module objects." That is because I am referencing a module from the main object.</p>
<p>I know I can write up a little something to replace that module with a facade that would contain the module's attributes, but that would have its own issues(1).</p>
<p>So what I would like is a pickling function that automatically replaces modules (and any other hard-to-pickle objects) with facades that contain their attributes. That may not produce a perfect pickling, but in many cases it would be sufficient.</p>
<p>Is there anything like this? Does anyone have an idea how to approach this?</p>
<p><hr /></p>
<p>(1) One issue would be that the module may be referencing other modules from within it.</p>
| 6 | 2009-08-28T17:13:40Z | 1,348,828 | <p>Hmmm, something like this?</p>
<pre><code>import sys
attribList = dir(someobject)
for attrib in attribList:
if(type(attrib) == type(sys)): #is a module
#put in a facade, either recursively list the module and do the same thing, or just put in something like str('modulename_module')
else:
#proceed with normal pickle
</code></pre>
<p>Obviously, this would go into an extension of the pickle class with a reimplemented dump method...</p>
| 0 | 2009-08-28T19:14:32Z | [
"python",
"pickle",
"graceful-degradation"
] |
Gracefully-degrading pickling in Python | 1,348,315 | <p>(You may read <a href="http://stackoverflow.com/questions/1336908/python-alternatives-to-pickling-a-module">this</a> question for some background)</p>
<p>I would like to have a gracefully-degrading way to pickle objects in Python.</p>
<p>When pickling an object, let's call it the main object, sometimes the Pickler raises an exception because it can't pickle a certain sub-object of the main object. For example, an error I've been getting a lot is "canât pickle module objects." That is because I am referencing a module from the main object.</p>
<p>I know I can write up a little something to replace that module with a facade that would contain the module's attributes, but that would have its own issues(1).</p>
<p>So what I would like is a pickling function that automatically replaces modules (and any other hard-to-pickle objects) with facades that contain their attributes. That may not produce a perfect pickling, but in many cases it would be sufficient.</p>
<p>Is there anything like this? Does anyone have an idea how to approach this?</p>
<p><hr /></p>
<p>(1) One issue would be that the module may be referencing other modules from within it.</p>
| 6 | 2009-08-28T17:13:40Z | 1,349,243 | <p>You can decide and implement how any previously-unpicklable type gets pickled and unpickled: see standard library module <a href="http://docs.python.org/library/copy%5Freg.html" rel="nofollow">copy_reg</a> (renamed to <code>copyreg</code> in Python 3.*).</p>
<p>Essentially, you need to provide a function which, given an instance of the type, reduces it to a tuple -- with the same protocol as the <a href="http://docs.python.org/library/pickle.html#object.%5F%5Freduce%5F%5F" rel="nofollow"><strong>reduce</strong></a> special method (except that the reduce special method takes no arguments, since when provided it's called directly on the object, while the function you provide will take the object as the only argument).</p>
<p>Typically, the tuple you return has 2 items: a callable, and a tuple of arguments to pass to it. The callable must be registered as a "safe constructor" or equivalently have an attribute <code>__safe_for_unpickling__</code> with a true value. Those items will be pickled, and at unpickling time the callable will be called with the given arguments and must return the unpicked object.</p>
<p>For example, suppose that you want to just pickle modules by name, so that unpickling them just means re-importing them (i.e. suppose for simplicity that you don't care about dynamically modified modules, nested packages, etc, just plain top-level modules). Then:</p>
<pre><code>>>> import sys, pickle, copy_reg
>>> def savemodule(module):
... return __import__, (module.__name__,)
...
>>> copy_reg.pickle(type(sys), savemodule)
>>> s = pickle.dumps(sys)
>>> s
"c__builtin__\n__import__\np0\n(S'sys'\np1\ntp2\nRp3\n."
>>> z = pickle.loads(s)
>>> z
<module 'sys' (built-in)>
</code></pre>
<p>I'm using the old-fashioned ASCII form of pickle so that <code>s</code>, the string containing the pickle, is easy to examine: it instructs unpickling to call the built-in import function, with the string <code>sys</code> as its sole argument. And <code>z</code> shows that this does indeed give us back the built-in <code>sys</code> module as the result of the unpickling, as desired.</p>
<p>Now, you'll have to make things a bit more complex than just <code>__import__</code> (you'll have to deal with saving and restoring dynamic changes, navigate a nested namespace, etc), and thus you'll have to also call <code>copy_reg.constructor</code> (passing as argument your own function that performs this work) before you <code>copy_reg</code> the module-saving function that returns your other function (and, if in a separate run, also before you unpickle those pickles you made using said function). But I hope this simple cases helps to show that there's really nothing much to it that's at all "intrinsically" complicated!-)</p>
| 3 | 2009-08-28T20:41:58Z | [
"python",
"pickle",
"graceful-degradation"
] |
SQLAlchemy session query with INSERT IGNORE | 1,348,510 | <p>I'm trying to do a bulk insert/update with SQLAlchemy. Here's a snippet:</p>
<pre><code>for od in clist:
where = and_(Offer.network_id==od['network_id'],
Offer.external_id==od['external_id'])
o = session.query(Offer).filter(where).first()
if not o:
o = Offer()
o.network_id = od['network_id']
o.external_id = od['external_id']
o.title = od['title']
o.updated = datetime.datetime.now()
payout = od['payout']
countrylist = od['countries']
session.add(o)
session.flush()
for country in countrylist:
c = session.query(Country).filter(Country.name==country).first()
where = and_(OfferPayout.offer_id==o.id,
OfferPayout.country_name==country)
opayout = session.query(OfferPayout).filter(where).first()
if not opayout:
opayout = OfferPayout()
opayout.offer_id = o.id
opayout.payout = od['payout']
if c:
opayout.country_id = c.id
opayout.country_name = country
else:
opayout.country_id = 0
opayout.country_name = country
session.add(opayout)
session.flush()
</code></pre>
<p>It looks like my issue was touched on here, <a href="http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg05983.html" rel="nofollow">http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg05983.html</a>, but I don't know how to use "textual clauses" with session query objects and couldn't find much (though admittedly I haven't had as much time as I'd like to search).</p>
<p>I'm new to SQLAlchemy and I'd imagine there's some issues in the code besides the fact that it throws an exception on a duplicate key. For example, doing a flush after every iteration of clist (but I don't know how else to get an the o.id value that is used in the subsequent OfferPayout inserts).</p>
<p>Guidance on any of these issues is very appreciated.</p>
| 1 | 2009-08-28T17:57:34Z | 1,351,309 | <p>The way you should be doing these things is with session.merge(). </p>
<p>You should also be using your objects relation properties. So the o above should have o.offerpayout and this a list (of objects) and your offerpayout has offerpayout.country property which is the related countries object.</p>
<p>So the above would look something like</p>
<pre><code>for od in clist:
o = Offer()
o.network_id = od['network_id']
o.external_id = od['external_id']
o.title = od['title']
o.updated = datetime.datetime.now()
payout = od['payout']
countrylist = od['countries']
for country in countrylist:
opayout = OfferPayout()
opayout.payout = od['payout']
country_obj = Country()
country_obj.name = country
opayout.country = country_obj
o.offerpayout.append(opayout)
session.merge(o)
session.flush()
</code></pre>
<p>This should work as long as all the primary keys are correct (i.e the country table has a primary key of name). <a href="http://www.sqlalchemy.org/docs/05/session.html#merging" rel="nofollow">Merge</a> essentially checks the primary keys and if they are there merges your object with one in the database (it will also cascade down the joins).</p>
| 2 | 2009-08-29T12:16:57Z | [
"python",
"sqlalchemy"
] |
Different versions of msvcrt in ctypes | 1,348,547 | <p>In Windows, the <code>ctypes.cdll.msvcrt</code> object automatically exists when I import the ctypes module, and it represents the <code>msvcrt</code> Microsoft C++ runtime library <a href="http://docs.python.org/library/ctypes.html#loading-dynamic-link-libraries">according to the docs</a>.</p>
<p>However, I notice that there is also a <a href="http://docs.python.org/library/ctypes.html#ctypes.util.find_msvcrt">find_msvcrt</a> function which will <code>"return the filename of the VC runtype library used by Python"</code>.</p>
<p>It further states, <code>"If you need to free memory, for example, allocated by an extension module with a call to the free(void *), it is important that you use the function in the same library that allocated the memory."</code></p>
<p>So my question is, what's the difference between the <code>ctypes.cdll.msvcrt</code> library that I already have and the one which I can load with the <code>find_msvcrt</code> function? Under what specific circumstances might they not be the same library?</p>
| 5 | 2009-08-28T18:05:29Z | 1,348,903 | <p>It's not just that <code>ctypes.cdll.msvcrt</code> automatically exists, but <code>ctypes.cdll.anything</code> automatically exists, and is loaded on first access, loading <code>anything.dll</code>. So <code>ctypes.cdll.msvcrt</code> loads <code>msvcrt.dll</code>, which is a library that ships as part of Windows. It is not the C runtime that Python links with, so you shouldn't call the malloc/free from <code>msvcrt</code>.</p>
<p>For example, for Python 2.6/3.1, you should be using <code>ctypes.cdll.msvcr90</code>. As this will change over time, <code>find_msvcrt()</code> gives you the name of the library that you should really use (and then load through <code>ctypes.CDLL</code>).</p>
<p>Here are the names of a few different versions of the Microsoft CRT, released at various points as part of MSC, VC++, the platform SDK, or Windows: crtdll.dll, msvcrt.dll, msvcrt4.dll, msvcr70.dll, msvcr71.dll, msvcr80.dll, msvcr90.dll.</p>
| 10 | 2009-08-28T19:30:12Z | [
"python",
"ctypes",
"msvcrt"
] |
How do you add a custom section to the Django admin home page? | 1,348,710 | <p>In the Django admin each app you have registered with the admin gets its own section. I want to add a custom section for reporting that isn't associated with any app. How do I do that?</p>
| 2 | 2009-08-28T18:46:11Z | 1,349,413 | <p>To add a section not associated with an app, you'll have to override the admin index template. Create an admin/ directory in your project templates directory, and copy the file django/contrib/admin/templates/admin/index.html into it. Then you can add whatever markup you want to this file. The only downside (unfortunately there's no good way around it at the moment) is that if you upgrade Django, you'll have to be on the lookout for any changes to that index.html file, and copy those changes over into your version as well.</p>
| 1 | 2009-08-28T21:16:28Z | [
"python",
"django",
"django-admin"
] |
How do you add a custom section to the Django admin home page? | 1,348,710 | <p>In the Django admin each app you have registered with the admin gets its own section. I want to add a custom section for reporting that isn't associated with any app. How do I do that?</p>
| 2 | 2009-08-28T18:46:11Z | 1,349,768 | <p>Here you go: <a href="http://docs.djangoproject.com/en/dev/obsolete/admin-css/" rel="nofollow">http://docs.djangoproject.com/en/dev/obsolete/admin-css/</a></p>
<p>That should take care of you :P</p>
| 0 | 2009-08-28T22:51:53Z | [
"python",
"django",
"django-admin"
] |
Is there any way to add a class attribute to an input tag generated by django.models? | 1,348,723 | <p>I can't figure it out for the life of me. I don't think it's possible. Something so simple shouldn't be hard at all. Anyone?</p>
| 1 | 2009-08-28T18:48:44Z | 1,348,758 | <p>Not sure what you're referring to. Do you mean an HTML <input> tag generated by django.forms? If so, just specify a custom widget, using the attrs attribute in the constructor. See <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances">docs</a>.</p>
| 5 | 2009-08-28T19:01:36Z | [
"python",
"css",
"django"
] |
Is there any way to add a class attribute to an input tag generated by django.models? | 1,348,723 | <p>I can't figure it out for the life of me. I don't think it's possible. Something so simple shouldn't be hard at all. Anyone?</p>
| 1 | 2009-08-28T18:48:44Z | 1,349,702 | <p>You just need to override the relevant field in your form class, and add your attribute to the widget. This is described clearly <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types" rel="nofollow">in the documentation</a>.</p>
| 1 | 2009-08-28T22:33:01Z | [
"python",
"css",
"django"
] |
Is there any way to add a class attribute to an input tag generated by django.models? | 1,348,723 | <p>I can't figure it out for the life of me. I don't think it's possible. Something so simple shouldn't be hard at all. Anyone?</p>
| 1 | 2009-08-28T18:48:44Z | 1,354,181 | <p><a href="http://github.com/simonw/django-html" rel="nofollow">django-html</a> provides a templatetag which allows you to add extra attributes in the template, like so:</p>
<pre><code>{% field form.fieldname class="myclass" %}
</code></pre>
| 3 | 2009-08-30T16:07:21Z | [
"python",
"css",
"django"
] |
Is there any way to add a class attribute to an input tag generated by django.models? | 1,348,723 | <p>I can't figure it out for the life of me. I don't think it's possible. Something so simple shouldn't be hard at all. Anyone?</p>
| 1 | 2009-08-28T18:48:44Z | 17,663,424 | <p>I don't think any of these is particularly what the asker was looking for and now a few years after the question was posted this can be done much more intuitively. I think the asker wants the ModelForm field to render the input tag with a class attribute which you set in your view.</p>
<p>If so, the answer is here:</p>
<p><a href="http://stackoverflow.com/questions/3679431/how-do-i-set-default-widget-attributes-for-a-django-modelform">How do I set default widget attributes for a Django ModelForm?</a></p>
<p>Indeed, maybe this was the case even way back in 09, in which case the other answers should be downvoted. But I wasn't working with Django back then so I'll leave that to others.</p>
| 0 | 2013-07-15T20:35:26Z | [
"python",
"css",
"django"
] |
Show/hide a plot's legend | 1,349,202 | <p>I'm relatively new to python and am developing a pyqt GUI. I want to provide a checkbox option to show/hide a plot's legend. Is there a way to hide a legend? </p>
<p>I've tried using pyplot's '<code>_nolegend_</code>' and it appears to work on select legend entries but it creates a ValueError if applied to all entries. </p>
<p>I can brute force the legend to hide by clearing and redrawing the whole plot but... it's a terrible thing to do, especially with large data sets.</p>
<p>Appreciate any help with this.</p>
| 4 | 2009-08-28T20:34:48Z | 1,351,678 | <p>Here's something you can try on the command line:</p>
<pre><code>plot([3,1,4,1],label='foo')
lgd=legend()
# when you want it to be invisible:
lgd.set_visible(False)
draw()
# when you want it to be visible:
lgd.set_visible(True)
draw()
</code></pre>
<p>In a GUI program it's best to avoid pyplot and use the object-oriented API, i.e., <code>ax.legend</code> and <code>canvas.draw</code>.</p>
| 6 | 2009-08-29T15:15:00Z | [
"python",
"matplotlib"
] |
Matplotlib coord. sys origin to top left | 1,349,230 | <p>How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).</p>
<p>I'm looking for the equivalent of the matlab command: axis ij;</p>
<p>Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.</p>
| 8 | 2009-08-28T20:40:31Z | 1,350,146 | <p><code>axis ij</code> just makes the y-axis increase downward instead of upward, right? If so, then <a href="http://matplotlib.sourceforge.net/api/axes%5Fapi.html#matplotlib.axes.Axes.invert%5Fyaxis"><code>matplotlib.axes.invert_yaxis()</code></a> might be all you need -- but I can't test that right now.</p>
<p>If that doesn't work, I found <a href="http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg04291.html">a mailing post</a> suggesting that</p>
<pre><code>setp(gca(), 'ylim', reversed(getp(gca(), 'ylim')))
</code></pre>
<p>might do what you want to resemble <code>axis ij</code>.</p>
| 12 | 2009-08-29T01:27:29Z | [
"python",
"matplotlib",
"axes"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.