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
Django payment proccessing
772,240
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
22
2009-04-21T12:05:31Z
850,508
<p>Django paypal is very cool. I've used in on couple of my projects. It is relatively easy to integrate with an existing website. Satchmo is good, if you want a full internet store, but if you want to sell just couple items from your website, which is devoted to something else, you will find Satchmo to be very heavy (a lot of dependencies to install, really complicates your admin). </p>
2
2009-05-11T23:22:33Z
[ "python", "django" ]
Django payment proccessing
772,240
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
22
2009-04-21T12:05:31Z
3,851,479
<p>There is <a href="http://github.com/emesik/mamona" rel="nofollow">Django payments application called Mamona</a> which currently supports only PayPal. It can be used with any existing application without changing it's code. Basically, it can use <strong>any exiting model</strong> as order.</p>
3
2010-10-03T20:27:59Z
[ "python", "django" ]
Django payment proccessing
772,240
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
22
2009-04-21T12:05:31Z
5,317,978
<p>You may want to take a look at <a href="https://github.com/bkeating/python-payflowpro/" rel="nofollow">https://github.com/bkeating/python-payflowpro/</a> which isn't django-specific but works nicely with it or in plain ole python.</p>
0
2011-03-15T20:58:39Z
[ "python", "django" ]
Django payment proccessing
772,240
<p>Can anyone suggest any good payment processing libraries for python/django?</p>
22
2009-04-21T12:05:31Z
13,676,998
<p>I created Paython: <a href="https://github.com/abunsen/Paython" rel="nofollow">https://github.com/abunsen/Paython</a></p> <p>Supports a few different processors:</p> <ol> <li>Stripe</li> <li>Authorize.net</li> <li>First Data / Linkpoint</li> <li>Innovative Gateway (from intuit)</li> <li>Plugnpay</li> <li>Samurai</li> </ol>
0
2012-12-03T04:10:03Z
[ "python", "django" ]
Oracle / Python Converting to string -> HEX (for RAW column) -> varchar2
772,518
<p>I have a table with a RAW column for holding an encrypted string.</p> <p>I have the PL/SQL code for encrypting from plain text into this field.</p> <p>I wish to create a trigger containg the encryption code.</p> <p>I wish to 'misuse' the RAW field to pass the plain text into the trigger. (I can't modify the schema, for example to add another column for the plain text field)</p> <p>The client inserting the data is Python (cx_Oracle).</p> <p>My question is how to best convert from a python string into HEX, then back to VARCHAR2 in the trigger so that the encryption code can be used without modification (encryption code expects VARCHAR2).</p> <p>Here's an example:</p> <pre><code>create table BOB (name_enc raw(16)); </code></pre> <p>In python. This is my initial attempt at encoding, I suspect I'll need something more portable for international character sets.</p> <pre><code>name_enc = 'some text'.encode('hex') </code></pre> <p>The trigger</p> <pre><code>create or replace trigger enc_bob before insert on BOB for each row DECLARE v_name varchar2(50); BEGIN v_name := :new.name_enc; &lt;---- WHAT DO I NEED HERE TO CONVERT FROM HEX to VARCHAR? -- -- encryption code that expects v_name to contain string END; </code></pre> <p><strong>UPDATE</strong></p> <p>The suggestion for using Base64 worked for me</p> <p>Python:</p> <pre><code>name_enc = base64.b64encode('some text') </code></pre> <p>PL/SQL:</p> <pre><code>v_name := utl_raw.cast_to_varchar2(UTL_ENCODE.BASE64_DECODE(:new.name_enc)); </code></pre>
1
2009-04-21T13:12:06Z
772,611
<p>Do you have to encode to hex?</p> <p>I think there is a package (<a href="http://download.oracle.com/docs/cd/B19306%5F01/appdev.102/b14258/u%5Fencode.htm" rel="nofollow">utl_encode</a>) available for PL/SQL to decode Base64 for instance, you could use that? </p>
2
2009-04-21T13:34:03Z
[ "python", "oracle" ]
How to create a password protected zipfile with python?
772,814
<p>Since python2.6, it's now easier to extract data from a password protected zip. But how to create a password protected zipfile in pure python ?</p>
3
2009-04-21T14:20:48Z
772,842
<p>I've looked for this in the past and been unsuccessful. (I'd love to see a solution get posted!)</p> <p>One option is a commercial package from chilkatsoft that will do this, but at $150. Makes sense if you are doing a commercial app, but tough to swallow otherwise.</p> <p>I wound up calling out to the system for my solution, a while ago. Unfortunately, this locks it to a platform.</p>
3
2009-04-21T14:26:39Z
[ "python", "zip" ]
Why are 0d arrays in Numpy not considered scalar?
773,030
<p>Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept? </p> <pre><code>&gt;&gt;&gt; foo = numpy.array(1.11111111111, numpy.float64) &gt;&gt;&gt; numpy.ndim(foo) 0 &gt;&gt;&gt; numpy.isscalar(foo) False &gt;&gt;&gt; foo.item() 1.11111111111 </code></pre>
41
2009-04-21T15:02:51Z
773,125
<p>You have to create the scalar array a little bit differently:</p> <pre><code>&gt;&gt;&gt; x = numpy.float64(1.111) &gt;&gt;&gt; x 1.111 &gt;&gt;&gt; numpy.isscalar(x) True &gt;&gt;&gt; numpy.ndim(x) 0 </code></pre> <p>It looks like <a href="http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html" rel="nofollow">scalars in numpy</a> may be a bit different concept from what you may be used to from a purely mathematical standpoint. I'm guessing you're thinking in terms of scalar matricies?</p>
4
2009-04-21T15:20:27Z
[ "python", "numpy" ]
Why are 0d arrays in Numpy not considered scalar?
773,030
<p>Surely a 0d array is scalar, but Numpy does not seem to think so... am I missing something or am I just misunderstanding the concept? </p> <pre><code>&gt;&gt;&gt; foo = numpy.array(1.11111111111, numpy.float64) &gt;&gt;&gt; numpy.ndim(foo) 0 &gt;&gt;&gt; numpy.isscalar(foo) False &gt;&gt;&gt; foo.item() 1.11111111111 </code></pre>
41
2009-04-21T15:02:51Z
794,812
<p>One should not think too hard about it. It's ultimately better for the mental health and longevity of the individual.</p> <p>The curious situation with Numpy scalar-types was bore out of the fact that there is no graceful and consistent way to degrade the 1x1 matrix to scalar types. Even though mathematically they are the same thing, they are handled by very different code.</p> <p>If you've been doing any amount of scientific code, ultimately you'd want things like <code>max(a)</code> to work on matrices of all sizes, even scalars. Mathematically, this is a perfectly sensible thing to expect. However for programmers this means that whatever presents scalars in Numpy should have the .shape and .ndim attirbute, so at least the ufuncs don't have to do explicit type checking on its input for the 21 possible scalar types in Numpy. </p> <p>On the other hand, they should also work with existing Python libraries that <em>does</em> do explicit type-checks on scalar type. This is a dilemma, since a Numpy ndarray have to individually change its type when they've been reduced to a scalar, and there is no way of knowing whether that has occurred without it having do checks on all access. Actually going that route would probably make bit ridiculously slow to work with by scalar type standards.</p> <p>The Numpy developer's solution is to inherit from both ndarray and Python scalars for its own scalary type, so that all scalars also have .shape, .ndim, .T, etc etc. The 1x1 matrix will still be there, but its use will be discouraged if you know you'll be dealing with a scalar. While this should work fine in theory, occasionally you could still see some places where they missed with the paint roller, and the ugly innards are exposed for all to see:</p> <pre><code>&gt;&gt;&gt; from numpy import * &gt;&gt;&gt; a = array(1) &gt;&gt;&gt; b = int_(1) &gt;&gt;&gt; a.ndim 0 &gt;&gt;&gt; b.ndim 0 &gt;&gt;&gt; a[...] array(1) &gt;&gt;&gt; a[()] 1 &gt;&gt;&gt; b[...] array(1) &gt;&gt;&gt; b[()] 1 </code></pre> <p>There's really no reason why <code>a[...]</code> and <code>a[()]</code> should return different things, but it does. There are proposals in place to change this, but looks like they forgot to finish the job for 1x1 arrays.</p> <p>A potentially bigger, and possibly non-resolvable issue, is the fact that Numpy scalars are immutable. Therefore "spraying" a scalar into a ndarray, mathematically the adjoint operation of collapsing an array into a scalar, is a PITA to implement. You can't actually grow a Numpy scalar, it cannot by definition be cast into an ndarray, even though <code>newaxis</code> mysteriously works on it:</p> <pre><code>&gt;&gt;&gt; b[0,1,2,3] = 1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'numpy.int32' object does not support item assignment &gt;&gt;&gt; b[newaxis] array([1]) </code></pre> <p>In Matlab, growing the size of a scalar is a perfectly acceptable and brainless operation. In Numpy you have to stick jarring <code>a = array(a)</code> everywhere you <em>think</em> you'd have the possibility of starting with a scalar and ending up with an array. I understand why Numpy has to be this way to play nice with Python, but that doesn't change the fact that many new switchers are deeply confused about this. Some have explicit memory of struggling with this behaviour and eventually persevering, while others who are too far gone are generally left with some deep shapeless mental scar that frequently haunts their most innocent dreams. It's an ugly situation for all.</p>
76
2009-04-27T18:55:32Z
[ "python", "numpy" ]
Updating tkinter labels in python
773,797
<p>I'm working on giving a python server a GUI with tkinter by passing the Server's root instance to the Tkinter window. The problem is in keeping information in the labels up to date.</p> <p>For instance, the server has a Users list, containing the users that are logged on. It's simple enough to do this for an initial list:</p> <pre><code>string = "" for user in self.server.Users: string += user + "\n" Label(master, text=string) </code></pre> <p>But that will only do it once. After that, how am I supposed to update the list? I could add an 'update users' button, but I need the list to be self-updating.</p>
2
2009-04-21T17:54:18Z
773,846
<p>You could use callbacks on the server instance. Install a callback that updates the label whenever the user-list changes.</p> <p>If you can't change the server code, you would need to poll the list for updates every few seconds. You could use the Tkinter event system to keep track of the updates.</p> <pre><code>def user_updater(self): self.user_updater_id = self.user_label.after(1000, self.user_updater) lines = [] for user in self.server.Users: lines.append(user) self.user_label["text"] = "\n".join(lines) def stop_user_updater(self): self.user_label.after_cancel(self.user_updater_id) </code></pre>
3
2009-04-21T18:06:49Z
[ "python", "tkinter" ]
Updating tkinter labels in python
773,797
<p>I'm working on giving a python server a GUI with tkinter by passing the Server's root instance to the Tkinter window. The problem is in keeping information in the labels up to date.</p> <p>For instance, the server has a Users list, containing the users that are logged on. It's simple enough to do this for an initial list:</p> <pre><code>string = "" for user in self.server.Users: string += user + "\n" Label(master, text=string) </code></pre> <p>But that will only do it once. After that, how am I supposed to update the list? I could add an 'update users' button, but I need the list to be self-updating.</p>
2
2009-04-21T17:54:18Z
790,423
<p>You change the text of a <code>Label</code> by setting the text of its corresponding <code>StringVar</code> object, for example:</p> <pre><code>from tkinter import * root = Tk() string = StringVar() lab = Label(root, textvariable=string) lab.pack() string.set('Changing the text displayed in the Label') root.mainloop() </code></pre> <p>Note the use of the <code>set</code> function to change the displayed text of the Label <code>lab</code>. </p> <p>See <code>New Mexico Tech</code> Tkinter reference about this <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/control-variables.html" rel="nofollow">topic</a> for more information.</p>
2
2009-04-26T07:35:22Z
[ "python", "tkinter" ]
Plot logarithmic axes with matplotlib in python
773,814
<p>I want to plot a graph with one logarithmic axis using matplotlib. </p> <p>I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right</p> <p>Sample program: </p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.plot(a, color='blue', lw=2) show() </code></pre>
188
2009-04-21T18:00:26Z
773,850
<p>You simply need to use <a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.semilogy">semilogy</a> instead of plot:</p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.semilogy(a, color='blue', lw=2) show() </code></pre>
48
2009-04-21T18:07:42Z
[ "python", "matplotlib", "scale", "logarithm" ]
Plot logarithmic axes with matplotlib in python
773,814
<p>I want to plot a graph with one logarithmic axis using matplotlib. </p> <p>I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right</p> <p>Sample program: </p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.plot(a, color='blue', lw=2) show() </code></pre>
188
2009-04-21T18:00:26Z
1,183,415
<p>You can use the <a href="http://matplotlib.sourceforge.net/api/axes%5Fapi.html#matplotlib.axes.Axes.set%5Fyscale">Axes.set_yscale</a> method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.</p> <p>The relevant line to add is:</p> <pre><code>ax.set_yscale('log') </code></pre> <p>You can use 'linear' to switch back to a linear scale. Here's what your code would look like:</p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.plot(a, color='blue', lw=2) ax.set_yscale('log') show() </code></pre>
201
2009-07-26T00:14:42Z
[ "python", "matplotlib", "scale", "logarithm" ]
Plot logarithmic axes with matplotlib in python
773,814
<p>I want to plot a graph with one logarithmic axis using matplotlib. </p> <p>I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right</p> <p>Sample program: </p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.plot(a, color='blue', lw=2) show() </code></pre>
188
2009-04-21T18:00:26Z
3,513,577
<p>First of all, it's not very tidy to mix <code>pylab</code> and <code>pyplot</code> code. What's more, <a href="http://matplotlib.org/faq/usage_faq.html#matplotlib-pyplot-and-pylab-how-are-they-related">pyplot style is preferred over using pylab</a>.</p> <p>Here is a slightly cleaned up code, using only <code>pyplot</code> functions:</p> <pre><code>from matplotlib import pyplot a = [ pow(10,i) for i in range(10) ] pyplot.subplot(2,1,1) pyplot.plot(a, color='blue', lw=2) pyplot.yscale('log') pyplot.show() </code></pre> <p>The relevant function is <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.yscale"><code>pyplot.yscale()</code></a>. If you use the object-oriented version, replace it by the method <a href="http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_yscale"><code>Axes.set_yscale()</code></a>. Remember that you can also change the scale of X axis, using <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xscale"><code>pyplot.xscale()</code></a> (or <a href="http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale"><code>Axes.set_xscale()</code></a>).</p> <p>Check my question <a href="http://stackoverflow.com/questions/3305865/what-is-the-difference-between-log-and-symlog">What is the difference between ‘log’ and ‘symlog’?</a> to see a few examples of the graph scales that matplotlib offers.</p>
175
2010-08-18T15:10:32Z
[ "python", "matplotlib", "scale", "logarithm" ]
Plot logarithmic axes with matplotlib in python
773,814
<p>I want to plot a graph with one logarithmic axis using matplotlib. </p> <p>I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right</p> <p>Sample program: </p> <pre><code>from pylab import * import matplotlib.pyplot as pyplot a = [ pow(10,i) for i in range(10) ] fig = pyplot.figure() ax = fig.add_subplot(2,1,1) line, = ax.plot(a, color='blue', lw=2) show() </code></pre>
188
2009-04-21T18:00:26Z
22,945,052
<p>I know this is slightly off-topic, since some comments mentioned the <code>ax.set_yscale('log')</code> to be "nicest" solution I thought a rebuttal could be due. I would not recommend using <code>ax.set_yscale('log')</code> for histograms and bar plots. In my version (0.99.1.1) i run into some rendering problems - not sure how general this issue is. However both bar and hist has optional arguments to set the y-scale to log, which work fine.</p> <p>references: <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar</a></p> <p><a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist</a></p>
5
2014-04-08T18:14:47Z
[ "python", "matplotlib", "scale", "logarithm" ]
Python +sockets
773,869
<p>i have to create connecting server&lt;=>client. I use this code: Server:</p> <pre><code>import socket HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() </code></pre> <p>Client:</p> <pre><code>import socket HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) </code></pre> <p>It works fine! But if server is created on the computer which hasn't router. If u have router, before server creating you should open 50007 port on your modem. How can i create server on all computers without port enabling? Torrent-clients do it somehow. Thanks.</p>
5
2009-04-21T18:12:19Z
773,920
<p>The question is a little confusing, but I will try to help out. Basically, if the port (50007) is blocked on the server machine by a firewall, you will NOT be able to make a tcp connection to it from the client. That is the purpose of the firewall. A lot of protocols (SIP and bittorrent for example) do use firewall and NAT navigation strategies, but that is a complex subject that you can <a href="http://www.dessent.net/btfaq/#ports">get more information on here</a>. You will note that to use bittorrent effectively, you have to enable port forwarding for NAT and unblock port ranges for firewalls. Also, bittorrent uses tcp connections for most data transfer. Here is the takeaway:</p> <blockquote> <p>First, note that there are two types of connections that the BitTorrent program must make:</p> <ul> <li>Outbound HTTP connections to the tracker, usually on port 6969.</li> <li>Inbound and outbound connections to the peer machines, usually on port 6881 and up.</li> </ul> </blockquote>
7
2009-04-21T18:21:56Z
[ "python", "sockets", "ports" ]
Python +sockets
773,869
<p>i have to create connecting server&lt;=>client. I use this code: Server:</p> <pre><code>import socket HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() </code></pre> <p>Client:</p> <pre><code>import socket HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) </code></pre> <p>It works fine! But if server is created on the computer which hasn't router. If u have router, before server creating you should open 50007 port on your modem. How can i create server on all computers without port enabling? Torrent-clients do it somehow. Thanks.</p>
5
2009-04-21T18:12:19Z
773,939
<p>Very difficult to understand your question...</p> <blockquote> <p>(...) Torrent-clients do it somehow.</p> </blockquote> <p>The Torrent-clients can do this only when the router -- Internet gateway device (IGD) -- supports the <a href="http://en.wikipedia.org/wiki/Universal%5FPlug%5Fand%5FPlay" rel="nofollow">uPNP protocol</a>. The interesting part for your problem is <a href="http://en.wikipedia.org/wiki/Universal%5FPlug%5Fand%5FPlay#NAT%5Ftraversal" rel="nofollow">the section about NAT traversal</a>.</p>
2
2009-04-21T18:26:43Z
[ "python", "sockets", "ports" ]
SFTP listing directory
774,039
<p>I'm trying to make a connection to a secure sftp site, however I'm not able to list the directory,however, it's possible to connect using python "expect" or php"ssh2_connect" but it gives me the following mesg: Received disconnect from xx.xx.xx.</p> <p>If I use a GUI appliction like winscp I'm able to go to the sftp server and retrieve files.</p> <p>I need to script it thus a cli interface is needed.</p> <p>PS: just in case someone ran into this. I'm trying to connect to Avisena.com sftp server</p>
0
2009-04-21T18:49:03Z
774,195
<p>You can do this easily with <a href="http://www.lag.net/paramiko" rel="nofollow">paramiko</a>, checkout <a href="http://commandline.org.uk/python/sftp-python/" rel="nofollow">SFTP with Python</a></p>
3
2009-04-21T19:25:30Z
[ "php", "python", "sftp" ]
Business rules for calculating prices
774,245
<p>The business I work for is an on-line retailer, I'm currently working on a project that among other things involves calculating the customer prices for products. We will probably create a service that looks something like...</p> <pre><code>public interface IPriceService { decimal CalculateCustomerPrice(ISupplierPriceProvider product); } public interface ISupplierPriceProvider { decimal SupplierPrice { get; } string Currency { get; } } </code></pre> <p>Don't worry it will not look exactly like that, but you get the general idea. In our implementation of this service there will be a number of rules for calculating this price, these rules can change quite often and what we probably want to do sometime down the line is to create some sort of DSL for these rules. At the moment though we're not quite sure what changes will actually be requested by sales department and so forth so I'm thinking about hosting the DLR and having an Iron Python or Iron Ruby script file that contains a lot of the price calculation. This way we can rapidly update the price calculation rules and also get a feel for what type DSL the business people needs. Does this at all sound like a sane idea and also does anyone have any links articles/tutorials on how to host the DLR and letting the script files interact with CLR-objects and return values?</p>
0
2009-04-21T19:34:36Z
774,289
<p>It definitely sounds like a sane idea to me. You can trivially access CLR internals (objects and return values) from IronPython, I don't know about IronRuby. Chapters 1 and 7 of <a href="http://www.ironpythoninaction.com" rel="nofollow">IronPython in Action</a> are available online and would probably be helpful. There is also a "hello world" style tutorial available at the <a href="http://www.learningpython.com/2006/10/02/ironpython-hello-world-tutorial/" rel="nofollow">learning python</a> blog.</p>
1
2009-04-21T19:43:49Z
[ "python", "ruby", "scripting", "rules", "dynamic-language-runtime" ]
Python difflib: highlighting differences inline?
774,316
<p>When comparing similar lines, I want to highlight the differences on the same line:</p> <pre><code>a) lorem ipsum dolor sit amet b) lorem foo ipsum dolor amet lorem &lt;ins&gt;foo&lt;/ins&gt; ipsum dolor &lt;del&gt;sit&lt;/del&gt; amet </code></pre> <p>While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.</p> <p>Unfortunately, I have not been able to find another class/method which does not operate on a line-by-line basis.</p> <p>Am I missing anything? Any pointers would be appreciated!</p>
15
2009-04-21T19:57:32Z
774,338
<p><a href="http://docs.python.org/library/difflib.html#sequencematcher-objects" rel="nofollow">difflib.SequenceMatcher</a> will operate on single lines. You can use the "opcodes" to determine how to change the first line to make it the second line.</p>
2
2009-04-21T20:04:02Z
[ "python", "diff" ]
Python difflib: highlighting differences inline?
774,316
<p>When comparing similar lines, I want to highlight the differences on the same line:</p> <pre><code>a) lorem ipsum dolor sit amet b) lorem foo ipsum dolor amet lorem &lt;ins&gt;foo&lt;/ins&gt; ipsum dolor &lt;del&gt;sit&lt;/del&gt; amet </code></pre> <p>While difflib.HtmlDiff appears to do this sort of inline highlighting, it produces very verbose markup.</p> <p>Unfortunately, I have not been able to find another class/method which does not operate on a line-by-line basis.</p> <p>Am I missing anything? Any pointers would be appreciated!</p>
15
2009-04-21T19:57:32Z
788,780
<p>For your simple example:</p> <pre><code>import difflib def show_diff(seqm): """Unify operations between two compared strings seqm is a difflib.SequenceMatcher instance whose a &amp; b are strings""" output= [] for opcode, a0, a1, b0, b1 in seqm.get_opcodes(): if opcode == 'equal': output.append(seqm.a[a0:a1]) elif opcode == 'insert': output.append("&lt;ins&gt;" + seqm.b[b0:b1] + "&lt;/ins&gt;") elif opcode == 'delete': output.append("&lt;del&gt;" + seqm.a[a0:a1] + "&lt;/del&gt;") elif opcode == 'replace': raise NotImplementedError, "what to do with 'replace' opcode?" else: raise RuntimeError, "unexpected opcode" return ''.join(output) &gt;&gt;&gt; sm= difflib.SequenceMatcher(None, "lorem ipsum dolor sit amet", "lorem foo ipsum dolor amet") &gt;&gt;&gt; show_diff(sm) 'lorem&lt;ins&gt; foo&lt;/ins&gt; ipsum dolor &lt;del&gt;sit &lt;/del&gt;amet' </code></pre> <p>This works with strings. You should decide what to do with "replace" opcodes.</p>
28
2009-04-25T12:05:12Z
[ "python", "diff" ]
Python scripted mp3 database, with a php front end
774,502
<p>So, here's the deal. I am attempting to write a quick python script that reads the basic id3 tags from an mp3 (artist, album, songname, genre, etc). The python script will use most likely the mutagen library (unless you know of a better one). I'm not sure how to recursively scan through a directory to get each mp3's tags, and then fill a database. Also, as far as the database end, I want to make it as solid as possible, so I was wondering if anyone had any ideas on how I should design the database itself. Should I just use one big table, should I use certain relationships, etc. I am not very good at relational databases so I would appreciate any help. Oh, this is running on a linux box.</p>
2
2009-04-21T20:44:08Z
774,547
<p>To get started with extracting ID3 tags in Python, there's a module for that.</p> <pre><code>from ID3 import ID3 mp3_filepath = r'/music/song.mp3' id3_data = ID3(mp3_filepath) print 'Artist:', id3_data['ARTIST'] print 'Title:', id3_data['TITLE'] </code></pre> <p><a href="http://id3-py.sourceforge.net/" rel="nofollow">More info on ID3 module.</a></p> <p>If you want to recursively search a directory for mp3 files, the built-in <code>os</code> module can do that:</p> <pre><code>import os def mp3_files(root): # this is a generator that will return mp3 file paths within given dir for f in os.listdir(root): fullpath = os.path.join(root,f) if os.path.isdir(fullpath) and not os.path.islink(fullpath): for x in mp3_files(fullpath): # recurse into subdir yield x else: if fullpath[len(fullpath)-3:] == 'mp3': yield fullpath for p in mp3_files(root_dir): id3_data = ID3(p) print 'Artist:', id3_data['ARTIST'] print 'Title:', id3_data['TITLE'] </code></pre> <p><a href="http://code.activestate.com/recipes/105873/" rel="nofollow">Reference.</a></p> <p>In terms of creating the database, you don't need to reinvent the wheel (storing music data is a common database problem) -- a Google search will help you out. <a href="http://webforumz.com/databases/4711-music-database-design-help.htm" rel="nofollow">Here's one example</a>.</p>
4
2009-04-21T20:53:35Z
[ "php", "python", "database", "mp3", "id3" ]
Is it possible to overload ++ operators in Python?
774,784
<p>Is it possible to overload ++ operators in Python?</p>
0
2009-04-21T21:49:16Z
774,791
<p>Nope, it is not possible to overload the unary ++ operator, because it is not an operator at all in Python.</p> <p>Only (a subset of) the operators that are allowed by the Python syntax (those operators that already have one or more uses in the language) may be overloaded.</p> <p><a href="http://docs.python.org/reference/lexical%5Fanalysis.html#operators">These</a> are valid Python operators, and <a href="http://docs.python.org/library/operator.html">this page</a> lists the methods that you can define to overload them (the ones with two leading and trailing underscores).</p> <p>Instead of i++ as commonly used in other languages, in Python one writes i += 1.</p> <p>In python the + sign needs an operand to its right. It <em>may</em> also have an operand to its left, in which case it will be interpreted as a binary instead of a unary operator. +5, ++5, ..., ++++++5 are all valid Python expressions (all evaluating to 5), as are 7 + 5, 7 ++ 5, ..., 7 ++++++++ 5 (all evaluating to 7 + (+...+5) = 12). 5+ is <em>not</em> valid Python. See also <a href="http://stackoverflow.com/questions/470139/why-does-12-3-in-python">this question</a>.</p> <p><strong>Alternative idea</strong>: Depending on what you actually wanted to use the ++ operator for, you may want to consider overloading the <a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fpos%5F%5F">unary (prefix) plus operator</a>. Note, thought, that this may lead to some odd looking code. Other people looking at your code would probably assume it's a no-op and be confused.</p>
16
2009-04-21T21:51:54Z
[ "python", "operator-overloading" ]
Is it possible to overload ++ operators in Python?
774,784
<p>Is it possible to overload ++ operators in Python?</p>
0
2009-04-21T21:49:16Z
774,792
<p>There is no <code>++</code> operator in Python (nor '--'). Incrementing is usually done with the <code>+=</code> operator instead.</p>
17
2009-04-21T21:52:13Z
[ "python", "operator-overloading" ]
Is it possible to overload ++ operators in Python?
774,784
<p>Is it possible to overload ++ operators in Python?</p>
0
2009-04-21T21:49:16Z
774,794
<p>Well, the ++ operator doesn't exist in Python, so you really can't overload it.</p> <p>What happens when you do something like:</p> <pre>1 ++ 2</pre> <p>is actually</p> <pre>1 + (+2)</pre>
5
2009-04-21T21:53:05Z
[ "python", "operator-overloading" ]
Is it possible to overload ++ operators in Python?
774,784
<p>Is it possible to overload ++ operators in Python?</p>
0
2009-04-21T21:49:16Z
774,843
<p>Everyone makes good points, I'd just like to clear up one other thing. Open up a Python interpreter and check this out:</p> <pre><code>&gt;&gt;&gt; i = 1 &gt;&gt;&gt; ++i 1 &gt;&gt;&gt; i 1 </code></pre> <p>There is no ++ (or --) operator in Python. The reason it behaves as it did (instead of a syntax error) is that + and - are valid unary operators, acting basically like a sign would on digits. You can think of <code>++i</code> as a "+(+i)", and <code>--i</code> as "-(-i)". Expecting <code>++i</code> to work like in any other language leads to absolutely insidious bug-hunts. <em>C programmers: ye be warned.</em></p> <p>A straight <code>i++</code> or <code>i--</code> does fail adequately, for what it's worth.</p>
7
2009-04-21T22:05:23Z
[ "python", "operator-overloading" ]
Is it possible to overload ++ operators in Python?
774,784
<p>Is it possible to overload ++ operators in Python?</p>
0
2009-04-21T21:49:16Z
1,197,174
<p>You could hack it, though this introduces some undesirable consequences:</p> <pre><code>class myint_plus: def __init__(self,myint_instance): self.myint_instance = myint_instance def __pos__(self): self.myint_instance.i += 1 return self.myint_instance class myint: def __init__(self,i): self.i = i def __pos__(self): return myint_plus(self) def __repr__(self): return self.i.__repr__() x = myint(1) print x ++x print x </code></pre> <p>the output is:</p> <pre><code>1 2 </code></pre>
5
2009-07-28T22:49:21Z
[ "python", "operator-overloading" ]
Explain Python entry points?
774,824
<p>I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does?</p>
107
2009-04-21T21:59:55Z
774,859
<p>From abstract point of view, entry points are used to create a system-wide registry of Python callables that implement certain interfaces. There are APIs in pkg_resources to see which entry points are advertised by a given package as well as APIs to determine which packages advertise a certain entry point.</p> <p>Entry points are useful for allowing one package do use plugins that are in another package. For instance, Ian Bicking's <a href="http://pythonpaste.org/">Paste</a> project uses entry points extensively. In this case, you can write a package that advertises its WSGI application factory using the entry point <code>paste.app_factory</code>. </p> <p>Another use for entry points is enumerating all the packages on the system that provide some plugin functionality. The <a href="http://www.turbogears.org">TurboGears</a> web framework uses the <a href="http://docs.turbogears.org/1.0/TemplatePlugins"><code>python.templating.engines</code></a> entry point to look up templating libraries that are installed and available. </p>
16
2009-04-21T22:10:16Z
[ "python", "setuptools" ]
Explain Python entry points?
774,824
<p>I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does?</p>
107
2009-04-21T21:59:55Z
782,984
<p>An "entry point" is typically a function (or other callable function-like object) that a developer or user of your Python package might want to use, though a non-callable object can be supplied as an entry point as well (as correctly pointed out in the comments!).</p> <p>The most popular kind of entry point is the "console_script" entry point, which points to a function that you want made available as a command-line tool to whoever installs your package. This goes into your setup.py like:</p> <pre><code>entry_points={ 'console_scripts': [ 'cursive = cursive.tools.cmd:cursive_command', ], }, </code></pre> <p>I have a package I've just deployed called "cursive.tools", and I wanted it to make available a "cursive" command that someone could run from the command line, like:</p> <pre><code>$ cursive --help usage: cursive ... </code></pre> <p>The way to do this is define a function, like maybe a "cursive_command" function in cursive/tools/cmd.py that looks like:</p> <pre><code>def cursive_command(): args = sys.argv[1:] if len(args) &lt; 1: print "usage: ..." </code></pre> <p>and so forth; it should assume that it's been called from the command line, parse the arguments that the user has provided, and ... well, do whatever the command is designed to do.</p> <p>Install the <a href="http://pypi.python.org/pypi/docutils/">docutils</a> package for a great example of entry-point use: it will install something like a half-dozen useful commands for converting Python documentation to other formats.</p>
90
2009-04-23T18:37:08Z
[ "python", "setuptools" ]
Explain Python entry points?
774,824
<p>I've read the documentation on egg entry points in Pylons and on the Peak pages, and I still don't really understand. Could someone explain them to me, or point me at an article or book that does?</p>
107
2009-04-21T21:59:55Z
9,615,473
<p><a href="https://setuptools.readthedocs.io/en/latest/pkg_resources.html#entry-points">EntryPoints</a> provide a persistent, filesystem-based object name registration and name-based direct object import mechanism (implemented by the <a href="http://pypi.python.org/pypi/setuptools">setuptools</a> package). </p> <p>They associate names of Python objects with free-form identifiers. So any other code using the same Python installation and knowing the identifier can access an object with the associated name, no matter where the object is defined. The <strong>associated names can be any names existing in a Python module</strong>; for example name of a class, function or variable. The entry point mechanism does not care what the name refers to, as long as it is importable.</p> <p>As an example, let's use (the name of) a function, and an imaginary python module with a fully-qualified name 'myns.mypkg.mymodule':</p> <pre><code>def the_function(): "function whose name is 'the_function', in 'mymodule' module" print "hello from the_function" </code></pre> <p>Entry points are registered via an entry points declaration in setup.py. To register the_function under entrypoint called 'my_ep_func':</p> <pre><code> entry_points = { 'my_ep_group_id': [ 'my_ep_func = myns.mypkg.mymodule:the_function' ] }, </code></pre> <p>As the example shows, entry points are grouped; there's corresponding API to look up all entry points belonging to a group (example below).</p> <p>Upon a package installation (ie. running 'python setup.py install'), the above declaration is parsed by setuptools. It then writes the parsed information in special file. After that, the <a href="https://pythonhosted.org/setuptools/pkg_resources.html#entry-points">pkg_resources API</a> (part of setuptools) can be used to look up the entry point and access the object(s) with the associated name(s):</p> <pre><code>import pkg_resources named_objects = {} for ep in pkg_resources.iter_entry_points(group='my_ep_group_id'): named_objects.update({ep.name: ep.load()}) </code></pre> <p>Here, setuptools read the entry point information that was written in special files. It found the entry point, imported the module (myns.mypkg.mymodule), and retrieved the_function defined there, upon call to pkg_resources.load().</p> <p>Assuming there were no other entry point registrations for the same group id, calling the_function would then be simple:</p> <pre><code>&gt;&gt;&gt; named_objects['my_ep_func']() hello from the_function </code></pre> <p>Thus, while perhaps a bit difficult to grasp at first, the entry point mechanism is actually quite simple to use. It provides an useful tool for pluggable Python software development.</p>
115
2012-03-08T09:39:04Z
[ "python", "setuptools" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,889
<p>First of all, you likely don't want to use <code>print</code>. It doesn't return anything, so use a conventional <code>for</code> loop if you just want to print out stuff. What you are looking for is:</p> <pre><code>&gt;&gt;&gt; list1 = (1,2,3,4) &gt;&gt;&gt; list2 = [(i, i*2) for i in list1] # Notice the braces around both items &gt;&gt;&gt; print(list2) [(1, 2), (2, 4), (3, 6), (4, 8)] </code></pre>
0
2009-04-21T22:18:18Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,892
<p>I'm not quite sure what you're trying to do but it's probably something like</p> <pre><code>list2 = [(i, i*2, i) for i in list1] print list2 </code></pre> <p>The statement in the list comprehension has to be a single statement, but you could always make it a function call:</p> <pre><code>def foo(i): print i print i * 2 return i list2 = [foo(i) for i in list1] </code></pre>
2
2009-04-21T22:18:46Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,896
<p>Here's an example from <a href="http://stackoverflow.com/questions/364621/python-get-position-in-list/364769#364769">another question</a>:</p> <pre><code>[i for i,x in enumerate(testlist) if x == 1] </code></pre> <p>the enumerate generator returns a 2-tuple which goes into i,x.</p>
2
2009-04-21T22:20:33Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,921
<p>Print is a weird thing to call in a list comprehension. It'd help if you showed us what output you want, not just the code that doesn't work.</p> <p>Here are two guesses for you. Either way, the important point is that the value statement in a list comprehension has to be a <em>single</em> value. You can't insert multiple items all at once. (If that's what you're trying to do, skip to the 2nd example.)</p> <pre><code>list1 = [1, 2, 3] list2 = [(i, i*2, i) for i in list1] # list2 = [(1, 2, 1), (2, 4, 2), (3, 6, 3)] </code></pre> <p>To get a flat list:</p> <pre><code>list1 = [1, 2, 3] tmp = [(i, i*2) for i in list1] list2 = [] map(list2.extend, tmp) # list2 = [1, 2, 1, 2, 4, 2, 3, 6, 3] </code></pre> <p>Edit: Incrementing a value in the middle of the list comprehension is still weird. If you really need to do it, you're better off just writing a regular for loop, and appending values as you go. In Python, cleverness like that is almost always branded as "unpythonic." Do it if you must, but you will get no end of flak in forums like this. ;)</p>
1
2009-04-21T22:25:15Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,968
<p>You can't do multiple statements, but you can do a function call. To do what you seem to want above, you could do:</p> <pre><code>list1 = ... list2 = [ (sum(list1[:i], i) for i in list1 ] </code></pre> <p>in general, since list comprehensions are part of the 'functional' part of python, you're restricted to... functions. Other folks have suggested that you could write your own functions if necessary, and that's also a valid suggestion.</p>
0
2009-04-21T22:36:57Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
774,987
<p>Statements <em>cannot</em> go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that <strong>did</strong> make it into the language: generators. Watch:</p> <pre><code>def total_and_item(sequence): total = 0 for i in sequence: total += i yield (total, i) list2 = list(total_and_item(list1)) </code></pre> <p>The generator keeps a running tally of the items seen so far, and prefixes it to each item, just like it looks like you example tries to do. Of course, a straightforward loop might be even simpler, that creates an empty list at the top and just calls append() a lot! :-)</p>
18
2009-04-21T22:45:01Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
775,157
<p>For your edited example:</p> <pre><code>currentValue += sum(list1) </code></pre> <p>or:</p> <pre><code>for x in list1: currentValue += x </code></pre> <p>List comprehensions are great, I love them, but there's nothing wrong with the humble <code>for</code> loop and you shouldn't be afraid to use it :-)</p> <p>EDIT: "But what if I wanna increment different than the collected values?"</p> <p>Well, what do you want to increment by? You have the entire power of python at your command!</p> <p>Increment by x-squared?</p> <pre><code>for x in list1: currentValue += x**2 </code></pre> <p>Increment by some function of x and its position in the list?</p> <pre><code>for i, x in enumerate(list1): currentValue += i*x </code></pre>
1
2009-04-21T23:46:55Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
784,688
<p>Why would you create a duplicate list. It seems like all that list comprehension would do is just sum the contents.</p> <p>Why not just.</p> <pre><code>list2 = list(list1) #this makes a copy currentValue = sum(list2) </code></pre>
1
2009-04-24T06:02:04Z
[ "python", "list-comprehension" ]
Multiple statements in list compherensions in Python?
774,876
<p>Is it possible to have something like:</p> <pre><code>list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] </code></pre> <p>I tried that but didn't work? What's the proper syntax to write those?</p> <p>EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.</p>
6
2009-04-21T22:14:48Z
1,166,538
<p>As pjz said, you can use functions, so here you can use a closure to keep track of the counter value:</p> <pre><code># defines a closure to enclose the sum variable def make_counter(init_value=0): sum = [init_value] def inc(x=0): sum[0] += x return sum[0] return inc </code></pre> <p>Then you do what you want with list1:</p> <pre><code>list1 = range(5) # list1 = [0, 1, 2, 3, 4] </code></pre> <p>And now with just two lines, we get list2:</p> <pre><code>counter = make_counter(10) # counter with initial value of 10 list2 = reduce(operator.add, ([counter(x), x] for x in list1)) </code></pre> <p>In the end, list2 contains:</p> <pre><code>[10, 0, 11, 1, 13, 2, 16, 3, 20, 4] </code></pre> <p>which is what you wanted, and you can get the value of the counter after the loop with one call:</p> <pre><code>counter() # value is 20 </code></pre> <p>Finally, you can replace the closure stuff by any kind of operation you want, here we have an increment, but it's really up to you. Note also that we use a reduce to flatten list2, and this little trick requires you to import <em>operator</em> before calling the line with the reduce:</p> <pre><code>import operator </code></pre>
2
2009-07-22T16:33:03Z
[ "python", "list-comprehension" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
775,075
<p>By using the <a href="http://docs.python.org/library/functions.html#divmod"><code>divmod()</code></a> function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:</p> <pre><code>m, s = divmod(seconds, 60) h, m = divmod(m, 60) print "%d:%02d:%02d" % (h, m, s) </code></pre>
284
2009-04-21T23:15:54Z
[ "python" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
775,095
<p>or you can do</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; str(datetime.timedelta(seconds=666)) '0:11:06' </code></pre>
344
2009-04-21T23:22:15Z
[ "python" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
24,507,708
<p>I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use <a href="https://docs.python.org/2/library/time.html#time.strftime">time.strftime</a>, which gives more control over formatting:</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; time.strftime("%H:%M:%S", time.gmtime(666)) '00:11:06' </code></pre> <p><a href="https://docs.python.org/2/library/time.html#time.gmtime">gmtime</a> is used to convert seconds to special tuple format that <code>strftime()</code> requires.</p>
22
2014-07-01T10:13:42Z
[ "python" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
31,946,730
<pre><code>&gt;&gt;&gt; "{:0&gt;8}".format(datetime.timedelta(seconds=66)) &gt;&gt;&gt; '00:01:06' # good </code></pre> <p>and:</p> <pre><code>&gt;&gt;&gt; "{:0&gt;8}".format(datetime.timedelta(seconds=666777) &gt;&gt;&gt; '7 days, 17:12:57' # nice </code></pre> <p>without ':0>8':</p> <pre><code>&gt;&gt;&gt; "{}".format(datetime.timedelta(seconds=66)) &gt;&gt;&gt; '0:01:06' # not HH:MM:SS </code></pre> <p>and:</p> <pre><code>&gt;&gt;&gt; time.strftime("%H:%M:%S", time.gmtime(666777)) &gt;&gt;&gt; '17:12:57' # wrong </code></pre> <p>but:</p> <pre><code>&gt;&gt;&gt; "{:0&gt;8}".format(datetime.timedelta(seconds=620000)) &gt;&gt;&gt; '7 days, 4:13:20' # bummer </code></pre>
8
2015-08-11T16:06:05Z
[ "python" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
33,504,562
<p>This is how I got it.</p> <pre><code>def sec2time(sec, n_msec=3): ''' Convert seconds to 'D days, HH:MM:SS.FFF' ''' if hasattr(sec,'__len__'): return [sec2time(s) for s in sec] m, s = divmod(sec, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) if n_msec &gt; 0: pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec) else: pattern = r'%02d:%02d:%02d' if d == 0: return pattern % (h, m, s) return ('%d days, ' + pattern) % (d, h, m, s) </code></pre> <p>Some examples:</p> <pre><code>$ sec2time(10, 3) Out: '00:00:10.000' $ sec2time(1234567.8910, 0) Out: '14 days, 06:56:07' $ sec2time(1234567.8910, 4) Out: '14 days, 06:56:07.8910' $ sec2time([12, 345678.9], 3) Out: ['00:00:12.000', '4 days, 00:01:18.900'] </code></pre>
0
2015-11-03T16:42:14Z
[ "python" ]
Python Time Seconds to h:m:s
775,049
<p>I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds. Is there an easy way to convert the seconds to this format in python?</p>
178
2009-04-21T23:08:16Z
37,368,085
<p>If you need to get <code>datetime.time</code> value, you can use this trick:</p> <pre><code>my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time() </code></pre> <p>You cannot add <code>timedelta</code> to <code>time</code>, but can add it to <code>datetime</code>.</p>
1
2016-05-21T21:14:33Z
[ "python" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,175
<p>Sorry I don't have an easy answer, but I can tell you that as the manager of a development team at a company in the late 90's we were tasked with solving this very problem and it was HARD.</p> <p>It's not the weekly hours that's tough, that can be done with a relatively small bitmask (168 bits = 1 per hour of the week), the trick is the businesses which are closed every alternating Tuesday.</p> <p>Starting with a bitmask then moving on to an exceptions field is the best solution I've ever seen.</p>
3
2009-04-21T23:52:58Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,211
<p>The bitmap field mentioned by another respondent would be incredibly efficient, but gets messy if you want to be able to handle half-hour or quarter-hour times, since you have to increase arithmetically the number of bits and the design of the field each time you encounter a new resolution that you have to match.</p> <p>I would instead try storing the values as datetimes inside a list:</p> <pre><code>openclosings = [ open1, close1, open2, close2, ... ] </code></pre> <p>Then, I would use Python's "bisect_right()" function in its built-in "bisect" module to find, in fast O(log n) time, where in that list your query time "fits". Then, look at the index that is returned. If it is an even number (0, 2, 4...) then the time lies between one of the "closed" times and the next "open" time, so the shop is closed then. If, instead, the bisection index is an odd number (1, 3, 5...) then the time has landed between an opening and a closing time, and the shop is open.</p> <p>Not as fast as bitmaps, but you don't have to worry about resolution, and I can't think of another O(log n) solution that's as elegant.</p>
5
2009-04-22T00:08:07Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,247
<p>If you are willing to just look at single week at a time, you can canonicalize all opening/closing times to be set numbers of minutes since the start of the week, say Sunday 0 hrs. For each store, you create a number of tuples of the form [startTime, endTime, storeId]. (For hours that spanned Sunday midnight, you'd have to create two tuples, one going to the end of the week, one starting at the beginning of the week). This set of tuples would be indexed (say, with a tree you would pre-process) on both startTime and endTime. The tuples shouldn't be that large: there are only ~10k minutes in a week, which can fit in 2 bytes. This structure would be graceful inside a MySQL table with appropriate indexes, and would be very resilient to constant insertions &amp; deletions of records as information changed. Your query would simply be "select storeId where startTime &lt;= time and endtime >= time", where time was the canonicalized minutes since midnight on sunday.</p> <p>If information doesn't change very often, and you want to have lookups be very fast, you could solve every possible query up front and cache the results. For instance, there are only 672 quarter-hour periods in a week. With a list of businesses, each of which had a list of opening &amp; closing times like Brandon Rhodes's solution, you could simply, iterate through every 15-minute period in a week, figure out who's open, then store the answer in a lookup table or in-memory list.</p>
8
2009-04-22T00:25:59Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,354
<p>You say you're using SOLR, don't care about storage, and want the lookups to be fast. Then instead of storing open/close tuples, index an entry for every open block of time at the level of granularity you need (15 mins). For the encoding itself, you could use just cumulative hours:minutes.</p> <p>For example, a store open from 4-5 pm on Monday, would have indexed values added for [40:00, 40:15, 40:30, 40:45]. A query at 4:24 pm on Monday would be normalized to 40:15, and therefore match that store document.</p> <p>This may seem inefficient at first glance, but it's a relatively small constant penalty for indexing speed and space. And makes the searches as fast as possible.</p>
4
2009-04-22T01:13:48Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,364
<p>If you can control your data well, I see a simple solution, similar to @Sebastian's. Follow the advice of creating the tuples, except create them of the form [time=startTime, storeId] and [time=endTime, storeId], then sort these in a list. To find out if a store is open, simply do a query like:</p> <pre><code>select storeId from table where time &lt;= '@1' group by storeId having count(storeId) % 2 == 1 </code></pre> <p>To optimize this, you could build a lookup table at each of time t, store the stores that are open at t, and the store openings/closings between t and t+1 (for any grouping of t).</p> <p>However, this has the drawback of being harder to maintain (overlapping openings/closings need to be merged into a longer open-close period).</p>
0
2009-04-22T01:18:43Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
775,459
<p>Have you looked at how many unique open/close time combinations there are? If there are not that many, make a reference table of the unique combinations and store the index of the appropriate entry against each business. Then you only have to search the reference table and then find the business with those indices.</p>
0
2009-04-22T02:03:30Z
[ "python", "mysql", "performance", "solr" ]
Efficiently determining if a business is open or not based on store hours
775,161
<p>Given a time (eg. currently 4:24pm on Tuesday), I'd like to be able to select all businesses that are currently open out of a set of businesses. </p> <ul> <li>I have the open and close times for every business for every day of the week</li> <li>Let's assume a business can open/close only on 00, 15, 30, 45 minute marks of each hour</li> <li>I'm assuming the same schedule each week.</li> <li>I am most interested in being able to quickly look up a set of businesses that is open at a certain time, not the space requirements of the data.</li> <li>Mind you, some my open at 11pm one day and close 1am the next day. </li> <li>Holidays don't matter - I will handle these separately</li> </ul> <p>What's the most efficient way to store these open/close times such that with a single time/day-of-week tuple I can <strong>speedily</strong> figure out which businesses are open?</p> <p>I am using Python, SOLR and mysql. I'd like to be able to do the querying in SOLR. But frankly, I'm open to any suggestions and alternatives.</p>
6
2009-04-21T23:48:14Z
777,443
<p>In your Solr index, instead of indexing each business as one document with hours, index every "retail session" for every business during the course of a week. </p> <p>For example if Joe's coffee is open Mon-Sat 6am-9pm and closed on Sunday, you would index six distinct documents, each with two indexed fields, "open" and "close". If your units are 15 minute intervals, then the values can range from 0 to 7*24*4. Assuming you have a unique ID for each business, store this in each document so you can map the sessions to businesses.</p> <p>Then you can simply do a range search in Solr:</p> <p>open:[* TO N] AND close:[N+1 TO *]</p> <p>where N is computed to the Nth 15 minute interval that the current time falls into. For examples if it's 10:10AM on Wednesday, your query would be:</p> <p>open:[* TO 112] AND close:[113 TO *]</p> <p>aka "find a session that starts at or before 10:00am Wed and ends at or after 10:15am Wed"</p> <p>If you want to include other criteria in your search, such as location or products, you will need to index this with each session document as well. This is a bit redundant, but if your index is not huge, it shouldn't be a problem.</p>
1
2009-04-22T14:18:22Z
[ "python", "mysql", "performance", "solr" ]
Directory Walker for Python
775,231
<p>I am currently using the directory walker from <a href="http://effbot.org/librarybook/os-path-walk-example-3.py" rel="nofollow">Here</a></p> <pre><code>import os class DirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) return fullname for file in DirectoryWalker(os.path.abspath('.')): print file </code></pre> <p>This minor change allows you to have the full path within the file.</p> <p>Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.</p>
4
2009-04-22T00:19:13Z
775,249
<p>Rather than using '.' as your directory, refer to its absolute path:</p> <pre><code>for file in DirectoryWalker(os.path.abspath('.')): print file </code></pre> <p>Also, I'd recommend using a word other than 'file', because it means something in the python language. Not a keyword, though so it still runs.</p> <p>As an aside, when dealing with filenames, I find the os.path module to be incredibly useful - I'd recommend having a look through that, especially</p> <pre><code>os.path.normpath </code></pre> <p>Normalises paths (gets rid of redundant '.'s and 'theFolderYouWereJustIn/../'s)</p> <pre><code>os.path.join </code></pre> <p>Joins two paths</p>
6
2009-04-22T00:26:32Z
[ "python", "directory-listing" ]
Directory Walker for Python
775,231
<p>I am currently using the directory walker from <a href="http://effbot.org/librarybook/os-path-walk-example-3.py" rel="nofollow">Here</a></p> <pre><code>import os class DirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) return fullname for file in DirectoryWalker(os.path.abspath('.')): print file </code></pre> <p>This minor change allows you to have the full path within the file.</p> <p>Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.</p>
4
2009-04-22T00:19:13Z
775,252
<p>Just prepend the current directory path to the "./foo" path returned:</p> <pre><code>print os.path.join(os.getcwd(), file) </code></pre>
0
2009-04-22T00:27:16Z
[ "python", "directory-listing" ]
Directory Walker for Python
775,231
<p>I am currently using the directory walker from <a href="http://effbot.org/librarybook/os-path-walk-example-3.py" rel="nofollow">Here</a></p> <pre><code>import os class DirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) return fullname for file in DirectoryWalker(os.path.abspath('.')): print file </code></pre> <p>This minor change allows you to have the full path within the file.</p> <p>Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.</p>
4
2009-04-22T00:19:13Z
775,253
<p>os.path.dirname()? os.path.normpath()? os.path.abspath()?</p> <p>This would also be a lovely place to think recursion.</p>
1
2009-04-22T00:27:32Z
[ "python", "directory-listing" ]
Directory Walker for Python
775,231
<p>I am currently using the directory walker from <a href="http://effbot.org/librarybook/os-path-walk-example-3.py" rel="nofollow">Here</a></p> <pre><code>import os class DirectoryWalker: # a forward iterator that traverses a directory tree def __init__(self, directory): self.stack = [directory] self.files = [] self.index = 0 def __getitem__(self, index): while 1: try: file = self.files[self.index] self.index = self.index + 1 except IndexError: # pop next directory from stack self.directory = self.stack.pop() self.files = os.listdir(self.directory) self.index = 0 else: # got a filename fullname = os.path.join(self.directory, file) if os.path.isdir(fullname) and not os.path.islink(fullname): self.stack.append(fullname) return fullname for file in DirectoryWalker(os.path.abspath('.')): print file </code></pre> <p>This minor change allows you to have the full path within the file.</p> <p>Can anyone help me how to find just the filename as well using this? I need both the full path, and just the filename.</p>
4
2009-04-22T00:19:13Z
778,377
<p>Why do you want to do such boring thing yourself?</p> <pre><code>for path, directories, files in os.walk('.'): print 'ls %r' % path for directory in directories: print ' d%r' % directory for filename in files: print ' -%r' % filename </code></pre> <p>Output:</p> <pre><code>'.' d'finction' d'.hg' -'setup.py' -'.hgignore' './finction' -'finction' -'cdg.pyc' -'util.pyc' -'cdg.py' -'util.py' -'__init__.pyc' -'__init__.py' './.hg' d'store' -'hgrc' -'requires' -'00changelog.i' -'undo.branch' -'dirstate' -'undo.dirstate' -'branch' './.hg/store' d'data' -'undo' -'00changelog.i' -'00manifest.i' './.hg/store/data' d'finction' -'.hgignore.i' -'setup.py.i' './.hg/store/data/finction' -'util.py.i' -'cdg.py.i' -'finction.i' -'____init____.py.i' </code></pre> <p>But if you insist, there's path related tools in <a href="http://docs.python.org/library/os.path.html">os.path</a>, os.basename is what you are looking at.</p> <pre><code>&gt;&gt;&gt; import os.path &gt;&gt;&gt; os.path.basename('/hello/world.h') 'world.h' </code></pre>
12
2009-04-22T17:40:32Z
[ "python", "directory-listing" ]
Python MySQL Parameterized Queries
775,296
<p>I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table. </p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (var1, var2, var3, var4, var5, var6) """) </code></pre> <p>Can someone help me with the syntax here?</p>
44
2009-04-22T00:43:21Z
775,320
<p>The linked docs give the following example:</p> <pre><code> cursor.execute (""" UPDATE animal SET name = %s WHERE name = %s """, ("snake", "turtle")) print "Number of rows updated: %d" % cursor.rowcount </code></pre> <p>So you just need to adapt this to your own code - example:</p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (%s, %s, %s, %s, %s, %s) """, (var1, var2, var3, var4, var5, var6)) </code></pre> <p>(If SongLength is numeric, you may need to use %d instead of %s).</p>
10
2009-04-22T00:53:31Z
[ "python", "mysql" ]
Python MySQL Parameterized Queries
775,296
<p>I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table. </p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (var1, var2, var3, var4, var5, var6) """) </code></pre> <p>Can someone help me with the syntax here?</p>
44
2009-04-22T00:43:21Z
775,344
<p>You have a few options available. You'll want to get comfortable with python's string iterpolation. Which is a term you might have more success searching for in the future when you want to know stuff like this.</p> <p>Better for queries:</p> <pre><code>some_dictionary_with_the_data = { 'name': 'awesome song', 'artist': 'some band', etc... } cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (%(name)s, %(artist)s, %(album)s, %(genre)s, %(length)s, %(location)s) """, some_dictionary_with_the_data) </code></pre> <p>Considering you probably have all of your data in an object or dictionary already, the second format will suit you better. Also it sucks to have to count "%s" appearances in a string when you have to come back and update this method in a year :)</p>
21
2009-04-22T01:04:31Z
[ "python", "mysql" ]
Python MySQL Parameterized Queries
775,296
<p>I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table. </p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (var1, var2, var3, var4, var5, var6) """) </code></pre> <p>Can someone help me with the syntax here?</p>
44
2009-04-22T00:43:21Z
775,399
<p>Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. <strong>The difference might seem trivial, but in reality it's huge</strong>.</p> <h3>Incorrect (with security issues)</h3> <pre><code>c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2)) </code></pre> <h3>Correct (with escaping)</h3> <pre><code>c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2)) </code></pre> <p>It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses <code>printf</code> style syntax instead of the more commonly accepted '?' marker (used by eg. <code>python-sqlite</code>).</p>
167
2009-04-22T01:35:26Z
[ "python", "mysql" ]
Python MySQL Parameterized Queries
775,296
<p>I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table. </p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (var1, var2, var3, var4, var5, var6) """) </code></pre> <p>Can someone help me with the syntax here?</p>
44
2009-04-22T00:43:21Z
5,448,353
<p>Actually, even if your variable (SongLength) is numeric, you will still have to format it with %s in order to bind the parameter correctly. If you try to use %d, you will get an error. Here's a small excerpt from this link <a href="http://mysql-python.sourceforge.net/MySQLdb.html" rel="nofollow">http://mysql-python.sourceforge.net/MySQLdb.html</a>:</p> <p>To perform a query, you first need a cursor, and then you can execute queries on it:</p> <pre><code>c=db.cursor() max_price=5 c.execute("""SELECT spam, eggs, sausage FROM breakfast WHERE price &lt; %s""", (max_price,)) </code></pre> <p>In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price &lt; 5".</p>
4
2011-03-27T09:31:30Z
[ "python", "mysql" ]
Python MySQL Parameterized Queries
775,296
<p>I am having a hard time using the MySQLdb module to insert information into my database. I need to insert 6 variables into the table. </p> <pre><code>cursor.execute (""" INSERT INTO Songs (SongName, SongArtist, SongAlbum, SongGenre, SongLength, SongLocation) VALUES (var1, var2, var3, var4, var5, var6) """) </code></pre> <p>Can someone help me with the syntax here?</p>
44
2009-04-22T00:43:21Z
15,980,304
<p>As an alternative to the chosen answer, and with the same safe semantics of Marcel's, here is a compact way of using a Python dictionary to specify the values. It has the benefit of being easy to modify as you add or remove columns to insert:</p> <pre><code> meta_cols=('SongName','SongArtist','SongAlbum','SongGenre') insert='insert into Songs ({0}) values ({1})'. .format(','.join(meta_cols), ','.join( ['%s']*len(meta_cols) )) args = [ meta[i] for i in meta_cols ] cursor=db.cursor() cursor.execute(insert,args) db.commit() </code></pre> <p>Where <strong>meta</strong> is the dictionary holding the values to insert. Update can be done in the same way:</p> <pre><code> meta_cols=('SongName','SongArtist','SongAlbum','SongGenre') update='update Songs set {0} where id=%s'. .format(','.join([ '{0}=%s'.format(c) for c in meta_cols ])) args = [ meta[i] for i in meta_cols ] args.append( songid ) cursor=db.cursor() cursor.execute(update,args) db.commit() </code></pre>
1
2013-04-12T20:28:19Z
[ "python", "mysql" ]
os.path.exists() for files in your Path?
775,351
<p>I commonly use os.path.exists() to check if a file is there before doing anything with it.</p> <p>I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.</p> <p>Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())</p> <p>btw - I'm doing this on windows.</p>
11
2009-04-22T01:09:31Z
775,360
<p>You could get the PATH environment variable, and try "exists()" for the .exe in each dir in the path. But that could perform horribly.</p> <p>example for finding notepad.exe:</p> <pre><code>import os for p in os.environ["PATH"].split(os.pathsep): print os.path.exists(os.path.join(p, 'notepad.exe')) </code></pre> <p>more clever example:</p> <pre><code>if not any([os.path.exists(os.path.join(p, executable) for p in os.environ["PATH"].split(os.pathsep)]): print "can't find %s" % executable </code></pre> <p>Is there a specific reason you want to avoid exception? (besides dogma?)</p>
12
2009-04-22T01:16:08Z
[ "python", "windows" ]
os.path.exists() for files in your Path?
775,351
<p>I commonly use os.path.exists() to check if a file is there before doing anything with it.</p> <p>I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.</p> <p>Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())</p> <p>btw - I'm doing this on windows.</p>
11
2009-04-22T01:09:31Z
777,010
<p>On Unix you have to split the PATH var.</p> <pre><code>if any([os.path.exists(os.path.join(p,progname)) for p in os.environ["PATH"].split(":")]): do_something() </code></pre>
0
2009-04-22T12:37:50Z
[ "python", "windows" ]
os.path.exists() for files in your Path?
775,351
<p>I commonly use os.path.exists() to check if a file is there before doing anything with it.</p> <p>I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.</p> <p>Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())</p> <p>btw - I'm doing this on windows.</p>
11
2009-04-22T01:09:31Z
777,067
<p>Please note that checking for existance and then opening is always open to race-conditions. The file can disappear between your program's check and its next access of the file, since other programs continue to run on the machine.</p> <p>Thus there might still be an exception being thrown, even though your code is "certain" that the file exists. This is, after all, why they're called exceptions.</p>
2
2009-04-22T12:51:26Z
[ "python", "windows" ]
os.path.exists() for files in your Path?
775,351
<p>I commonly use os.path.exists() to check if a file is there before doing anything with it.</p> <p>I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.</p> <p>Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())</p> <p>btw - I'm doing this on windows.</p>
11
2009-04-22T01:09:31Z
777,961
<p>You generally shouldn't should os.path.exists to try to figure out if something is going to succeed. You should just try it and if you want you can handle the exception if it fails.</p>
2
2009-04-22T15:53:31Z
[ "python", "windows" ]
os.path.exists() for files in your Path?
775,351
<p>I commonly use os.path.exists() to check if a file is there before doing anything with it.</p> <p>I've run across a situation where I'm calling a executable that's in the configured env path, so it can be called without specifying the abspath.</p> <p>Is there something that can be done to check if the file exists before calling it? (I may fall back on try/except, but first I'm looking for a replacement for os.path.exists())</p> <p>btw - I'm doing this on windows.</p>
11
2009-04-22T01:09:31Z
1,322,060
<p>Extending Trey Stout's search with Carl Meyer's comment on PATHEXT:</p> <pre><code>import os def exists_in_path(cmd): # can't search the path if a directory is specified assert not os.path.dirname(cmd) extensions = os.environ.get("PATHEXT", "").split(os.pathsep) for directory in os.environ.get("PATH", "").split(os.pathsep): base = os.path.join(directory, cmd) options = [base] + [(base + ext) for ext in extensions] for filename in options: if os.path.exists(filename): return True return False </code></pre> <p>EDIT: Thanks to Aviv (on my blog) I now know there's a Twisted implementation: <a href="http://twistedmatrix.com/trac/browser/tags/releases/twisted-8.2.0/twisted/python/procutils.py" rel="nofollow">twisted.python.procutils.which</a></p>
3
2009-08-24T12:25:35Z
[ "python", "windows" ]
how can I decode the REG_BINARY value HKLM\Software\Microsoft\Ole\DefaultLaunchPermission to see which users have permission?
775,365
<p>I am trying to find a way to decode the REG_BINARY value for "<strong>HKLM\Software\Microsoft\Ole\DefaultLaunchPermission</strong>" to see which users have permissions by default, and if possible, a method in which I can also append other users by their username. </p> <p>At work we make use of DCOM and for the most part we always give the same users permission but in some cases we are forced to accommodate our clients and add custom users/groups to suit their needs. Unfortunately the custom users we need to add are random usernames so I am unable to just add all the users and copy the value from the key like I have done with the default users we use 95% of the time.</p> <p>I am currently working on a command-line executable application where I have a command to set permissions for pre-defined users but I would also like to be able to add an option to append a custom user(s) to add to the default permission along with our predefined default users list.</p> <p>Currently, to set the default users list with my application I would just type:</p> <p><strong>MyTool.exe Policies</strong></p> <p>But I would like to be able to make it a bit more verbose, closer to how NET command is used for windows users, something like:</p> <p><strong>MyTool.exe Policies /ADD:"MyCustomUsername"</strong></p> <p>The problem is that the data stored in the REG_BINARY value doesn't seem to be easily decoded. I was able to decode the hex portion in python but I am left with some sort of binary data which I don't have a clue what to do with as I don't even know what kind of encoding was used in the first place to know what to use to decode it. :P</p> <p>I have done quite a bit of googling but I think my lack of understanding the terminology around this topic has probably caused me to overlook the answer without recognizing it for what it is.</p> <p>I guess my first real question would have to be what kind of encoding is used for the above key after it has been decoded from hex? </p> <p>Or better yet, is it even possible to obtain/modify the key's value programmatically so that I can obtain a list of the users that are currently set, and if necessary, append additional users/groups?</p> <p>I would prefer to keep this application written strictly in Python if possible (or WMI/WMIC), but if necessary I can attempt to implement other types of code into my python application if it means getting the job finally done! I guess it would also be useful to mention that this application is primarily used on Windows XP Professional and most Windows Server versions so I am not worried if any possible solution will not be compatible with earlier Windows OS version(s).</p> <p>Any assistance, code or just some simple help with getting familiar with this topic, would be <em>GREATLY</em> appreciated!</p> <p>Thanks in advance for any help you can provide!! :D</p>
1
2009-04-22T01:19:40Z
775,410
<p>Well REG_BINARY isn't any particular format, it's just a way to tell the registry the data is a custom binary format. So you're right about needing to find out what's in there.</p> <p>Also, what do you mean by converting the data from hex? Are you unpacking it? I doubt you're interpreting it correctly until you know what has been saved in there in the first place.</p> <p>Once you find out what's in that registry field, python's struct module will be your best friend.</p> <p><a href="http://docs.python.org/library/struct.html" rel="nofollow">http://docs.python.org/library/struct.html</a></p> <p>Further reading (you've probably already seen these)</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms687317" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms687317</a>(VS.85).aspx &lt;--windows info on perms</li> <li><a href="http://docs.python.org/library/_winreg.html" rel="nofollow">http://docs.python.org/library/_winreg.html</a> &lt;-- python registry access</li> </ul>
0
2009-04-22T01:39:33Z
[ "python", "binary", "wmi", "registry", "decode" ]
how can I decode the REG_BINARY value HKLM\Software\Microsoft\Ole\DefaultLaunchPermission to see which users have permission?
775,365
<p>I am trying to find a way to decode the REG_BINARY value for "<strong>HKLM\Software\Microsoft\Ole\DefaultLaunchPermission</strong>" to see which users have permissions by default, and if possible, a method in which I can also append other users by their username. </p> <p>At work we make use of DCOM and for the most part we always give the same users permission but in some cases we are forced to accommodate our clients and add custom users/groups to suit their needs. Unfortunately the custom users we need to add are random usernames so I am unable to just add all the users and copy the value from the key like I have done with the default users we use 95% of the time.</p> <p>I am currently working on a command-line executable application where I have a command to set permissions for pre-defined users but I would also like to be able to add an option to append a custom user(s) to add to the default permission along with our predefined default users list.</p> <p>Currently, to set the default users list with my application I would just type:</p> <p><strong>MyTool.exe Policies</strong></p> <p>But I would like to be able to make it a bit more verbose, closer to how NET command is used for windows users, something like:</p> <p><strong>MyTool.exe Policies /ADD:"MyCustomUsername"</strong></p> <p>The problem is that the data stored in the REG_BINARY value doesn't seem to be easily decoded. I was able to decode the hex portion in python but I am left with some sort of binary data which I don't have a clue what to do with as I don't even know what kind of encoding was used in the first place to know what to use to decode it. :P</p> <p>I have done quite a bit of googling but I think my lack of understanding the terminology around this topic has probably caused me to overlook the answer without recognizing it for what it is.</p> <p>I guess my first real question would have to be what kind of encoding is used for the above key after it has been decoded from hex? </p> <p>Or better yet, is it even possible to obtain/modify the key's value programmatically so that I can obtain a list of the users that are currently set, and if necessary, append additional users/groups?</p> <p>I would prefer to keep this application written strictly in Python if possible (or WMI/WMIC), but if necessary I can attempt to implement other types of code into my python application if it means getting the job finally done! I guess it would also be useful to mention that this application is primarily used on Windows XP Professional and most Windows Server versions so I am not worried if any possible solution will not be compatible with earlier Windows OS version(s).</p> <p>Any assistance, code or just some simple help with getting familiar with this topic, would be <em>GREATLY</em> appreciated!</p> <p>Thanks in advance for any help you can provide!! :D</p>
1
2009-04-22T01:19:40Z
775,461
<p>We came across similar issues when installing a COM server that was hosted by our .NET service, i.e. we wanted to programmatically alter the the COM ACLs in our install logic. I think you'll find that it's just a binary ACL format that you can manipulate in .NET using the class:</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.commonsecuritydescriptor.aspx" rel="nofollow">System.Security.AccessControl.CommonSecurityDescriptor</a></p> <p>So sorry I can't help you in getting a Python solution, but if your back is to the wall and you can manage .NET, some sample code would look like:</p> <pre><code>int launchMask = (int) (COM_RIGHTS.EXECUTE | COM_RIGHTS.EXECUTE_LOCAL | COM_RIGHTS.ACTIVATE_LOCAL); SecurityIdentifier sidAdmins = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); SecurityIdentifier sidInteractive = new SecurityIdentifier(WellKnownSidType.InteractiveSid, null); DiscretionaryAcl launchAcl = new DiscretionaryAcl(false, false, 3); launchAcl.AddAccess(AccessControlType.Allow, sidAdmins, launchMask, InheritanceFlags.None, PropagationFlags.None); launchAcl.AddAccess(AccessControlType.Allow, sidInteractive, launchMask, InheritanceFlags.None, PropagationFlags.None); CommonSecurityDescriptor launchSD = new CommonSecurityDescriptor(false, false, ControlFlags.DiscretionaryAclPresent | ControlFlags.SelfRelative, sidAdmins, sidAdmins, null, launchAcl); byte[] launchPermission = new byte[launchSD.BinaryLength]; launchSD.GetBinaryForm(launchPermission, 0); </code></pre> <p>You then take the launch permission byte array and write it to the registry. If .NET is a non-starter you can at least have a look at how the .NET classes work and see what win32 functions they use. You can either use the <a href="http://www.red-gate.com/products/reflector/" rel="nofollow">reflector</a> tool to look at the relevant assembly, or MSFT actually <a href="http://weblogs.asp.net/scottgu/archive/2008/01/16/net-framework-library-source-code-now-available.aspx" rel="nofollow">publish the .NET source</a>.</p>
2
2009-04-22T02:04:35Z
[ "python", "binary", "wmi", "registry", "decode" ]
How to catch POST using WSGIREF
775,396
<p>I am trying to catch POST data from a simple form.</p> <p>This is the first time I am playing around with WSGIREF and I can't seem to find the correct way to do this.</p> <pre><code>This is the form: &lt;form action="test" method="POST"&gt; &lt;input type="text" name="name"&gt; &lt;input type="submit"&gt;&lt;/form&gt; </code></pre> <p>And the function that is obviously missing the right information to catch post:</p> <pre><code>def app(environ, start_response): """starts the response for the webserver""" path = environ[ 'PATH_INFO'] method = environ['REQUEST_METHOD'] if method == 'POST': if path.startswith('/test'): start_response('200 OK',[('Content-type', 'text/html')]) return "POST info would go here %s" % post_info else: start_response('200 OK', [('Content-type', 'text/html')]) return form() </code></pre>
0
2009-04-22T01:34:39Z
775,698
<p>You should be reading responses from the server.</p> <p>From <a href="http://stackoverflow.com/questions/394465/python-post-data-using-modwsgi">nosklo's answer</a> to a similar problem: "<a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">PEP 333</a> says <a href="http://www.python.org/dev/peps/pep-0333/#input-and-error-streams" rel="nofollow">you must read environ['wsgi.input']</a>."</p> <p>Tested code (adapted from <a href="http://stackoverflow.com/questions/336866/how-to-implement-a-minimal-server-for-ajax-in-python">this answer</a>): <br /> &nbsp;&nbsp;&nbsp;&nbsp;Caveat: This code is for demonstrative purposes only. <br /> &nbsp;&nbsp;&nbsp;&nbsp;Warning: Try to avoid hard-coding paths or filenames.</p> <pre><code>def app(environ, start_response): path = environ['PATH_INFO'] method = environ['REQUEST_METHOD'] if method == 'POST': if path.startswith('/test'): try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(request_body) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open('test.html').read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] </code></pre>
3
2009-04-22T04:37:13Z
[ "python", "wsgi", "wsgiref" ]
How do you transfer binary data with Python?
775,482
<p>I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.</p> <p>I'm going to use <a href="http://code.google.com/p/protobuf/" rel="nofollow">Google Protocol Buffers</a> to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the client will serialize the data, send it to the server, which will then deserialize the data.</p> <p>The problem is, I'm really not sure where to begin for sending binary data to the server. I was hoping it'd be something "simple" like an HTTP request, but I've been searching around Google for ways to transfer binary data and getting lost in the vast multitude of tutorials, guides and documentation. I can't even tell if I'm barking up the wrong tree by investigating HTTP transfers (I was hoping to use it, so I could knock it up a notch to HTTPS if security is necessary). I really don't want to have to go to the level of socket programming, though - I'd like to use the libraries available before turning to that. (I'd also prefer standard Python libraries, though if there's the perfect 3rd party library I'll live.)</p> <p>So, if anyone has a good starting point (or wants to explain a bit themselves) on how a good way to transfer binary data via Python, I'd be grateful. The server I'm running is currently running Apache with mod_python, by the way.</p>
3
2009-04-22T02:11:12Z
775,515
<p>Any time you're going to move binary data from one system to another there a couple of things to keep in mind.</p> <p>Different machines store the same information differently. This has implication both in memory and on the network. More info here (<a href="http://en.wikipedia.org/wiki/Endianness" rel="nofollow">http://en.wikipedia.org/wiki/Endianness</a>)</p> <p>Because you're using python you can cut yourself some slack here (assuming the client and server will both by in python) and just use cPickle to serialize your data. If you really want binary, you're going to have to get comfortable with python's struct module (<a href="http://docs.python.org/library/struct.html" rel="nofollow">http://docs.python.org/library/struct.html</a>). And learn how to pack/unpack your data.</p> <p>I would first start out with simple line-protocol servers until you get past the difficulty of network communication. If you've never done it before it can get confusing very fast. How to issue commands, how to pass data, how to re-sync on errors etc...</p> <p>If you already know the basics of client/server protocol design, then practice packing and unpacking binary structures on your disk first. I also refer to the RFCs of HTTP and FTP for cases like this.</p> <p>-------EDIT BASED ON COMMENT-------- Normally this sort of thing is done by sending the server a "header" that contains a checksum for the file as well as the size of the file in bytes. Note that I don't mean an HTTP header, you can customize it however you want. The chain of events needs to go something like this...</p> <pre><code>CLIENT: "UPLOAD acbd18db4cc2f85cedef654fccc4a4d8 253521" SERVER: "OK" (server splits the text line to get the command, checksum, and size) CLIENT: "010101101010101100010101010etc..." (up to 253521 bytes) (server reasembles all received data into a file, then checksums it to make sure it matches the original) SERVER: "YEP GOT IT" CLIENT: "COOL CYA" </code></pre> <p>This is overly simplified, but I hope you can see what I'm talking about here.</p>
4
2009-04-22T02:28:37Z
[ "python", "http", "file", "client-server", "protocol-buffers" ]
How do you transfer binary data with Python?
775,482
<p>I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.</p> <p>I'm going to use <a href="http://code.google.com/p/protobuf/" rel="nofollow">Google Protocol Buffers</a> to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the client will serialize the data, send it to the server, which will then deserialize the data.</p> <p>The problem is, I'm really not sure where to begin for sending binary data to the server. I was hoping it'd be something "simple" like an HTTP request, but I've been searching around Google for ways to transfer binary data and getting lost in the vast multitude of tutorials, guides and documentation. I can't even tell if I'm barking up the wrong tree by investigating HTTP transfers (I was hoping to use it, so I could knock it up a notch to HTTPS if security is necessary). I really don't want to have to go to the level of socket programming, though - I'd like to use the libraries available before turning to that. (I'd also prefer standard Python libraries, though if there's the perfect 3rd party library I'll live.)</p> <p>So, if anyone has a good starting point (or wants to explain a bit themselves) on how a good way to transfer binary data via Python, I'd be grateful. The server I'm running is currently running Apache with mod_python, by the way.</p>
3
2009-04-22T02:11:12Z
775,550
<p>I'm not sure I got your question right, but maybe you can take a look at the <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted project</a>.</p> <p>As you can see in the FAQ, "Twisted is a networking engine written in Python, supporting numerous protocols. It contains a web server, numerous chat clients, chat servers, mail servers, and more. Twisted is made up of a number of sub-projects which can be accessed individually[...]".</p> <p>The documentation is pretty good, and there are lots of examples on the internet. Hope it helps.</p>
3
2009-04-22T02:50:27Z
[ "python", "http", "file", "client-server", "protocol-buffers" ]
How do you transfer binary data with Python?
775,482
<p>I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.</p> <p>I'm going to use <a href="http://code.google.com/p/protobuf/" rel="nofollow">Google Protocol Buffers</a> to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the client will serialize the data, send it to the server, which will then deserialize the data.</p> <p>The problem is, I'm really not sure where to begin for sending binary data to the server. I was hoping it'd be something "simple" like an HTTP request, but I've been searching around Google for ways to transfer binary data and getting lost in the vast multitude of tutorials, guides and documentation. I can't even tell if I'm barking up the wrong tree by investigating HTTP transfers (I was hoping to use it, so I could knock it up a notch to HTTPS if security is necessary). I really don't want to have to go to the level of socket programming, though - I'd like to use the libraries available before turning to that. (I'd also prefer standard Python libraries, though if there's the perfect 3rd party library I'll live.)</p> <p>So, if anyone has a good starting point (or wants to explain a bit themselves) on how a good way to transfer binary data via Python, I'd be grateful. The server I'm running is currently running Apache with mod_python, by the way.</p>
3
2009-04-22T02:11:12Z
775,576
<p>I guess it depends on how tied you are to Google Protocol Buffers, but you might like to check out <a href="http://incubator.apache.org/thrift/" rel="nofollow"><strong>Thrift</strong></a>.</p> <blockquote> <p><strong>Thrift</strong> is a software framework for scalable cross-language services development. It combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, Smalltalk, and OCaml.</p> </blockquote> <p>There's a great example for getting started on their home page.</p>
1
2009-04-22T03:19:03Z
[ "python", "http", "file", "client-server", "protocol-buffers" ]
How do you transfer binary data with Python?
775,482
<p>I'm working on a client-server program for the first time, and I'm feeling woefully inadequate on where to begin for what I'm doing.</p> <p>I'm going to use <a href="http://code.google.com/p/protobuf/" rel="nofollow">Google Protocol Buffers</a> to transfer binary data between my client and my server. I'm going to be using the Python variant. The basic idea, as I understand, is that the client will serialize the data, send it to the server, which will then deserialize the data.</p> <p>The problem is, I'm really not sure where to begin for sending binary data to the server. I was hoping it'd be something "simple" like an HTTP request, but I've been searching around Google for ways to transfer binary data and getting lost in the vast multitude of tutorials, guides and documentation. I can't even tell if I'm barking up the wrong tree by investigating HTTP transfers (I was hoping to use it, so I could knock it up a notch to HTTPS if security is necessary). I really don't want to have to go to the level of socket programming, though - I'd like to use the libraries available before turning to that. (I'd also prefer standard Python libraries, though if there's the perfect 3rd party library I'll live.)</p> <p>So, if anyone has a good starting point (or wants to explain a bit themselves) on how a good way to transfer binary data via Python, I'd be grateful. The server I'm running is currently running Apache with mod_python, by the way.</p>
3
2009-04-22T02:11:12Z
775,585
<p>One quick question: why binary? Is the payload itself binary, or do you just prefer a binary format? If former, it's possible to use base64 encoding with JSON or XML too; it does use more space (~34%), and bit more processing overhead, but not necessarily enough to matter for many use cases.</p>
0
2009-04-22T03:24:39Z
[ "python", "http", "file", "client-server", "protocol-buffers" ]
Sorted collections: How do i get (extended) slices right?
775,490
<p>How can I resolve this?</p> <pre><code>&gt;&gt;&gt; class unslice: ... def __getitem__(self, item): print type(item), ":", item ... &gt;&gt;&gt; u = unslice() &gt;&gt;&gt; u[1,2] # using an extended slice &lt;type 'tuple'&gt; : (1, 2) &gt;&gt;&gt; t = (1, 2) &gt;&gt;&gt; u[t] # or passing a plain tuple &lt;type 'tuple'&gt; : (1, 2) </code></pre> <p>Rational: </p> <p>I'm currently overengineering a sorted associative collection with the ability to return ranges of items. It is quite likely that I will want to store tuples of small integers (or even more pathologically wierd values like Ellipsis) in the collection (as keys), and will need some kind of sane way of differentiating extended slices from plain keys</p> <p>In the one-dimensional case, it's sort of a non-issue. I can't think of any real reason I would want to collect values of type <code>slice</code>, especially since <code>xrange</code> values are functionally similar and more recognizable to pythonistas (in my judgement). All other extended slice constructs are tuples of <code>slice</code>, <code>Ellipsis</code> or plain-old python values</p> <p>No other type of extended slice seems to be in common use for any kind of collection except multidimensional arrays as in NumPy.</p> <p>I do need to support n-dimensional axes, similar to oct-trees or GiS indices. </p>
2
2009-04-22T02:14:31Z
775,559
<p>Since there is no way to differentiate between the calls u[x,y] and u[(x,y)], you should shift one of the two operations you are trying to define off to an actual method. You know, something named u.slice() or u.range() or u.getslice() or u.getrange() or something like that.</p> <p>Actually, when writing my <em>own</em> programs, I generally find that when I'm trying to overload a Python operation with two quite distinct semantics, it means that <strong>both</strong> of the things I am doing need to be turned into named methods! Because if the two are so similar in meaning that neither one has an obviously superior claim to getting to use the braces [] getitem shortcut, then probably my code will be more readable if <strong>both</strong> operations get real, readable, explicit method names.</p> <p>But, it's hard to say more since you haven't told us how on earth you've gotten into this mess. Why would you want to both store things under tuples <strong>and</strong> get ranges of things? One suspects you are doing something to complicated to begin with. :-)</p> <p>Oh, and other languages with this problem make you say a[1][2] to do multi-dimensional access to easily distinguish from a[1,2]. Just so you know there's another option.</p>
5
2009-04-22T03:01:14Z
[ "python" ]
Sorted collections: How do i get (extended) slices right?
775,490
<p>How can I resolve this?</p> <pre><code>&gt;&gt;&gt; class unslice: ... def __getitem__(self, item): print type(item), ":", item ... &gt;&gt;&gt; u = unslice() &gt;&gt;&gt; u[1,2] # using an extended slice &lt;type 'tuple'&gt; : (1, 2) &gt;&gt;&gt; t = (1, 2) &gt;&gt;&gt; u[t] # or passing a plain tuple &lt;type 'tuple'&gt; : (1, 2) </code></pre> <p>Rational: </p> <p>I'm currently overengineering a sorted associative collection with the ability to return ranges of items. It is quite likely that I will want to store tuples of small integers (or even more pathologically wierd values like Ellipsis) in the collection (as keys), and will need some kind of sane way of differentiating extended slices from plain keys</p> <p>In the one-dimensional case, it's sort of a non-issue. I can't think of any real reason I would want to collect values of type <code>slice</code>, especially since <code>xrange</code> values are functionally similar and more recognizable to pythonistas (in my judgement). All other extended slice constructs are tuples of <code>slice</code>, <code>Ellipsis</code> or plain-old python values</p> <p>No other type of extended slice seems to be in common use for any kind of collection except multidimensional arrays as in NumPy.</p> <p>I do need to support n-dimensional axes, similar to oct-trees or GiS indices. </p>
2
2009-04-22T02:14:31Z
775,598
<p>From <a href="http://docs.python.org/reference/expressions.html#index-917" rel="nofollow">the docs</a>:</p> <blockquote> <p>There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the slice list contains no proper slice nor ellipses). Similarly, when the slice list has exactly one short slice and no trailing comma, the interpretation as a simple slicing takes priority over that as an extended slicing.</p> </blockquote> <p>As such, I don't think it's possible to distinguish <code>u[1,2]</code>-as-extended-slice from <code>u[1,2]</code>-as-tuple-key.</p>
0
2009-04-22T03:30:54Z
[ "python" ]
Sorted collections: How do i get (extended) slices right?
775,490
<p>How can I resolve this?</p> <pre><code>&gt;&gt;&gt; class unslice: ... def __getitem__(self, item): print type(item), ":", item ... &gt;&gt;&gt; u = unslice() &gt;&gt;&gt; u[1,2] # using an extended slice &lt;type 'tuple'&gt; : (1, 2) &gt;&gt;&gt; t = (1, 2) &gt;&gt;&gt; u[t] # or passing a plain tuple &lt;type 'tuple'&gt; : (1, 2) </code></pre> <p>Rational: </p> <p>I'm currently overengineering a sorted associative collection with the ability to return ranges of items. It is quite likely that I will want to store tuples of small integers (or even more pathologically wierd values like Ellipsis) in the collection (as keys), and will need some kind of sane way of differentiating extended slices from plain keys</p> <p>In the one-dimensional case, it's sort of a non-issue. I can't think of any real reason I would want to collect values of type <code>slice</code>, especially since <code>xrange</code> values are functionally similar and more recognizable to pythonistas (in my judgement). All other extended slice constructs are tuples of <code>slice</code>, <code>Ellipsis</code> or plain-old python values</p> <p>No other type of extended slice seems to be in common use for any kind of collection except multidimensional arrays as in NumPy.</p> <p>I do need to support n-dimensional axes, similar to oct-trees or GiS indices. </p>
2
2009-04-22T02:14:31Z
775,607
<p>My current thinking about this is to simply let the types that normally associate with slices be uncollectable. I can't think of any sane reason why anyone would want to do anything with a <code>slice</code> value or <code>Ellipsis</code> except to use them in subscript expressions. </p> <p>On the off chance a user of the collection wants to sort on a tuple (instead of numbers or strings or dates or any other obvious thing) It might make sense to just require some extra cruft. As the example...</p> <pre><code>&gt;&gt;&gt; u[t] &lt;type 'tuple'&gt; : (1, 2) &gt;&gt;&gt; u[t,] &lt;type 'tuple'&gt; : ((1, 2),) </code></pre> <p>Haven't really tried it with actual code (don't actually have a working GiS index at this time) but i suspect that this might just automatically do the right thing, since the extended slice is a tuple of length one (one dimension), which happens to be a tuple.</p>
0
2009-04-22T03:40:00Z
[ "python" ]
drawing a pixbuf onto a drawing area using pygtk and glade
775,528
<p>i'm trying to make a GTK application in python where I can just draw a loaded image onto the screen where I click on it. The way I am trying to do this is by loading the image into a pixbuf file, and then drawing that pixbuf onto a drawing area.</p> <p>the main line of code is here:</p> <pre><code>def drawing_refresh(self, widget, event): #clear the screen widget.window.draw_rectangle(widget.get_style().white_gc, True, 0, 0, 400, 400) for n in self.nodes: widget.window.draw_pixbuf(widget.get_style().fg_gc[gtk.STATE_NORMAL], self.node_image, 0, 0, 0, 0) </code></pre> <p>This should just draw the pixbuf onto the image in the top left corner, but nothing shows but the white image. I have tested that the pixbuf loads by putting it into a gtk image. What am I doing wrong here?</p>
1
2009-04-22T02:34:43Z
776,067
<p>I found out I just need to get the function to call another expose event with <code>widget.queue_draw()</code> at the end of the function. The function was only being called once at the start, and there were no nodes available at this point so nothing was being drawn.</p>
2
2009-04-22T07:46:15Z
[ "python", "drawing", "pygtk", "glade" ]
drawing a pixbuf onto a drawing area using pygtk and glade
775,528
<p>i'm trying to make a GTK application in python where I can just draw a loaded image onto the screen where I click on it. The way I am trying to do this is by loading the image into a pixbuf file, and then drawing that pixbuf onto a drawing area.</p> <p>the main line of code is here:</p> <pre><code>def drawing_refresh(self, widget, event): #clear the screen widget.window.draw_rectangle(widget.get_style().white_gc, True, 0, 0, 400, 400) for n in self.nodes: widget.window.draw_pixbuf(widget.get_style().fg_gc[gtk.STATE_NORMAL], self.node_image, 0, 0, 0, 0) </code></pre> <p>This should just draw the pixbuf onto the image in the top left corner, but nothing shows but the white image. I have tested that the pixbuf loads by putting it into a gtk image. What am I doing wrong here?</p>
1
2009-04-22T02:34:43Z
900,800
<p>You can make use of cairo to do this. First, create a gtk.DrawingArea based class, and connect the expose-event to your expose func.</p> <pre><code>class draw(gtk.gdk.DrawingArea): def __init__(self): self.connect('expose-event', self._do_expose) self.pixbuf = self.gen_pixbuf_from_file(PATH_TO_THE_FILE) def _do_expose(self, widget, event): cr = self.window.cairo_create() cr.set_operator(cairo.OPERATOR_SOURCE) cr.set_source_rgb(1,1,1) cr.paint() cr.set_source_pixbuf(self.pixbuf, 0, 0) cr.paint() </code></pre> <p>This will draw the image every time the expose-event is emited.</p>
1
2009-05-23T03:41:31Z
[ "python", "drawing", "pygtk", "glade" ]
Python bindings for libparted?
775,580
<p>I'm looking for a way to interact with the GNU <code>libparted</code> library from Python, but so far what I've found, a <a href="http://code.google.com/soc" rel="nofollow">GSOC</a> <a href="http://pylibparted.tigris.org" rel="nofollow">project from 2005</a> and an <a href="https://edge.launchpad.net/ubuntu/+source/python-parted" rel="nofollow">Ubuntu/debian package</a> that's been <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=379034" rel="nofollow">dropped from the archive</a>, have been disheartening. </p> <p>Is there something I'm missing, or should I just get used to manipulating <code>libparted</code> from the command line / trying to fix the bitrot that's occurred in the other packages?</p>
2
2009-04-22T03:21:06Z
775,639
<p>The reason debian dropped the package is lack of a maintainer. If you are willing (and able) to maintain the existing package and become their maintainer that would be a great contribution to FOSS.</p>
2
2009-04-22T04:06:01Z
[ "python" ]
Python bindings for libparted?
775,580
<p>I'm looking for a way to interact with the GNU <code>libparted</code> library from Python, but so far what I've found, a <a href="http://code.google.com/soc" rel="nofollow">GSOC</a> <a href="http://pylibparted.tigris.org" rel="nofollow">project from 2005</a> and an <a href="https://edge.launchpad.net/ubuntu/+source/python-parted" rel="nofollow">Ubuntu/debian package</a> that's been <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=379034" rel="nofollow">dropped from the archive</a>, have been disheartening. </p> <p>Is there something I'm missing, or should I just get used to manipulating <code>libparted</code> from the command line / trying to fix the bitrot that's occurred in the other packages?</p>
2
2009-04-22T03:21:06Z
775,764
<p>You can try using <a href="http://www.riverbankcomputing.co.uk/software/sip/intro" rel="nofollow">SIP</a> to generate a Python binding for it. It works for QT so it may work for libparted.</p>
1
2009-04-22T05:03:14Z
[ "python" ]
Python bindings for libparted?
775,580
<p>I'm looking for a way to interact with the GNU <code>libparted</code> library from Python, but so far what I've found, a <a href="http://code.google.com/soc" rel="nofollow">GSOC</a> <a href="http://pylibparted.tigris.org" rel="nofollow">project from 2005</a> and an <a href="https://edge.launchpad.net/ubuntu/+source/python-parted" rel="nofollow">Ubuntu/debian package</a> that's been <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=379034" rel="nofollow">dropped from the archive</a>, have been disheartening. </p> <p>Is there something I'm missing, or should I just get used to manipulating <code>libparted</code> from the command line / trying to fix the bitrot that's occurred in the other packages?</p>
2
2009-04-22T03:21:06Z
775,903
<p>You mean like the <a href="https://github.com/rhinstaller/pyparted" rel="nofollow">pyparted</a> library?</p>
3
2009-04-22T06:13:13Z
[ "python" ]
Python bindings for libparted?
775,580
<p>I'm looking for a way to interact with the GNU <code>libparted</code> library from Python, but so far what I've found, a <a href="http://code.google.com/soc" rel="nofollow">GSOC</a> <a href="http://pylibparted.tigris.org" rel="nofollow">project from 2005</a> and an <a href="https://edge.launchpad.net/ubuntu/+source/python-parted" rel="nofollow">Ubuntu/debian package</a> that's been <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=379034" rel="nofollow">dropped from the archive</a>, have been disheartening. </p> <p>Is there something I'm missing, or should I just get used to manipulating <code>libparted</code> from the command line / trying to fix the bitrot that's occurred in the other packages?</p>
2
2009-04-22T03:21:06Z
10,078,403
<p>Old thread, but you can also checkout <a href="http://pypi.python.org/pypi/reparted/" rel="nofollow">reparted</a>, it's a ctypes python binding.</p>
0
2012-04-09T19:11:17Z
[ "python" ]
Filetype information
775,674
<p>I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).</p> <p>I've heard about python-magic, but I'm really looking for <em>the</em> solution that will allow me to find this information, without requiring the installation of additional packages.</p> <p>Am I stuck to maintaining a list of file extensions, or does python have something in the standard library? I was not able to find it in the docs.</p>
0
2009-04-22T04:28:18Z
775,786
<p>The standard library has support for <a href="http://docs.python.org/library/mimetypes.html#module-mimetypes" rel="nofollow">mapping filenames to mimetypes</a>.</p> <p>Your question also sounds like you are interested in other information besides mimetype. The <a href="http://docs.python.org/library/stat.html" rel="nofollow">stat</a> module will also give you information about size, owner, time of last modification, etc. but otherwise the most common filesystems (Windows NTFS/FAT, Linux Ext 2/3, Mac OS X) do not store any metadata or "other information" about files. That's why we need to use extensions to find the mimetype for example.</p>
1
2009-04-22T05:14:27Z
[ "python" ]
Filetype information
775,674
<p>I'm in the process of writing a python script, and I want to find out information about a file, such as for example a mime-type (or any useful depiction of what a file contains).</p> <p>I've heard about python-magic, but I'm really looking for <em>the</em> solution that will allow me to find this information, without requiring the installation of additional packages.</p> <p>Am I stuck to maintaining a list of file extensions, or does python have something in the standard library? I was not able to find it in the docs.</p>
0
2009-04-22T04:28:18Z
775,792
<p>I am not sure if you want to infer something from file content but if you want to know mime type from file extension mimetypes module will be sufficient</p> <pre><code>&gt;&gt;&gt; import mimetypes &gt;&gt;&gt; mimetypes.init() &gt;&gt;&gt; mimetypes.knownfiles ['/etc/mime.types', '/etc/httpd/mime.types', ... ] &gt;&gt;&gt; mimetypes.suffix_map['.tgz'] '.tar.gz' &gt;&gt;&gt; mimetypes.encodings_map['.gz'] 'gzip' &gt;&gt;&gt; mimetypes.types_map['.tgz'] 'application/x-tar-gz' </code></pre> <p><a href="http://docs.python.org/library/mimetypes.html">http://docs.python.org/library/mimetypes.html</a></p>
5
2009-04-22T05:18:46Z
[ "python" ]
access eggs in python?
775,880
<p>Is there any way to call an installed python egg from python code? I need to cal a sphinx documentation generator from within a python code, and currently i'm doing it like this:</p> <p><code>os.system( "sphinx-build.exe -b html c:\\src c:\\dst" )</code></p> <p>This works, but requires some additional configuration: 'scripts' folder inside a python installation folder need to be added to a system PATH ( i'm on Windows ). Is it any better, native way to call an installed python egg?</p>
0
2009-04-22T05:55:19Z
775,908
<p>Adding the egg to PYTHONPATH or to sys.path will allow you to access the modules and packages within.</p>
1
2009-04-22T06:16:02Z
[ "python", "egg" ]
access eggs in python?
775,880
<p>Is there any way to call an installed python egg from python code? I need to cal a sphinx documentation generator from within a python code, and currently i'm doing it like this:</p> <p><code>os.system( "sphinx-build.exe -b html c:\\src c:\\dst" )</code></p> <p>This works, but requires some additional configuration: 'scripts' folder inside a python installation folder need to be added to a system PATH ( i'm on Windows ). Is it any better, native way to call an installed python egg?</p>
0
2009-04-22T05:55:19Z
776,425
<p>So basically, you want to use Sphinx as a library?</p> <p>Here is what <code>sphinx-build</code> does:</p> <pre><code>from pkg_resources import load_entry_point load_entry_point('Sphinx==0.5.1', 'console_scripts', 'sphinx-build')() </code></pre> <p>Looking at <code>entry-points.txt</code> in the EGG-INFO directory, notice that the sphinx-build entry point is the <code>sphinx.main</code> function (located in <code>__init__.py</code>).</p> <p>Have a look at that and duplicate what it does, and you can use sphinx as a library. I have not looked at the code in detail, but it seems that the bulk of the <code>sphinx-build</code>-command is done by the <code>build</code> method on a <code>Sphinx</code> object.</p> <p>In your code, you would have to do something like:</p> <pre><code>from sphinx.application import Sphinx s = Sphinx(...) s.build(...) </code></pre> <p>You need to have a look at the Sphinx source code to figure out the parameters to <code>Sphinx.__init__()</code> and <code>Sphinx.build()</code></p>
2
2009-04-22T09:47:06Z
[ "python", "egg" ]
What is "generator object" in django?
776,060
<p>Am using Django voting package and when i use the method get_top() in the shell, it returns something like <strong>"generator object at 0x022f7AD0</strong>, i've never seen anything like this before, how do you access it and what is it?</p> <p>my code:</p> <pre><code>v=Vote.objects.get_top(myModel, limit=10, reversed=False) print v &lt;generator object at 0x022f7AD0&gt; </code></pre> <p>NB: I thought <strong>get_top</strong> will just return a nice list of myModel, which i can do something like <strong>v.name</strong> etc</p>
4
2009-04-22T07:41:35Z
776,089
<p>If you want a list, just call list() on your generator object.</p> <p>A generator object in python is something like a lazy list. The elements are only evaluated as soon as you iterate over them. (Thus calling list on it evaluates all of them.)</p> <p>For example you can do:</p> <pre><code>&gt;&gt;&gt; def f(x): ... print "yay!" ... return 2 * x &gt;&gt;&gt; g = (f(i) for i in xrange(3)) # generator comprehension syntax &gt;&gt;&gt; g &lt;generator object &lt;genexpr&gt; at 0x37b6c0&gt; &gt;&gt;&gt; for j in g: print j ... yay! 0 yay! 2 yay! 4 </code></pre> <p>See how f is evaluated only as you iterate over it. You can find excellent material on the topic here: <a href="http://www.dabeaz.com/generators/" rel="nofollow">http://www.dabeaz.com/generators/</a></p>
19
2009-04-22T07:55:01Z
[ "python", "generator" ]
What is "generator object" in django?
776,060
<p>Am using Django voting package and when i use the method get_top() in the shell, it returns something like <strong>"generator object at 0x022f7AD0</strong>, i've never seen anything like this before, how do you access it and what is it?</p> <p>my code:</p> <pre><code>v=Vote.objects.get_top(myModel, limit=10, reversed=False) print v &lt;generator object at 0x022f7AD0&gt; </code></pre> <p>NB: I thought <strong>get_top</strong> will just return a nice list of myModel, which i can do something like <strong>v.name</strong> etc</p>
4
2009-04-22T07:41:35Z
776,139
<p>Hmmmm </p> <p>I've read <a href="http://www.dalkescientific.com/writings/NBN/generators.html" rel="nofollow">this</a> and <a href="http://www.neotitans.com/resources/python/python-generators-tutorial.html" rel="nofollow">this</a> and things are quiet clear now;</p> <p>Actually i can convert generators to list by just doing </p> <pre><code>mylist=list(myGenerator) </code></pre>
1
2009-04-22T08:10:28Z
[ "python", "generator" ]
What is "generator object" in django?
776,060
<p>Am using Django voting package and when i use the method get_top() in the shell, it returns something like <strong>"generator object at 0x022f7AD0</strong>, i've never seen anything like this before, how do you access it and what is it?</p> <p>my code:</p> <pre><code>v=Vote.objects.get_top(myModel, limit=10, reversed=False) print v &lt;generator object at 0x022f7AD0&gt; </code></pre> <p>NB: I thought <strong>get_top</strong> will just return a nice list of myModel, which i can do something like <strong>v.name</strong> etc</p>
4
2009-04-22T07:41:35Z
776,143
<p>A generator is a kind of iterator. An iterator is a kind of iterable object, and like any other iterable,</p> <p>You can iterate over every item using a for loop:</p> <pre><code>for vote in Vote.objects.get_top(myModel, limit=10, reversed=False): print v.name, vote </code></pre> <p>If you need to access items by index, you can convert it to a list:</p> <pre><code>top_votes = list(Vote.objects.get_top(myModel, limit=10, reversed=False)) print top_votes[0] </code></pre> <p>However, you can only iterate over a particular instance of an iterator once (unlike a more general iterable object, like a list):</p> <pre><code>&gt;&gt;&gt; top_votes_generator = Vote.objects.get_top(myModel, limit=3) &gt;&gt;&gt; top_votes_generator &lt;generator object at 0x022f7AD0&gt; &gt;&gt;&gt; list(top_votes_generator) [&lt;Vote: a&gt;, &lt;Vote: b&gt;, &lt;Vote: c&gt;] &gt;&gt;&gt; list(top_votes_generator) [] </code></pre> <p>For more on creating your own generators, see <a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">http://docs.python.org/tutorial/classes.html#generators</a></p>
7
2009-04-22T08:11:20Z
[ "python", "generator" ]
How to get the public channel URL from YouTubeVideoFeed object using the YouTube API?
776,110
<p>I'm using the Python version of the YouTube API to get a YouTubeVideoFeed object using the following URL:</p> <blockquote> <p><a href="http://gdata.youtube.com/feeds/api/users/USERNAME/uploads" rel="nofollow">http://gdata.youtube.com/feeds/api/users/USERNAME/uploads</a></p> </blockquote> <p><em>Note: I've replaced USERNAME with the account I need to follow.</em></p> <p>So far getting the feed, iterating the entries, getting player urls, titles and thumbnails has all been straightforward. But now I want to add a "Visit Channel" link to the page. I can't figure out how to get the "public" URL of a channel (in this case, the default channel from the user) out of the feed. From what I can tell, the only URLs stored directly in the feed point to the <code>http://gdata.youtube.com/</code>, <em>not</em> the public site.</p> <p>How can I link to a channel based on a feed?</p>
1
2009-04-22T08:01:09Z
776,200
<p>you might be confusing usernames... when I use my username I get my public page <a href="http://gdata.youtube.com/feeds/api/users/drdredel/uploads" rel="nofollow">http://gdata.youtube.com/feeds/api/users/drdredel/uploads</a> They have some wacky distinction between your gmail username and your youtube username. Or am I misunderstanding your question?</p>
0
2009-04-22T08:29:51Z
[ "python", "youtube", "feeds", "youtube-api" ]
How to get the public channel URL from YouTubeVideoFeed object using the YouTube API?
776,110
<p>I'm using the Python version of the YouTube API to get a YouTubeVideoFeed object using the following URL:</p> <blockquote> <p><a href="http://gdata.youtube.com/feeds/api/users/USERNAME/uploads" rel="nofollow">http://gdata.youtube.com/feeds/api/users/USERNAME/uploads</a></p> </blockquote> <p><em>Note: I've replaced USERNAME with the account I need to follow.</em></p> <p>So far getting the feed, iterating the entries, getting player urls, titles and thumbnails has all been straightforward. But now I want to add a "Visit Channel" link to the page. I can't figure out how to get the "public" URL of a channel (in this case, the default channel from the user) out of the feed. From what I can tell, the only URLs stored directly in the feed point to the <code>http://gdata.youtube.com/</code>, <em>not</em> the public site.</p> <p>How can I link to a channel based on a feed?</p>
1
2009-04-22T08:01:09Z
786,979
<p>Well, the youtube.com/user/USERNAME is a pretty safe bet if you want to construct the URL yourself, but I think what you want is the link rel='alternate'</p> <p>You have to get the link array from the feed and iterate to find alternate, then grab the href</p> <p>something like:</p> <pre><code>client = gdata.youtube.service.YouTubeService() feed = client.GetYouTubeVideoFeed('http://gdata.youtube.com/feeds/api/users/username/uploads') for link in feed.link: if link.rel == 'alternate': print link.href </code></pre> <p>Output: </p> <p><a href="http://www.youtube.com/profile_videos?user=username" rel="nofollow">http://www.youtube.com/profile_videos?user=username</a></p> <p>The most correct thing would be to grab the 'alternate' link from the user profile feed, as technically the above URL goes to the uploaded videos, not the main channel page</p> <pre><code>feed = client.GetYouTubeUserEntry('http://gdata.youtube.com/feeds/api/users/username') for link in feed.link: if link.rel == 'alternate': print link.href </code></pre> <p>output: <a href="http://www.youtube.com/profile?user=username" rel="nofollow">http://www.youtube.com/profile?user=username</a></p>
1
2009-04-24T18:09:41Z
[ "python", "youtube", "feeds", "youtube-api" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
776,128
<p>If you're up for a bit of a conceptual challenge, I'd look into using twisted. </p> <p>Your case should be trivial to implement as a part of twisted. <a href="http://twistedmatrix.com/projects/core/documentation/howto/servers.html" rel="nofollow">http://twistedmatrix.com/projects/core/documentation/howto/servers.html</a></p>
2
2009-04-22T08:06:46Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
776,157
<p>You need some form of asynchronous socket IO. Have a look at <a href="http://squirl.nightmare.com/medusa/async%5Fsockets.html" rel="nofollow">this explanation</a>, which discusses the concept in low-level socket terms, and the related examples which are implemented in Python. That should point you in the right direction.</p>
4
2009-04-22T08:16:13Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
776,314
<p>For a really easy win implement you solution using SocketServer &amp; the SocketServer.ThreadingMixIn</p> <p>have a look a this echo server example it looks quite similar to what you're doing anyway: <a href="http://www.oreillynet.com/onlamp/blog/2007/12/pymotw_socketserver.html" rel="nofollow">http://www.oreillynet.com/onlamp/blog/2007/12/pymotw_socketserver.html</a></p>
2
2009-04-22T09:10:38Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
776,845
<p>Implemented in <a href="http://twistedmatrix.com/">twisted</a>:</p> <pre><code>from twisted.internet.protocol import Factory, Protocol from twisted.internet import reactor class SendContent(Protocol): def connectionMade(self): self.transport.write(self.factory.text) self.transport.loseConnection() class SendContentFactory(Factory): protocol = SendContent def __init__(self, text=None): if text is None: text = """Hello, how are you my friend? Feeling fine? Good!""" self.text = text reactor.listenTCP(50000, SendContentFactory()) reactor.run() </code></pre> <p>Testing:</p> <pre><code>$ telnet localhost 50000 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Hello, how are you my friend? Feeling fine? Good! Connection closed by foreign host. </code></pre> <p>Seriously, when it comes to asynchronous network, twisted is the way to go. It handles multiple connections in a single-thread single-process approach.</p>
16
2009-04-22T11:54:36Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
776,865
<p>If you want to do it in pure python (sans-twisted), you need to do some threading. If you havnt seen it before, check out: <a href="http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf" rel="nofollow">http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf</a></p> <p>around page 5/6 is an example that is <em>very</em> relevant ;)</p>
0
2009-04-22T12:00:17Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
777,734
<p>First, buy Comer's books on <a href="http://www.cs.purdue.edu/homes/dec/netbooks.html" rel="nofollow">TCP/IP programming</a>. </p> <p>In those books, Comer will provide several alternative algorithms for servers. There are two standard approaches.</p> <ul> <li><p>Thread-per-request.</p></li> <li><p>Process-per-request.</p></li> </ul> <p>You must pick one of these two and implement that.</p> <p>In thread-per, each telnet session is a separate thread in your overall application.</p> <p>In process-per, you fork each telnet session into a separate subprocess.</p> <p>You'll find that process-per-request is much, much easier to handle in Python, and it generally makes more efficient use of your system.</p> <p>Thread-per-request is fine for things that come and go quickly (like HTTP requests). Telnet has long-running sessions where the startup cost for a subprocess does not dominate performance.</p>
0
2009-04-22T15:10:49Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
2,397,206
<p>Late for the reply, but with the only answers being Twisted or threads (ouch), I wanted to add an answer for MiniBoa. </p> <p><a href="http://code.google.com/p/miniboa/" rel="nofollow">http://code.google.com/p/miniboa/</a></p> <p>Twisted is great, but it's a rather large beast that may not be the best introduction to single-threaded asynchronous Telnet programming. MiniBoa is a lightweight, asynchronous single-threaded Python Telnet implementation originally designed for muds, which suits the OP's question perfectly. </p>
3
2010-03-07T17:47:24Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
5,927,337
<p>Try MiniBoa server? It has exactly 0 dependencies, no twisted or other stuff needed. MiniBoa is a non-blocking async telnet server, single threaded, exactly what you need.</p> <p><a href="http://code.google.com/p/miniboa/" rel="nofollow">http://code.google.com/p/miniboa/</a></p>
1
2011-05-08T12:12:46Z
[ "python", "sockets", "telnet" ]
Multiple simultaneous network connections - Telnet server, Python
776,120
<p>I'm currently writing a telnet server in Python. It's a content server. People would connect to the server via telnet, and be presented with text-only content.</p> <p>My problem is that the server would obviously need to support more than one simultaneous connection. The current implementation I have now supports only one. </p> <p>This is the basic, proof-of-concept server I began with (while the program has changed greatly over time, the basic telnet framework hasn't):</p> <pre><code>import socket, os class Server: def __init__(self): self.host, self.port = 'localhost', 50000 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((self.host, self.port)) def send(self, msg): if type(msg) == str: self.conn.send(msg + end) elif type(msg) == list or tuple: self.conn.send('\n'.join(msg) + end) def recv(self): self.conn.recv(4096).strip() def exit(self): self.send('Disconnecting you...'); self.conn.close(); self.run() # closing a connection, opening a new one # main runtime def run(self): self.socket.listen(1) self.conn, self.addr = self.socket.accept() # there would be more activity here # i.e.: sending things to the connection we just made S = Server() S.run() </code></pre> <p>Thanks for your help. </p>
16
2009-04-22T08:03:44Z
18,166,699
<p>Use threading and then add the handler into a function. The thread will call every time a request i made:</p> <p>Look at this</p> <pre><code> import socket # Import socket module import pygame import thread import threading,sys s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.bind((host, port)) print ((host, port)) name = "" users = [] def connection_handler (c, addr): print "conn handle" a = c.recv (1024) if a == "c": b = c.recv (1024) if a == "o": c.send (str(users)) a = c.recv (1024) if a == "c": b = c.recv (1024) print a,b s.listen(6) # Now wait for client connection. while True: c, addr = s.accept() print 'Connect atempt from:', addr[0] username = c.recv(1024) print "2" if username == "END_SERVER_RUBBISH101": if addr[0] == "192.168.1.68": break users.append(username) thread.start_new_thread (connection_handler, (c, addr)) #New thread for connection print s.close() </code></pre>
1
2013-08-10T21:53:34Z
[ "python", "sockets", "telnet" ]
Appengine - Possible to get an entity using only key string without model name?
776,324
<p>I want to be able to have a view that will act upon a number of different types of objects</p> <p>all the view will get is the key string eg:</p> <p>agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww</p> <p>without knowing the model type, is it possible to retrieve the entity from just that key string?</p> <p>thanks</p>
3
2009-04-22T09:15:04Z
776,332
<p>If you design your models so they all use a common superclass it should be possible to retrieve your objects by using something like:</p> <pre><code>entity = CommonSuperclass.get('agpwb2xsdGhyZWFkchULEg9wb2xsY29yZV9hbnN3ZXIYAww') </code></pre>
1
2009-04-22T09:18:19Z
[ "python", "google-app-engine" ]