title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
7,161,355
<p>As you can see <a href="http://docs.python.org/library/optparse.html#module-optparse">optparse</a> "The optparse module is deprecated with and will not be developed further; development will continue with the <a href="http://docs.python.org/library/argparse.html#module-argparse">argparse</a> module." </p>
5
2011-08-23T12:57:14Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
7,875,868
<p>My solution is <a href="https://github.com/ponty/entrypoint2" rel="nofollow">entrypoint2</a>. Example:</p> <pre><code>from entrypoint2 import entrypoint @entrypoint def add(file, quiet=True): ''' This function writes report. :param file: write report to FILE :param quiet: don't print status messages to stdout ''' print file,quiet </code></pre> <p>help text:</p> <pre><code>usage: report.py [-h] [-q] [--debug] file This function writes report. positional arguments: file write report to FILE optional arguments: -h, --help show this help message and exit -q, --quiet don't print status messages to stdout --debug set logging level to DEBUG </code></pre>
0
2011-10-24T12:48:37Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
10,545,218
<pre><code>#set default args as -h , if no args: if len(sys.argv) == 1: sys.argv[1:] = ["-h"] </code></pre>
18
2012-05-11T03:53:30Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
14,790,373
<p>The <a href="https://github.com/docopt/docopt">docopt</a> library is really slick. It builds an argument dict from the usage string for your app.</p> <p>Eg from the docopt readme:</p> <pre><code>"""Naval Fate. Usage: naval_fate.py ship new &lt;name&gt;... naval_fate.py ship &lt;name&gt; move &lt;x&gt; &lt;y&gt; [--speed=&lt;kn&gt;] naval_fate.py ship shoot &lt;x&gt; &lt;y&gt; naval_fate.py mine (set|remove) &lt;x&gt; &lt;y&gt; [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=&lt;kn&gt; Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='Naval Fate 2.0') print(arguments) </code></pre>
24
2013-02-09T16:52:31Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
18,296,313
<p>I recommend looking at <a href="http://docopt.org/" rel="nofollow">docopt</a> as a simple alternative to these others.</p> <p>docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.</p>
4
2013-08-18T06:21:51Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
25,272,710
<p>Pocoo's <a href="http://click.pocoo.org/" rel="nofollow">click</a> is more intuitive, requires less boilerplate, and is at least as powerful as argparse.</p> <p>The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and <a href="http://docopt.org/" rel="nofollow">docopt</a> seems like the clear choice when it is.</p>
3
2014-08-12T19:38:40Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
33,329,251
<p>If you need something fast and not very flexible</p> <p><strong>main.py:</strong></p> <pre><code>import sys first_name = sys.argv[1] last_name = sys.argv[2] print("Hello " + first_name+ " " + last_name ) </code></pre> <p>Then run <code>python main.py James Smith</code></p> <p>to produce the following output:</p> <blockquote> <p>Hello James Smith</p> </blockquote>
6
2015-10-25T11:40:25Z
[ "python", "command-line", "command-line-arguments" ]
Command Line Arguments In Python
1,009,860
<p>I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. </p> <p>What are some of the ways Python programmers can do this?</p> <h3>Related</h3> <ul> <li><a href="http://stackoverflow.com/questions/20063/whats-the-best-way-to-grab-parse-command-line-arguments-passed-to-a-python-scrip">What’s the best way to grab/parse command line arguments passed to a Python script?</a></li> <li><a href="http://stackoverflow.com/questions/362426/implementing-a-command-action-parameter-style-command-line-interfaces">Implementing a “[command] [action] [parameter]” style command-line interfaces?</a></li> <li><a href="http://stackoverflow.com/questions/567879/how-can-i-process-command-line-arguments-in-python">How can I process command line arguments in Python?</a></li> <li><a href="http://stackoverflow.com/questions/642648/how-do-i-format-positional-argument-help-using-pythons-optparse">How do I format positional argument help using Python’s optparse?</a></li> </ul>
269
2009-06-17T22:38:30Z
33,660,810
<p>Yet another option is <a href="https://pypi.python.org/pypi/argh" rel="nofollow">argh</a>. It builds on argparse, and lets you write things like:</p> <pre><code>import argh # declaring: def echo(text): "Returns given word as is." return text def greet(name, greeting='Hello'): "Greets the user with given name. The greeting is customizable." return greeting + ', ' + name # assembling: parser = argh.ArghParser() parser.add_commands([echo, greet]) # dispatching: if __name__ == '__main__': parser.dispatch() </code></pre> <p>It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.</p>
1
2015-11-11T22:10:35Z
[ "python", "command-line", "command-line-arguments" ]
Python - Get original function arguments in decorator
1,010,080
<p>I am trying to write a "login_required" decorator for the views in a WSGI+Werkzeug application.</p> <p>In order to do this, I need to get at the user's session, which is accessible via the Request object that is passed into the view methods.</p> <p>I can't figure out how to get at that instance of Request in the decorator, though. I looked at PEP318, specifically the fourth example, but I'm not quite getting it.</p> <p>Here's what I'm trying:</p> <pre><code>def login_required(*args, **kw): def goto_login(**kw): return redirect(url_for('login')) def decorate(f): # args[0] should be request args[0].client_session['test'] = True logged_in = 0 if logged_in: return f else: return goto_login return decorate @login_required() @expose('/hello/&lt;string:name&gt;') def hello(request, name): return render_template('say_hello.html', name=name) </code></pre> <p>but I get an index out of bounds error trying to call <code>args[0]</code>.</p> <p>Is there any way I can get access to the request argument passed into the "hello" function in the "login_required" decorator?</p>
9
2009-06-17T23:55:25Z
1,010,109
<p>The decorator <code>login_required</code> is passed the function (<code>hello</code> in this case).</p> <p>So what you want to do is:</p> <pre><code>def login_required(f): # This function is what we "replace" hello with def wrapper(*args, **kw): args[0].client_session['test'] = True logged_in = 0 if logged_in: return f(*args, **kw) # Call hello else: return redirect(url_for('login')) return wrapper </code></pre>
17
2009-06-18T00:02:17Z
[ "python", "decorator" ]
How to construct a webob.Request or a WSGI 'environ' dict from raw HTTP request byte stream?
1,010,103
<p>Suppose I have a byte stream with the following in it:</p> <pre> POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"] </pre> <p>Is there a way to produce an WSGI-style 'environ' dict from it?</p> <p>Hopefully, I've overlooked an easy answer, and it is as easy to achieve as the opposite operation. Consider:</p> <pre><code>>>> import json >>> from webob import Request >>> r = Request.blank('/mum/ble?q=huh') >>> r.method = 'POST' >>> r.content_type = 'application/json' >>> r.charset = 'utf-8' >>> r.body = json.dumps(['do', 're', 'mi']) >>> print str(r) # Request's __str__ method gives raw HTTP bytes back! </code></pre> <pre>POST /mum/ble?q=huh Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"] </pre>
3
2009-06-18T00:00:43Z
1,010,639
<p>Reusing Python's standard library code for the purpose is a bit tricky (it was not designed to be reused that way!-), but should be doable, e.g:</p> <pre><code>import cStringIO from wsgiref import simple_server, util input_string = """POST /mum/ble?q=huh HTTP/1.0 Content-Length: 18 Content-Type: application/json; charset="utf-8" Host: localhost:80 ["do", "re", "mi"] """ class FakeHandler(simple_server.WSGIRequestHandler): def __init__(self, rfile): self.rfile = rfile self.wfile = cStringIO.StringIO() # for error msgs self.server = self self.base_environ = {} self.client_address = ['?', 80] self.raw_requestline = self.rfile.readline() self.parse_request() def getenv(self): env = self.get_environ() util.setup_testing_defaults(env) env['wsgi.input'] = self.rfile return env handler = FakeHandler(rfile=cStringIO.StringIO(input_string)) wsgi_env = handler.getenv() print wsgi_env </code></pre> <p>Basically, we need to subclass the request handler to fake out the construction process that's normally performed for it by the server (<code>rfile</code> and <code>wfile</code> built from the socket to the client, and so on). This isn't quite complete, I think, but should be close and I hope it proves helpful!</p> <p>Note that I've also fixed your example HTTP request: without an <code>HTTP/1.0</code> or 1.1 at the end of the raw request line, a <code>POST</code> is considered ill-formed and causes an exception and a resulting error message on <code>handler.wfile</code>.</p>
5
2009-06-18T03:27:59Z
[ "python", "wsgi", "webob" ]
How to distribute proportionally dates on a scale with Python
1,010,139
<p>I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would return 0, 16.667, and 100 (1 month = 16.667%).</p> <p>I tried to play with the <code>datetime</code> and <code>timedelta</code> classes of Python 2.5 and I am unable to achieve this. I thought I could use the number of ticks, but I am not even able to get that info from <code>datetime</code>.</p> <p>Any idea how I could write this algorithm in Python? Otherwise, any other ideas or algorithms?</p>
0
2009-06-18T00:13:16Z
1,010,169
<p>I don't know if I fully understand what you are trying to do, but you can just deal with times as number of seconds since the UNIX epoch and then just use plain old subtraction to get a range that you can scale to the size of your plot.</p> <p>In processing, the map function will handle this case for you. <a href="http://processing.org/reference/map_.html" rel="nofollow">http://processing.org/reference/map_.html</a> I'm sure you can adapt this for your purpose</p>
0
2009-06-18T00:26:47Z
[ "python", "algorithm", "datetime", "timedelta" ]
How to distribute proportionally dates on a scale with Python
1,010,139
<p>I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would return 0, 16.667, and 100 (1 month = 16.667%).</p> <p>I tried to play with the <code>datetime</code> and <code>timedelta</code> classes of Python 2.5 and I am unable to achieve this. I thought I could use the number of ticks, but I am not even able to get that info from <code>datetime</code>.</p> <p>Any idea how I could write this algorithm in Python? Otherwise, any other ideas or algorithms?</p>
0
2009-06-18T00:13:16Z
1,010,200
<p>It's fairly easy to convert a timedelta into a numeric value.</p> <p>Select an epoch time. Calculate deltas for every value relative to the epoch. Convert the delta's into a numeric value. Then map the numeric values as you normally would.</p> <p>Conversion is straight forward. Something like:</p> <pre><code>def f(delta): return delta.seconds + delta.days * 1440 * 60 + (delta.microseconds / 1000000.0) </code></pre>
1
2009-06-18T00:37:20Z
[ "python", "algorithm", "datetime", "timedelta" ]
How to distribute proportionally dates on a scale with Python
1,010,139
<p>I have a very simple charting component which takes integer on the x/y axis. My problem is that I need to represent date/float on this chart. So I though I could distribute proportionally dates on a scale. In other words, let's say I have the following date : 01/01/2008, 02/01/2008 and 31/12/2008. The algorithm would return 0, 16.667, and 100 (1 month = 16.667%).</p> <p>I tried to play with the <code>datetime</code> and <code>timedelta</code> classes of Python 2.5 and I am unable to achieve this. I thought I could use the number of ticks, but I am not even able to get that info from <code>datetime</code>.</p> <p>Any idea how I could write this algorithm in Python? Otherwise, any other ideas or algorithms?</p>
0
2009-06-18T00:13:16Z
1,010,248
<p>If you're dealing with dates, then you can use the method <a href="http://docs.python.org/library/datetime.html#datetime.date.toordinal" rel="nofollow">toordinal</a>.</p> <pre><code>import datetime jan1=datetime.datetime(2008,1,1) dec31=datetime.datetime(2008,12,31) feb1=datetime.datetime(2008,02,01) dates=[jan1,dec31,feb1] dates.sort() datesord=[d.toordinal() for d in dates] start,end=datesord[0],datesord[-1] def datetofloat(date,start,end): """date,start,end are ordinal dates ie Jan 1 of the year 1 has ordinal 1 Jan 1 of the year 2008 has ordinal 733042""" return (date-start)*1.0/(end-start) print datetofloat(dates[0],start,end) 0.0 print datetofloat(dates[1],start,end) 0.0849315068493* print datetofloat(dates[2],start,end) 1.0 </code></pre> <p>*16.67% is about two months of a year, so the proportion for Feb 1 is about half of that.</p>
3
2009-06-18T00:51:12Z
[ "python", "algorithm", "datetime", "timedelta" ]
Would extracting page metadata be a good use of multiple inheritance?
1,010,349
<p>I was wondering if I have a couple of models which both include fields like "meta_keywords" or "slug" which have to do with the web page the model instance will be displayed on, whether it would be advisable to break those page metadata elements out into their own class, say PageMeta, and have my other models subclass those via multiple inheritance?</p>
1
2009-06-18T01:26:58Z
1,010,420
<p>General advice for a lightly-specified question:</p> <p>Nontrivial multiple inheritance in Python requires Advanced Techniques to deal with the metaclass/metatype conflict. Look over <a href="http://code.activestate.com/recipes/204197/" rel="nofollow">this recipe</a> from the ActiveState archives and see if it looks like the kind of stuff you like:</p> <h2>Extract from linked recipe:</h2> <blockquote> <p>The simplest case where a metatype conflict happens is the following. Consider a class A with metaclass <code>M_A</code> and a class B with an independent metaclass <code>M_B</code>; suppose we derive C from A and B. The question is: what is the metaclass of C ? Is it <code>M_A</code> or <code>M_B</code> ?</p> <p>The correct answer (see the book "Putting metaclasses to work" for a thoughtful discussion) is <code>M_C</code>, where <code>M_C</code> is a metaclass that inherits from <code>M_A</code> and <code>M_B</code>.</p> <p>However, Python is not that magic, and it does not automatically create <code>M_C</code>. Instead, it raises a TypeError, warning the programmer of the possible confusion.</p> </blockquote> <p>Consequently, I recommend limiting your use of multiple inheritance in Python to the following cases:</p> <ol> <li>You must, because your problem domain requires you to combine two separately-maintained single-inheritance libraries.</li> <li>You have achieved such fluency with metatype and metaclass that you can write <a href="http://code.activestate.com/recipes/204197/" rel="nofollow">recipe 204197</a> or its equivalent as easily and confidently as you can write a print statement. </li> </ol> <p>Edit:</p> <p>Here's Guido van Rossum in <a href="http://www.network-theory.co.uk/docs/pytut/MultipleInheritance.html" rel="nofollow">An Introduction to Python</a>:</p> <blockquote> <p>It is clear that indiscriminate use of multiple inheritance is a maintenance nightmare, given the reliance in Python on conventions to avoid accidental name conflicts.</p> </blockquote> <p>Here he is again in <a href="http://www.python.org/dev/peps/pep-0253/" rel="nofollow">PEP 253</a>, which describes the ideas which were incorporated into Python, but not the implementation:</p> <blockquote> <p>Metatypes determine various <em>policies</em> for types, such as what happens when a type is called, how dynamic types are (whether a type's <strong>dict</strong> can be modified after it is created), what the method resolution order is, how instance attributes are looked up, and so on.</p> <p>I'll argue that left-to-right depth-first is not the best solution when you want to get the most use from multiple inheritance.</p> <p>I'll argue that with multiple inheritance, the metatype of the subtype must be a descendant of the metatypes of all base types.</p> </blockquote> <p>This does <em>not</em> mean you shouldn't use multiple inheritance; I'm just warning you so you won't be suprised one day to find yourself slapping your forehead and exclaiming "D'oh! The metatype of one of my subtypes isn't a descendant of the metatypes of all its base types! Don't you hate when that happens?"</p>
0
2009-06-18T02:01:10Z
[ "python", "django", "architecture", "multiple-inheritance", "mixins" ]
Python factorization
1,010,381
<p>I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.<br/> For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360)<br/> Then I could write:<br/></p> <pre><code>for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k </code></pre> <p>But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?</p>
11
2009-06-18T01:39:13Z
1,010,445
<p>Basically, what you have here is a set, consisting of each factor of the target number. In your example, the set would be <code>{2 2 2 3 3 5}</code>. Each strict subset of that set is the factorization of one of the divisors of your number, so if you can generate all the subsets of that set, you can multiply the elements of each subset together and get all the integer divisors.</p> <p>The code should be pretty obvious from there: generate a list containing the factorization, generate all subsets of that list (bonus points for using a generator; I think there's a relevant function in the standard library). Then multiply and go from there. Not optimally efficient by any means, but nice looking.</p>
1
2009-06-18T02:11:16Z
[ "python", "algorithm" ]
Python factorization
1,010,381
<p>I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.<br/> For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360)<br/> Then I could write:<br/></p> <pre><code>for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k </code></pre> <p>But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?</p>
11
2009-06-18T01:39:13Z
1,010,460
<p>Using <a href="http://docs.python.org/library/itertools.html#itertools.product"><code>itertools.product</code></a> from Python 2.6:</p> <pre><code>#!/usr/bin/env python import itertools, operator def all_factors(prime_dict): series = [[p**e for e in range(maxe+1)] for p, maxe in prime_dict.items()] for multipliers in itertools.product(*series): yield reduce(operator.mul, multipliers) </code></pre> <p>Example:</p> <pre><code>print sorted(all_factors({2:3, 3:2, 5:1})) </code></pre> <p>Output:</p> <pre><code>[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360] </code></pre>
10
2009-06-18T02:17:59Z
[ "python", "algorithm" ]
Python factorization
1,010,381
<p>I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.<br/> For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360)<br/> Then I could write:<br/></p> <pre><code>for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k </code></pre> <p>But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?</p>
11
2009-06-18T01:39:13Z
1,010,461
<p>Yes. When you've got an algorithm that needs n nested for loops, you can usually turn it into a recursive function:</p> <pre><code>def print_factors(d, product=1): if len(d) == 0: # Base case: we've dealt with all prime factors, so print product # Just print the product return d2 = dict(d) # Copy the dict because we don't want to modify it k,v = d2.popitem() # Pick any k**v pair from it for i in range(v+1): # For all possible powers i of k from 0 to v (inclusive) # Multiply the product by k**i and recurse. print_factors(d2, product*k**i) d = {2:3, 3:2, 5:1} print_factors(d) </code></pre>
3
2009-06-18T02:18:11Z
[ "python", "algorithm" ]
Python factorization
1,010,381
<p>I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.<br/> For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360)<br/> Then I could write:<br/></p> <pre><code>for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k </code></pre> <p>But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?</p>
11
2009-06-18T01:39:13Z
1,010,463
<p>Well, not only you have 3 loops, but this approach won't work if you have more than 3 factors :)</p> <p>One possible way:</p> <pre><code>def genfactors(fdict): factors = set([1]) for factor, count in fdict.iteritems(): for ignore in range(count): factors.update([n*factor for n in factors]) # that line could also be: # factors.update(map(lambda e: e*factor, factors)) return factors factors = {2:3, 3:2, 5:1} for factor in genfactors(factors): print factor </code></pre> <p>Also, you can avoid duplicating some work in the inner loop: if your working set is (1,3), and want to apply to 2^3 factors, we were doing:</p> <ul> <li><code>(1,3) U (1,3)*2 = (1,2,3,6)</code></li> <li><code>(1,2,3,6) U (1,2,3,6)*2 = (1,2,3,4,6,12)</code></li> <li><code>(1,2,3,4,6,12) U (1,2,3,4,6,12)*2 = (1,2,3,4,6,8,12,24)</code></li> </ul> <p>See how many duplicates we have in the second sets?</p> <p>But we can do instead:</p> <ul> <li><code>(1,3) + (1,3)*2 = (1,2,3,6)</code></li> <li><code>(1,2,3,6) + ((1,3)*2)*2 = (1,2,3,4,6,12)</code></li> <li><code>(1,2,3,4,6,12) + (((1,3)*2)*2)*2 = (1,2,3,4,6,8,12,24)</code></li> </ul> <p>The solution looks even nicer without the sets:</p> <pre><code>def genfactors(fdict): factors = [1] for factor, count in fdict.iteritems(): newfactors = factors for ignore in range(count): newfactors = map(lambda e: e*factor, newfactors) factors += newfactors return factors </code></pre>
9
2009-06-18T02:18:50Z
[ "python", "algorithm" ]
Python factorization
1,010,381
<p>I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents.<br/> For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360)<br/> Then I could write:<br/></p> <pre><code>for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k </code></pre> <p>But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?</p>
11
2009-06-18T01:39:13Z
1,011,573
<p>I have <a href="http://numericalrecipes.wordpress.com/tag/divisors/">blogged about this</a>, and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators:</p> <pre><code>def divisors(factors) : """ Generates all divisors, unordered, from the prime factorization. """ ps = sorted(set(factors)) omega = len(ps) def rec_gen(n = 0) : if n == omega : yield 1 else : pows = [1] for j in xrange(factors.count(ps[n])) : pows += [pows[-1] * ps[n]] for q in rec_gen(n + 1) : for p in pows : yield p * q for p in rec_gen() : yield p </code></pre> <p>Note that the way it is written, it takes a list of prime factors, not a dictionary, i.e. <code>[2, 2, 2, 3, 3, 5]</code> instead of <code>{2 : 3, 3 : 2, 5 : 1}</code>.</p>
14
2009-06-18T08:53:59Z
[ "python", "algorithm" ]
plot line at particular angle and offset
1,010,423
<p>I'm attempting to plot a particular line over an original image (an array) that i have. Basically, I have an angle and offset (measured from the center of the image) that I want to plot the line over. The problem is, I'm not exactly sure how to do this. I can write a really complicated piece of code to do this, but I'm wondering if there's an easier way that I don't know of (maybe with matplotlib). Thanks.</p>
0
2009-06-18T02:02:47Z
1,010,604
<p>Assuming that your offset is actually a x, y coordinate of the center of the line, and that the line should be a fixed length, then it's a simple matter of trigonometry with matplotlib:</p> <pre><code>x = [offsetx-linelength*cos(angle), offsetx+linelength*cos(angle)] y = [offsety-linelength*sin(angle), offsety+linelength*sin(angle)] plot(x, y, '-') </code></pre>
0
2009-06-18T03:15:13Z
[ "python", "image", "plot", "offset", "angle" ]
plot line at particular angle and offset
1,010,423
<p>I'm attempting to plot a particular line over an original image (an array) that i have. Basically, I have an angle and offset (measured from the center of the image) that I want to plot the line over. The problem is, I'm not exactly sure how to do this. I can write a really complicated piece of code to do this, but I'm wondering if there's an easier way that I don't know of (maybe with matplotlib). Thanks.</p>
0
2009-06-18T02:02:47Z
1,010,644
<p>You may want to look at <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> If you do a lot of image manipulation.</p>
0
2009-06-18T03:30:44Z
[ "python", "image", "plot", "offset", "angle" ]
plot line at particular angle and offset
1,010,423
<p>I'm attempting to plot a particular line over an original image (an array) that i have. Basically, I have an angle and offset (measured from the center of the image) that I want to plot the line over. The problem is, I'm not exactly sure how to do this. I can write a really complicated piece of code to do this, but I'm wondering if there's an easier way that I don't know of (maybe with matplotlib). Thanks.</p>
0
2009-06-18T02:02:47Z
1,010,659
<p>Use PIL and draw line, cricle, or another image over the original image</p> <pre><code>import Image, ImageDraw im = Image.open("my.png") draw = ImageDraw.Draw(im) draw.line((0, 0, 100, 100), fill=128) del draw # write to stdout im.save(sys.stdout, "PNG") </code></pre>
1
2009-06-18T03:37:30Z
[ "python", "image", "plot", "offset", "angle" ]
Mapping URL Pattern to a Single RequestHandler in a WSGIApplication
1,010,427
<p>Is it possible to map a URL pattern (regular expression or some other mapping) to a single RequestHandler? If so how can I accomplish this?</p> <p>Ideally I'd like to do something like this:</p> <pre><code>application=WSGIApplication([('/*',MyRequestHandler),]) </code></pre> <p>So that MyRequestHandler handles all requests made. Note that I'm working on a proof of concept app where by definition I won't know all URLs that will be coming to the domain. Also note that I'm doing this on Google App Engine if that matters.</p>
3
2009-06-18T02:05:22Z
1,010,452
<pre><code>application=WSGIApplication([(r'.*',MyRequestHandler),]) </code></pre> <p>for more see <a href="http://code.google.com/appengine/docs/python/tools/webapp/running.html" rel="nofollow">the AppEngine docs</a></p>
1
2009-06-18T02:16:30Z
[ "python", "google-app-engine" ]
Mapping URL Pattern to a Single RequestHandler in a WSGIApplication
1,010,427
<p>Is it possible to map a URL pattern (regular expression or some other mapping) to a single RequestHandler? If so how can I accomplish this?</p> <p>Ideally I'd like to do something like this:</p> <pre><code>application=WSGIApplication([('/*',MyRequestHandler),]) </code></pre> <p>So that MyRequestHandler handles all requests made. Note that I'm working on a proof of concept app where by definition I won't know all URLs that will be coming to the domain. Also note that I'm doing this on Google App Engine if that matters.</p>
3
2009-06-18T02:05:22Z
1,012,365
<p>The pattern you describe will work fine. Also, any groups in the regular expression you specify will be passed as arguments to the handler methods (get, post, etc). For example:</p> <pre><code>class MyRequestHandler(webapp.RequestHandler): def get(self, date, id): # Do stuff. Note that date and id are both strings, even if the groups are numeric. application = WSGIApplication([('/(\d{4}-\d{2}-\d{2})/(\d+)', MyRequestHandler)]) </code></pre> <p>In the above example, the two groups (a date and an id) are broken out and passed as arguments to your handler functions.</p>
8
2009-06-18T12:27:29Z
[ "python", "google-app-engine" ]
Mathematical equation manipulation in Python
1,010,583
<p>I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.</p> <p>For example:</p> <hr> <pre><code>a = (b+c*d)/e </code></pre> <p><i>Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:</i></p> <pre><code>d = (a*e - b)/c </code></pre> <hr> <p>As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.</p> <p>Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. </p> <p>But that is just my opinion, so please point out if I am wrong. Also, I will be using <a href="http://en.wikipedia.org/wiki/SymPy" rel="nofollow">SymPy</a> for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.</p>
10
2009-06-18T03:07:52Z
1,010,613
<p>Sage has support for symbolic math. You could just use some of the equation manipulating functions built-in:</p> <p><a href="http://sagemath.org/" rel="nofollow">http://sagemath.org/</a></p>
3
2009-06-18T03:16:47Z
[ "python", "math", "equation" ]
Mathematical equation manipulation in Python
1,010,583
<p>I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.</p> <p>For example:</p> <hr> <pre><code>a = (b+c*d)/e </code></pre> <p><i>Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:</i></p> <pre><code>d = (a*e - b)/c </code></pre> <hr> <p>As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.</p> <p>Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. </p> <p>But that is just my opinion, so please point out if I am wrong. Also, I will be using <a href="http://en.wikipedia.org/wiki/SymPy" rel="nofollow">SymPy</a> for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.</p>
10
2009-06-18T03:07:52Z
1,010,637
<p>What you want to do isn't easy. Some equations are quite straight forward to rearrange (like make <code>b</code> the subject of <code>a = b*c+d</code>, which is <code>b = (a-d)/c</code>), while others are not so obvious (like make <code>x</code> the subject of <code>y = x*x + 4*x + 4</code>), while others are not possible (especially when you trigonometric functions and other complications).</p> <p>As other people have said, check out Sage. It <a href="http://sagemath.org/doc/tutorial/tour%5Falgebra.html" rel="nofollow">does</a> what you want:</p> <pre><code>You can solve equations for one variable in terms of others: sage: x, b, c = var('x b c') sage: solve([x^2 + b*x + c == 0],x) [x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)] </code></pre>
4
2009-06-18T03:26:53Z
[ "python", "math", "equation" ]
Mathematical equation manipulation in Python
1,010,583
<p>I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.</p> <p>For example:</p> <hr> <pre><code>a = (b+c*d)/e </code></pre> <p><i>Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:</i></p> <pre><code>d = (a*e - b)/c </code></pre> <hr> <p>As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.</p> <p>Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. </p> <p>But that is just my opinion, so please point out if I am wrong. Also, I will be using <a href="http://en.wikipedia.org/wiki/SymPy" rel="nofollow">SymPy</a> for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.</p>
10
2009-06-18T03:07:52Z
1,010,666
<p>Using <a href="http://sympy.org/" rel="nofollow">SymPy</a>, your example would go something like this:</p> <pre><code>&gt;&gt;&gt; import sympy &gt;&gt;&gt; a,b,c,d,e = sympy.symbols('abcde') &gt;&gt;&gt; r = (b+c*d)/e &gt;&gt;&gt; l = a &gt;&gt;&gt; r = sympy.solve(l-r,d) &gt;&gt;&gt; l = d &gt;&gt;&gt; r [(-b + a*e)/c] &gt;&gt;&gt; </code></pre> <p>It seems to work for trigonometric functions too:</p> <pre><code>&gt;&gt;&gt; l = a &gt;&gt;&gt; r = b*sympy.sin(c) &gt;&gt;&gt; sympy.solve(l-r,c) [asin(a/b)] &gt;&gt;&gt; </code></pre> <p>And since you are working with a GUI, you'll (probably) want to convert back and forth from strings to expressions:</p> <pre><code>&gt;&gt;&gt; r = '(b+c*d)/e' &gt;&gt;&gt; sympy.sympify(r) (b + c*d)/e &gt;&gt;&gt; sympy.sstr(_) '(b + c*d)/e' &gt;&gt;&gt; </code></pre> <p>or you may prefer to display them as rendered <a href="http://docs.sympy.org/latest/tutorial/printing.html" rel="nofollow">LaTeX or MathML</a>.</p>
20
2009-06-18T03:40:25Z
[ "python", "math", "equation" ]
Mathematical equation manipulation in Python
1,010,583
<p>I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.</p> <p>For example:</p> <hr> <pre><code>a = (b+c*d)/e </code></pre> <p><i>Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:</i></p> <pre><code>d = (a*e - b)/c </code></pre> <hr> <p>As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.</p> <p>Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. </p> <p>But that is just my opinion, so please point out if I am wrong. Also, I will be using <a href="http://en.wikipedia.org/wiki/SymPy" rel="nofollow">SymPy</a> for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.</p>
10
2009-06-18T03:07:52Z
1,010,712
<p>If you want to do this out of the box, without relying on librairies, I think that the problems you will find are not Python related. If you want to find such equations, you have to describe the heuristics necessary to solve these equations.</p> <p>First, you have to represent your equation. What about separating:</p> <ul> <li>operands: <ul> <li>symbolic operands (a,b)</li> <li>numeric operands (1,2)</li> </ul></li> <li>operators: <ul> <li>unary operators (-, trig functions)</li> <li>binary operators (+,-,*,/)</li> </ul></li> </ul> <p>Unary operators will obviously enclose one operand, binary ops will enclose two.</p> <p>What about types?</p> <p>I think that all of these components should derivate from a single common <code>expression</code> type. And this class would have a <code>getsymbols</code> method to locate quickly symbols in your expressions. </p> <p>And then distinguish between unary and binary operators, add a few basic complement/reorder primitives...</p> <p>Something like:</p> <pre><code>class expression(object): def symbols(self): if not hasattr(self, '_symbols'): self._symbols = self._getsymbols() return self._symbols def _getsymbols(self): """ return type: list of strings """ raise NotImplementedError class operand(expression): pass class symbolicoperand(operand): def __init__(self, name): self.name = name def _getsymbols(self): return [self.name] def __str__(self): return self.name class numericoperand(operand): def __init__(self, value): self.value = value def _getsymbols(self): return [] def __str__(self): return str(self.value) class operator(expression): pass class binaryoperator(operator): def __init__(self, lop, rop): """ @type lop, rop: expression """ self.lop = lop self.rop = rop def _getsymbols(self): return self.lop._getsymbols() + self.rop._getsymbols() @staticmethod def complementop(): """ Return complement operator: op.complementop()(op(a,b), b) = a """ raise NotImplementedError def reorder(): """ for op1(a,b) return op2(f(b),g(a)) such as op1(a,b) = op2(f(a),g(b)) """ raise NotImplementedError def _getstr(self): """ string representing the operator alone """ raise NotImplementedError def __str__(self): lop = str(self.lop) if isinstance(self.lop, operator): lop = '(%s)' % lop rop = str(self.rop) if isinstance(self.rop, operator): rop = '(%s)' % rop return '%s%s%s' % (lop, self._getstr(), rop) class symetricoperator(binaryoperator): def reorder(self): return self.__class__(self.rop, self.lop) class asymetricoperator(binaryoperator): @staticmethod def _invert(operand): """ div._invert(a) -&gt; 1/a sub._invert(a) -&gt; -a """ raise NotImplementedError def reorder(self): return self.complementop()(self._invert(self.rop), self.lop) class div(asymetricoperator): @staticmethod def _invert(operand): if isinstance(operand, div): return div(self.rop, self.lop) else: return div(numericoperand(1), operand) @staticmethod def complementop(): return mul def _getstr(self): return '/' class mul(symetricoperator): @staticmethod def complementop(): return div def _getstr(self): return '*' class add(symetricoperator): @staticmethod def complementop(): return sub def _getstr(self): return '+' class sub(asymetricoperator): @staticmethod def _invert(operand): if isinstance(operand, min): return operand.op else: return min(operand) @staticmethod def complementop(): return add def _getstr(self): return '-' class unaryoperator(operator): def __init__(self, op): """ @type op: expression """ self.op = op @staticmethod def complement(expression): raise NotImplementedError def _getsymbols(self): return self.op._getsymbols() class min(unaryoperator): @staticmethod def complement(expression): if isinstance(expression, min): return expression.op else: return min(expression) def __str__(self): return '-' + str(self.op) </code></pre> <p>With this basic structure set up, you should be able to describe a simple heuristic to solve very simple equations. Just think of the simple rules you learned to solve equations, and write them down. That should work :)</p> <p>And then a very naive solver:</p> <pre><code>def solve(left, right, symbol): """ @type left, right: expression @type symbol: string """ if symbol not in left.symbols(): if symbol not in right.symbols(): raise ValueError('%s not in expressions' % symbol) left, right = right, left solved = False while not solved: if isinstance(left, operator): if isinstance(left, unaryoperator): complementor = left.complement right = complementor(right) left = complementor(left) elif isinstance(left, binaryoperator): if symbol in left.rop.symbols(): left = left.reorder() else: right = left.complementop()(right, left.rop) left = left.lop elif isinstance(left, operand): assert isinstance(left, symbolicoperand) assert symbol==left.name solved = True print symbol,'=',right a,b,c,d,e = map(symbolicoperand, 'abcde') solve(a, div(add(b,mul(c,d)),e), 'd') # d = ((a*e)-b)/c solve(numericoperand(1), min(min(a)), 'a') # a = 1 </code></pre>
6
2009-06-18T03:58:12Z
[ "python", "math", "equation" ]
Mathematical equation manipulation in Python
1,010,583
<p>I want to develop a GUI application which displays a given mathematical equation. When you click upon a particular variable in the equation to signify that it is the unknown variable ie., to be calculated, the equation transforms itself to evaluate the required unknown variable.</p> <p>For example:</p> <hr> <pre><code>a = (b+c*d)/e </code></pre> <p><i>Let us suppose that I click upon "d" to signify that it is the unknown variable. Then the equation should be re-structured to:</i></p> <pre><code>d = (a*e - b)/c </code></pre> <hr> <p>As of now, I just want to know how I can go about rearranging the given equation based on user input. One suggestion I got from my brother was to use pre-fix/post-fix notational representation in back end to evaluate it.</p> <p>Is that the only way to go or is there any simpler suggestion? Also, I will be using not only basic mathematical functions but also trignometric and calculus (basic I think. No partial differential calculus and all that) as well. I think that the pre/post-fix notation evaluation might not be helpful in evaluation higher mathematical functions. </p> <p>But that is just my opinion, so please point out if I am wrong. Also, I will be using <a href="http://en.wikipedia.org/wiki/SymPy" rel="nofollow">SymPy</a> for mathematical evaluation so evaluation of a given mathematical equation is not a problem, creating a specific equation from a given generic one is my main problem.</p>
10
2009-06-18T03:07:52Z
18,307,095
<p>Things have sure changed since 2009. I don't know how your GUI application is going, but this is now possible directly in IPython qtconsole (which one could embed inside a custom PyQt/PySide application, and keep track of all the defined symbols, to allow GUI interaction in a separate listbox, etc.)</p> <p><img src="http://i.stack.imgur.com/ax15B.png" alt="enter image description here"></p> <p><em>(Uses the <code>sympyprt</code> extension for IPython</em>)</p>
4
2013-08-19T05:47:47Z
[ "python", "math", "equation" ]
Customizing Django auto admin terminology
1,010,794
<p>I'm playing around with Django's admin module, but I've seemed to run into a bit of a bump that's more of an annoyance than an error. I have my modules setup using names like UserData and Status, so Django's admin panel likes to try to call each row in UserData a user datas and each status a statuss. Is there any way I can change the terminology so it will say, for example, Profiles instead of User Datas.</p>
2
2009-06-18T04:36:20Z
1,010,798
<p>You can define <code>verbose_name</code> and <code>verbose_name_plural</code> in your model's inner <code>Meta</code> class to override the values used there. See <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name-plural" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/options/#verbose-name-plural</a></p>
6
2009-06-18T04:40:25Z
[ "python", "django" ]
Traversing multi-dimensional dictionary in django
1,010,848
<p>I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.</p> <p>So I can create multi-dimensional arrays using <a href="http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/" rel="nofollow">this</a>, but i can't loop it in a django template. <a href="http://code.activestate.com/recipes/389639/" rel="nofollow">this</a> doesnt work but i imagine i cant loop through it if i could get it to work.</p> <pre><code>{% for key,val in dictionary.items %} </code></pre> <p>only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes. </p> <p>I'm creating my dictionary from a sql query:</p> <pre><code>vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ] vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0 vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ] </code></pre> <p>I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.</p> <p>I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn't figure that out either.</p> <p>Any help on how to accomplish my goal would be appreciated. I hope my question is clear</p> <h2>EDIT:</h2> <p>When im done looping in my template it looks like this...</p> <pre><code>&lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; </code></pre>
-1
2009-06-18T05:01:43Z
1,010,862
<p>I'm also a Django beginner...</p> <p>You should be able to nest the for loops to get something like this:</p> <pre><code>{% for key,val in dictionary.items %} {% for key,val in val.items %} </code></pre> <p>and so on.</p>
0
2009-06-18T05:08:08Z
[ "python", "django", "django-models", "dictionary", "django-templates" ]
Traversing multi-dimensional dictionary in django
1,010,848
<p>I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.</p> <p>So I can create multi-dimensional arrays using <a href="http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/" rel="nofollow">this</a>, but i can't loop it in a django template. <a href="http://code.activestate.com/recipes/389639/" rel="nofollow">this</a> doesnt work but i imagine i cant loop through it if i could get it to work.</p> <pre><code>{% for key,val in dictionary.items %} </code></pre> <p>only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes. </p> <p>I'm creating my dictionary from a sql query:</p> <pre><code>vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ] vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0 vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ] </code></pre> <p>I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.</p> <p>I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn't figure that out either.</p> <p>Any help on how to accomplish my goal would be appreciated. I hope my question is clear</p> <h2>EDIT:</h2> <p>When im done looping in my template it looks like this...</p> <pre><code>&lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; </code></pre>
-1
2009-06-18T05:01:43Z
1,010,870
<p>If you built your complicated dictionary in the following way:</p> <pre><code>vid[ video[ 7 ], 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ], 'cat_name' ] = video[ 1 ] vid[ video[ 7 ], 'cat_id' ] = video[ 7 ] vid[ video[ 7 ], 'companies', video[ 14 ], 'comp_short_name' ] = video[ 5 ] </code></pre> <p>etc, would that help? The key in this case would be a tuple (with 2 items in the first three cases, 4 items in the fourth), and I'm not sure how you mean to treat it, but the loop on items to get key and value, per se, should work fine.</p>
0
2009-06-18T05:10:13Z
[ "python", "django", "django-models", "dictionary", "django-templates" ]
Traversing multi-dimensional dictionary in django
1,010,848
<p>I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.</p> <p>So I can create multi-dimensional arrays using <a href="http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/" rel="nofollow">this</a>, but i can't loop it in a django template. <a href="http://code.activestate.com/recipes/389639/" rel="nofollow">this</a> doesnt work but i imagine i cant loop through it if i could get it to work.</p> <pre><code>{% for key,val in dictionary.items %} </code></pre> <p>only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes. </p> <p>I'm creating my dictionary from a sql query:</p> <pre><code>vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ] vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0 vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ] </code></pre> <p>I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.</p> <p>I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn't figure that out either.</p> <p>Any help on how to accomplish my goal would be appreciated. I hope my question is clear</p> <h2>EDIT:</h2> <p>When im done looping in my template it looks like this...</p> <pre><code>&lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; </code></pre>
-1
2009-06-18T05:01:43Z
1,011,027
<p><code></p> <pre><code>{% for key, val in vid.items %} &lt;h1&gt;{{ val.cat_name }}&lt;/h1&gt; {% for k2, v2 in val.companies.items %} &lt;h2&gt;{{ v2.comp_name }}&lt;/h2&gt; &lt;ul&gt; {% for k3, v3 in v2.videos.items %} &lt;li&gt;{{ v3.vid_name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} {% endfor %} </code></pre> <p></code></p>
0
2009-06-18T06:04:25Z
[ "python", "django", "django-models", "dictionary", "django-templates" ]
Traversing multi-dimensional dictionary in django
1,010,848
<p>I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.</p> <p>So I can create multi-dimensional arrays using <a href="http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/" rel="nofollow">this</a>, but i can't loop it in a django template. <a href="http://code.activestate.com/recipes/389639/" rel="nofollow">this</a> doesnt work but i imagine i cant loop through it if i could get it to work.</p> <pre><code>{% for key,val in dictionary.items %} </code></pre> <p>only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes. </p> <p>I'm creating my dictionary from a sql query:</p> <pre><code>vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ] vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0 vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ] </code></pre> <p>I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.</p> <p>I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn't figure that out either.</p> <p>Any help on how to accomplish my goal would be appreciated. I hope my question is clear</p> <h2>EDIT:</h2> <p>When im done looping in my template it looks like this...</p> <pre><code>&lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; </code></pre>
-1
2009-06-18T05:01:43Z
1,011,082
<p>When moving from one language or framework to another, you need to realise that it's not usually a good idea to write your code in exactly the same way, even if you can.</p> <p>For example:</p> <blockquote> <p>I'm creating my dictionary from a sql query</p> </blockquote> <p>Why are you doing this? The way to represent objects from a database in Django is to use a model. That will take care of a whole lot of stuff for you, including the SQL but will also help with iterating through related tables.</p>
2
2009-06-18T06:22:54Z
[ "python", "django", "django-models", "dictionary", "django-templates" ]
Traversing multi-dimensional dictionary in django
1,010,848
<p>I'm a PHP guy on my first day in Python-land, trying to convert a php site to python (learning experience), and I'm hurting for advice. I never thought it would be so hard to use multi-dimensional arrays or dictionaries as you pythoners call them.</p> <p>So I can create multi-dimensional arrays using <a href="http://parand.com/say/index.php/2007/07/13/simple-multi-dimensional-dictionaries-in-python/" rel="nofollow">this</a>, but i can't loop it in a django template. <a href="http://code.activestate.com/recipes/389639/" rel="nofollow">this</a> doesnt work but i imagine i cant loop through it if i could get it to work.</p> <pre><code>{% for key,val in dictionary.items %} </code></pre> <p>only works for actual dictionaries it seems, not the custon multi-dimensional dictionary classes. </p> <p>I'm creating my dictionary from a sql query:</p> <pre><code>vid[ video[ 7 ] ][ 'cat_short_name' ] = video[ 2 ] vid[ video[ 7 ] ][ 'cat_name' ] = video[ 1 ] vid[ video[ 7 ] ][ 'cat_id' ] = video[ 7 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_short_name' ] = video[ 5 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_name' ] = video[ 4 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'comp_website' ] = video[ 6 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'top_video' ] = 0 vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_id' ] = video[ 8 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_name' ] = video[ 9 ] vid[ video[ 7 ] ][ 'companies' ][ video[ 14 ] ][ 'videos' ][ video[ 8 ] ][ 'vid_url' ] = video[ 10 ] </code></pre> <p>I basically need to get all companies in a certain category and then get all videos in that company so i can nest them easily in my template. This is how i did it in php, creating one huge deep array. Trying to duplicate in Python has proven difficult.</p> <p>I thought maybe i could do with the backwards lookups in django using set_MODEL but i couldn't figure that out either.</p> <p>Any help on how to accomplish my goal would be appreciated. I hope my question is clear</p> <h2>EDIT:</h2> <p>When im done looping in my template it looks like this...</p> <pre><code>&lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h1&gt;Category&lt;/h1&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; &lt;h2&gt;Company&lt;/h2&gt; &lt;ul&gt; &lt;li&gt;video&lt;/li&gt; &lt;li&gt;video&lt;/li&gt; &lt;/ul&gt; </code></pre>
-1
2009-06-18T05:01:43Z
1,011,145
<p>You should be using the built in <a href="http://docs.djangoproject.com/en/dev/topics/db/" rel="nofollow">ORM</a> instead of using your own queries (at least for something simple like this), makes things much easier (assuming you've also built your models in your models.py file)</p> <p>In your view:</p> <pre><code>def categories_view(request): categories = Categories.objects.all() #maybe put an order_by or filter here return render_to_response("your_template.html", {'categories':categories}) </code></pre> <p>In your template:</p> <pre><code>{% for category in categories %} &lt;h1&gt;{{ category.name }}&lt;/h1&gt; {% for company in category.company_set.all %} &lt;h2&gt;{{ company.name }}&lt;/h2&gt; &lt;ul&gt; {% for video in company.video_set.all %} &lt;li&gt;{{ video.name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endfor %} {% endfor %} </code></pre> <p>I haven't tested it but it should work. Compare this code to what you would have to write if you weren't using ORM, in either PHP or Python.</p> <p>take a look at the django docs for more info, I'd recommend taking a few hours and doing the <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01" rel="nofollow">tutorial</a>.</p> <p><strong>Update:</strong> modified the code to use "_set.all"</p>
3
2009-06-18T06:54:50Z
[ "python", "django", "django-models", "dictionary", "django-templates" ]
how many places are optimized in Python's bytecode(version 2.5)
1,010,914
<p>Can anyone tell me how many places there are optimized in Python's bytecode? I was trying to de-compile Python's bytecode these days,but I found that in Python's version 2.5 there are a lot of optimization.For example: to this code</p> <pre><code>a,b,c=([],[],[])#build list </code></pre> <p>the non-optimized bytecode before version2.5 is like that:</p> <pre><code>BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_4 UNPACK_LIST_ STORE_NAME 'a' STORE_NAME 'b' STORE_NAME 'c' </code></pre> <p>In the version2.5,the optimized bytecode is like this:</p> <pre><code>BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_0 ROT_THREE ROT_TWO STORE_FAST 'a' STORE_FAST 'b' STORE_FAST 'c' </code></pre> <p>This is only one example,but there are many other places may be optimized. So,does anybode know is there some documentation to clarify these optimization or tell me in which way I can find all of them?</p>
1
2009-06-18T05:33:29Z
1,010,947
<p>I don't think there's any documentation per se, but there's the C code for the Python interpreter. You can find several different versions of it <a href="http://python.org/download/releases/" rel="nofollow">here</a>.</p>
0
2009-06-18T05:41:59Z
[ "python", "bytecode" ]
how many places are optimized in Python's bytecode(version 2.5)
1,010,914
<p>Can anyone tell me how many places there are optimized in Python's bytecode? I was trying to de-compile Python's bytecode these days,but I found that in Python's version 2.5 there are a lot of optimization.For example: to this code</p> <pre><code>a,b,c=([],[],[])#build list </code></pre> <p>the non-optimized bytecode before version2.5 is like that:</p> <pre><code>BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_4 UNPACK_LIST_ STORE_NAME 'a' STORE_NAME 'b' STORE_NAME 'c' </code></pre> <p>In the version2.5,the optimized bytecode is like this:</p> <pre><code>BUILD_LIST_0 BUILD_LIST_0 BUILD_LIST_0 ROT_THREE ROT_TWO STORE_FAST 'a' STORE_FAST 'b' STORE_FAST 'c' </code></pre> <p>This is only one example,but there are many other places may be optimized. So,does anybode know is there some documentation to clarify these optimization or tell me in which way I can find all of them?</p>
1
2009-06-18T05:33:29Z
1,010,963
<p>The <a href="http://svn.python.org/projects/python/trunk/Python/peephole.c" rel="nofollow">Python/peephole.c</a> source file is where basically all such optimizations are performed -- the link I gave is to the current version (2.6 or better), because I'm having trouble getting to the dynamic source browser <a href="http://svn.python.org/view/python/?view=log" rel="nofollow">here</a>, but once it works again it's easy to see specific versions such as the one that was extant for (say) 2.5.2 or whatever other specific version you need this information for.</p>
2
2009-06-18T05:46:05Z
[ "python", "bytecode" ]
String Slicing Python
1,010,961
<p>I have a string, example:</p> <pre><code>s = "this is a string, a" </code></pre> <p>where ','(comma) will always be the 3rd last character, aka s[-3].</p> <p>I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task. </p> <p>How can i accomplish this in a simpler way?</p>
5
2009-06-18T05:45:47Z
1,010,973
<p>Normally, you would just do:</p> <pre><code>s = s[:-3] + s[-2:] </code></pre> <p>The <code>s[:-3]</code> gives you a string up to, but not including, the comma you want removed (<code>"this is a string"</code>) and the <code>s[-2:]</code> gives you another string starting one character beyond that comma (<code>" a"</code>).</p> <p>Then, joining the two strings together gives you what you were after (<code>"this is a string a"</code>).</p>
23
2009-06-18T05:48:55Z
[ "python" ]
String Slicing Python
1,010,961
<p>I have a string, example:</p> <pre><code>s = "this is a string, a" </code></pre> <p>where ','(comma) will always be the 3rd last character, aka s[-3].</p> <p>I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task. </p> <p>How can i accomplish this in a simpler way?</p>
5
2009-06-18T05:45:47Z
1,010,991
<p>Python strings are immutable. This means that you <strong>must</strong> create at least 1 new string in order to remove the comma, as opposed to editing the string in place in a language like C.</p>
2
2009-06-18T05:52:41Z
[ "python" ]
String Slicing Python
1,010,961
<p>I have a string, example:</p> <pre><code>s = "this is a string, a" </code></pre> <p>where ','(comma) will always be the 3rd last character, aka s[-3].</p> <p>I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task. </p> <p>How can i accomplish this in a simpler way?</p>
5
2009-06-18T05:45:47Z
1,011,397
<p>For deleting every ',' character in the text, you can try</p> <pre><code>s = s.split(',') &gt;&gt; ["this is a string", " a"] s = "".join(s) &gt;&gt; "this is a string a" </code></pre> <p>Or in one line:</p> <pre><code>s0 = "".join(s.split(',')) </code></pre>
1
2009-06-18T08:08:53Z
[ "python" ]
String Slicing Python
1,010,961
<p>I have a string, example:</p> <pre><code>s = "this is a string, a" </code></pre> <p>where ','(comma) will always be the 3rd last character, aka s[-3].</p> <p>I am thinking of ways to remove the ',' but can only think of converting the string into a list, deleting it, and converting it back to a string. This however seems a bit too much for simple task. </p> <p>How can i accomplish this in a simpler way?</p>
5
2009-06-18T05:45:47Z
1,011,645
<p>A couple of variants, using the "delete the last comma" rather than "delete third last character" are:</p> <pre><code>s[::-1].replace(",","",1)[::-1] </code></pre> <p>or</p> <pre><code>''.join(s.rsplit(",", 1)) </code></pre> <p>But these are pretty ugly. Slightly better is:</p> <pre><code>a, _, b = s.rpartition(",") s = a + b </code></pre> <p>This may be the best approach if you don't know the comma's position (except for last comma in string) and effectively need a "replace from right". However <a href="http://stackoverflow.com/questions/1010961/string-slicing-python/1010973#1010973">Anurag's answer</a> is more pythonic for the "delete third last character".</p>
5
2009-06-18T09:13:15Z
[ "python" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
1,011,195
<p>Silverlight/Flash are interesting but closed platform</p> <p><a href="http://www.openlaszlo.org/" rel="nofollow">openlaszlo</a> is another RIA platform which you should consider, you write in XML/javascript and output to multiple platforms e.g. Flash/DHTML and may be more in future</p> <p>another candidate is <a href="http://www.appcelerator.com/" rel="nofollow">Titanium</a> where you can use python</p> <p>my personal choice would be to just use plain javascript/HTML and may be HTML5 if possible django on server side, jquery on client side</p>
1
2009-06-18T07:09:50Z
[ "python", "silverlight", "html5", "ria" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
1,011,196
<p>If you have a year to prepare I recommend that you research all the technologies you can. Build the hello worlds for the different platforms. Then build the SAME simple RIA on each candidate framework to get a good feel for the differences. Obviously you will not uncover every little gotcha, but the gross architectures and styles will be evident.</p>
2
2009-06-18T07:10:04Z
[ "python", "silverlight", "html5", "ria" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
1,011,396
<p>You should focus on “HTML5” where “HTML5” is the new “Ajax” buzzword aka. the “Open Web Platform”—not just the HTML 5 spec itself.</p> <p>Flash, Silverlight and JavaFX are all single-vendor plug-in offerings but “HTML5” is a multi-vendor browser-native thing.</p> <p>If you want to an IDE workflow, you can use the Google Web Toolkit to have a Java workflow that targets the browser-native plug-inless feature set. Unfortunately, there’s no GWT-like Python system yet.</p>
2
2009-06-18T08:08:47Z
[ "python", "silverlight", "html5", "ria" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
1,020,743
<p>I would recommend Flash/Flex/AIR. It would definitely gives you the most freedom to build what you want.</p> <p>Flex is great for making RIAs, and now with AIR, you can now deploy to the desktop.</p> <p>Here are a few links:</p> <ul> <li><a href="http://www.adobe.com/resources/business/rich%5Finternet%5Fapps/#open" rel="nofollow">Rich internet apps on Adobe.com</a></li> <li><a href="http://www.flex888.com/" rel="nofollow">Flex RIA</a></li> </ul>
1
2009-06-20T02:03:14Z
[ "python", "silverlight", "html5", "ria" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
1,020,763
<p>Check out <a href="http://www.appcelerator.com/" rel="nofollow">Titanium</a> while you're looking around. It's similar to AIR, and you can use your Python chops.</p> <p>Otherwise, I would say go as HTML/CSS/JavaScript as you can, and use Flash for any multimedia that you can't get to work otherwise. Keep in mind that mobile web is exploding and right now Flash is not a great solution for mobile (or at least not yet).</p>
1
2009-06-20T02:15:22Z
[ "python", "silverlight", "html5", "ria" ]
What to learn for RIA
1,011,168
<p>I am planning to build a RIA about a year from now (when my current contract ends). What technology would you recommend investing time in? </p> <p>I will need good cross browser/platform support for video, music, and canvas. And ideally I would like to leverage my Python skills.</p> <p>Silverlight looks interesting because I could use Python through .NET. But I'm on Linux so I'd always be a 2nd class citizen. And it has a low install base. Flash on the other hand has a large install base. And I'm not sure about JavaFX because of the Oracle deal.</p> <p>Or should I hold my hopes out for HTML 5?</p> <p>Thanks!</p>
1
2009-06-18T06:59:45Z
12,746,438
<p><a href="http://pyjs.org/" rel="nofollow">http://pyjs.org/</a> pyjs is a Rich Internet Application (RIA) Development Platform for both Web and Desktop. With pyjs you can write your JavaScript-powered web applications entirely in Python.</p>
0
2012-10-05T12:37:45Z
[ "python", "silverlight", "html5", "ria" ]
Relative file paths in Python packages
1,011,337
<p>How do I reference a file relatively to a package's directory?</p> <p>My directory structure is:</p> <pre> /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py </pre> <p><code>script.py</code> imports packages <code>package1</code> and <code>package2</code>. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, <code>package1</code> to ensure it would work in case <code>os.path.curdir</code> is arbitrary?</p>
8
2009-06-18T07:51:23Z
1,011,366
<p>If you want to reference files from the <code>foo/package1/resources</code> folder you would want to use the <code>__file__</code> variable of the module. Inside <code>foo/package1/__init__.py</code>:</p> <pre><code>from os import path resources_dir = path.join(path.dirname(__file__), 'resources') </code></pre>
10
2009-06-18T08:00:44Z
[ "python", "reference", "packages", "relative-path" ]
Relative file paths in Python packages
1,011,337
<p>How do I reference a file relatively to a package's directory?</p> <p>My directory structure is:</p> <pre> /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py </pre> <p><code>script.py</code> imports packages <code>package1</code> and <code>package2</code>. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, <code>package1</code> to ensure it would work in case <code>os.path.curdir</code> is arbitrary?</p>
8
2009-06-18T07:51:23Z
1,011,435
<p>This is a bad idea, because, if your package was installed as zipped egg, then resources can be unavailable.</p> <p>If you use setuptool, don't forget to add zip_safe=False to the setup.py config.</p>
0
2009-06-18T08:20:28Z
[ "python", "reference", "packages", "relative-path" ]
Relative file paths in Python packages
1,011,337
<p>How do I reference a file relatively to a package's directory?</p> <p>My directory structure is:</p> <pre> /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py </pre> <p><code>script.py</code> imports packages <code>package1</code> and <code>package2</code>. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, <code>package1</code> to ensure it would work in case <code>os.path.curdir</code> is arbitrary?</p>
8
2009-06-18T07:51:23Z
1,011,491
<p>You can be zip-safe and at the same time use a nice convenient API if you use <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.python.modules.html" rel="nofollow">twisted.python.modules</a>.</p> <p>For example, if I have a <code>data.txt</code> with some text in it and and this <code>sample.py</code> in one directory:</p> <pre><code>from twisted.python.modules import getModule moduleDirectory = getModule(__name__).filePath.parent() print repr(moduleDirectory.child("data.txt").open().read()) </code></pre> <p>then importing <code>sample</code> will do this:</p> <pre><code>&gt;&gt;&gt; import sample 'Hello, data!\n' &gt;&gt;&gt; </code></pre> <p>If your module is in a regular directory, <code>getModule(__name__).filePath</code> will be a <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.python.filepath.FilePath.html" rel="nofollow">FilePath</a>; if it's in a zip file, it will be a <a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.python.zippath.ZipPath.html" rel="nofollow">ZipPath</a>, which supports most, but not all, of the same APIs.</p>
3
2009-06-18T08:33:57Z
[ "python", "reference", "packages", "relative-path" ]
Relative file paths in Python packages
1,011,337
<p>How do I reference a file relatively to a package's directory?</p> <p>My directory structure is:</p> <pre> /foo package1/ resources/ __init__.py package2/ resources/ __init__.py script.py </pre> <p><code>script.py</code> imports packages <code>package1</code> and <code>package2</code>. Although the packages can be imported by any other script on the system. How should I reference resources inside, say, <code>package1</code> to ensure it would work in case <code>os.path.curdir</code> is arbitrary?</p>
8
2009-06-18T07:51:23Z
39,864,336
<p>A simple/safe way to do this is using the <code>resource_filename</code> method from <a href="http://setuptools.readthedocs.io/en/latest/pkg_resources.html" rel="nofollow">pkg_resources</a> (which is distributed with <a href="https://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a>) like so:</p> <pre><code>from pkg_resources import resource_filename filepath = resource_filename('package1', 'resources/thefile') </code></pre> <p>Or, if you're implementing this inside <code>package1/___init___.py</code>:</p> <pre><code>from pkg_resources import resource_filename filepath = resource_filename(__name__, 'resources/thefile') </code></pre> <p>This gives you a clean solution that is also (if I'm not mistaken) zip safe.</p>
0
2016-10-05T02:01:22Z
[ "python", "reference", "packages", "relative-path" ]
Configuring Django to use SQLAlchemy
1,011,476
<p>how we configure django with SQLAlchemy??</p>
17
2009-06-18T08:31:04Z
1,011,495
<p>Check this:</p> <p><a href="http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/">Replacing django orm</a></p>
8
2009-06-18T08:34:42Z
[ "python", "django", "sqlalchemy", "configure" ]
Configuring Django to use SQLAlchemy
1,011,476
<p>how we configure django with SQLAlchemy??</p>
17
2009-06-18T08:31:04Z
1,011,507
<p>alchemy? :)</p> <p>Google links:</p> <ul> <li><a href="http://lethain.com/entry/2008/jul/23/replacing-django-s-orm-with-sqlalchemy/" rel="nofollow">replacing-django-s-orm-with-sqlalchemy</a></li> <li><a href="http://code.google.com/p/django-sqlalchemy/" rel="nofollow">django-sqlalchemy</a></li> <li><a href="http://groups.google.com/group/django-developers/browse%5Fthread/thread/5149e1c60dc65bff/a177bb34cfde1ec7?pli=1" rel="nofollow">googleGroups</a></li> </ul>
3
2009-06-18T08:38:50Z
[ "python", "django", "sqlalchemy", "configure" ]
Configuring Django to use SQLAlchemy
1,011,476
<p>how we configure django with SQLAlchemy??</p>
17
2009-06-18T08:31:04Z
8,539,407
<p>You can use SQLAlchemy within a Django project with Aldjemy:</p> <p><a href="https://github.com/Deepwalker/aldjemy" rel="nofollow">https://github.com/Deepwalker/aldjemy</a></p>
8
2011-12-16T19:53:12Z
[ "python", "django", "sqlalchemy", "configure" ]
Configuring Django to use SQLAlchemy
1,011,476
<p>how we configure django with SQLAlchemy??</p>
17
2009-06-18T08:31:04Z
27,579,486
<p>Please find this little tutorial on <a href="http://rodic.fr/blog/sqlalchemy-django/" rel="nofollow">how to use SQLAlchemy with Django</a></p>
3
2014-12-20T10:54:37Z
[ "python", "django", "sqlalchemy", "configure" ]
How can you add a camera to a robot in the Breve Simulator?
1,011,602
<p>I've created a two wheeled robot based on the braitenberg vehicle. Our robots have two wheels and a PolygonDisk body(Much like kepera and e-puck robots). I would like to add a camera to the front of the robot. The problem then becomes how to control the camera and how to keep pointing it in the right direction(same direction as the robot). How can you make the camera point in the same direction as the robot ?</p>
1
2009-06-18T09:01:23Z
1,027,059
<p>After much trying and failing I finally made it work. So here is how I did it:</p> <p>The general idea is to have an link or object linked to the vehicle and then measuring its rotation and location in order to find out in which direction the camera should be aimed.</p> <p>1) Add an object that is linked to the robot:</p> <pre><code>def addVisualCam(self): joint = None cam = breve.createInstances(breve.Link,1) cam.setShape(breve.createInstances(breve.PolygonCone, 1).initWith(10,0.08,0.08)) joint = breve.createInstances(breve.FixedJoint,1) # So ad-hoc it hurts. oh well... joint.setRelativeRotation(breve.vector(0,1,0), -3.14/2) joint.link(breve.vector(0,1.05,0), breve.vector(0,0,0), cam, self.vehicle.bodyLink, 0) joint.setDoubleSpring(300, 1.01000, -1.01000) self.vehicle.addDependency(joint) self.vehicle.addDependency(cam) cam.setColor(breve.vector(0,0,0)) self.cam = cam </code></pre> <p>2) Add this postIterate:</p> <pre><code>def postIterate(self): look_at = self.cam.getLocation() + (self.cam.getRotation() * breve.vector(0,0,1)) look_from = -(self.cam.getRotation()*breve.vector(0,0,1)) self.vision.look(look_at, look_from) </code></pre>
1
2009-06-22T12:54:10Z
[ "python", "simulation", "robotics" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,011,846
<p>If you're not bound to a specific language you could have a look at <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> which is made especially for things like this. I had good experiences with it for automating things like mouseclicks or keystrokes.</p>
3
2009-06-18T09:52:49Z
[ "python", "ruby", "perl", "winapi", "windows" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,011,855
<p>What function(s) are you using to accomplish this?</p> <p>I'd expect <a href="http://msdn.microsoft.com/en-us/library/ms646310.aspx" rel="nofollow">SendInput</a> with a chain of 2 passed in MOUSEINPUT structures (one button down, the other button up) would pull this off for you. You can even play games with the timestamps on the faked events to more deterministic behavior than you'll get with sleep().</p> <p>There's no CLICK to send, as its the responsibility of an application to collapse low level events (mouse move, button down, button up, key down, key up, etc.) into "user level" events.</p> <p><hr /></p> <p>Some code, to clarify. This is straight-up untested/compiled C (read: the bad kind of C), but I hope it illustrates my point.</p> <pre><code>LPINPUT events = (LPINPUT)malloc(sizeof(INPUT) * 2); events[0].type = INPUT_MOUSE; events[0].mi.dwFlags = MOUSEEVENTF_LEFTDOWN; events[0].mi.time = 0; //Here, you can play with timestamps (milliseconds) events[1].type = INPUT_MOUSE; events[1].mi.dwFlags = MOUSEEVENTF_LEFTUP; events[1].mi.time = 0; //Likewise //Push both events into the event queue SendInput(2, events, sizeof(INPUT)); </code></pre> <p>I have zero Ruby experience, so I don't know how you'd interop this for your case.</p>
1
2009-06-18T09:55:35Z
[ "python", "ruby", "perl", "winapi", "windows" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,011,872
<p>I guess 2 things:</p> <ol> <li>I bet ruby doesn't and can't guarantee that sleep 0.1 really sleeps only 0.1 seconds. As this is probably out of rubys control and OS controlled</li> <li>The call to the Win32 API via Win32 itself may take an arbitrary time and cause the delay</li> </ol>
1
2009-06-18T10:00:09Z
[ "python", "ruby", "perl", "winapi", "windows" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,011,902
<p>Since the Windows API supports sleeping down to 1 millisecond, why not just sleep a shorter time? 0.01 seconds should be enough?</p>
1
2009-06-18T10:10:21Z
[ "python", "ruby", "perl", "winapi", "windows" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,012,559
<p>You do not decide what delay setting between mouse down and mouse up results in a valid single click, the operating system does.</p> <p>No <code>sleep</code> function can guarantee the timing between the mouse down and mouse up events you want. Perl's <a href="http://search.cpan.org/~karasik/Win32-GuiTest-1.56/" rel="nofollow">Win32::GuiTest</a> module allows you to send an actual click event rather than messing with the timing of down and up events. <strong>Later:</strong> Looking at the source code, Win32::GuiTest seems to just fire mouse down and up events without any delay between them <a href="http://cpansearch.perl.org/src/KARASIK/Win32-GuiTest-1.56/lib/Win32/GuiTest.pm" rel="nofollow">see GuiTest.pm</a>:</p> <pre><code>elsif ( $item =~ /leftclick/i ) { SendLButtonDown (); SendLButtonUp (); } </code></pre> <p>In addition, <a href="http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx</a> states that <code>mouse_event</code> has been superseded by <code>SendInput</code> <a href="http://msdn.microsoft.com/en-us/library/ms646310(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms646310(VS.85).aspx</a> which allows you to send a <code>MOUSEINPUT</code> event with timestamps etc.</p>
3
2009-06-18T13:11:58Z
[ "python", "ruby", "perl", "winapi", "windows" ]
How can I accurately program an automated "click" on Windows?
1,011,799
<p>I wrote a program to click on an application automatically at scheduled time using Win32, using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. It usually works well, except I found that I need to put in a </p> <pre><code>sleep 0.1 </code></pre> <p>between the <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>. (using Ruby, which allows sleeping a fraction of a second).</p> <p>Without the sleep, sometimes the click doesn't go through. But I noticed that sometimes, the click is "too long". The click is actually on a Flash app's Right Arrow. This right arrow will go to the next item on a list. So if you <code>MOUSE_DOWN</code> for a little longer, it actually will shift 2 or 3 items instead of just 1 item.</p> <p>So I wonder, is there a way to accurately simulate 1 click in this case. Probably there is no <code>MOUSE_CLICK</code> event? It has to be simulated using <code>MOUSE_DOWN</code> and <code>MOUSE_UP</code>?</p> <p>(it is actually called <code>MOUSEEVENTF_LEFTDOWN</code> and <code>MOUSEEVENTF_LEFTUP</code> on Win32, just for simplicity it is stated as <code>MOUSE_DOWN</code> instead.)</p>
0
2009-06-18T09:44:12Z
1,015,717
<p>I'd use AutoHotKey. It's open source and free, been around a long time and actively maintained, to the point that others have built an IDE for it. I use it for generating unique random test data for form testing but it does mouse stuff too. </p> <p><a href="http://www.autohotkey.com/" rel="nofollow">http://www.autohotkey.com/</a></p>
1
2009-06-18T23:30:54Z
[ "python", "ruby", "perl", "winapi", "windows" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
1,011,962
<p>This should do the trick.</p> <pre><code>foo = somevalue previous = next_ = None l = len(objects) for index, obj in enumerate(objects): if obj == foo: if index &gt; 0: previous = objects[index - 1] if index &lt; (l - 1): next_ = objects[index + 1] </code></pre> <p>Here's the docs on the <a href="http://docs.python.org/library/functions.html#enumerate"><code>enumerate</code></a> function.</p>
45
2009-06-18T10:28:51Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
1,012,017
<p>You could just use <code>index</code> on the list to find where <code>somevalue</code> is and then get the previous and next as needed:</p> <pre> <code> def find_prev_next(elem, elements): previous, next = None, None index = elements.index(elem) if index &gt; 0: previous = elements[index -1] if index &lt; (len(elements)-1): next = elements[index +1] return previous, next foo = 'three' list = ['one','two','three', 'four', 'five'] previous, next = find_prev_next(foo, list) print previous # should print 'two' print next # should print 'four' </code> </pre>
0
2009-06-18T10:49:16Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
1,012,063
<p>using conditional expressions for conciseness for python >= 2.5</p> <pre><code>def prenext(l,v) : i=l.index(v) return l[i-1] if i&gt;0 else None,l[i+1] if i&lt;len(l)-1 else None # example x=range(10) prenext(x,3) &gt;&gt;&gt; (2,4) prenext(x,0) &gt;&gt;&gt; (None,2) prenext(x,9) &gt;&gt;&gt; (8,None) </code></pre>
1
2009-06-18T11:02:48Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
1,012,089
<p>Solutions until now only deal with lists, and most are copying the list. In my experience a lot of times that isn't possible.</p> <p>Also, they don't deal with the fact that you can have repeated elements in the list.</p> <p>The title of your question says "<em>Previous and next values inside a loop</em>", but if you run most answers here inside a loop, you'll end up iterating over the entire list again on each element to find it.</p> <p>So I've just created a function that. using the <a href="http://docs.python.org/library/itertools.html"><code>itertools</code></a> module, splits and slices the iterable, and generates tuples with the previous and next elements together. Not exactly what your code does, but it is worth taking a look, because it can probably solve your problem.</p> <pre><code>from itertools import tee, islice, chain, izip def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) </code></pre> <p>Then use it in a loop, and you'll have previous and next items in it:</p> <pre><code>mylist = ['banana', 'orange', 'apple', 'kiwi', 'tomato'] for previous, item, nxt in previous_and_next(mylist): print "Item is now", item, "next is", nxt, "previous is", previous </code></pre> <p>The results:</p> <pre><code>Item is now banana next is orange previous is None Item is now orange next is apple previous is banana Item is now apple next is kiwi previous is orange Item is now kiwi next is tomato previous is apple Item is now tomato next is None previous is kiwi </code></pre> <p>It'll work with any size list (because it doesn't copy the list), and with any iterable (files, sets, etc). This way you can just iterate over the sequence, and have the previous and next items available inside the loop. No need to search again for the item in the sequence.</p> <p>A short explanation of the code:</p> <ul> <li><code>tee</code> is used to efficiently create 3 independent iterators over the input sequence</li> <li><code>chain</code> links two sequences into one; it's used here to append a single-element sequence <code>[None]</code> to <code>prevs</code></li> <li><code>islice</code> is used to make a sequence of all elements except the first, then <code>chain</code> is used to append a <code>None</code> to its end</li> <li>There are now 3 independent sequences based on <code>some_iterable</code> that look like: <ul> <li><code>prevs</code>: <code>None, A, B, C, D, E</code></li> <li><code>items</code>: <code>A, B, C, D, E</code></li> <li><code>nexts</code>: <code>B, C, D, E, None</code></li> </ul></li> <li>finally <code>izip</code> is used to change 3 sequences into one sequence of triplets.</li> </ul> <p>Note that <code>izip</code> stops when any input sequence gets exhausted, so the last element of <code>prevs</code> will be ignored, which is correct - there's no such element that the last element would be its <code>prev</code>. We could try to strip off the last elements from <code>prevs</code> but <code>izip</code>'s behaviour makes that redundant </p> <p>Also note that <code>tee</code>, <code>izip</code>, <code>islice</code> and <code>chain</code> come from the <code>itertools</code> module; they operate on their input sequences on-the-fly (lazily), which makes them efficient and doesn't introduce the need of having the whole sequence in memory at once at any time.</p>
71
2009-06-18T11:12:58Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
1,012,169
<p>Here's a version using generators with no boundary errors:</p> <pre><code>def trios(input): input = iter(input) # make sure input is an iterator try: prev, current = input.next(), input.next() except StopIteration: return for next in input: yield prev, current, next prev, current = current, next def find_prev_next(objects, foo): prev, next = 0, 0 for temp_prev, current, temp_next in trios(objects): if current == foo: prev, next = temp_prev, temp_next return prev, next print find_prev_next(range(10), 1) print find_prev_next(range(10), 0) print find_prev_next(range(10), 10) print find_prev_next(range(0), 10) print find_prev_next(range(1), 10) print find_prev_next(range(2), 10) </code></pre> <p>Please notice that the boundary behavior is that we never look for "foo" in the first or last element, unlike your code. Again, the boundary semantics are strange...and are hard to fathom from your code :)</p>
2
2009-06-18T11:29:11Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
22,608,381
<p>AFAIK this should be pretty fast, but I didn't test it:</p> <pre><code>def iterate_prv_nxt(my_list): prv, cur, nxt = None, iter(my_list), iter(my_list) next(nxt, None) while True: try: if prv: yield next(prv), next(cur), next(nxt, None) else: yield None, next(cur), next(nxt, None) prv = iter(my_list) except StopIteration: break </code></pre> <p>Example usage:</p> <pre><code>&gt;&gt;&gt; my_list = ['a', 'b', 'c'] &gt;&gt;&gt; for prv, cur, nxt in iterate_prv_nxt(my_list): ... print prv, cur, nxt ... None a b a b c b c None </code></pre>
0
2014-03-24T11:40:31Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
32,714,764
<p>Using a list comprehension, return a 3-tuple with current, previous and next elements:</p> <pre><code>three_tuple = [(current, my_list[idx - 1] if idx &gt;= 1 else None, my_list[idx + 1] if idx &lt; len(my_list) - 1 else None) for idx, current in enumerate(my_list)] </code></pre>
0
2015-09-22T10:40:53Z
[ "python", "loops" ]
Python - Previous and next values inside a loop
1,011,938
<p>How can I do thing like this in python?</p> <pre><code>foo = somevalue previous = next = 0 for (i=1; i&lt;objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } } </code></pre>
33
2009-06-18T10:23:38Z
33,036,692
<p>Pythonic and elegant way:</p> <pre><code>objects = [1, 2, 3, 4, 5] value = 3 if value in objects: index = objects.index(value) previous_value = objects[index-1] next_value = objects[index+1] if index + 1 &lt; len(objects) else None </code></pre>
0
2015-10-09T11:06:07Z
[ "python", "loops" ]
How to get links on a webpage using mechanize and open those links
1,011,975
<p>I want to use mechanize with python to get all the links of the page, and then open the links.How can I do it?</p>
1
2009-06-18T10:32:44Z
1,012,022
<p>The <code>Browser</code> object in <code>mechanize</code> has a <code>links</code> method that will retrieve all the links on the page.</p>
0
2009-06-18T10:51:03Z
[ "python", "mechanize" ]
How to get links on a webpage using mechanize and open those links
1,011,975
<p>I want to use mechanize with python to get all the links of the page, and then open the links.How can I do it?</p>
1
2009-06-18T10:32:44Z
1,012,030
<p>Here is an example from the project's <a href="http://wwwsearch.sourceforge.net/mechanize/">page</a>:</p> <pre><code> import re from mechanize import Browser br = Browser() br.open("http://www.example.com/") # ... # .links() optionally accepts the keyword args of .follow_/.find_link() for link in br.links(url_regex="python.org"): print link br.follow_link(link) # takes EITHER Link instance OR keyword args br.back() </code></pre>
5
2009-06-18T10:53:11Z
[ "python", "mechanize" ]
how to generate a many-to-many-relationship FORM in web2py?
1,012,179
<p>Do I need a custom validator? Do I need a custom widget?</p> <p>If this helps to clear the problem, the relationship is between <code>member</code> and <code>language</code> where a member can have multiple languages and a language is spoken by multiple members.</p> <p>I would like to add a multi-select box in the "add member" form (that I generate using SQLFORM).</p> <p>Thanks :)</p>
2
2009-06-18T11:32:10Z
1,075,983
<p>It depends and I suggest you take this on the web2py mailin list. One way to do it is</p> <pre><code>db.table.field.requires=IS_IN_DB(db,'othertable.id','%(otherfield)',multiple=True) </code></pre>
1
2009-07-02T18:34:00Z
[ "python", "web2py" ]
how to generate a many-to-many-relationship FORM in web2py?
1,012,179
<p>Do I need a custom validator? Do I need a custom widget?</p> <p>If this helps to clear the problem, the relationship is between <code>member</code> and <code>language</code> where a member can have multiple languages and a language is spoken by multiple members.</p> <p>I would like to add a multi-select box in the "add member" form (that I generate using SQLFORM).</p> <p>Thanks :)</p>
2
2009-06-18T11:32:10Z
1,401,702
<p>Another way to do this:</p> <pre><code>db.define_table( 'make', Field( 'name' ) ) db.define_table( 'model', Field( 'name' ), Field( 'make', db.make, requires = IS_IN_DB( db, 'make.id', '%(name)' ) ) ) </code></pre>
0
2009-09-09T19:46:49Z
[ "python", "web2py" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
1,012,197
<pre><code>T = [L[i] for i in Idx] </code></pre>
85
2009-06-18T11:38:46Z
[ "python", "list", "indexing" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
1,012,204
<pre><code>T = map(lambda i: L[i], Idx) </code></pre>
4
2009-06-18T11:39:58Z
[ "python", "list", "indexing" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
1,012,484
<p>If you are using numpy, you can perform extended slicing like that:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) &gt;&gt;&gt; Idx = [0, 3, 7] &gt;&gt;&gt; a[Idx] array(['a', 'd', 'h'], dtype='|S1') </code></pre> <p>...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)</p>
16
2009-06-18T12:54:26Z
[ "python", "list", "indexing" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
29,447,861
<p>I wasn't happy with any of these approaches, so I came up with a <code>Flexlist</code> class that allows for flexible indexing, either by integer, slice or index-list:</p> <pre><code>class Flexlist(list): def __getitem__(self, keys): if isinstance(keys, (int, slice)): return list.__getitem__(self, keys) return [self[k] for k in keys] </code></pre> <p>Which, for your example, you would use as:</p> <pre><code>L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) Idx = [0, 3, 7] T = L[ Idx ] print(T) # ['a', 'd', 'h'] </code></pre>
2
2015-04-04T14:59:55Z
[ "python", "list", "indexing" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
29,448,401
<pre><code> L= {'a':'a','d':'d', 'h':'h} index= ['a','d','h'] for keys in index: print(L[keys]) </code></pre> <p>I would use a <code>Dict add</code> desired <code>keys</code> to <code>index</code> </p>
0
2015-04-04T15:55:18Z
[ "python", "list", "indexing" ]
In Python, how do I index a list with another list?
1,012,185
<p>I would like to index a list with another list like this</p> <pre><code>L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] </code></pre> <p>and T should end up being a list containing ['a', 'd', 'h'].</p> <p>Is there a better way than</p> <pre><code>T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] </code></pre>
36
2009-06-18T11:36:06Z
31,257,239
<p>A functional approach:</p> <pre><code>a = [1,"A", 34, -123, "Hello", 12] b = [0, 2, 5] from operator import itemgetter print(list(itemgetter(*b)(a))) [1, 34, 12] </code></pre>
1
2015-07-06T23:12:25Z
[ "python", "list", "indexing" ]
How to concatenate strings with binary values in python?
1,012,457
<p>What's the easiest way in python to concatenate string with binary values ?</p> <pre><code>sep = 0x1 data = ["abc","def","ghi","jkl"] </code></pre> <p>Looking for result data <code>"abc0x1def0x1ghi0x1jkl"</code> with the 0x1 being binary value not string "0x1".</p>
3
2009-06-18T12:48:28Z
1,012,472
<p>I think</p> <pre><code>joined = '\x01'.join(data) </code></pre> <p>should do it. <code>\x01</code> is the escape sequence for a byte with value 0x01.</p>
9
2009-06-18T12:51:12Z
[ "python", "string", "binary", "concatenation" ]
How to concatenate strings with binary values in python?
1,012,457
<p>What's the easiest way in python to concatenate string with binary values ?</p> <pre><code>sep = 0x1 data = ["abc","def","ghi","jkl"] </code></pre> <p>Looking for result data <code>"abc0x1def0x1ghi0x1jkl"</code> with the 0x1 being binary value not string "0x1".</p>
3
2009-06-18T12:48:28Z
1,012,526
<p>The chr() function will have the effect of translating a variable into a string with the binary value you are looking for.</p> <pre><code>&gt;&gt;&gt; sep = 0x1 &gt;&gt;&gt; sepc = chr(sep) &gt;&gt;&gt; sepc '\x01' </code></pre> <p>The join() function can then be used to concat a series of strings with your binary value as a separator.</p> <pre><code>&gt;&gt;&gt; data = ['abc']*3 &gt;&gt;&gt; data ['abc', 'abc', 'abc'] &gt;&gt;&gt; sepc.join(data) 'abc\x01abc\x01abc' </code></pre>
3
2009-06-18T13:03:35Z
[ "python", "string", "binary", "concatenation" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,012,512
<p>In bash you can use <code>sort -r filename</code> and <code>tail -n filename</code> to read the file backwards.</p> <pre><code>$LINES=`tail -n filename | sort -r` # now iterate through the lines and do your checking </code></pre>
-1
2009-06-18T13:01:17Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,012,520
<p>Why shouldn't it possible in bash? You don't need to keep the whole file in memory, just the last three lines (if I understood correctly), and write what's appropriate to standard-out. Redirect that into a temporary file, check that everything worked as expected, and overwrite the source file with the temporary one.</p> <p>Same goes for Python.</p> <p>I'd provide a script of my own, but that wouldn't be tested. ;-)</p>
1
2009-06-18T13:03:05Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,012,543
<p>Of course Python will work as well. Simply store the last three lines in an array and check if the first element in the array is the same as the value you are currently reading. Then delete the value and print out the current array. You would then move over your elements to make room for the new value and repeat. Of course when the array is filled you'd have to make sure to continue to move values out of the array and put in the newly read values, stopping to check each time to see if the first value in the array matches the value you are currently reading.</p>
2
2009-06-18T13:07:59Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,012,637
<p>This code will scan through the file, and remove lines starting with the marker. It only keeps only three lines in memory by default:</p> <pre><code>from collections import deque def delete(fp, marker, gap=3): """Delete lines from *fp* if they with *marker* and are followed by another line starting with *marker* *gap* lines after. """ buf = deque() for line in fp: if len(buf) &lt; gap: buf.append(line) else: old = buf.popleft() if not (line.startswith(marker) and old.startswith(marker)): yield old buf.append(line) for line in buf: yield line </code></pre> <p>I've tested it with:</p> <pre><code>&gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; fp = StringIO('''a ... b ... xxx 1 ... c ... xxx 2 ... d ... e ... xxx 3 ... f ... g ... h ... xxx 4 ... i''') &gt;&gt;&gt; print ''.join(delete(fp, 'xxx')) a b xxx 1 c d e xxx 3 f g h xxx 4 i </code></pre>
1
2009-06-18T13:33:09Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,012,953
<p>I would consider using sed. gnu sed supports definition of line ranges. if sed would fail, then there is another beast - awk and I'm sure you can do it with awk.</p> <p>O.K. I feel I should put my awk POC. I could not figure out to use sed addresses. I have not tried combination of awk+sed, but it seems to me it's overkill.</p> <p>my awk script works as follows:</p> <ul> <li><p>It reads lines and stores them into 3 line buffer</p></li> <li><p>once desired pattern is found (/^data.*/ in my case), the 3-line buffer is looked up to check, whether desired pattern has been seen three lines ago</p></li> <li><p>if pattern has been seen, then 3 lines are scratched</p></li> </ul> <p>to be honest, I would probably go with python also, given that awk is really awkward. the AWK code follows:</p> <pre> function max(a, b) { if (a > b) return a; else return b; } BEGIN { w = 0; #write index r = 0; #read index buf[0, 1, 2]; #buffer } END { # flush buffer # start at read index and print out up to w index for (k = r % 3; k r - max(r - 3, 0); k--) { #search in 3 line history buf if (match(buf[k % 3], /^data.*/) != 0) { # found -> remove lines from history # by rewriting them -> adjust write index w -= max(r, 3); } } buf[w % 3] = $0; w++; } /^.*/ { # store line into buffer, if the history # is full, print out the oldest one. if (w > 2) { print buf[r % 3]; r++; buf[w % 3] = $0; } else { buf[w] = $0; } w++; } </pre>
-2
2009-06-18T14:27:17Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,013,162
<p>As AlbertoPL said, store lines in a fifo for later use--don't "go backwards". For this I would definitely use python over bash+sed/awk/whatever. </p> <p>I took a few moments to code this snippet up:</p> <pre><code>from collections import deque line_fifo = deque() for line in open("test"): line_fifo.append(line) if len(line_fifo) == 4: # "look 3 lines backward" if line_fifo[0] == line_fifo[-1] == "@STRING_A\n": # get rid of that match line_fifo.popleft() else: # print out the top of the fifo print line_fifo.popleft(), # don't forget to print out the fifo when the file ends for line in line_fifo: print line, </code></pre>
1
2009-06-18T14:57:11Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,015,515
<p>My awk-fu has never been that good... but the following may provide you what you're looking for in a bash-shell/shell-utility form:</p> <pre><code>sed `awk 'BEGIN{ORS=";"} /@STRING_A/ { if(LAST!="" &amp;&amp; LAST+3 &gt;= NR) print LAST "d" LAST = NR }' test_file` test_file </code></pre> <p>Basically... awk is producing a command for sed to strip certain lines. I'm sure there's a relatively easy way to make awk do all of the processing, but this does seem to work.</p> <p>The bad part? It does read the test_file twice.</p> <p>The good part? It is a bash/shell-utility implementation.</p> <p>Edit: Alex Martelli points out that the sample file above might have confused me. (my above code deletes the whole line, rather than the @STRING_A flag only)</p> <p>This is easily remedied by adjusting the command to sed:</p> <pre><code>sed `awk 'BEGIN{ORS=";"} /@STRING_A/ { if(LAST!="" &amp;&amp; LAST+3 &gt;= NR) print LAST "s/@STRING_A//" LAST = NR }' test_file` test_file </code></pre>
0
2009-06-18T22:23:33Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,015,598
<p>Here is a more fun solution, using two iterators with a three element offset :)</p> <pre><code>from itertools import izip, chain, tee f1, f2 = tee(open("foo.txt")) for third, line in izip(chain(" ", f1), f2): if not (third.startswith("@STRING_A") and line.startswith("@STRING_A")): print line, </code></pre>
2
2009-06-18T22:53:20Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,015,960
<p>Funny that after all these hours nobody's yet given a solution to the problem as actually phrased (as @John Machin points out in a comment) -- remove just the leading marker (if followed by another such marker 3 lines down), not the whole line containing it. It's not hard, of course -- here's a tiny mod as needed of @truppo's fun solution, for example:</p> <pre><code>from itertools import izip, chain f = "foo.txt" for third, line in izip(chain(" ", open(f)), open(f)): if third.startswith("@STRING_A") and line.startswith("@STRING_A"): line = line[len("@STRING_A"):] print line, </code></pre> <p>Of course, in real life, one would use an <code>iterator.tee</code> instead of reading the file twice, have this code in a function, not repeat the marker constant endlessly, &c;-).</p>
4
2009-06-19T01:10:30Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,016,123
<p>This may be what you're looking for?</p> <pre><code>lines = open('sample.txt').readlines() needle = "@string " for i,line in enumerate(lines): if line.startswith(needle) and lines[i-3].startswith(needle): lines[i-3] = lines[i-3].replace(needle, "") print ''.join(lines) </code></pre> <p>this outputs:</p> <pre><code>string 0 extra text string 1 extra text string 2 extra text string 3 extra text --replaced -- 4 extra text string 5 extra text string 6 extra text @string 7 extra text string 8 extra text string 9 extra text string 10 extra text </code></pre>
-1
2009-06-19T02:37:20Z
[ "python", "bash" ]
Bash or Python to go backwards?
1,012,490
<p>I have a text file which a lot of random occurrences of the string @STRING_A, and I would be interested in writing a short script which removes only some of them. Particularly one that scans the file and once it finds a line which starts with this string like</p> <pre><code>@STRING_A </code></pre> <p>then checks if 3 lines backwards there is another occurrence of a line starting with the same string, like</p> <pre><code>@STRING_A @STRING_A </code></pre> <p>and if it happens, to delete the occurrence 3 lines backward. I was thinking about bash, but I do not know how to "go backwards" with it. So I am sure that this is not possible with bash. I also thought about python, but then I should store all information in memory in order to go backwards and then, for long files it would be unfeasible. </p> <p>What do you think? Is it possible to do it in bash or python?</p> <p>Thanks</p>
6
2009-06-18T12:56:09Z
1,017,298
<p>This "answer" is for lyrae ... I'll amend my previous comment: if the needle is in the first 3 lines of the file, your script will either cause an IndexError or access a line that it shouldn't be accessing, sometimes with interesting side-effects.</p> <p>Example of your script causing IndexError:</p> <pre><code>&gt;&gt;&gt; lines = "@string line 0\nblah blah\n".splitlines(True) &gt;&gt;&gt; needle = "@string " &gt;&gt;&gt; for i,line in enumerate(lines): ... if line.startswith(needle) and lines[i-3].startswith(needle): ... lines[i-3] = lines[i-3].replace(needle, "") ... Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>and this example shows not only that the Earth is round but also why your "fix" to the "don't delete the whole line" problem should have used <code>.replace(needle, "", 1)</code> or <code>[len(needle):]</code> instead of <code>.replace(needle, "")</code> </p> <pre><code>&gt;&gt;&gt; lines = "NEEDLE x NEEDLE y\nnoddle\nnuddle\n".splitlines(True) &gt;&gt;&gt; needle = "NEEDLE" &gt;&gt;&gt; # Expected result: no change to the file ... for i,line in enumerate(lines): ... if line.startswith(needle) and lines[i-3].startswith(needle): ... lines[i-3] = lines[i-3].replace(needle, "") ... &gt;&gt;&gt; print ''.join(lines) x y &lt;&lt;&lt;=== whoops! noddle nuddle &lt;&lt;&lt;=== still got unwanted newline in here &gt;&gt;&gt; </code></pre>
0
2009-06-19T10:23:05Z
[ "python", "bash" ]
Why does this python code hang on import/compile but work in the shell?
1,013,064
<p>I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once.</p> <p>When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors. </p> <p>How do I get the code to compile, or does someone have working code that accomplishes sftp by some other method?</p> <p>This code hangs right at the ssh.connect() statement:</p> <pre> """ ProblemDemo.py Chopped down from the paramiko demo file. This code works in the shell but hangs when I try to import it! """ from time import sleep import os import paramiko sOutputFilename = "redacted.htm" #-- The payload file hostname = "redacted.com" ####-- WARNING! Embedded passwords! Remove ASAP. sUsername = "redacted" sPassword = "redacted" sTargetDir = "redacted" #-- Get host key, if we know one. hostkeytype = None hostkey = None host_keys = {} try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' host_keys = {} if host_keys.has_key(hostname): hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] print 'Using host key of type %s' % hostkeytype ssh = paramiko.Transport((hostname, 22)) ssh.connect(username=sUsername, password=sPassword, hostkey=hostkey) sftp = paramiko.SFTPClient.from_transport(ssh) sftp.chdir (sTargetDir) sftp.put (sOutputFilename, sOutputFilename) ssh.close() </pre>
1
2009-06-18T14:45:19Z
1,013,135
<p>This may not be a direct reason why, but <strong>rarely do you ever</strong> want to have "functionality" executed upon import. Normally you should define a <em>class</em> or <em>function</em> that you then call like this:</p> <pre><code>import mymodule mymodule.run() </code></pre> <p>The "global" code that you run in an import typically should be limited to imports, variable definitions, function and class definitions, and the like...</p>
1
2009-06-18T14:54:21Z
[ "python", "shell", "compilation", "sftp" ]
Why does this python code hang on import/compile but work in the shell?
1,013,064
<p>I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once.</p> <p>When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors. </p> <p>How do I get the code to compile, or does someone have working code that accomplishes sftp by some other method?</p> <p>This code hangs right at the ssh.connect() statement:</p> <pre> """ ProblemDemo.py Chopped down from the paramiko demo file. This code works in the shell but hangs when I try to import it! """ from time import sleep import os import paramiko sOutputFilename = "redacted.htm" #-- The payload file hostname = "redacted.com" ####-- WARNING! Embedded passwords! Remove ASAP. sUsername = "redacted" sPassword = "redacted" sTargetDir = "redacted" #-- Get host key, if we know one. hostkeytype = None hostkey = None host_keys = {} try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' host_keys = {} if host_keys.has_key(hostname): hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] print 'Using host key of type %s' % hostkeytype ssh = paramiko.Transport((hostname, 22)) ssh.connect(username=sUsername, password=sPassword, hostkey=hostkey) sftp = paramiko.SFTPClient.from_transport(ssh) sftp.chdir (sTargetDir) sftp.put (sOutputFilename, sOutputFilename) ssh.close() </pre>
1
2009-06-18T14:45:19Z
1,013,232
<p>That's indeed a bad idea to execute this kind of code at import time, although I am not sure why it hangs - it may be that import mechanism does something strange which interacts badly with paramiko (thread related issues maybe ?). Anyway, the usual solution is to implement the functionality into a function:</p> <pre><code>def my_expensive_function(args): pass if __name__ == '__main__': import sys my_expensive_functions(sys.args) </code></pre> <p>This way, just importing the module will not do anything, but running the script will execute the function with the given arguments at command line.</p>
3
2009-06-18T15:09:50Z
[ "python", "shell", "compilation", "sftp" ]
Why does this python code hang on import/compile but work in the shell?
1,013,064
<p>I'm trying to use python to sftp a file, and the code works great in the interactive shell -- even pasting it in all at once.</p> <p>When I try to import the file (just to compile it), the code hangs with no exceptions or obvious errors. </p> <p>How do I get the code to compile, or does someone have working code that accomplishes sftp by some other method?</p> <p>This code hangs right at the ssh.connect() statement:</p> <pre> """ ProblemDemo.py Chopped down from the paramiko demo file. This code works in the shell but hangs when I try to import it! """ from time import sleep import os import paramiko sOutputFilename = "redacted.htm" #-- The payload file hostname = "redacted.com" ####-- WARNING! Embedded passwords! Remove ASAP. sUsername = "redacted" sPassword = "redacted" sTargetDir = "redacted" #-- Get host key, if we know one. hostkeytype = None hostkey = None host_keys = {} try: host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts')) except IOError: try: # try ~/ssh/ too, because windows can't have a folder named ~/.ssh/ host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/ssh/known_hosts')) except IOError: print '*** Unable to open host keys file' host_keys = {} if host_keys.has_key(hostname): hostkeytype = host_keys[hostname].keys()[0] hostkey = host_keys[hostname][hostkeytype] print 'Using host key of type %s' % hostkeytype ssh = paramiko.Transport((hostname, 22)) ssh.connect(username=sUsername, password=sPassword, hostkey=hostkey) sftp = paramiko.SFTPClient.from_transport(ssh) sftp.chdir (sTargetDir) sftp.put (sOutputFilename, sOutputFilename) ssh.close() </pre>
1
2009-06-18T14:45:19Z
1,013,366
<p>Weirdness aside, I was just using import to compile the code. Turning the script into a function seems like an unnecessary complication for this kind of application.</p> <p>Searched for alternate means to compile and found:</p> <pre> import py_compile py_compile.compile("ProblemDemo.py") </pre> <p>This generated a pyc file that works as intended. So the lesson learned is that import is not a robust way to compile python scripts.</p>
0
2009-06-18T15:29:12Z
[ "python", "shell", "compilation", "sftp" ]
Call Python From Bat File And Get Return Code
1,013,246
<p>I'm looking for a way to call a python script from a batch file and getting a return code from the python script. Confusing I know, but it's based on a system that's currently in use. I'd re-write it, but this way would be much, much quicker.</p> <p>So:</p> <pre><code>Bat ---------------------&gt; Python * call python file * Bat &lt;--------------------------------- Python * python does a load of work * * and returns a return code * </code></pre>
10
2009-06-18T15:11:43Z
1,013,293
<p>The windows shell saves the return code in the <code>ERRORLEVEL</code> variable:</p> <pre><code>python somescript.py echo %ERRORLEVEL% </code></pre> <p>In the python script you can exit the script and set the return value by calling <code>exit()</code>:</p> <pre><code>exit(15) </code></pre> <p>In older versions of python you might first have to import the <code>exit()</code> function from the <code>sys</code> module:</p> <pre><code>from sys import exit exit(15) </code></pre>
14
2009-06-18T15:17:46Z
[ "python", "batch-file" ]
Call Python From Bat File And Get Return Code
1,013,246
<p>I'm looking for a way to call a python script from a batch file and getting a return code from the python script. Confusing I know, but it's based on a system that's currently in use. I'd re-write it, but this way would be much, much quicker.</p> <p>So:</p> <pre><code>Bat ---------------------&gt; Python * call python file * Bat &lt;--------------------------------- Python * python does a load of work * * and returns a return code * </code></pre>
10
2009-06-18T15:11:43Z
1,013,296
<p>Try:</p> <pre><code>import os os._exit(ret_value) </code></pre> <p>You should also check:</p> <ul> <li><a href="http://bytes.com/groups/python/585533-sys-exit-versus-raise-systemexit" rel="nofollow">sys.exit()</a></li> </ul>
3
2009-06-18T15:18:16Z
[ "python", "batch-file" ]
What is the purpose of the two colons in this Python string-slicing statement?
1,013,272
<p>For example,</p> <pre><code>str = "hello" str[1::3] </code></pre> <p>And where can I find this in Python documentation?</p>
13
2009-06-18T15:14:57Z
1,013,295
<p>in <a href="http://docs.python.org/library/stdtypes.html#index-510">sequences' description</a>:</p> <pre><code>s[i:j:k] slice of s from i to j with step k </code></pre> <blockquote> <p>The slice of <code>s</code> from <code>i</code> to <code>j</code> with step <code>k</code> is defined as the sequence of items with index <code>x = i + n*k</code> such that <code>0 &lt;= n &lt; (j-i)/k</code>. In other words, the indices are <code>i</code>, <code>i+k</code>, <code>i+2*k</code>, <code>i+3*k</code> and so on, stopping when <code>j</code> is reached (but never including <code>j</code>). If <code>i</code> or <code>j</code> is greater than <code>len(s)</code>, use <code>len(s</code>). <strong>If <code>i</code> or <code>j</code> are omitted or <code>None</code>, they become “end” values (which end depends on the sign of <code>k</code>)</strong>. Note, <code>k</code> cannot be zero. If <code>k</code> is <code>None</code>, it is treated like 1.</p> </blockquote>
19
2009-06-18T15:18:13Z
[ "python", "slice" ]
python ORM allowing for table creation and bulk inserting?
1,013,282
<p>I'm looking for an ORM that allows me to do bulk inserts, as well as create code based on python classes. I tried sqlobject, it worked fine for creating the tables but inserting was unacceptibly slow for the amount of data I wanted to insert. If such an ORM doesn't exist any pointers on classes that can help with things like sanitizing input and building SQL strings would be appreciated.</p>
1
2009-06-18T15:16:00Z
1,013,307
<p>You might want to try <a href="http://www.sqlalchemy.org/">SQLAlchemy</a>.</p>
5
2009-06-18T15:19:38Z
[ "python", "database", "orm" ]