title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Why is Python's "append" not "push"? | 1,566,266 | 176 | 2009-10-14T13:34:26Z | 1,566,287 | 9 | 2009-10-14T13:37:03Z | [
"python"
] | Does anyone know why Python's `list.append` function is not called `list.push` given that there's already a `list.pop` that removes and returns the last element (that indexed at -1) and `list.append` semantic is consistent with that use? | Because it appends an element to a list? Push is usually used when referring to stacks. |
Why is Python's "append" not "push"? | 1,566,266 | 176 | 2009-10-14T13:34:26Z | 1,566,294 | 9 | 2009-10-14T13:38:01Z | [
"python"
] | Does anyone know why Python's `list.append` function is not called `list.push` given that there's already a `list.pop` that removes and returns the last element (that indexed at -1) and `list.append` semantic is consistent with that use? | Because "append" intuitively means "add at the end of the list". If it was called "push", then it would be unclear whether we're adding stuff at the tail or at head of the list. |
Why is Python's "append" not "push"? | 1,566,266 | 176 | 2009-10-14T13:34:26Z | 1,569,007 | 168 | 2009-10-14T21:07:43Z | [
"python"
] | Does anyone know why Python's `list.append` function is not called `list.push` given that there's already a `list.pop` that removes and returns the last element (that indexed at -1) and `list.append` semantic is consistent with that use? | Because "append" existed long before "pop" was thought of. [Python 0.9.1](http://www.dalkescientific.com/writings/diary/archive/2009/03/27/python%5F0%5F9%5F1p1.html) supported list.append in early 1991. By comparison, here's part of a [discussion on comp.lang.python](http://groups.google.com/group/comp.lang.python/brow... |
Easy pretty printing of floats in python? | 1,566,936 | 43 | 2009-10-14T15:07:38Z | 1,566,957 | 15 | 2009-10-14T15:10:43Z | [
"python",
"printing",
"formatting",
"floating-point"
] | I have a list of floats. If I simply `print` it, it shows up like this:
```
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
```
I could use `print "%.2f"`, which would require a `for` loop to traverse the list, but then it wouldn't work for more comp... | Note that you can also multiply a string like "%.2f" (example: "%.2f "\*10).
```
>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31
``` |
Easy pretty printing of floats in python? | 1,566,936 | 43 | 2009-10-14T15:07:38Z | 1,566,970 | 36 | 2009-10-14T15:12:55Z | [
"python",
"printing",
"formatting",
"floating-point"
] | I have a list of floats. If I simply `print` it, it shows up like this:
```
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
```
I could use `print "%.2f"`, which would require a `for` loop to traverse the list, but then it wouldn't work for more comp... | You can do:
```
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
``` |
Easy pretty printing of floats in python? | 1,566,936 | 43 | 2009-10-14T15:07:38Z | 1,567,166 | 45 | 2009-10-14T15:41:43Z | [
"python",
"printing",
"formatting",
"floating-point"
] | I have a list of floats. If I simply `print` it, it shows up like this:
```
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
```
I could use `print "%.2f"`, which would require a `for` loop to traverse the list, but then it wouldn't work for more comp... | As noone has added it, it should be noted that going forward from Python 2.6+ the recommended way to do [string formating](http://docs.python.org/library/string.html#string-formatting) is with [`format`](http://docs.python.org/library/string.html#string.Formatter.format), to get ready for Python 3+.
```
print ["{0:0.2... |
Easy pretty printing of floats in python? | 1,566,936 | 43 | 2009-10-14T15:07:38Z | 1,567,630 | 44 | 2009-10-14T16:57:29Z | [
"python",
"printing",
"formatting",
"floating-point"
] | I have a list of floats. If I simply `print` it, it shows up like this:
```
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
```
I could use `print "%.2f"`, which would require a `for` loop to traverse the list, but then it wouldn't work for more comp... | A more permanent solution is to subclass `float`:
```
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
```
The problem with subclass... |
Wrapping an interactive command line application in a python script | 1,567,371 | 12 | 2009-10-14T16:12:21Z | 1,567,447 | 10 | 2009-10-14T16:29:12Z | [
"python",
"command-line"
] | I am interested in controlling an interactive CLI application from python calls.
I guess at the most basic level I need a python script that will start a CLI application on the host OS. Pipe anything from stdin to the cli application, and then pipe any output from the cli application to stdout.
From this base It shou... | Maybe you want something from [Subprocess](http://docs.python.org/library/subprocess.html) ([MOTW](http://blog.doughellmann.com/2007/07/pymotw-subprocess.html)).
I use code like this to make calls out to the shell:
```
from subprocess import Popen, PIPE
## shell out, prompt
def shell(args, input=''):
''' uses su... |
Why is BeautifulSoup modifying my self-closing elements? | 1,567,402 | 2 | 2009-10-14T16:19:14Z | 1,567,417 | 7 | 2009-10-14T16:22:13Z | [
"python",
"xml",
"beautifulsoup"
] | This is the script I have:
```
import BeautifulSoup
if __name__ == "__main__":
data = """
<root>
<obj id="3"/>
<obj id="5"/>
<obj id="3"/>
</root>
"""
soup = BeautifulSoup.BeautifulStoneSoup(data)
print soup
```
When ran, this prints:
```
<root>
<obj id="3"></obj>
... | From the [Beautiful Soup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML):
> The most common shortcoming of `BeautifulStoneSoup` is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can... |
Buildout and Virtualenv | 1,567,494 | 12 | 2009-10-14T16:35:42Z | 1,842,685 | 8 | 2009-12-03T20:28:31Z | [
"python",
"virtualenv",
"buildout"
] | I am messing around with the combination of buildout and virtualenv to setup an *isolated* development environment in python that allows to do reproducible builds.
There is a recipe for buildout that let's you integrate virtualenv into buildout:
```
tl.buildout_virtual_python
```
With this my buildout.cfg looks lik... | You don't need virtualenv: buildout already provides an isolated environment, just like virtualenv.
As an example, look at files buildout generates in the bin directory. They'll have something like:
```
import sys
sys.path[0:0] = [
'/some/thing1.egg',
# and other things
]
```
So the `sys.path` gets co... |
How can I view a text representation of an lxml element? | 1,567,903 | 6 | 2009-10-14T17:48:03Z | 1,567,932 | 15 | 2009-10-14T17:52:03Z | [
"python",
"xml",
"lxml"
] | If I'm parsing an XML document using lxml, is it possible to view a text representation of an element?
I tried to do :
```
print repr(node)
```
but this outputs
```
<Element obj at b743c0>
```
What can I use to see the node like it exists in the XML file? Is there some `to_xml` method or something? | From <http://lxml.de/tutorial.html#serialisation>
```
>>> root = etree.XML('<root><a><b/></a></root>')
>>> etree.tostring(root)
b'<root><a><b/></a></root>'
>>> print(etree.tostring(root, xml_declaration=True))
<?xml version='1.0' encoding='ASCII'?>
<root><a><b/></a></root>
>>> print(etree.tostring(root, encoding='i... |
Django: How do I make fields non-editable by default in an inline model formset? | 1,568,058 | 4 | 2009-10-14T18:13:19Z | 2,242,468 | 12 | 2010-02-11T05:26:45Z | [
"python",
"django",
"django-forms"
] | I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like th... | This one stumped me for a bit too. Hopefully this is what you're looking for.
```
<TABLE>
<form method="post" action=".">
{{ formset.management_form }}
{% for form in formset.forms %}
{{ form.id }}
<tr>
<td>{{ form.FirstName }}</td> <!-- This is a normal, edi... |
Given a Python class, how can I inspect and find the place in my code where it is defined? | 1,568,544 | 5 | 2009-10-14T19:46:32Z | 1,568,650 | 8 | 2009-10-14T20:04:27Z | [
"python"
] | I'm building a debugging tool.
IPython lets me do stuff like
```
MyCls??
```
And it will show me the source. | ```
sys.modules[MyCls.__module__].__file__
```
or
```
inspect.getsourcefile(MyCls)
```
There are more [`__xxx__` attributes](http://docs.python.org/library/inspect.html#types-and-members) on various objects you might find useful. |
How do I convert RFC822 to a python datetime object? | 1,568,856 | 16 | 2009-10-14T20:39:39Z | 1,568,882 | 28 | 2009-10-14T20:43:57Z | [
"python",
"rfc822"
] | I know how to do this the other way around... it would be:
```
>>> dt.rfc822()
'Sun, 09 Mar 1997 13:45:00 -0500'
``` | ```
In [1]: import rfc822 # This only works for python 2 series
In [2]: rfc822.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500')
Out[2]: (1997, 3, 9, 13, 45, 0, 0, 1, 0, -18000)
```
in python3 parsedate\_tz has moved to email.utils
```
>>> import email.utils # this works on Python2.5 and up
>>> email.utils.parse... |
Making Python's `assert` throw an exception that I choose | 1,569,049 | 20 | 2009-10-14T21:15:43Z | 1,569,074 | 29 | 2009-10-14T21:19:18Z | [
"python",
"exception",
"assert"
] | Can I make `assert` throw an exception that I choose instead of `AssertionError`?
**UPDATE:**
I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a `Node` object with certain arguments, it would check if the arguments were good for creatin... | This will work. But it's kind of crazy.
```
try:
assert False, "A Message"
except AssertionError, e:
raise Exception( e.args )
```
Why not the following? This is less crazy.
```
if not someAssertion: raise Exception( "Some Message" )
```
It's only a little wordier than the `assert` statement, but doesn't vi... |
Making Python's `assert` throw an exception that I choose | 1,569,049 | 20 | 2009-10-14T21:15:43Z | 1,569,237 | 13 | 2009-10-14T21:55:25Z | [
"python",
"exception",
"assert"
] | Can I make `assert` throw an exception that I choose instead of `AssertionError`?
**UPDATE:**
I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a `Node` object with certain arguments, it would check if the arguments were good for creatin... | How about this?
```
>>> def myraise(e): raise e
...
>>> cond=False
>>> assert cond or myraise(RuntimeError)
Traceback (most recent call last):
File "", line 1, in
File "", line 1, in myraise
RuntimeError
``` |
Python's libxml2 can't parse unicode strings | 1,569,076 | 2 | 2009-10-14T21:20:08Z | 1,569,140 | 9 | 2009-10-14T21:35:10Z | [
"python",
"xml",
"unicode",
"libxml2"
] | OK, the docs for Python's libxml2 bindings are really `****`. My problem:
An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this:
```
# -*- coding: utf-8 -*-
import libxml2
D... | It should be
```
# -*- coding: utf-8 -*-
import libxml2
DOC = u"""<?xml version="1.0" encoding="UTF-8"?>
<data>
<something>Bäääh!</something>
</data>
""".encode("UTF-8")
xml_doc = libxml2.parseDoc(DOC)
```
The .encode("UTF-8") is needed to get the binary representation of the unicode string with the utf8 encod... |
How to use Python to log into Facebook/Myspace and crawl the content? | 1,569,206 | 4 | 2009-10-14T21:49:39Z | 1,569,257 | 7 | 2009-10-14T21:59:46Z | [
"python",
"authentication",
"session",
"post",
"web-crawler"
] | Right now, I can crawl regular pages using urllib2.
```
request = urllib2.Request('http://stackoverflow.com')
request.add_header('User-Agent',random.choice(agents))
response = urllib2.urlopen(request)
htmlSource = response.read()
print htmlSource
```
However...I would like to simulate a POST (or fake sessions)? so th... | You'll need to keep the cookie your site of choice sends you when you log in; that's what keeps your session. With `urllib2`, you do this by creating an Opener object that supports cookie processing:
```
import urllib2, cookielib
jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar... |
Clojure equivalent to Python's lxml library? | 1,569,223 | 10 | 2009-10-14T21:51:49Z | 1,572,391 | 7 | 2009-10-15T13:31:22Z | [
"java",
"python",
"clojure",
"lxml"
] | I'm looking for the Clojure/Java equivalent to Python's lxml library.
I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure libra... | Enlive: <http://github.com/cgrand/enlive>
I've used it for screen-scraping and it works quite well for that. It uses a CSS selector like syntax for getting at elements in the document. |
"setup.py upload" is failing with "Upload failed (401): You must be identified to edit package information" | 1,569,315 | 42 | 2009-10-14T22:15:41Z | 1,569,331 | 61 | 2009-10-14T22:19:24Z | [
"python",
"packaging",
"setuptools"
] | When running..
```
python setup.py sdist register upload
```
..I get the following output:
```
running register
We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
Your se... | Just found [this page](http://www.davidcramer.net/code/python/443/problems-uploading-packages-with-setuptools-on-os-x.html), which solves the issue:
> I also noticed that while it was asking me to save my login information, and I hit Y everytime, it still asked me for the username and password. It turned out that it w... |
How to create a custom 404 page for my Django/Apache? | 1,569,682 | 3 | 2009-10-15T00:22:32Z | 1,569,694 | 14 | 2009-10-15T00:26:36Z | [
"python",
"django",
"apache"
] | I know that you use .htaccess in the document-root directory in standard apache.
What if I use Django? Can someone give me step by step how to create a custom 404 page?
THanks. | The default 404 handler calls 404.html . You could edit that if you don't need anything fancy or can override the 404 handler by setting the handler404 view -- [more here](http://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view) |
Django - how can I get permalink to work with "throwaway" slug | 1,569,837 | 4 | 2009-10-15T01:21:36Z | 1,569,882 | 7 | 2009-10-15T01:40:24Z | [
"python",
"django",
"django-urls",
"permalinks"
] | I'm trying to add slugs to the url in my django app, much like SO does.
Currently, I have pages that work just fine with a url like this:
```
http://example.com/foo/123/
```
I'd like to add 'slugified' urls like so:
```
http://example.com/foo/123/foo-name-here
```
I can get it to work just fine, by simply modifyin... | One thing to check for, because I also ran into this problem:
```
(?P<name_slug>\w+)
```
Is slugify adding hyphens anywhere? If so the regex won't match, hypens are a non-word character. To fix use `[\w-]+` or similar. |
In Python, how do I transform a string into a file? | 1,570,230 | 3 | 2009-10-15T04:05:54Z | 1,570,244 | 15 | 2009-10-15T04:15:29Z | [
"python",
"string",
"file",
"types"
] | There is a read-only library function that takes a file as an argument.
But I have a string.
How do I convert a string to a file, that if you read the file it will return this string?
I don't want to write to disk. | The `StringIO` module:
```
>>> import StringIO
>>> f = StringIO.StringIO("foo")
>>> f.read()
'foo'
```
The `cStringIO` module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters.
[StringIO documentation](http://docs.python.org/library/stringio.html) |
Create a user-group in linux using python | 1,570,401 | 5 | 2009-10-15T05:13:02Z | 1,570,448 | 9 | 2009-10-15T05:26:09Z | [
"python",
"linux",
"usergroups"
] | I want to create a user group using python on CentOS system. When I say 'using python' I mean I don't want to do something like os.system and give the unix command to create a new group. I would like to know if there is any python module that deals with this.
Searching on the net did not reveal much about what I want,... | I don't know of a python module to do it, but the /etc/group and /etc/gshadow format is pretty standard, so if you wanted you could just open the files, parse their current contents and then add the new group if necessary.
Before you go doing this, consider:
* What happens if you try to add a group that already exist... |
Please help install matplotlib. It won't work! (Python) | 1,570,495 | 8 | 2009-10-15T05:45:29Z | 1,570,501 | 20 | 2009-10-15T05:47:56Z | [
"python",
"installation",
"matplotlib"
] | I downloaded the source. Untarred it.
"sudo python setup.py install". And below are the errors I get. Can someone help? By the way, Numpy is installed. Thanks a lot.
```
src/_image.cpp:5:17: error: png.h: No such file or directory
src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&)':
src/... | Those particular errors stem from the lack of the development package for libpng.
If you use Debian/Ubuntu, try `apt-get install libpng-dev` first. |
Please help install matplotlib. It won't work! (Python) | 1,570,495 | 8 | 2009-10-15T05:45:29Z | 1,570,506 | 9 | 2009-10-15T05:51:06Z | [
"python",
"installation",
"matplotlib"
] | I downloaded the source. Untarred it.
"sudo python setup.py install". And below are the errors I get. Can someone help? By the way, Numpy is installed. Thanks a lot.
```
src/_image.cpp:5:17: error: png.h: No such file or directory
src/_image.cpp: In member function 'Py::Object Image::write_png(const Py::Tuple&)':
src/... | if you are apt-based try
`$ sudo apt-get build-dep matplotlib` |
Can a dictionary be passed to django models on create? | 1,571,570 | 55 | 2009-10-15T10:41:29Z | 1,571,593 | 110 | 2009-10-15T10:49:09Z | [
"python",
"django",
"django-models",
"dictionary"
] | Is is possible to do something similar to this with a list, dictionary or something else even?
```
data_dict = {
'title' : 'awesome title',
'body' : 'great body of text',
}
Model.objects.create(data_dict)
```
Even better if I can extend it
```
Model.objects.create(data_dict, extra='hello', extra2='world)
``` | If `title` and `body` are fields in your model, then [you can deliver the keyword arguments in your dictionary using the \*\* operator](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
Assuming your model is called `MyModel`:
```
# create instance of model
m = MyModel(**data_dict)
# don't f... |
In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing? | 1,572,691 | 11 | 2009-10-15T14:23:55Z | 1,572,966 | 20 | 2009-10-15T15:03:47Z | [
"python",
"python-imaging-library"
] | I am probably looking for the wrong thing in the handbook, but I am looking to take an image object and expand it without resizing (stretching/squishing) the original image.
Toy example: imagine a blue rectangle, 200 x 100, then I perform some operation and I have a new image object, 400 x 300, consisting of a white b... | The ImageOps.expand function will expand the image, but it adds the same amount of pixels in each direction.
The best way is simply to make a new image and paste:
```
newImage = Image.new(mode, (newWidth,newHeight))
newImage.paste(srcImage, (x1,y1,x1+oldWidth,y1+oldHeight))
```
If performance is an issue, make your ... |
Python def function: How do you specify the end of the function? | 1,573,548 | 17 | 2009-10-15T16:32:53Z | 1,573,555 | 40 | 2009-10-15T16:34:42Z | [
"python",
"syntax"
] | I'm just learning python and confused when a "def" of a function ends?
I see code samples like:
```
def myfunc(a=4,b=6):
sum = a + b
return sum
myfunc()
```
I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this ... | In Python whitespace is significant. The function ends when the indentation becomes smaller (less).
```
def f():
pass # first line
pass # second line
pass # <-- less indentation, not part of function f.
```
Note that one-line functions can be written without indentation, on one line:
```
def f(): pass
```
A... |
Python def function: How do you specify the end of the function? | 1,573,548 | 17 | 2009-10-15T16:32:53Z | 1,573,556 | 20 | 2009-10-15T16:34:47Z | [
"python",
"syntax"
] | I'm just learning python and confused when a "def" of a function ends?
I see code samples like:
```
def myfunc(a=4,b=6):
sum = a + b
return sum
myfunc()
```
I know it doesn't end because of the return (because I've seen if statements... if FOO than return BAR, else return FOOBAR). How does Python know this ... | Python is white-space sensitive in regard to the indentation. Once the indentation level falls back to the level at which the function is defined, the function has ended. |
How to find duplicates in MySQL | 1,574,064 | 2 | 2009-10-15T18:02:15Z | 1,574,082 | 7 | 2009-10-15T18:05:46Z | [
"python",
"mysql"
] | Suppose I have many columns. If 2 columns match and are exactly the same, then they are duplicates.
```
ID | title | link | size | author
```
Suppose if link and size are similar for 2 rows or more, then those rows are duplicates.
How do I get those duplicates into a list and process them? | Will return all records that have dups:
```
SELECT theTable.*
FROM theTable
INNER JOIN (
SELECT link, size
FROM theTable
GROUP BY link, size
HAVING count(ID) > 1
) dups ON theTable.link = dups.link AND theTable.size = dups.size
```
I like the subquery b/c I can do things like select all but the first or last... |
Plotting time in Python with Matplotlib | 1,574,088 | 63 | 2009-10-15T18:07:10Z | 1,574,146 | 77 | 2009-10-15T18:18:26Z | [
"python",
"graph",
"plot",
"matplotlib"
] | I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.
Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?
I was trying to, but somehow it was only accepting arrays of floats. How can I ... | You must first convert your timestamps to Python `datetime` objects (use `datetime.strptime`). Then use `date2num` to convert the dates to matplotlib format.
Plot the dates and values using [`plot_date`](http://matplotlib.org/api/pyplot_api.html?highlight=plot_date#matplotlib.pyplot.plot_date):
```
dates = matplotlib... |
Plotting time in Python with Matplotlib | 1,574,088 | 63 | 2009-10-15T18:07:10Z | 16,428,019 | 29 | 2013-05-07T20:30:05Z | [
"python",
"graph",
"plot",
"matplotlib"
] | I have an array of timestamps in the format (HH:MM:SS.mmmmmm) and another array of floating point numbers, each corresponding to a value in the timestamp array.
Can I plot time on the x axis and the numbers on the y-axis using Matplotlib?
I was trying to, but somehow it was only accepting arrays of floats. How can I ... | You can also plot the timestamp, value pairs using [pyplot.plot](http://matplotlib.org/api/pyplot_api.html?highlight=plot_date#matplotlib.pyplot.plot) (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)
Example:
```
import datetime
import random
import matplotlib.... |
Efficient way to convert strings from split function to ints in Python | 1,574,678 | 7 | 2009-10-15T19:59:54Z | 1,574,703 | 9 | 2009-10-15T20:03:06Z | [
"python",
"variables",
"casting"
] | I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with ... | efficient as in fewer lines of code?
```
(xval,yval,zval) = [int(s) for s in file.split('-')]
``` |
Efficient way to convert strings from split function to ints in Python | 1,574,678 | 7 | 2009-10-15T19:59:54Z | 1,574,718 | 24 | 2009-10-15T20:04:31Z | [
"python",
"variables",
"casting"
] | I have a string of data with the following format: xpos-ypos-zoom (i.e. 8743-12083-15) that I want to split up and store in the variables xpos, ypos, and zoom. Since I need to do some calculations with these number I'd like to convert them to integers right from the beginning. Currently, the way I'm doing this is with ... | My original suggestion with a list comprehension.
```
test = '8743-12083-15'
lst_int = [int(x) for x in test.split("-")]
```
**EDIT:**
As to which is most efficient (cpu-cyclewise) is something that should always be tested.
Some quick testing on my Python 2.6 install indicates **map** is probably the most efficient ... |
Python - Twisted and Unit Tests | 1,575,966 | 16 | 2009-10-16T01:03:08Z | 1,575,983 | 7 | 2009-10-16T01:09:02Z | [
"python",
"unit-testing",
"twisted"
] | I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.
Our HTTP server is using Twisted. One problem... | I believe that for unit testing within Twisted you're supposed to use [TwistedTrial](http://twistedmatrix.com/trac/wiki/TwistedTrial) (it's a core component, i.e., comes with the Twisted tarball in the twisted/trial directory). However, as the URL I've pointed to says, the doc is mostly by having a look through the sou... |
Python - Twisted and Unit Tests | 1,575,966 | 16 | 2009-10-16T01:03:08Z | 1,575,992 | 17 | 2009-10-16T01:12:36Z | [
"python",
"unit-testing",
"twisted"
] | I'm writing unit tests for a portion of an application that runs as an HTTP server. The approach I have been trying to take is to import the module that contains the HTTP server, start it. Then, the unit tests will use urllib2 to connect, send data, and check the response.
Our HTTP server is using Twisted. One problem... | Here's some info: [Writing tests for Twisted code using Trial](http://twistedmatrix.com/projects/core/documentation/howto/testing.html)
You should also look at the -help of the trial command. There'a lot of good stuff in trial! But it's not always easy to do testing in a async application. Good luck! |
Using Sphinx to write personal websites and blogs | 1,576,340 | 31 | 2009-10-16T05:56:08Z | 1,576,635 | 11 | 2009-10-16T07:30:40Z | [
"python",
"plugins",
"website",
"blogs",
"python-sphinx"
] | [Sphinx](http://sphinx.pocoo.org/) is a Python library to generate nice documentation from a set of [ReST](http://docutils.sourceforge.net/rst.html) formatted text files.
I wonder if any one has written Sphinx plugins to make it **generate personal websites and blogs**.
Especially for blogs, there needs to be a way t... | Doug hellmann, author of the 'Python Module of the Week' does his site using Sphinx.
<http://www.doughellmann.com/PyMOTW/>
He has several posts which cover sphinx topics that can probably help you on your way:
[http://blog.doughellmann.com](http://doughellmann.com/?s=sphinx) |
Using Sphinx to write personal websites and blogs | 1,576,340 | 31 | 2009-10-16T05:56:08Z | 1,588,720 | 15 | 2009-10-19T13:39:15Z | [
"python",
"plugins",
"website",
"blogs",
"python-sphinx"
] | [Sphinx](http://sphinx.pocoo.org/) is a Python library to generate nice documentation from a set of [ReST](http://docutils.sourceforge.net/rst.html) formatted text files.
I wonder if any one has written Sphinx plugins to make it **generate personal websites and blogs**.
Especially for blogs, there needs to be a way t... | I've done it at <http://reinout.vanrees.org/weblog>. The key trick is to add a preprocessor step. I've got my blog entries in a `weblog/yyyy/mm/dd/` folder structure.
A script iterates through that folder structure, creating `index.txt` files in every directory, listing the sub-items. The normal Sphinx process then re... |
Using Sphinx to write personal websites and blogs | 1,576,340 | 31 | 2009-10-16T05:56:08Z | 9,238,379 | 13 | 2012-02-11T06:41:23Z | [
"python",
"plugins",
"website",
"blogs",
"python-sphinx"
] | [Sphinx](http://sphinx.pocoo.org/) is a Python library to generate nice documentation from a set of [ReST](http://docutils.sourceforge.net/rst.html) formatted text files.
I wonder if any one has written Sphinx plugins to make it **generate personal websites and blogs**.
Especially for blogs, there needs to be a way t... | As of now (February, 2012), there are different resources available to do what you want:
A blog engine based on sphinx: <http://tinkerer.me/>
Reinout Van Rees' blog: <https://github.com/reinout/reinout.vanrees.org>
The feed contrib extension: <https://bitbucket.org/birkenfeld/sphinx-contrib/src/tip/feed/README> |
Using Sphinx to write personal websites and blogs | 1,576,340 | 31 | 2009-10-16T05:56:08Z | 13,031,104 | 10 | 2012-10-23T13:05:57Z | [
"python",
"plugins",
"website",
"blogs",
"python-sphinx"
] | [Sphinx](http://sphinx.pocoo.org/) is a Python library to generate nice documentation from a set of [ReST](http://docutils.sourceforge.net/rst.html) formatted text files.
I wonder if any one has written Sphinx plugins to make it **generate personal websites and blogs**.
Especially for blogs, there needs to be a way t... | If you need to write in [reStructuredText](http://docutils.sourceforge.net/rst.html) , you should try [Pelican](http://docs.getpelican.com/).
Pelican is a static site generator, written in Python. You'll be able to write your blog entries directly in reStructuredText or Markdown. |
Generate pretty diff html in Python | 1,576,459 | 20 | 2009-10-16T06:39:20Z | 1,576,759 | 20 | 2009-10-16T08:15:22Z | [
"python",
"html",
"diff",
"prettify"
] | I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output).
I have tried difflib.HtmlDiff but it's output is less than pretty.
Is there a way in Python (or external library) that would generate clean looking HTML of the... | There's `diff_prettyHtml()` in the [diff-match-patch](https://code.google.com/p/google-diff-match-patch/) library from Google. |
Generate pretty diff html in Python | 1,576,459 | 20 | 2009-10-16T06:39:20Z | 1,579,110 | 12 | 2009-10-16T16:40:35Z | [
"python",
"html",
"diff",
"prettify"
] | I have two chunks of text that I would like to compare and see which words/lines have been added/removed/modified in Python (similar to a Wiki's Diff Output).
I have tried difflib.HtmlDiff but it's output is less than pretty.
Is there a way in Python (or external library) that would generate clean looking HTML of the... | Generally, if you want some HTML to render in a prettier way, you do it by adding CSS.
For instance, if you generate the HTML like this:
```
import difflib
import sys
fromfile = "xxx"
tofile = "zzz"
fromlines = open(fromfile, 'U').readlines()
tolines = open(tofile, 'U').readlines()
diff = difflib.HtmlDiff().make_fi... |
Why does else behave differently in for/while statements as opposed to if/try statements? | 1,576,537 | 6 | 2009-10-16T06:58:27Z | 1,576,552 | 13 | 2009-10-16T07:03:50Z | [
"python",
"flow-control"
] | I have recently stumbled over a seeming inconsistency in Python's way of dealing with else clauses in different compound statements. Since Python is so well designed, I'm sure that there is a good explanation, but I can't think of it.
Consider the following:
```
if condition:
do_something()
else:
do_something_e... | The `for else` construct executes the `else` clause if no `break` statement was executed for the loop, [as described here](http://docs.python.org/reference/compound_stmts.html#the-for-statement) For example, this else clause is never evaluated
```
for i in range(1,10):
if i % 5 == 0:
print i
break
el... |
pyqt installation problem in mac osx snow leopard | 1,576,629 | 4 | 2009-10-16T07:29:28Z | 1,583,091 | 8 | 2009-10-17T20:09:25Z | [
"python",
"osx",
"qt",
"macports"
] | I'm following a tutorial of making desktop apps. with python and qt4, I downloaded and installed qt creator ide, created the .ui file and then I had to convert it using pyuic4, I've been trying a lot of things and still can't do it.
I thought that pyuic4 would be installed with Qt creator IDE, but it seems that's not ... | I've solved it, you have to use the python of macports instead of the default that comes with OS X, to do that install python\_select through macports:
```
sudo port install python_select
sudo python_select python26
``` |
In regex, what does \w* mean? | 1,576,789 | 6 | 2009-10-16T08:23:41Z | 1,576,812 | 28 | 2009-10-16T08:27:57Z | [
"python",
"regex",
"syntax"
] | In Python. r^[\w\*]$
whats that mean? | **Quick answer:** Match a string consisting of a single character, where that character is alphanumeric (letters, numbers) an underscore (`_`) or an asterisk (`*`).
**Details:**
* The "`\w`" means "any word character" which usually means alphanumeric (letters, numbers, regardless of case) plus underscore (\_)
* The "... |
How to get path of an element in lxml? | 1,577,293 | 15 | 2009-10-16T10:24:06Z | 1,577,495 | 30 | 2009-10-16T11:23:32Z | [
"python",
"xpath",
"lxml"
] | I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:
```
page.xpath('//text()').each do |textnode|
path = textnode.path
puts path
end
```
print for example '**/html/body/div/div[1]/div[1]/p/text()[1]**' and this i... | Use [`getpath`](http://codespeak.net/lxml/api/lxml.etree.%5FElementTree-class.html#getpath) from ElementTree objects.
```
from lxml import etree
root = etree.fromstring('<foo><bar>Data</bar><bar><baz>data</baz>'
'<baz>data</baz></bar></foo>')
tree = etree.ElementTree(root)
for e in root.iter(... |
How to get path of an element in lxml? | 1,577,293 | 15 | 2009-10-16T10:24:06Z | 1,577,498 | 16 | 2009-10-16T11:24:53Z | [
"python",
"xpath",
"lxml"
] | I'm searching in a HTML document using XPath from lxml in python. How can I get the path to a certain element? Here's the example from ruby nokogiri:
```
page.xpath('//text()').each do |textnode|
path = textnode.path
puts path
end
```
print for example '**/html/body/div/div[1]/div[1]/p/text()[1]**' and this i... | See the [Xpath and XSLT with lxml from the lxml documentation](http://lxml.de/xpathxslt.html) This gives the path of the element containg the text
An example would be
```
import cStringIO
from lxml import etree
f = cStringIO.StringIO('<foo><bar><x1>hello</x1><x1>world</x1></bar></foo>')
tree = lxml.etree.parse(f)
fi... |
How can I get all days between two days? | 1,577,538 | 3 | 2009-10-16T11:33:53Z | 1,577,588 | 9 | 2009-10-16T11:45:27Z | [
"python",
"algorithm"
] | I need all the weekdays between two days.
Example:
```
Wednesday - Friday = Wednesday, Thursday, Friday
3 - 5 = 3, 4, 5
Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
6 - 2 = 6, 7, 1, 2
```
I'm pretty sure there is a clever algorithm out there to solve this. The only algorith... | How about (in pseudo code):
```
weekday[] = {"Mon" .. "Sun"}
for(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7)
printf("%s ", weekday[i]);
```
It works like a circular buffer, wkday\_start being the index to start at (0-based), wkday\_end being the end index.
Hope this helps
George. |
How can I get all days between two days? | 1,577,538 | 3 | 2009-10-16T11:33:53Z | 1,577,626 | 8 | 2009-10-16T11:52:20Z | [
"python",
"algorithm"
] | I need all the weekdays between two days.
Example:
```
Wednesday - Friday = Wednesday, Thursday, Friday
3 - 5 = 3, 4, 5
Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
6 - 2 = 6, 7, 1, 2
```
I'm pretty sure there is a clever algorithm out there to solve this. The only algorith... | ```
>>> def weekdays_between(s, e):
... return [n % 7 for n in range(s, e + (1 if e > s else 8))]
...
>>> weekdays_between(2, 4)
[2, 3, 4]
>>> weekdays_between(5, 1)
[5, 6, 0, 1]
```
It's a bit more complex if you have to convert from/to actual days.
```
>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
>>> days_... |
Replace SRC of all IMG elements using Parser | 1,579,133 | 2 | 2009-10-16T16:47:03Z | 1,579,733 | 15 | 2009-10-16T18:47:15Z | [
"python",
"html",
"parsing",
"image",
"src"
] | I am looking for a way to replace the SRC attribute in all IMG tags not using Regular expressions. (Would like to use any out-of-the box HTML parser included with default Python install) I need to reduce the source from what ever it may be to:
```
<img src="cid:imagename">
```
I am trying to replace all src tags to p... | There is a HTML parser in the Python standard library, but itâs not very useful and itâs deprecated since Python 2.6. Doing this kind of things with [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) is really easy:
```
from BeautifulSoup import BeautifulSoup
from os.path import basename, splitext
soup... |
Extremely large Boolean list in Python | 1,579,919 | 5 | 2009-10-16T19:21:27Z | 1,579,941 | 12 | 2009-10-16T19:25:29Z | [
"python",
"arrays",
"list"
] | I want to create an object in python that is a collection of around 200,000,000 true/false values. So that I can most effectively change or recall any given true/false value, so that I can quickly determine if any given number, like 123,456,000 is true or false or change its value.
Is the best way to do this a list? o... | You can try the [`bitarray`](http://pypi.python.org/pypi/bitarray) module, or write a similar thing using an [`array`](http://docs.python.org/library/array.html) of integers yourself. |
What's the best way to search for a Python dictionary value in a list of dictionaries? | 1,580,270 | 12 | 2009-10-16T20:38:11Z | 1,580,303 | 23 | 2009-10-16T20:45:26Z | [
"python"
] | I have the following data structure:
```
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
```
I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain... | ```
any(d['site'] == 'Superuser' for d in data)
``` |
What's the best way to search for a Python dictionary value in a list of dictionaries? | 1,580,270 | 12 | 2009-10-16T20:38:11Z | 1,580,304 | 7 | 2009-10-16T20:45:26Z | [
"python"
] | I have the following data structure:
```
data = [
{'site': 'Stackoverflow', 'id': 1},
{'site': 'Superuser', 'id': 2},
{'site': 'Serverfault', 'id': 3}
]
```
I want to search the above list to see if it has any site with a specific value. For instance, search the above to see if the list contain... | ```
filter( lambda x: x['site']=='Superuser', data )
``` |
How to avoid excessive parameter passing? | 1,580,792 | 2 | 2009-10-16T22:52:16Z | 1,580,848 | 7 | 2009-10-16T23:11:16Z | [
"python",
"design-patterns"
] | I am developing a medium size program in python spread across 5 modules. The program accepts command line arguments using OptionParser in the main module e.g. main.py. These options are later used to determine how methods in other modules behave (e.g. a.py, b.py). As I extend the ability for the user to customise the b... | Create objects of types relevant to your program, and store the command line options relevant to each in them. Example:
```
import WidgetFrobnosticator
f = WidgetFrobnosticator()
f.allow_oncave_widgets = option_allow_concave_widgets
f.respect_weasel_pins = option_respect_weasel_pins
# Now the methods of WidgetFrobnos... |
Python TCP stack implementation | 1,581,087 | 7 | 2009-10-17T00:50:53Z | 1,581,892 | 7 | 2009-10-17T10:19:10Z | [
"python",
"tcp",
"network-programming",
"network-protocols",
"raw-sockets"
] | Is there a python library which implements a standalone TCP stack?
I can't use the usual python socket library because I'm receiving a stream of packets over a socket (they are being tunneled to me over this socket). When I receive a TCP SYN packet addressed to a particular port, I'd like to accept the connection (sen... | You don't say which platform you are working on, but if you are working on linux, I'd open a [tun/tap interface](http://www.kernel.org/pub/linux/kernel/people/marcelo/linux-2.4/Documentation/networking/tuntap.txt) and get the IP packets back into the kernel as a real network interface so the kernel can do all that tric... |
How to draw a bitmap real quick in python using Tk only? | 1,581,799 | 3 | 2009-10-17T09:18:39Z | 1,582,896 | 12 | 2009-10-17T18:34:06Z | [
"python",
"visualization",
"tk"
] | Here is a problem. I want to visualize a specific vector field as a bitmap. It's ok with the representation itself, so I allready have some matrix of RGB lists like [255,255,115], but I have no good idea of how to draw it on screen. So far I make thousands of colored 1px rectangles, but this works too slow. I'm sure th... | **ATTEMPT 3 - I swear last one...**
I believe this is the fastest pure TK way to do this. Generates 10,000 RGB values in a list of lists, creates a Tkinter.PhotoImage and then puts the pixel values into it.
```
import Tkinter, random
class App:
def __init__(self, t):
self.i = Tkinter.PhotoImage(width=100,... |
How check if a task is already in python Queue? | 1,581,895 | 10 | 2009-10-17T10:21:43Z | 1,581,937 | 10 | 2009-10-17T10:46:37Z | [
"python",
"multithreading",
"queue"
] | I'm writing a simple crawler in Python using the threading and Queue modules. I fetch a page, check links and put them into a queue, when a certain thread has finished processing page, it grabs the next one from the queue. I'm using an array for the pages I've already visited to filter the links I add to the queue, but... | If you don't care about the order in which items are processed, I'd try a subclass of `Queue` that uses `set` internally:
```
class SetQueue(Queue):
def _init(self, maxsize):
self.maxsize = maxsize
self.queue = set()
def _put(self, item):
self.queue.add(item)
def _get(self):
... |
Dynamic URL with CherryPY MethodDispatcher | 1,582,297 | 10 | 2009-10-17T14:19:25Z | 1,582,444 | 9 | 2009-10-17T15:27:00Z | [
"python",
"rest",
"cherrypy"
] | I need to configure a RESTful style URL that support the following URL scheme:
* /parent/
* /parent/1
* /parent/1/children
* /parent/1/chidren/1
I want to use the MethodDispatcher so that each of the above can have GET/POST/PUT/DELETE functions. I have it working for the first and second, but can't figure out how to ... | <http://tools.cherrypy.org/wiki/RestfulDispatch> might be what you're looking for.
In CherryPy 3.2 (just now coming out of beta), there will be a new `_cp_dispatch` method you can use in your object tree to do the same thing, or even alter traversal as it happens, somewhat along the lines of Quixote's `_q_lookup` and ... |
Long, slow operation in Django view causes timeout. Any way for Python to speak AJAX instead? | 1,582,708 | 5 | 2009-10-17T17:19:45Z | 1,582,971 | 7 | 2009-10-17T19:09:27Z | [
"python",
"ajax",
"django",
"timeout"
] | I've been programming Python a while, but DJango and web programming in general is new to me.
I have a very long operation performed in a Python view. Since the local() function in my view takes so long to return, there's an HTTP timeout. Fair enough, I understand that part.
What's the best way to give an HTTPrespons... | Ajax doesn't require any particular technology on the server side. All you need is to return a response in some form that some Javascript on the client side can understand. JSON is an excellent choice here, as it's easy to create in Python (there's a `json` library in 2.6, and Django has `django.utils.simplejson` for o... |
edit text file using Python | 1,582,750 | 6 | 2009-10-17T17:35:22Z | 2,363,893 | 23 | 2010-03-02T14:43:26Z | [
"python",
"text",
"editing"
] | I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.
1. Create variable LASTKNOWN = "212.171.135.53"
This is the ip address we have while writing this script.
2. Get the current IP address. It will change on a daily basis.
3. Create variable CURRENT for... | Another way to simply edit files in place is to use the [`fileinput`](http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Ffileinput.html&ei=TGeZUPCRHOfP0QXQhIHAAw&usg=AFQjCNEmKT3Z55eqWRpCJIDCDyy1ACOGhg) module:
```
import fileinput, sys
fo... |
pycurl installation on Windows | 1,582,814 | 12 | 2009-10-17T17:57:36Z | 3,817,095 | 29 | 2010-09-28T21:12:00Z | [
"python",
"libcurl",
"pycurl"
] | I am not able to install pycurl on Windows on Python2.6. Getting following error:
```
C:\Documents and Settings\vijayendra\Desktop\Downloads\pycurl-7.19.0>python setup.py install --curl-dir="C:\Documents and Settings\vijayendra\Desktop\Downloads\
curl-7.19.5-win32-ssl\curl-7.19.5"
Using curl directory: C:\Documents an... | Andelf's answer didn't work on my Win 7 x64 machine, but [Christoph Gohlke's site](http://www.lfd.uci.edu/~gohlke/pythonlibs/) has a package that works for me. |
Python: Int not iterable errror | 1,583,148 | 5 | 2009-10-17T20:42:08Z | 1,583,189 | 7 | 2009-10-17T20:56:49Z | [
"python"
] | I'm attempting to get my feet wet with python on Project Euler, but I'm having an issue with the first problem (find the sum of the multiples of 3 or 5 up to 1,000). I can successfully print out multiples of three and five, but when I attempt to include the sum function I get the following error:
> TypeError: 'int' ob... | In the for-loop
```
for numbers in x:
```
"numbers" steps through the elements in x one at a time, for each pass through the loop.
It would be perhaps better to name the variable "number" because you are only getting
one number at a time. "numbers" equals an integer each time through the loop.
```
sum(numbers)
```
... |
Idiomatic Python has_one | 1,583,364 | 3 | 2009-10-17T22:23:15Z | 1,583,465 | 10 | 2009-10-17T23:09:55Z | [
"python",
"idioms"
] | I just invented a stupid little helper function:
```
def has_one(seq, predicate=bool):
"""Return whether there is exactly one item in `seq` that matches
`predicate`, with a minimum of evaluation (short-circuit).
"""
iterator = (item for item in seq if predicate(item))
try:
iterator.next()
... | How about calling [`any`](http://docs.python.org/3.1/library/functions.html#any) twice, on an iterator (Python 2.x and 3.x compatible)?
```
>>> def has_one(seq, predicate=bool):
... seq = (predicate(e) for e in seq)
... return any(seq) and not any(seq)
...
>>> has_one([])
False
>>> has_one([1])
True
>>> has_o... |
What does "lambda" mean in Python, and what's the simplest way to use it? | 1,583,617 | 10 | 2009-10-18T00:44:25Z | 1,583,630 | 26 | 2009-10-18T00:50:12Z | [
"python",
"lambda"
] | Can you give an example and other examples that show when and when not to use Lambda?
My book gives me examples, but they're confusing. | Lambda, which originated from [Lambda Calculus](http://en.wikipedia.org/wiki/Lambda%5Fcalculus) and (AFAIK) was first implemented in [Lisp](http://en.wikipedia.org/wiki/Lisp%5F%28programming%5Flanguage%29), is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words yo... |
Return value while using cProfile | 1,584,425 | 12 | 2009-10-18T09:04:26Z | 1,584,468 | 24 | 2009-10-18T09:39:37Z | [
"python"
] | I'm trying to profile an instance method, so I've done something like:
```
import cProfile
class Test():
def __init__(self):
pass
def method(self):
cProfile.runctx("self.method_actual()", globals(), locals())
def method_actual(self):
print "Run"
if __name__ == "__main__":
T... | I discovered that you can do this:
```
prof = cProfile.Profile()
retval = prof.runcall(self.method_actual, *args, **kwargs)
prof.dump_stats(datafn)
```
The downside is that it's undocumented. |
Return value while using cProfile | 1,584,425 | 12 | 2009-10-18T09:04:26Z | 17,259,420 | 10 | 2013-06-23T09:35:45Z | [
"python"
] | I'm trying to profile an instance method, so I've done something like:
```
import cProfile
class Test():
def __init__(self):
pass
def method(self):
cProfile.runctx("self.method_actual()", globals(), locals())
def method_actual(self):
print "Run"
if __name__ == "__main__":
T... | An option for any arbitrary code:
```
import cProfile, pstats, sys
pr = cProfile.Profile()
pr.enable()
...
my_return_val = my_func(my_arg)
...
pr.disable()
ps = pstats.Stats(pr, stream=sys.stdout)
ps.print_stats()
```
Taken from <https://docs.python.org/2/library/profile.html#profile.Profile> |
Python things which are neither True nor False | 1,584,733 | 10 | 2009-10-18T12:09:00Z | 1,584,743 | 8 | 2009-10-18T12:13:37Z | [
"python",
"boolean"
] | I just found this :
```
a = (None,)
print (a is True)
print (a is False)
print (a == True)
print (a == False)
print (a == None)
print (a is None)
if a : print "hello"
if not a : print "goodbye"
```
which produces :
```
False
False
False
False
False
False
hello
```
So a neither is, nor equals True nor False, but act... | `a` is a one-member tuple, which evaluates to `True`. `is` test identity of the object, therefore, you get `False` in all those test. `==` test equality of the objects, therefore, you get `False` again.
in `if` statement a `__bool__` (or `__nonzero__`) used to evaluate the object, for a non-empty tuple it should retur... |
Python things which are neither True nor False | 1,584,733 | 10 | 2009-10-18T12:09:00Z | 1,584,865 | 12 | 2009-10-18T13:12:54Z | [
"python",
"boolean"
] | I just found this :
```
a = (None,)
print (a is True)
print (a is False)
print (a == True)
print (a == False)
print (a == None)
print (a is None)
if a : print "hello"
if not a : print "goodbye"
```
which produces :
```
False
False
False
False
False
False
hello
```
So a neither is, nor equals True nor False, but act... | I find almost all the explanations here unhelpful, so here is another try:
The confusion here is based on that testing with "is", "==" and "if" are three different things.
* "is" tests identity, that is, if it's the same object. That is obviously not true in this case.
* "==" tests value equality, and obviously the o... |
Is the Python GIL really per interpreter? | 1,585,181 | 8 | 2009-10-18T15:35:23Z | 1,585,939 | 7 | 2009-10-18T20:25:55Z | [
"python",
"multithreading",
"gil"
] | I often see people talking that the GIL is per Python Interpreter (even here on stackoverflow).
But what I see in the source code it seems to be that the GIL is a global variable and therefore there is one GIL for all Interpreters in each python process. I know they did this because there is no interpreter object pass... | The GIL is indeed per-process, not per-interpreter. This is unchanged in 3.x. |
Python optional parameters | 1,585,247 | 23 | 2009-10-18T16:05:44Z | 1,585,265 | 15 | 2009-10-18T16:11:36Z | [
"python",
"optional-arguments"
] | Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:
```
class B:
pass
class A:
def __init__(self, builds = B()):
self.builds = builds
```
If I create A twice
```
b = A()
c = A()
```
and print their builds
```
print b.builds
print c.b... | you need to do the following:
```
class A:
def __init__(self, builds=None):
if builds is None:
builds = B()
self.builds = builds
```
it's a very wide-spread error, using mutable parameters as a default arguments. there are plenty of dupes probably on SO. |
Python optional parameters | 1,585,247 | 23 | 2009-10-18T16:05:44Z | 1,585,451 | 45 | 2009-10-18T17:10:36Z | [
"python",
"optional-arguments"
] | Guys, I just started python recently and get confused with the optional parameters, say I have the program like this:
```
class B:
pass
class A:
def __init__(self, builds = B()):
self.builds = builds
```
If I create A twice
```
b = A()
c = A()
```
and print their builds
```
print b.builds
print c.b... | You need to understand how default values work in order to use them effectively.
Functions are objects. As such, they have attributes. So, if I create this function:
```
>>> def f(x, y=[]):
y.append(x)
return y
```
I've created an object. Here are its attributes:
```
>>> dir(f)
['__call__', '__class... |
Is there a way to perform "if" in python's lambda | 1,585,322 | 119 | 2009-10-18T16:28:03Z | 1,585,334 | 10 | 2009-10-18T16:31:18Z | [
"python",
"lambda"
] | In **python 2.6**, I want to do:
```
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
```
This clearly isn't the syntax. Is it possible to perform an `if` in `lambda` and if so how to do it?
thanks | Lambdas in Python are fairly restrictive with regard to what you're allowed to use. Specifically, you can't have any keywords (except for operators like `and`, `not`, `or`, etc) in their body.
So, there's no way you could use a lambda for your example (because you can't use `raise`), but if you're willing to concede o... |
Is there a way to perform "if" in python's lambda | 1,585,322 | 119 | 2009-10-18T16:28:03Z | 1,585,343 | 26 | 2009-10-18T16:33:17Z | [
"python",
"lambda"
] | In **python 2.6**, I want to do:
```
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
```
This clearly isn't the syntax. Is it possible to perform an `if` in `lambda` and if so how to do it?
thanks | why don't you just define a function?
```
def f(x):
if x == 2:
print(x)
else:
raise ValueError
```
there really is no justification to use lambda in this case. |
Is there a way to perform "if" in python's lambda | 1,585,322 | 119 | 2009-10-18T16:28:03Z | 1,585,396 | 268 | 2009-10-18T16:48:43Z | [
"python",
"lambda"
] | In **python 2.6**, I want to do:
```
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
```
This clearly isn't the syntax. Is it possible to perform an `if` in `lambda` and if so how to do it?
thanks | The syntax you're looking for:
```
lambda x: True if x % 2 == 0 else False
```
But you can't use `print` or `raise` in a lambda. |
Is there a way to perform "if" in python's lambda | 1,585,322 | 119 | 2009-10-18T16:28:03Z | 1,586,124 | 13 | 2009-10-18T21:48:06Z | [
"python",
"lambda"
] | In **python 2.6**, I want to do:
```
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
```
This clearly isn't the syntax. Is it possible to perform an `if` in `lambda` and if so how to do it?
thanks | You can easily raise an exception in a lambda, if that's what you really want to do.
```
def Raise(exception):
raise exception
x = lambda y: 1 if y < 2 else Raise(ValueError("invalid value"))
```
Is this a good idea? My instinct in general is to leave the error reporting out of lambdas; let it have a value of Non... |
Is there a way to perform "if" in python's lambda | 1,585,322 | 119 | 2009-10-18T16:28:03Z | 33,251,758 | 9 | 2015-10-21T05:43:22Z | [
"python",
"lambda"
] | In **python 2.6**, I want to do:
```
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
```
This clearly isn't the syntax. Is it possible to perform an `if` in `lambda` and if so how to do it?
thanks | Probably the worst python line I've written so far:
```
f = lambda x: sys.stdout.write(["2\n",][2*(x==2)-2])
```
If x == 2 you print,
if x != 2 you raise. |
How to generate random 'greenish' colors | 1,586,147 | 32 | 2009-10-18T22:00:37Z | 1,586,157 | 54 | 2009-10-18T22:04:37Z | [
"python",
"language-agnostic",
"random",
"colors"
] | Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
```
color = (randint(100, 200), randint(120, 255), randint(100, 200))
```
That mostly works, but I get brownish colors a lot. | Simple solution: **Use the [HSL or HSV](http://en.wikipedia.org/wiki/HSL%5Fand%5FHSV) color space** instead of rgb (convert it to RGB afterwards if you need this). The difference is the meaning of the tuple: Where RGB means values for Red, Green and Blue, in HSL the H is the color (120 degree or 0.33 meaning green for ... |
How to generate random 'greenish' colors | 1,586,147 | 32 | 2009-10-18T22:00:37Z | 1,586,163 | 16 | 2009-10-18T22:09:00Z | [
"python",
"language-agnostic",
"random",
"colors"
] | Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
```
color = (randint(100, 200), randint(120, 255), randint(100, 200))
```
That mostly works, but I get brownish colors a lot. | Check out the `colorsys` module:
<http://docs.python.org/library/colorsys.html>
Use the HSL or HSV color space. Randomize the hue to be close to green, then choose completely random stuff for the saturation and V (brightness). |
How to generate random 'greenish' colors | 1,586,147 | 32 | 2009-10-18T22:00:37Z | 1,586,291 | 20 | 2009-10-18T23:10:07Z | [
"python",
"language-agnostic",
"random",
"colors"
] | Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
```
color = (randint(100, 200), randint(120, 255), randint(100, 200))
```
That mostly works, but I get brownish colors a lot. | As others have suggested, generating random colours is much easier in the HSV colour space (or HSL, the difference is pretty irrelevant for this)
So, code to generate random "green'ish" colours, and (for demonstration purposes) display them as a series of simple coloured HTML span tags:
```
#!/usr/bin/env python2.5
"... |
How to generate random 'greenish' colors | 1,586,147 | 32 | 2009-10-18T22:00:37Z | 1,586,296 | 9 | 2009-10-18T23:13:10Z | [
"python",
"language-agnostic",
"random",
"colors"
] | Anyone have any suggestions on how to make randomized colors that are all greenish? Right now I'm generating the colors by this:
```
color = (randint(100, 200), randint(120, 255), randint(100, 200))
```
That mostly works, but I get brownish colors a lot. | If you stick with RGB, you basically just need to make sure the G value is greater than the R and B, and try to keep the blue and red values similar so that the hue doesn't go too crazy. Extending from Slaks, maybe something like (I know next to nothing about Python):
```
greenval = randint(100, 255)
redval = randint(... |
Race-condition creating folder in Python | 1,586,648 | 13 | 2009-10-19T01:52:13Z | 1,586,668 | 11 | 2009-10-19T02:00:27Z | [
"python",
"caching",
"race-condition"
] | I have a urllib2 caching module, which sporadically crashes because of the following code:
```
if not os.path.exists(self.cache_location):
os.mkdir(self.cache_location)
```
The problem is, by the time the second line is being executed, the folder may exist, and will error:
```
File ".../cache.py", line 103, in... | Instead of
```
if not os.path.exists(self.cache_location):
os.mkdir(self.cache_location)
```
you could do
```
try:
os.makedirs(self.cache_location)
except OSError:
pass
```
As you would end up with the same *functionality*.
DISCLAIMER: I don't know how Pythonic this might be.
---
Using `SQLite3`, *mi... |
Lazy infinite sequences in Clojure and Python | 1,587,412 | 15 | 2009-10-19T07:47:41Z | 1,587,582 | 36 | 2009-10-19T08:45:49Z | [
"python",
"clojure"
] | Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:
Clojure:
```
(def fib-seq (lazy-cat [0 1]
(map + fib-seq (rest fib-seq))))
```
sample usage:
```
(take 5 fib-seq)
```
Python:
```
def fib():
a = b = 1
while True:
yield a
a,b = b,a+b... | I agree with Pavel, what is intuitive is subjective. Because I'm (slowly) starting to grok Haskell, I can tell what the Clojure code does, even though I've never written a line of Clojure in my life. So I would consider the Clojure line fairly intuitive, because I've seen it before and I'm adapting to a more functional... |
Lazy infinite sequences in Clojure and Python | 1,587,412 | 15 | 2009-10-19T07:47:41Z | 1,590,548 | 12 | 2009-10-19T19:16:12Z | [
"python",
"clojure"
] | Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:
Clojure:
```
(def fib-seq (lazy-cat [0 1]
(map + fib-seq (rest fib-seq))))
```
sample usage:
```
(take 5 fib-seq)
```
Python:
```
def fib():
a = b = 1
while True:
yield a
a,b = b,a+b... | If you didn't know any imperative languages, would this be intuitive for you?
```
a = a + 5
```
WTF? `a` *clearly* isn't the same as `a + 5`.
if `a = a + 5`, is `a + 5 = a`?
Why doesn't this work???
```
if (a = 5) { // should be == in most programming languages
// do something
}
```
There are a lot of things ... |
Lazy infinite sequences in Clojure and Python | 1,587,412 | 15 | 2009-10-19T07:47:41Z | 3,547,483 | 14 | 2010-08-23T12:25:30Z | [
"python",
"clojure"
] | Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:
Clojure:
```
(def fib-seq (lazy-cat [0 1]
(map + fib-seq (rest fib-seq))))
```
sample usage:
```
(take 5 fib-seq)
```
Python:
```
def fib():
a = b = 1
while True:
yield a
a,b = b,a+b... | I like:
```
(def fibs
(map first
(iterate
(fn [[ a, b ]]
[ b, (+ a b) ])
[0, 1])))
```
Which seems to have some similarities to the python/generator version. |
Light-weight renderer HTML with CSS in Python | 1,587,637 | 7 | 2009-10-19T09:03:32Z | 1,587,703 | 10 | 2009-10-19T09:21:37Z | [
"python",
"html",
"browser"
] | Sorry, perhaps I haven't described the problem well first time. All your answers are interesting, but most of them are almost full-featured web browsers, my task is much simpler.
I'm planning to write a GUI application using one of the available on linux GUI frameworks (I haven't yet chosen one). I shall use html in m... | You should use a UI framework:
* Qt: The simplest class to use would be [QWebView](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwebview.html)
* Gtk: pywebkitgtk would be the best answer, but you can find [others in the PyGTK page](http://faq.pygtk.org/index.py?file=faq19.001.htp&req=show).
* In Tk is th... |
how to determine if webpage has been modified | 1,587,902 | 6 | 2009-10-19T10:13:46Z | 1,587,919 | 8 | 2009-10-19T10:19:21Z | [
"python",
"diff",
"webpage",
"snapshot"
] | I have snapshots of multiple webpages taken at 2 times. What is a reliable method to determine which webpages have been modified?
I can't rely on something like an RSS feed, and I need to ignore minor noise like date text.
Ideally I am looking for a Python solution, but an intuitive algorithm would also be great.
Th... | Well, first you need to decide what is noise and what isn't. You can use a HTML parser like [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) to remove the noise, pretty-print the result, and compare it as a string.
If you are looking for an automatic solution, you can use [`difflib.SequenceMatcher`](http... |
Read two variables in a single line with Python | 1,588,058 | 5 | 2009-10-19T11:00:21Z | 1,588,071 | 21 | 2009-10-19T11:02:53Z | [
"python",
"input"
] | I am familiar with the input() function, to read a single variable from user input. Is there a similar easy way to read two variables?
I'm looking for the equivalent of:
```
scanf("%d%d", &i, &j); // accepts "10 20\n"
```
One way I am able to achieve this is to use `raw_input()` and then `split` what was entered. Is... | No, the usual way is `raw_input().split()`
In your case you might use `map(int, raw_input().split())` if you want them to be integers rather than strings
Don't use `input()` for that. Consider what happens if the user enters
> `import os;os.system('do something bad')` |
How to prepare a django project for future changes | 1,588,570 | 8 | 2009-10-19T13:04:09Z | 1,588,702 | 8 | 2009-10-19T13:35:51Z | [
"python",
"database",
"django"
] | As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new a... | * Deploy into a pure environment using [virtualenv](http://pypi.python.org/pypi/virtualenv).
* Document requirements using a [pip](http://pip.openplans.org/) requirements file.
I'm sure others will suggest their deployment strategies, but making these changes were big positives for me. |
How to prepare a django project for future changes | 1,588,570 | 8 | 2009-10-19T13:04:09Z | 1,590,806 | 7 | 2009-10-19T20:06:32Z | [
"python",
"database",
"django"
] | As I work on my first django powered site, I am constantly learning new things and making all sorts of changes and additions to my apps as I go. I try to follow DRY and pythonic principles and be smart in my coding but eventually I will have to take the site live and am certain that not long after I do, something new a... | Learn and use South at the outset, so when you make major DB schema changes, you'll have a migration tool already in place. Otherwise, you'll find you end up running two versions side by side while trying to figure out how to port the data, and it gets very VERY messy.
<http://south.aeracode.org/> |
What are the use cases for non relational datastores? | 1,588,708 | 3 | 2009-10-19T13:36:49Z | 1,588,758 | 7 | 2009-10-19T13:44:25Z | [
"python",
"google-app-engine",
"couchdb"
] | I'm looking at using CouchDB for one project and the GAE app engine datastore in the other. For relational stuff I tend to use postgres, although I much prefer an ORM.
Anyway, what use cases suit non relational datastores best? | Here is a nice little article (spread over three pages) that covers the use-case for non-relational databases.
<http://www.readwriteweb.com/enterprise/2009/02/is-the-relational-database-doomed.php>
In a nutshell, when you need massive scalability then you probably need a non-realtional db. Of course, you may well end... |
Nested Function in Python | 1,589,058 | 46 | 2009-10-19T14:40:51Z | 1,589,162 | 7 | 2009-10-19T14:55:37Z | [
"python",
"nested-function"
] | What benefit or implications could we get with Python code like this:
```
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
```
I found this in an open-source project, doing something useful inside the nested function, but doing absolute... | I can't image any good reason for code like that.
Maybe there was a reason for the inner function in older revisions, like other Ops.
For example, this makes *slightly* more sense:
```
class some_class(parent_class):
def doOp(self, op, x, y):
def add(x, y):
return x + y
def sub(x,y):
... |
Nested Function in Python | 1,589,058 | 46 | 2009-10-19T14:40:51Z | 1,589,209 | 35 | 2009-10-19T15:03:11Z | [
"python",
"nested-function"
] | What benefit or implications could we get with Python code like this:
```
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
```
I found this in an open-source project, doing something useful inside the nested function, but doing absolute... | Aside from function generators, where internal function creation is almost the definition of a function generator, the reason I create nested functions is to improve readability. If I have a tiny function that will only be invoked by the outer function, then I inline the definition so you don't have to skip around to d... |
Nested Function in Python | 1,589,058 | 46 | 2009-10-19T14:40:51Z | 1,589,606 | 67 | 2009-10-19T16:05:56Z | [
"python",
"nested-function"
] | What benefit or implications could we get with Python code like this:
```
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
```
I found this in an open-source project, doing something useful inside the nested function, but doing absolute... | Normally you do it to make *[closures](http://en.wikipedia.org/wiki/Closure%5F%28computer%5Fscience%29)*:
```
def make_adder(x):
def add(y):
return x + y
return add
plus5 = make_adder(5)
print(plus5(12)) # prints 17
```
Inner functions can access variables from the enclosing scope (in this case, the... |
Nested Function in Python | 1,589,058 | 46 | 2009-10-19T14:40:51Z | 13,397,600 | 17 | 2012-11-15T12:32:05Z | [
"python",
"nested-function"
] | What benefit or implications could we get with Python code like this:
```
class some_class(parent_class):
def doOp(self, x, y):
def add(x, y):
return x + y
return add(x, y)
```
I found this in an open-source project, doing something useful inside the nested function, but doing absolute... | One potential benefit of using inner methods is that it allows you to use outer method local variables without passing them as arguments.
```
def helper(feature, resultBuffer):
resultBuffer.print(feature)
resultBuffer.printLine()
resultBuffer.flush()
def save(item, resultBuffer):
helper(item.description, res... |
Python XMLRPC with concurrent requests | 1,589,150 | 5 | 2009-10-19T14:54:08Z | 1,589,936 | 11 | 2009-10-19T17:12:22Z | [
"python",
"xml-rpc"
] | I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming reques... | I think python SimpleXMLRPCServer module is what you want. I believe the default behavior of that model is blocking new requests when current request is processing. The default behavior gave me lots of trouble and I changed that behavior by mix in ThreadingMixIn class so that my xmlrpc server could respond multiple req... |
Iterating over arbitrary dimension of numpy.array | 1,589,706 | 21 | 2009-10-19T16:27:11Z | 1,593,130 | 24 | 2009-10-20T08:13:50Z | [
"python",
"numpy",
"loops"
] | Is there function to get an iterator over an arbitrary dimension of a numpy array?
Iterating over the first dimension is easy...
```
In [63]: c = numpy.arange(24).reshape(2,3,4)
In [64]: for r in c :
....: print r
....:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22... | What you propose is quite fast, but the legibility can be improved with the clearer forms:
```
for i in range(c.shape[-1]):
print c[:,:,i]
```
or, better (faster and more explicit):
```
for i in range(c.shape[-1]):
print c[...,i]
```
However, the first approach above appears to be about twice as slow as the... |
Iterating over arbitrary dimension of numpy.array | 1,589,706 | 21 | 2009-10-19T16:27:11Z | 5,923,332 | 10 | 2011-05-07T19:05:11Z | [
"python",
"numpy",
"loops"
] | Is there function to get an iterator over an arbitrary dimension of a numpy array?
Iterating over the first dimension is easy...
```
In [63]: c = numpy.arange(24).reshape(2,3,4)
In [64]: for r in c :
....: print r
....:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22... | I'd use the following:
```
c = numpy.arange(2 * 3 * 4)
c.shape = (2, 3, 4)
for r in numpy.rollaxis(c, 2):
print(r)
```
The function **rollaxis** creates a new view on the array. In this case it's moving axis 2 to the front, equivalent to the operation `c.transpose(2, 0, 1)`. |
Python: Difference between 'global' & globals().update(var) | 1,589,968 | 7 | 2009-10-19T17:19:12Z | 1,590,016 | 16 | 2009-10-19T17:29:41Z | [
"python",
"variables",
"global"
] | What is the difference between initializing a variable as `global var` or calling `globals().update(var)`.
Thanks | When you say
```
global var
```
you are telling Python that var is the same var that was defined in a global context.
You would use it in the following way:
```
var=0
def f():
global var
var=1
f()
print(var)
# 1 <---- the var outside the "def f" block is affected by calling f()
```
Without the global state... |
How do I write a unix filter in python? | 1,589,994 | 9 | 2009-10-19T17:24:43Z | 1,590,013 | 13 | 2009-10-19T17:28:44Z | [
"python",
"unix",
"filter"
] | I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars `x` from stdin. | Read from `sys.stdin` and write to `sys.stdout` (or use `print`). Your example program:
```
import sys
for line in sys.stdin:
print line.replace("x", ""),
```
There isn't a standard way to make stdin unbuffered, and you don't want that. Let the OS buffer it. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.