title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Event system in Python | 1,092,531 | <p>What event system for Python do you use? I'm already aware of <a href="http://pydispatcher.sourceforge.net/">pydispatcher</a>, but I was wondering what else can be found, or is commonly used?</p>
<p>I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution th... | 111 | 2009-07-07T14:00:51Z | 35,957,226 | <p>I made a variation of Longpoke's minimalistic approach that also ensures the signatures for both callees and callers:</p>
<pre><code>class EventHook(object):
'''
A simple implementation of the Observer-Pattern.
The user can specify an event signature upon inizializazion,
defined by kwargs in the for... | 1 | 2016-03-12T11:45:23Z | [
"python",
"events",
"event-handling",
"dispatcher"
] |
AppEngine server cannot import atom module | 1,092,648 | <p>I have gdata library install on my ArchLinux, and a simple application which imports atom library at the beginning, when I run gapp engine and access that web app,</p>
<blockquote>
<p>$ python2.5 ./dev_appserver.py ~/myapp</p>
</blockquote>
<p>It throws exception 'No module named atom'. But when I run 'import at... | 3 | 2009-07-07T14:26:49Z | 1,092,753 | <p>Add atom.py to the same directory you keep you GAE Python sources in, and make sure it's uploaded to the server when you upload your app. (The upload happens when you do <code>appcfg.py update myapp/</code> unless you go out of your way to stop it; use the <code>--verbose</code> flag on the command to see exactly wh... | 11 | 2009-07-07T14:43:09Z | [
"python",
"google-app-engine"
] |
how can I not distribute my secret key (facebook api) while using python? | 1,092,942 | <p>I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so:</p>
<pre><code>import facebook
fb = facebook.Facebook("my_api_key", "my_secret_key")
</code><... | 2 | 2009-07-07T15:15:29Z | 1,093,178 | <p>EDIT: cmb's session keys approach is better than the proxy described below. Config files and GAE are still applicable. /EDIT</p>
<p>You could take a couple approaches. If your code is open-source and will be used by other developers, you could allow the secret key to be set in a configuration file. When you distrib... | 1 | 2009-07-07T15:53:07Z | [
"python",
"facebook"
] |
how can I not distribute my secret key (facebook api) while using python? | 1,092,942 | <p>I'm writing a facebook desktop application for the first time using the PyFacebook api. Up until now, since I've been experimenting, I just passed the secret key along with the api key to the Facebook constructor like so:</p>
<pre><code>import facebook
fb = facebook.Facebook("my_api_key", "my_secret_key")
</code><... | 2 | 2009-07-07T15:15:29Z | 1,093,421 | <p>The <a href="http://wiki.developers.facebook.com/index.php/Desktop%5FApp%5FAuth%5FProcess" rel="nofollow">relevant page on the FB developer wiki</a> recommends a server component that just keeps your secret key and handles <code>auth.getSession()</code>, then gives your desktop app a session key. See that link for d... | 3 | 2009-07-07T16:38:49Z | [
"python",
"facebook"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 1,093,331 | <p>This information is available in the <a href="http://docs.python.org/2/library/sys.html#sys.version">sys.version</a> string in the <a href="http://docs.python.org/2/library/sys.html">sys</a> module:</p>
<pre><code>>>> import sys
</code></pre>
<p>Human readable:</p>
<pre><code>>>> print (sys.vers... | 636 | 2009-07-07T16:20:12Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 1,093,336 | <pre><code>import sys
sys.version.split(' ')[0]
</code></pre>
<p>sys.version gives you what you want, just pick the first number :)</p>
| -1 | 2009-07-07T16:20:59Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 3,016,171 | <p>Your best bet is probably something like so: </p>
<pre><code>>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
</code></pre>
<p>... | 46 | 2010-06-10T16:06:05Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 3,016,198 | <p>Put something like:</p>
<pre><code>#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
sys.stderr.write("You need python 2.6 or later to run this script\n")
exit(1)
</code></pre>
<p>at the top of your script.</p>
<p>Note that depending on what else is in your script, older versions of python than... | 40 | 2010-06-10T16:08:54Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 3,016,234 | <p>Like Seth said, the main script could check <code>sys.version_info</code> (but note that that didn't appear until 2.0, so if you want to support older versions you would need to check another version property of the sys module).</p>
<p>But you still need to take care of not using any Python language features in the... | 3 | 2010-06-10T16:12:50Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 3,018,075 | <p>I like <code>sys.hexversion</code> for stuff like this.</p>
<p><a href="http://docs.python.org/library/sys.html#sys.hexversion">http://docs.python.org/library/sys.html#sys.hexversion</a></p>
<pre><code>>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>... | 74 | 2010-06-10T20:08:35Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 7,730,858 | <p>To see a MSDOS script to check the version before running the Python interpreter (to avoid Python version syntax exceptions) See solution:</p>
<p><a href="http://stackoverflow.com/questions/446052/python-best-way-to-check-for-python-version-in-program-that-uses-new-language-fe/7642536#7642536">Python: Best way to c... | 0 | 2011-10-11T18:40:33Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 17,672,432 | <p>if you are working on linux just give command "python" output will be like this</p>
<p>**Python 2.4.3 (#1, Jun 11 2009, 14:09:37)</p>
<p>[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2</p>
<p>Type "help", "copyright", "credits" or "license" for more information.**</p>
| 1 | 2013-07-16T09:10:48Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 17,796,193 | <p>From the command line (note the capital 'V'):</p>
<pre><code>python -V
</code></pre>
<p>This is documented in 'man python'.</p>
| 125 | 2013-07-22T19:50:40Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 25,477,839 | <p>I found this method somewhere.</p>
<pre><code>>>> from platform import python_version
>>> print python_version()
2.7.8
</code></pre>
| 25 | 2014-08-25T01:11:33Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 25,631,445 | <p>Here's a short commandline version which exits straight away (handy for scripts and automated execution):</p>
<pre><code>python -c 'print __import__("sys").version'
</code></pre>
<p>Or just the major, minor and micro:</p>
<pre><code>python -c 'print __import__("sys").version_info[:1]' # (2,)
python -c 'print __im... | 9 | 2014-09-02T20:02:50Z | [
"python",
"version"
] |
How do I check what version of Python is running my script? | 1,093,322 | <p>How can I check what version of the Python Interpreter is interpreting my script?</p>
| 524 | 2009-07-07T16:17:49Z | 35,294,211 | <h1>The simplest way</h1>
<p>Just type python in your terminal and you can see the the version
as like following </p>
<pre><code>desktop:~$ python
Python 2.7.6 (default, Jun 22 2015, 18:00:18)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code></pre>
| 4 | 2016-02-09T14:11:24Z | [
"python",
"version"
] |
Run web.py as daemon | 1,093,485 | <p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p>
<p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_lin... | 4 | 2009-07-07T16:51:24Z | 1,093,519 | <p>I don't think you're telling the daemon to run. You need to instantiate a MyDaemon object and call o.run(). It looks like WebService only starts and stops the service interface to your web app, not the actual web app itself.</p>
| 0 | 2009-07-07T16:57:17Z | [
"python",
"backgroundworker"
] |
Run web.py as daemon | 1,093,485 | <p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p>
<p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_lin... | 4 | 2009-07-07T16:51:24Z | 1,094,810 | <p>I finally find the problem.</p>
<p>Web.py accept from command-line the optional port number:</p>
<pre><code>python code.py 80
</code></pre>
<p>And the script also take input from the command-line:</p>
<pre><code>python WebServer start
</code></pre>
<p>then web.py try to use "start" as port number and fail. I do... | 4 | 2009-07-07T20:54:41Z | [
"python",
"backgroundworker"
] |
Run web.py as daemon | 1,093,485 | <p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p>
<p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_lin... | 4 | 2009-07-07T16:51:24Z | 2,828,265 | <p>you can start the web.py by using this command</p>
<pre><code>/usr/bin/python index.py > log.txt 2>&1 &
</code></pre>
| 2 | 2010-05-13T15:57:11Z | [
"python",
"backgroundworker"
] |
Run web.py as daemon | 1,093,485 | <p>I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.</p>
<p>I try to put it as a background service with <a href="http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/" rel="nofollow">http://www.jejik.com/articles/2007/02/a_simple_unix_lin... | 4 | 2009-07-07T16:51:24Z | 7,941,807 | <p>Instead of overwrite the second argument like you wrote here:</p>
<pre><code>if __name__ == "__main__":
if DEBUG:
app.run()
else:
service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid'))
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
sys.arg... | 0 | 2011-10-29T21:23:00Z | [
"python",
"backgroundworker"
] |
Switching databases in TG2 during runtime | 1,093,589 | <p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p>
<p>I want to be able to switch between these databases according to user input. What is the most elegant way to do th... | 1 | 2009-07-07T17:14:52Z | 1,387,164 | <p>If ALL databases have the same schema then you should be able to create several Sessions using the same model to the different DBs.</p>
| 1 | 2009-09-07T00:56:50Z | [
"python",
"sqlite",
"turbogears",
"turbogears2"
] |
Switching databases in TG2 during runtime | 1,093,589 | <p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p>
<p>I want to be able to switch between these databases according to user input. What is the most elegant way to do th... | 1 | 2009-07-07T17:14:52Z | 1,403,620 | <p>Dzhelil,</p>
<p>I wrote a blog post a while back about using multiple databases in TG2. You could combine this method with Jorge's suggestion of multiple DBSessions and I think you could do this easily.</p>
<p><a href="http://blog.curiasolutions.com/?p=87" rel="nofollow">How to use multiple databases in TurboGears... | 1 | 2009-09-10T06:13:53Z | [
"python",
"sqlite",
"turbogears",
"turbogears2"
] |
Switching databases in TG2 during runtime | 1,093,589 | <p>I am doing an application which will use multiple sqlite3 databases, prepopuldated with data from an external application. Each database will have the exact same tables, but with different data.</p>
<p>I want to be able to switch between these databases according to user input. What is the most elegant way to do th... | 1 | 2009-07-07T17:14:52Z | 1,422,838 | <p>I am using two databases for a read-only application. The second database is a cache in case the primary database is down. I use two objects to hold the connection, metadata and compatible <code>Table</code> instances. The top of the view function assigns <code>db = primary</code> or <code>db = secondary</code> and ... | 1 | 2009-09-14T17:13:56Z | [
"python",
"sqlite",
"turbogears",
"turbogears2"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 1,093,661 | <pre><code>from serial import *
from threading import Thread
last_received = ''
def receiving(ser):
global last_received
buffer = ''
while True:
# last_received = ser.readline()
buffer += ser.read(ser.inWaiting())
if '\n' in buffer:
last_received, buffer = buffer.split... | 9 | 2009-07-07T17:27:56Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 1,093,662 | <p>Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.</p>
<p>If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code i... | 25 | 2009-07-07T17:28:01Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 1,093,742 | <p>You will need a loop to read everything sent, with the last call to readline() blocking until the timeout. So:</p>
<pre><code>def readLastLine(ser):
last_data=''
while True:
data=ser.readline()
if data!='':
last_data=data
else:
return last_data
</code></pre>
| 2 | 2009-07-07T17:44:05Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 1,144,994 | <p>Slight modification to mtasic & Vinay Sajip's code:</p>
<p>While I found this code quite helpful to me for a similar application, I needed <em>all</em> the lines coming back from a serial device that would send information periodically.</p>
<p>I opted to pop the first element off the top, record it, and then r... | 2 | 2009-07-17T18:40:17Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 3,999,994 | <p>These solutions will hog the CPU while waiting for characters.</p>
<p>You should do at least one blocking call to read(1)</p>
<pre><code>while True:
if '\n' in buffer:
pass # skip if a line already in buffer
else:
buffer += ser.read(1) # this will block until one more char or timeout
... | 7 | 2010-10-22T18:53:23Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 6,300,263 | <p>Using <code>.inWaiting()</code> inside an infinite loop may be problematic. It may hog up the entire <a href="http://en.wikipedia.org/wiki/Central_processing_unit" rel="nofollow">CPU</a> depending on the implementation. Instead, I would recommend using a specific size of data to be read. So in this case the followin... | 2 | 2011-06-09T22:59:22Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 15,572,128 | <p>This method allows you to separately control the timeout for gathering all the data for each line, and a different timeout for waiting on additional lines.</p>
<pre><code># get the last line from serial port
lines = serial_com()
lines[-1]
def serial_com():
'''Serial communications: get a response... | 1 | 2013-03-22T13:56:34Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 23,021,208 | <p>You can use <code>ser.flushInput()</code> to flush out all serial data that is currently in the buffer.</p>
<p>After clearing out the old data, you can user ser.readline() to get the most recent data from the serial device.</p>
<p>I think its a bit simpler than the other proposed solutions on here. Worked for me, ... | 1 | 2014-04-11T19:35:53Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
pyserial - How to read the last line sent from a serial device | 1,093,598 | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do yo... | 14 | 2009-07-07T17:16:43Z | 26,742,494 | <p><strong>Too much complications</strong></p>
<p>What is the reason to split the bytes object by newline or by other array manipulations?
I write the simplest method, which will solve your problem:</p>
<pre><code>import serial
s = serial.Serial(31)
s.write(bytes("ATI\r\n", "utf-8"));
while True:
last = ''
fo... | 2 | 2014-11-04T18:35:33Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] |
Objective-C string manipulation | 1,093,805 | <p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p>
<p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p>
<p><strong>Obj... | 1 | 2009-07-07T17:54:32Z | 1,093,835 | <p>Have you seen the appendString method from the NSMutableString class?</p>
<p>appendFormat from the same class will let you do many concatenations with one statement if that is what you're really interested in.</p>
| 4 | 2009-07-07T17:59:54Z | [
"python",
"objective-c",
"ruby",
"string",
"objective-c++"
] |
Objective-C string manipulation | 1,093,805 | <p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p>
<p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p>
<p><strong>Obj... | 1 | 2009-07-07T17:54:32Z | 1,093,851 | <p>For fixed size concatenation, you can use <code>[NSString stringWithFormat:]</code> like:</p>
<pre><code>NSString *str = [NSString stringWithFormat:@"%@ %@ %@",
@"Hello", @"World", @"Yay!"];
</code></pre>
| 9 | 2009-07-07T18:02:19Z | [
"python",
"objective-c",
"ruby",
"string",
"objective-c++"
] |
Objective-C string manipulation | 1,093,805 | <p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p>
<p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p>
<p><strong>Obj... | 1 | 2009-07-07T17:54:32Z | 1,093,863 | <p>you can use join operation.</p>
<pre><code>NSArray *chunks = ... get an array, say by splitting it;
string = [chunks componentsJoinedByString: @" :-) "];
</code></pre>
<p>would produce something like
oop :-) ack :-) bork :-) greeble :-) ponies</p>
| 9 | 2009-07-07T18:04:24Z | [
"python",
"objective-c",
"ruby",
"string",
"objective-c++"
] |
Objective-C string manipulation | 1,093,805 | <p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p>
<p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p>
<p><strong>Obj... | 1 | 2009-07-07T17:54:32Z | 1,093,867 | <p>I would avoid mixing languages, particularly if you don't know Python or Ruby well. What you gain in readable code in your Objective-C you will loose have having to read multiple languages to understand your own code base. Seems like a maintainability nightmare to me.</p>
<p>I'd strongly suggest taking one of the... | 3 | 2009-07-07T18:06:33Z | [
"python",
"objective-c",
"ruby",
"string",
"objective-c++"
] |
Objective-C string manipulation | 1,093,805 | <p>Currently I am working on a piece of software, which is currently written 100% in Objective-C using the iPhone 3.0 SDK.</p>
<p>I have come to a cross roads where I need to do quite a bit or string concatenation, more specifically, NSString concatenation and so far I have been doing it like this:</p>
<p><strong>Obj... | 1 | 2009-07-07T17:54:32Z | 1,093,891 | <p>Dragging in C++ just for this seems quite heavy-handed. Using <code>stringWithFormat:</code> on NSString or <code>appendFormat:</code> with an NSMutableString, as others have suggested, is much more natural and not particularly hard to read. Also, in order to use the strings with Cocoa, you'll have to add extra code... | 2 | 2009-07-07T18:11:26Z | [
"python",
"objective-c",
"ruby",
"string",
"objective-c++"
] |
Python Error | 1,093,884 | <p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options... | 0 | 2009-07-07T18:10:21Z | 1,093,902 | <p>The error is here:</p>
<pre><code>open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
</code></pre>
<p>You have three parameters, but only two %s in the string. You probably meant to say:</p>
<pre><code>open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr')
</code></pre>
<p>Although 'wr' is ... | 2 | 2009-07-07T18:14:10Z | [
"python",
"typeerror"
] |
Python Error | 1,093,884 | <p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options... | 0 | 2009-07-07T18:10:21Z | 1,093,905 | <p>Your tuple is misshaped</p>
<pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
</code></pre>
<p>Should be</p>
<pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr')
</code></pre>
| 3 | 2009-07-07T18:14:12Z | [
"python",
"typeerror"
] |
Python Error | 1,093,884 | <p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options... | 0 | 2009-07-07T18:10:21Z | 1,093,911 | <pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername), 'wr'))
</code></pre>
<p>You are passing three arguments (config['vsftp']['user_dir'], (vusername), 'wr') to a format string expecting two: "%s/%s". So the error is telling you that there is an argument to the format string that is not being used.... | 0 | 2009-07-07T18:15:32Z | [
"python",
"typeerror"
] |
Python Error | 1,093,884 | <p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options... | 0 | 2009-07-07T18:10:21Z | 1,093,917 | <p>I think you have a wrong parenthesis, your line should be:</p>
<pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], (vusername)), 'wr')
</code></pre>
| 0 | 2009-07-07T18:16:12Z | [
"python",
"typeerror"
] |
Python Error | 1,093,884 | <p>First python script and I'm getting an error I can't seem to get around using a config file. The first part of the script takes user input and puts that into a mysql database with no problem..Then I get to the filesystem work and things go a bit pear shaped..I can get it to work without using the config file options... | 0 | 2009-07-07T18:10:21Z | 1,093,931 | <p>It looks like this line should be:</p>
<pre><code>f = open("%s/%s" % (config['vsftp']['user_dir'], vusername), 'wr')
</code></pre>
<p>(I moved the closing parenthesis over.)</p>
| 0 | 2009-07-07T18:19:17Z | [
"python",
"typeerror"
] |
How to serve any file type with Python's BaseHTTPRequestHandler | 1,094,185 | <p>Consider the following example:</p>
<pre><code>import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith(".html"):
f = open(curdir + s... | 7 | 2009-07-07T19:06:36Z | 1,094,211 | <p>Your line would work just fine. The problem would be setting the <code>Content-type</code> appropriately. You'd want to set it to <code>application/zip</code> instead of <code>text/html</code>.</p>
| 4 | 2009-07-07T19:12:48Z | [
"python",
"httpserver"
] |
How to serve any file type with Python's BaseHTTPRequestHandler | 1,094,185 | <p>Consider the following example:</p>
<pre><code>import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith(".html"):
f = open(curdir + s... | 7 | 2009-07-07T19:06:36Z | 1,094,237 | <p>Pass binary as a parameter to open(). This:</p>
<pre><code>f = open(curdir + sep + self.path, 'rb')
</code></pre>
<p>Instead of this:</p>
<pre><code>f = open(curdir + sep + self.path)
</code></pre>
<p>UNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the "b" ... | 7 | 2009-07-07T19:18:14Z | [
"python",
"httpserver"
] |
How to serve any file type with Python's BaseHTTPRequestHandler | 1,094,185 | <p>Consider the following example:</p>
<pre><code>import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith(".html"):
f = open(curdir + s... | 7 | 2009-07-07T19:06:36Z | 6,798,443 | <p>If you want to share files in a folder of any type, then you can also try typing the command</p>
<pre><code>python -m SimpleHTTPServer
</code></pre>
<p>This will start the server at port 8000 and you can browse the files (via directory listing)</p>
| 5 | 2011-07-23T05:30:22Z | [
"python",
"httpserver"
] |
Elegant way to abstract multiple function calls? | 1,094,611 | <p>Example:</p>
<pre><code>>>> def write_to_terminal(fmt, *args):
... print fmt % args
>>> LOG = logging.getLogger(__name__)
>>> info = multicall(write_to_terminal, LOG.info)
>>> debug = multicall(write_debug_to_terminal, LOG.debug)
>>> ...
>>> info('Hello %s',... | 1 | 2009-07-07T20:16:01Z | 1,094,627 | <p>Something like this?</p>
<pre><code>def multicall(*functions):
def call_functions(*args, **kwds):
for function in functions:
function(*args, **kwds)
return call_functions
</code></pre>
<p>And if you want to aggregate the results:</p>
<pre><code>def multicall(*functions):
def call_f... | 5 | 2009-07-07T20:19:58Z | [
"python",
"function"
] |
Elegant way to abstract multiple function calls? | 1,094,611 | <p>Example:</p>
<pre><code>>>> def write_to_terminal(fmt, *args):
... print fmt % args
>>> LOG = logging.getLogger(__name__)
>>> info = multicall(write_to_terminal, LOG.info)
>>> debug = multicall(write_debug_to_terminal, LOG.debug)
>>> ...
>>> info('Hello %s',... | 1 | 2009-07-07T20:16:01Z | 1,094,644 | <p>You could look into Python decorators.</p>
<p>A clear description is here: <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=240808" rel="nofollow">http://www.artima.com/weblogs/viewpost.jsp?thread=240808</a></p>
| 1 | 2009-07-07T20:22:18Z | [
"python",
"function"
] |
Wavelet plot with Python libraries | 1,094,655 | <p>I know that SciPy has some signal processing tools for wavelets in scipy.signal.wavelets and a chart can be drawn using Matplotlib, but it seems I can't get it right. I have tried plotting a Daubechies wavelet against a linear space, but it's not what I am looking for. I am highly unskilled about wavelets and math i... | 6 | 2009-07-07T20:25:31Z | 1,118,619 | <p>With a recent trunk version of <a href="http://pybytes.com/pywavelets/">PyWavelets</a>, getting approximations of scaling function and wavelet function on x-grid is pretty straightforward:</p>
<pre><code>[phi, psi, x] = pywt.Wavelet('db2').wavefun(level=4)
</code></pre>
<p>Note that x-grid output is not available ... | 11 | 2009-07-13T10:03:00Z | [
"python",
"matplotlib",
"scipy",
"wavelet",
"pywt"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,721 | <p>How about this?</p>
<pre><code>>>> s = '23.45678'
>>> int(float(s))
23
</code></pre>
<p>Or...</p>
<pre><code>>>> int(Decimal(s))
23
</code></pre>
<p>Or...</p>
<pre><code>>>> int(s.split('.')[0])
23
</code></pre>
<p>I doubt it's going to get much simpler than that, I'm afraid... | 66 | 2009-07-07T20:36:52Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,741 | <p>You could use:</p>
<pre><code>s = '23.245678'
i = int(float(s))
</code></pre>
| 1 | 2009-07-07T20:40:58Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,745 | <p>What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:</p>
<pre><code>s = '234.67'
i = int(round(float(s)))
</code></pre>
<p>Otherwise, just do:</p>
<pre><code>s = '234.67'
i = int(float(s))
</code></pre>
| 12 | 2009-07-07T20:41:44Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,765 | <p>"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.</p>
<p>You want to round instead, probably (I hope that the numbers don't represent currency because then rounding... | 1 | 2009-07-07T20:45:05Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,775 | <pre><code>>>> s = '23.45678'
>>> int(float(s))
23
>>> int(round(float(s)))
23
>>> s = '23.54678'
>>> int(float(s))
23
>>> int(round(float(s)))
24
</code></pre>
<p>You don't specify if you want rounding or not...</p>
| 2 | 2009-07-07T20:47:25Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,776 | <pre><code>round(float("123.789"))
</code></pre>
<p>will give you an integer value, but a float type. With Python's duck typing, however, the actual type is usually not very relevant. This will also round the value, which you might not want. Replace 'round' with 'int' and you'll have it just truncated and an actual in... | 0 | 2009-07-07T20:47:26Z | [
"python",
"string",
"integer",
"decimal"
] |
Convert a string to integer with decimal in Python | 1,094,717 | <p>I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.</p>
<p>Direct conversion fails:</p>
<pre><code>>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int(... | 33 | 2009-07-07T20:35:48Z | 1,094,781 | <p>The expression <code>int(float(s))</code> mentioned by others is the best if you want to truncate the value. If you want rounding, using <code>int(round(float(s))</code> if the round algorithm matches what you want (see the <a href="http://docs.python.org/library/functions.html?highlight=round#round" rel="nofollow">... | 1 | 2009-07-07T20:48:21Z | [
"python",
"string",
"integer",
"decimal"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 1,094,845 | <p>One such library is <a href="http://pypi.python.org/pypi/hurry.filesize">hurry.filesize</a>.</p>
<pre><code>>>> from hurry.filesize import alternative
>>> size(1, system=alternative)
'1 byte'
>>> size(10, system=alternative)
'10 bytes'
>>> size(1024, system=alternative)
'1 KB'
</... | 7 | 2009-07-07T21:00:25Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 1,094,933 | <p>Addressing the above "too small a task to require a library" issue by a straightforward implementation:</p>
<pre><code>def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0... | 290 | 2009-07-07T21:15:41Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 1,095,051 | <p>DiveIntoPython3 also <a href="http://getpython3.com/diveintopython3/your-first-python-program.html#divingin" rel="nofollow">talks</a> about this function.</p>
| 2 | 2009-07-07T21:44:26Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 2,181,538 | <pre><code>def human_readable_data_quantity(quantity, multiple=1024):
if quantity == 0:
quantity = +0
SUFFIXES = ["B"] + [i + {1000: "B", 1024: "iB"}[multiple] for i in "KMGTPEZY"]
for suffix in SUFFIXES:
if quantity < multiple or suffix == SUFFIXES[-1]:
if suffix == SUFFIXES[... | 1 | 2010-02-02T02:29:43Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 6,547,474 | <p>Riffing on the snippet provided as an alternative to hurry.filesize(), here is a snippet that gives varying precision numbers based on the prefix used. It isn't as terse as some snippets, but I like the results.</p>
<pre><code>def human_size(size_bytes):
"""
format a size in bytes into a 'human' file size, ... | 6 | 2011-07-01T11:40:16Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 10,171,475 | <p>Here's my version. It does not use a for-loop. It has constant complexity, O(<em>1</em>), and is in theory more efficient than the answers here that use a for-loop.</p>
<pre class="lang-python prettyprint-override"><code>from math import log
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2... | 24 | 2012-04-16T09:16:44Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 10,194,541 | <p>Drawing from all the previous answers, here is my take on it. It's an object which will store the file size in bytes as an integer. But when you try to print the object, you automatically get a human readable version.</p>
<pre><code>class Filesize(object):
"""
Container for a size in bytes with a human read... | 3 | 2012-04-17T15:47:54Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 15,485,265 | <p>A library that has all the functionality that it seems you're looking for is <a href="https://pypi.python.org/pypi/humanize"><code>humanize</code></a>. <code>humanize.naturalsize()</code> seems to do everything you're looking for.</p>
| 37 | 2013-03-18T19:29:28Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 17,754,143 | <p>I like the fixed precision of <a href="http://stackoverflow.com/a/5414105/2595465">senderle's decimal version</a>, so here's a sort of hybrid of that with joctee's answer above (did you know you could take logs with non-integer bases?):</p>
<pre><code>from math import log
def human_readable_bytes(x):
# hybrid o... | 3 | 2013-07-19T19:36:16Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 23,773,174 | <p>Using either powers of 1000 or <a href="http://en.wikipedia.org/wiki/Kibibyte" rel="nofollow">kibibytes</a> would be more standard-friendly:</p>
<pre><code>def sizeof_fmt(num, use_kibibyte=True):
base, suffix = [(1000.,'B'),(1024.,'iB')][use_kibibyte]
for x in ['B'] + map(lambda x: x+suffix, list('kMGTP')):... | 5 | 2014-05-21T02:49:09Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 25,527,639 | <p>If you're using Django installed you can also try <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#filesizeformat">filesizeformat</a>:</p>
<pre><code>from django.template.defaultfilters import filesizeformat
filesizeformat(1073741824)
=>
"1.0 GB"
</code></pre>
| 5 | 2014-08-27T12:47:28Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 25,613,067 | <p>While I know this question is ancient, I recently came up with a version that avoids loops, using <code>log2</code> to determine the size order which doubles as a shift and an index into the suffix list:</p>
<pre><code>from math import log2
_suffixes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'Yi... | 15 | 2014-09-01T21:23:48Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 27,094,657 | <p>How about the very simple:</p>
<pre><code>import math
def humanizeFileSize(size):
size = abs(size)
if (size==0):
return "0B"
units = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']
p = math.floor(math.log(size, 2)/10)
return "%.3f%s" % (size/math.pow(1024,p),units[int(p)])
if __n... | 1 | 2014-11-23T21:39:33Z | [
"python",
"code-snippets",
"filesize"
] |
Reusable library to get human readable version of file size? | 1,094,841 | <p>There are various snippets on the web that would give you a function to return human readable size from bytes size:</p>
<pre><code>>>> human_readable(2048)
'2 kilobytes'
>>>
</code></pre>
<p>But is there a Python library that provides this?</p>
| 129 | 2009-07-07T20:59:32Z | 31,178,618 | <p>This will do what you need in almost any situation, is customizable with optional arguments, and as you can see, is <em>pretty</em> much self-documenting:</p>
<pre><code>from math import log
def pretty_size(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
pow,n=min(int(log(max(n*b**pow,1),b)),len(pre)-... | 3 | 2015-07-02T07:53:30Z | [
"python",
"code-snippets",
"filesize"
] |
Is there a Python language specification? | 1,094,961 | <p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
| 24 | 2009-07-07T21:23:25Z | 1,094,966 | <p>No, python is defined by its implementation.</p>
| -1 | 2009-07-07T21:25:31Z | [
"python",
"specifications"
] |
Is there a Python language specification? | 1,094,961 | <p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
| 24 | 2009-07-07T21:23:25Z | 1,094,977 | <p>You can check out the <a href="http://docs.python.org/dev/reference/index.html" rel="nofollow">Python Reference</a></p>
| 2 | 2009-07-07T21:26:22Z | [
"python",
"specifications"
] |
Is there a Python language specification? | 1,094,961 | <p>Is there anything in Python akin to Java's JLS or C#'s spec? </p>
| 24 | 2009-07-07T21:23:25Z | 1,094,987 | <p>There's no specification per se. The closest thing is the <a href="http://docs.python.org/reference/">Python Language Reference</a>, which details the syntax and semantics of the language.</p>
| 21 | 2009-07-07T21:27:30Z | [
"python",
"specifications"
] |
Python strings / match case | 1,095,026 | <p>I have a CSV file which has the following format:</p>
<pre><code>id,case1,case2,case3
</code></pre>
<p>Here is a sample:</p>
<pre><code>123,null,X,Y
342,X,X,Y
456,null,null,null
789,null,null,X
</code></pre>
<p>For each line I need to know which of the cases is not null. Is there an easy way to find out which... | 0 | 2009-07-07T21:39:56Z | 1,095,058 | <p>You probably want to take a look at the <a href="http://docs.python.org/library/csv.html#module-csv" rel="nofollow">CSV module</a>, which has readers and writers that will enable you to create transforms.</p>
<pre><code>>>> from StringIO import StringIO
>>> from csv import DictReader
>>> ... | 2 | 2009-07-07T21:45:33Z | [
"python",
"csv"
] |
Python strings / match case | 1,095,026 | <p>I have a CSV file which has the following format:</p>
<pre><code>id,case1,case2,case3
</code></pre>
<p>Here is a sample:</p>
<pre><code>123,null,X,Y
342,X,X,Y
456,null,null,null
789,null,null,X
</code></pre>
<p>For each line I need to know which of the cases is not null. Is there an easy way to find out which... | 0 | 2009-07-07T21:39:56Z | 1,095,059 | <p>Why do you treat spliting as a problem? For performance reasons?</p>
<p>Literally you could avoid splitting with smart regexps (like:</p>
<pre><code>\d+,null,\w+,\w+
\d+,\w+,null,\w+
...
</code></pre>
<p>but I find it a worse solution than reparsing the data into lists.</p>
| 0 | 2009-07-07T21:46:31Z | [
"python",
"csv"
] |
Python strings / match case | 1,095,026 | <p>I have a CSV file which has the following format:</p>
<pre><code>id,case1,case2,case3
</code></pre>
<p>Here is a sample:</p>
<pre><code>123,null,X,Y
342,X,X,Y
456,null,null,null
789,null,null,X
</code></pre>
<p>For each line I need to know which of the cases is not null. Is there an easy way to find out which... | 0 | 2009-07-07T21:39:56Z | 1,095,064 | <p>Anyway you slice it, you are still going to have to go through the list. There are more and less elegant ways to do it. Depending on the python version you are using, you can use list comprehensions.</p>
<pre><code>ids=line.split(",")
print "%s:%s" % (ids[0], ":".join(["case%d" % x for x in range(1, len(ids)) if ... | 1 | 2009-07-07T21:47:14Z | [
"python",
"csv"
] |
Python strings / match case | 1,095,026 | <p>I have a CSV file which has the following format:</p>
<pre><code>id,case1,case2,case3
</code></pre>
<p>Here is a sample:</p>
<pre><code>123,null,X,Y
342,X,X,Y
456,null,null,null
789,null,null,X
</code></pre>
<p>For each line I need to know which of the cases is not null. Is there an easy way to find out which... | 0 | 2009-07-07T21:39:56Z | 1,095,075 | <p>You could use the Python <a href="http://docs.python.org/library/csv.html" rel="nofollow">csv module</a>, comes in with the standard installation of python... It will not be <code>much</code> easier, though...</p>
| 0 | 2009-07-07T21:49:58Z | [
"python",
"csv"
] |
Django file upload input validation and security | 1,095,250 | <p>I'm creating a <strong>very</strong> simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:</p>
<ol>
<li>Disallow certain file extensions (.php, .htm... | 1 | 2009-07-07T22:50:23Z | 1,095,662 | <p>Disallowing a file extension is -- potentially -- a waste of time. A unix server doesn't use the extension -- it uses ownership and permissions. </p>
<p>When accepting an upload, you will often rename the file to prevent it being misused. Uploaded files should be simply named "upload_xxx" with the "xxx" being a ... | 4 | 2009-07-08T01:17:23Z | [
"python",
"django",
"security",
"file-upload"
] |
Django file upload input validation and security | 1,095,250 | <p>I'm creating a <strong>very</strong> simple django upload application but I want to make it as secure as possible. This is app is going to be completely one way, IE. anybody who uploads a file will never have to retrieve it. So far I've done the following:</p>
<ol>
<li>Disallow certain file extensions (.php, .htm... | 1 | 2009-07-07T22:50:23Z | 5,921,094 | <p>Also, you might want to put the target files outside Apache's DocumentRoot directory, so that they are not reachable by any URL. Rules in .htaccess offer a certain amount of protection if they're written well, but if you're seeking for maximum security, just put the files away from web-reachable directory.</p>
| 1 | 2011-05-07T12:38:50Z | [
"python",
"django",
"security",
"file-upload"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 1,095,296 | <p>You could write the matrix in Python to a CSV file and read it in MATLAB using csvread.</p>
| 3 | 2009-07-07T23:03:12Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 1,095,324 | <p>If you use numpy/scipy, you can use the <code>scipy.io.savemat</code> function:</p>
<pre><code>import numpy, scipy.io
arr = numpy.arange(10)
arr = arr.reshape((3, 3)) # 2d array of 3x3
scipy.io.savemat('c:/tmp/arrdata.mat', mdict={'arr': arr})
</code></pre>
<p>Now, you can load this data into MATLAB using File ... | 40 | 2009-07-07T23:13:52Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 1,095,414 | <p>I wrote a small function to do this same thing, without need for numpy. It takes a list of lists and returns a string with a MATLAB-formatted matrix.</p>
<pre><code>def arrayOfArrayToMatlabString(array):
return '[' + "\n ".join(" ".join("%6g" % val for val in line) for line in array) + ']'
</code></pre>
<p>Wri... | 4 | 2009-07-07T23:45:29Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 1,095,505 | <p>I think <a href="http://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab/1095324#1095324">ars</a> has the most straight-forward answer for saving the data to a .mat file from Python (using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html">savemat</a>). To add just a ... | 7 | 2009-07-08T00:13:44Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 6,885,144 | <p>You can also <a href="http://mlabwrap.sourceforge.net/" rel="nofollow">call matlab</a> directly from python:</p>
<pre><code>from mlabwrap import mlab
import numpy
a = numpy.array([1,2,3])
mlab.plot(a)
</code></pre>
| 1 | 2011-07-30T18:26:42Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Matrix from Python to MATLAB | 1,095,265 | <p>I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this? </p>
<p>Thanks!</p>
| 25 | 2009-07-07T22:55:08Z | 7,737,622 | <p>I would probably use <code>numpy.savetxt('yourfile.mat',yourarray)</code> in Python
and then <code>yourarray = load('yourfile.mat')</code> in MATLAB.</p>
| 2 | 2011-10-12T09:03:07Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] |
Finding partial strings in a list of strings - python | 1,095,270 | <p>I am trying to check if a user is a member of an Active Directory group, and I have this:</p>
<pre><code>ldap.set_option(ldap.OPT_REFERRALS, 0)
try:
con = ldap.initialize(LDAP_URL)
con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password)
ADUser = con.search_ext_s(ad_settings.AD_SEARCH_DN, ldap.SCOPE_SU... | 0 | 2009-07-07T22:56:02Z | 1,095,360 | <p>You can use set intersection (& operator) once you parse the group list out. For example:</p>
<pre><code>> memberOf = 'CN=group1,OU=Projects,OU=Office,OU=company,DC=domain,DC=com'
> groups = [token.split('=')[1] for token in memberOf.split(',')]
> groups
['group1', 'Projects', 'Office', 'company', '... | 1 | 2009-07-07T23:28:46Z | [
"python",
"regex",
"list"
] |
Finding partial strings in a list of strings - python | 1,095,270 | <p>I am trying to check if a user is a member of an Active Directory group, and I have this:</p>
<pre><code>ldap.set_option(ldap.OPT_REFERRALS, 0)
try:
con = ldap.initialize(LDAP_URL)
con.simple_bind_s(userid+"@"+ad_settings.AD_DNS_NAME, password)
ADUser = con.search_ext_s(ad_settings.AD_SEARCH_DN, ldap.SCOPE_SU... | 0 | 2009-07-07T22:56:02Z | 1,095,909 | <p>If the format example you give is somewhat reliable, something like:</p>
<pre><code>import re
grps = re.compile(r'CN=(\w+)').findall
def anyof(short_group_list, adu):
all_groups_of_user = set(g for gs in adu.get('memberOf',()) for g in grps(gs))
return sorted(all_groups_of_user.intersection(short_group_list))
... | 2 | 2009-07-08T02:50:51Z | [
"python",
"regex",
"list"
] |
Alternative Python imaging libraries on Google App Engine? | 1,095,325 | <p>I am thinking about uploading images to Google App Engine, but I need to brighten parts of the image. I am not sure if the App Engine imagine API will be sufficient. I consider to try an overlay with a white image and partial opacity. </p>
<p>However, if that does not yield the desired results, would there be anoth... | 4 | 2009-07-07T23:14:04Z | 1,095,867 | <p><a href="http://the.taoofmac.com/space/projects/PNGCanvas" rel="nofollow">PNGcanvas</a> might help, if PNG input and output is satisfactory -- it doesn't directly offer the "brighten" functionality you require, but it does let you load and save PNG files into memory and access them directly from Python, and it IS a ... | 4 | 2009-07-08T02:30:26Z | [
"python",
"google-app-engine",
"python-imaging-library"
] |
Get __name__ of calling function's module in Python | 1,095,543 | <p>Suppose <code>myapp/foo.py</code> contains:</p>
<pre><code>def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
</code></pre>
<p>And <code>myapp/bar.py</code> contains:</p>
<pre><code>import foo
foo.info('Hello') # => [myapp.foo] Hello
</code></pre>
<p>I want <code>caller_name</code>... | 54 | 2009-07-08T00:30:47Z | 1,095,621 | <p>Check out the inspect module:</p>
<p><code>inspect.stack()</code> will return the stack information.</p>
<p>Inside a function, <code>inspect.stack()[1]</code> will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.</p>
<p>See the docs for details:<... | 80 | 2009-07-08T01:03:42Z | [
"python",
"stack-trace",
"introspection"
] |
Get __name__ of calling function's module in Python | 1,095,543 | <p>Suppose <code>myapp/foo.py</code> contains:</p>
<pre><code>def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
</code></pre>
<p>And <code>myapp/bar.py</code> contains:</p>
<pre><code>import foo
foo.info('Hello') # => [myapp.foo] Hello
</code></pre>
<p>I want <code>caller_name</code>... | 54 | 2009-07-08T00:30:47Z | 1,095,711 | <p>I don't recommend do this, but you can accomplish your goal with the following method:</p>
<pre><code>def caller_name():
frame=inspect.currentframe()
frame=frame.f_back.f_back
code=frame.f_code
return code.co_filename
</code></pre>
<p>Then update your existing method as follows:</p>
<pre><code>def... | 3 | 2009-07-08T01:32:12Z | [
"python",
"stack-trace",
"introspection"
] |
Get __name__ of calling function's module in Python | 1,095,543 | <p>Suppose <code>myapp/foo.py</code> contains:</p>
<pre><code>def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
</code></pre>
<p>And <code>myapp/bar.py</code> contains:</p>
<pre><code>import foo
foo.info('Hello') # => [myapp.foo] Hello
</code></pre>
<p>I want <code>caller_name</code>... | 54 | 2009-07-08T00:30:47Z | 5,071,539 | <p>Confronted with a similar problem, I have found that <strong>sys._current_frames()</strong> from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.</p>
<pre><code>>>> sys._current_frames()
{4052: <frame object at 0x03200... | 12 | 2011-02-21T21:35:29Z | [
"python",
"stack-trace",
"introspection"
] |
Sending SIGINT to a subprocess of python | 1,095,549 | <p>I've got a python script managing a gdb process on windows, and I need to be able to send a SIGINT to the spawned process in order to halt the target process (managed by gdb) </p>
<p>It appears that there is only SIGTERM available in win32, but clearly if I run gdb from the console and Ctrl+C, it thinks it's recei... | 4 | 2009-07-08T00:34:14Z | 1,095,597 | <p>Windows doesn't have the unix signals IPC mechanism.</p>
<p>I would look at sending a CTRL-C to the gdb process.</p>
| 1 | 2009-07-08T00:52:20Z | [
"python",
"subprocess",
"sigint"
] |
Find module name of the originating exception in Python | 1,095,601 | <p>Example:</p>
<pre><code>>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
</code></pre>
<p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code... | 9 | 2009-07-08T00:55:16Z | 1,095,627 | <p>This should do the trick:</p>
<pre><code>import inspect
def modname():
t=inspect.trace()
if t:
return t[-1][1]
</code></pre>
| 0 | 2009-07-08T01:06:58Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] |
Find module name of the originating exception in Python | 1,095,601 | <p>Example:</p>
<pre><code>>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
</code></pre>
<p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code... | 9 | 2009-07-08T00:55:16Z | 1,095,656 | <p>You can use the <a href="http://docs.python.org/library/traceback.html">traceback module</a>, along with <a href="http://docs.python.org/library/sys.html#sys.exc%5Finfo"><code>sys.exc_info()</code></a>, to get the traceback programmatically:</p>
<pre><code>try:
myapp.foo.doSomething()
except Exception, e:
e... | 6 | 2009-07-08T01:15:58Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] |
Find module name of the originating exception in Python | 1,095,601 | <p>Example:</p>
<pre><code>>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
</code></pre>
<p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code... | 9 | 2009-07-08T00:55:16Z | 1,096,213 | <p>This should work:</p>
<pre><code>import inspect
try:
some_bad_code()
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
print 'Thrown from', mod.__name__
</code></pre>
<p>EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.<... | 8 | 2009-07-08T05:19:23Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] |
Find module name of the originating exception in Python | 1,095,601 | <p>Example:</p>
<pre><code>>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
</code></pre>
<p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code... | 9 | 2009-07-08T00:55:16Z | 1,096,327 | <p>Python's logging package already supports this - check the <a href="http://docs.python.org/library/logging.html#formatter-objects" rel="nofollow">documentation</a>. You just have to specify <code>%(module)s</code> in the format string. However, this gives you the module where the exception was <em>caught</em> - not ... | 0 | 2009-07-08T06:01:38Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] |
Find module name of the originating exception in Python | 1,095,601 | <p>Example:</p>
<pre><code>>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
</code></pre>
<p>In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the <code>__name__</code... | 9 | 2009-07-08T00:55:16Z | 1,169,138 | <p>I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: â<a href="http://blog.yoursway.com/2009/07/python-stack-trace-saga.html" rel="nofollow">Python stack trace saga</a>â. Working code included.</p>
| 0 | 2009-07-23T01:36:25Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] |
Does get_or_create() have to save right away? (Django) | 1,095,663 | <p>I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently.</p>
<p>I can set the fields to null=True, but I don't want... | 33 | 2009-07-08T01:17:30Z | 1,095,706 | <p>You can just do:</p>
<pre><code>try:
obj = Model.objects.get(**kwargs)
except Model.DoesNotExist:
obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))
</code></pre>
<p>which is pretty much what <a href="https://github.com/django/django/blob/master/django/db/models/query.py#L454" rel="nof... | 34 | 2009-07-08T01:29:09Z | [
"python",
"django"
] |
where does django install in ubuntu | 1,095,725 | <p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
| 29 | 2009-07-08T01:38:33Z | 1,095,738 | <p><a href="http://ubuntuforums.org/showthread.php?t=627773" rel="nofollow">http://ubuntuforums.org/showthread.php?t=627773</a></p>
| 2 | 2009-07-08T01:41:28Z | [
"python",
"django",
"ubuntu"
] |
where does django install in ubuntu | 1,095,725 | <p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
| 29 | 2009-07-08T01:38:33Z | 1,095,862 | <p>you can just print it out.</p>
<pre><code>>>> import django
>>> print django.__file__
/var/lib/python-support/python2.5/django/__init__.pyc
>>>
</code></pre>
<p>or:</p>
<pre><code>import inspect
import django
print inspect.getabsfile(django)
</code></pre>
| 86 | 2009-07-08T02:26:58Z | [
"python",
"django",
"ubuntu"
] |
where does django install in ubuntu | 1,095,725 | <p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
| 29 | 2009-07-08T01:38:33Z | 1,251,732 | <p>This (or something like this) also works when you are searching for files in other packages:</p>
<pre><code>$ dpkg -L python-django | grep __init__.py
</code></pre>
| 3 | 2009-08-09T16:50:09Z | [
"python",
"django",
"ubuntu"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.