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 |
|---|---|---|---|---|---|---|---|---|---|
python subprocess communicate() block | 2,133,345 | 14 | 2010-01-25T15:36:36Z | 2,133,383 | 22 | 2010-01-25T15:41:06Z | [
"python",
"subprocess",
"blocking"
] | I am using the *subprocess* module to call an external program (plink.exe) to log-in to a server; but when I call communicate to read the output, it is blocking. The code is below:
```
import subprocess
process = subprocess.Popen('plink.exe hello@10.120.139.170 -pw 123456'.split(), shell=False, stdout=subprocess.PIP... | The whole purpose of the `communicate` method is to wait for the process to finish and return all the output. If you don't want to wait, don't call `communicate`. Instead, read from the `stdout` or `stderr` attribute to read the output.
If the process outputs to both `stdout` and `stderr` (and you want to read it sepa... |
django: gettext and coercing to unicode | 2,133,508 | 6 | 2010-01-25T15:57:06Z | 2,133,690 | 20 | 2010-01-25T16:20:00Z | [
"python",
"django",
"unicode",
"gettext"
] | I have following code in my django application.
```
class Status(object):
def __init__(self, id, desc):
self.id = id
self.desc = desc
def __unicode__(self):
return self.desc
STATUS = Status(0, _(u"Some text"))
```
When I try to display some status (or even coerce it to unicode), I g... | The `_()` function from Django can return a `django.utils.functional.__proxy__` object, which is itself not unicode (see <http://docs.djangoproject.com/en/1.1/ref/unicode/#translated-strings>). Python does not call `unicode()` recursively, so it's an error for your Status object to return the `__proxy__` object directl... |
Most Pythonic way to concatenate strings | 2,133,571 | 21 | 2010-01-25T16:04:36Z | 2,133,580 | 50 | 2010-01-25T16:05:45Z | [
"python",
"concatenation"
] | Given this harmless little list:
```
>>> lst = ['o','s','s','a','m','a']
```
My goal is to pythonically concatenate the little devils using one of the following ways:
A. plain ol' string function to get the job done, short, no imports
```
>>> ''.join(lst)
'ossama'
```
B. lambda, lambda, lambda
```
>>> reduce(lamb... | ```
''.join(lst)
```
the only pythonic way:
* clear (that what all the big boys do and what they expect to see),
* simple (no additional imports needed, stable across all versions),
* fast (written in C) and
* concise (on an empty string join elements of iterable!). |
Most Pythonic way to concatenate strings | 2,133,571 | 21 | 2010-01-25T16:04:36Z | 2,133,605 | 28 | 2010-01-25T16:08:48Z | [
"python",
"concatenation"
] | Given this harmless little list:
```
>>> lst = ['o','s','s','a','m','a']
```
My goal is to pythonically concatenate the little devils using one of the following ways:
A. plain ol' string function to get the job done, short, no imports
```
>>> ''.join(lst)
'ossama'
```
B. lambda, lambda, lambda
```
>>> reduce(lamb... | Have a look at Guido's [essay](http://www.python.org/doc/essays/list2str/) on python optimization, it covers converting lists of numbers to strings. Unless you have a *good* reason to do otherwise, use the `join` example. |
Most Pythonic way to concatenate strings | 2,133,571 | 21 | 2010-01-25T16:04:36Z | 2,134,393 | 15 | 2010-01-25T17:59:09Z | [
"python",
"concatenation"
] | Given this harmless little list:
```
>>> lst = ['o','s','s','a','m','a']
```
My goal is to pythonically concatenate the little devils using one of the following ways:
A. plain ol' string function to get the job done, short, no imports
```
>>> ''.join(lst)
'ossama'
```
B. lambda, lambda, lambda
```
>>> reduce(lamb... | Of course it's `join`. How do I know? Let's do it in a really stupid way:
If the problem was only adding 2 strings, you'd most likely use `str1 + str2`. What does it take to get that to the next level? Instinctively, for most (I think), will be to use `sum`. Let's see how that goes:
```
In [1]: example = ['a', 'b', ... |
XQuery library under Python | 2,133,648 | 14 | 2010-01-25T16:15:14Z | 2,133,842 | 11 | 2010-01-25T16:39:02Z | [
"python",
"api",
"xquery"
] | Hey
Is there any existing way to run XQuery under python? (not starting to build a parser yourself in other words).
I got a ton of legacy XQuery that I want to port to our new system, or rather I want to
port the framework and not XQuery.
Therefore: Is there any library that allows me to run XQuery under python? | **Sort of ...**
Looking through the [W3C implementations list for XQuery](http://www.w3.org/XML/Query/#implementations) there is:
1. [Python bindings for Zorba](http://www.zorba-xquery.com/)
2. [Sedna](http://modis.ispras.ru/sedna/index.html) is a free native XML database with API for [Python](https://pypi.python.org... |
python select specific elements from a list | 2,134,539 | 19 | 2010-01-25T18:21:19Z | 2,134,551 | 7 | 2010-01-25T18:24:21Z | [
"python",
"list"
] | Is there a "pythonic" way of getting only certain values from a list, similar to this perl code:
```
my ($one,$four,$ten) = line.split(/,/)[1,4,10]
``` | ```
lst = line.split(',')
one, four, ten = lst[1], lst[4], lst[10]
``` |
python select specific elements from a list | 2,134,539 | 19 | 2010-01-25T18:21:19Z | 2,134,570 | 18 | 2010-01-25T18:26:35Z | [
"python",
"list"
] | Is there a "pythonic" way of getting only certain values from a list, similar to this perl code:
```
my ($one,$four,$ten) = line.split(/,/)[1,4,10]
``` | I think you are looking for `operator.itemgetter`:
```
import operator
line=','.join(map(str,range(11)))
print(line)
# 0,1,2,3,4,5,6,7,8,9,10
alist=line.split(',')
print(alist)
# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
one,four,ten=operator.itemgetter(1,4,10)(alist)
print(one,four,ten)
# ('1', '4', '1... |
python select specific elements from a list | 2,134,539 | 19 | 2010-01-25T18:21:19Z | 9,286,644 | 12 | 2012-02-15T01:17:44Z | [
"python",
"list"
] | Is there a "pythonic" way of getting only certain values from a list, similar to this perl code:
```
my ($one,$four,$ten) = line.split(/,/)[1,4,10]
``` | Using a list comprehension
```
line = '0,1,2,3,4,5,6,7,8,9,10'
lst = line.split(',')
one, four, ten = [lst[i] for i in [1,4,10]]
``` |
Hitting Maximum Recursion Depth Using Python's Pickle / cPickle | 2,134,706 | 28 | 2010-01-25T18:49:42Z | 2,135,176 | 22 | 2010-01-25T19:58:23Z | [
"python",
"recursion",
"tree",
"pickle",
"depth"
] | The background: I'm building a trie to represent a dictionary, using a minimal construction algorithm. The input list is 4.3M utf-8 strings, sorted lexicographically. The resulting graph is acyclic and has a maximum depth of 638 nodes. The first line of my script sets the recursion limit to 1100 via `sys.setrecursionli... | From [the docs](http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled):
> Trying to pickle a highly recursive data structure may exceed the maximum recursion depth, a RuntimeError will be raised in this case. You can carefully raise this limit with `sys.setrecursionlimit()`.
Although your trie ... |
Hitting Maximum Recursion Depth Using Python's Pickle / cPickle | 2,134,706 | 28 | 2010-01-25T18:49:42Z | 2,135,784 | 8 | 2010-01-25T21:28:36Z | [
"python",
"recursion",
"tree",
"pickle",
"depth"
] | The background: I'm building a trie to represent a dictionary, using a minimal construction algorithm. The input list is 4.3M utf-8 strings, sorted lexicographically. The resulting graph is acyclic and has a maximum depth of 638 nodes. The first line of my script sets the recursion limit to 1100 via `sys.setrecursionli... | Pickle does need to recursively walk your trie. If Pickle is using just 5 levels of function calls to do the work your trie of depth 638 will need the level set to more than 3000.
Try a much bigger number, the recursion limit is really just there to protect users from having to wait too long if the recursion falls in ... |
How can I make this long_description and README differ by a couple of sentences? | 2,134,941 | 6 | 2010-01-25T19:22:02Z | 2,140,899 | 7 | 2010-01-26T16:41:32Z | [
"python",
"github",
"setuptools",
"distutils",
"pypi"
] | For a package of mine, I have a README.rst file that is read into the setup.py's long description like so:
```
readme = open('README.rst', 'r')
README_TEXT = readme.read()
readme.close()
setup(
...
long_description = README_TEXT,
....
)
```
This way that I can have the README file show up on my [gith... | You can just use a ReST comment with some text like "split here", and then split on that in your setup.py. Ian Bicking does that in virtualenv with [index.txt](http://bitbucket.org/ianb/virtualenv/src/77d301cdbf8c/docs/index.txt) and [setup.py](http://bitbucket.org/ianb/virtualenv/src/tip/setup.py). |
Using LaTeX Beamer to display code | 2,135,339 | 5 | 2010-01-25T20:20:50Z | 2,135,475 | 9 | 2010-01-25T20:41:47Z | [
"python",
"latex",
"beamer"
] | I'm using the following LaTeX code in a Beamer presentation:
```
\begin{frame}
\begin{figure}
\centering
\tiny
\lstset{language=python}
\lstinputlisting{code/get_extent.py}
\end{figure}
\end{frame}
```
Is it possible to select specific lines from my get\_extent.py file rather than displaying ... | This has nothing to do with `beamer`; it's about a `listings` feature. Its excellent [manual](http://www.ctan.org/tex-archive/macros/latex/contrib/listings/listings.pdf) has more. For example:
```
\lstinputlisting[firstline=2,lastline=5]{code/get_extent.py}
``` |
How to write a wrapper over functions and member functions that executes some code before and after the wrapped function? | 2,135,457 | 7 | 2010-01-25T20:39:08Z | 2,140,112 | 11 | 2010-01-26T14:49:10Z | [
"c++",
"python",
"binding",
"wrapper",
"boost-python"
] | I'm trying to write some wrapper class or function that allows me to execute some code before and after the wrapped function.
```
float foo(int x, float y)
{
return x * y;
}
BOOST_PYTHON_MODULE(test)
{
boost::python::def("foo", <somehow wrap "&foo">);
}
```
Ideally, the wrapper should be generic, working fo... | In this case, you can write a Functor class that wraps over your function, and then overload boost::python::detail::get\_signature to accept your Functor!
UPDATE: Added support for member functions too!
Example:
```
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>
#include <boost/python/signature.hpp>
#in... |
Beautiful Soup and extracting a div and its contents by ID | 2,136,267 | 56 | 2010-01-25T22:46:05Z | 2,136,323 | 78 | 2010-01-25T22:55:30Z | [
"python",
"beautifulsoup"
] | ```
soup.find("tagName", { "id" : "articlebody" })
```
Why does this NOT return the `<div id="articlebody"> ... </div>` tags and stuff in between? It returns nothing. And I know for a fact it exists because I'm staring right at it from
```
soup.prettify()
```
`soup.find("div", { "id" : "articlebody" })` also does no... | You should post your example document, because the code works fine:
```
>>> import BeautifulSoup
>>> soup = BeautifulSoup.BeautifulSoup('<html><body><div id="articlebody"> ... </div></body></html')
>>> soup.find("div", {"id": "articlebody"})
<div id="articlebody"> ... </div>
```
Finding `<div>`s inside `<div>`s works... |
Beautiful Soup and extracting a div and its contents by ID | 2,136,267 | 56 | 2010-01-25T22:46:05Z | 2,376,703 | 9 | 2010-03-04T03:34:24Z | [
"python",
"beautifulsoup"
] | ```
soup.find("tagName", { "id" : "articlebody" })
```
Why does this NOT return the `<div id="articlebody"> ... </div>` tags and stuff in between? It returns nothing. And I know for a fact it exists because I'm staring right at it from
```
soup.prettify()
```
`soup.find("div", { "id" : "articlebody" })` also does no... | I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".
This happens with other classes as well. When I search for divs in general, it turns only those that are not so m... |
Beautiful Soup and extracting a div and its contents by ID | 2,136,267 | 56 | 2010-01-25T22:46:05Z | 22,410,466 | 20 | 2014-03-14T16:17:10Z | [
"python",
"beautifulsoup"
] | ```
soup.find("tagName", { "id" : "articlebody" })
```
Why does this NOT return the `<div id="articlebody"> ... </div>` tags and stuff in between? It returns nothing. And I know for a fact it exists because I'm staring right at it from
```
soup.prettify()
```
`soup.find("div", { "id" : "articlebody" })` also does no... | To find an element by its `id`:
```
div = soup.find(id="articlebody")
``` |
Matching one-line JavaScript comments (//) with re | 2,136,363 | 6 | 2010-01-25T23:01:59Z | 2,137,351 | 7 | 2010-01-26T03:23:19Z | [
"javascript",
"python",
"regex",
"replace"
] | I'd like to filter out (mostly one-line) comments from (mostly valid) JavaScript using python's `re` module. For example:
```
// this is a comment
var x = 2 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a comment' // however this one is
url += 'this "is no... | My regex powers had gone a bit stale so I've used your question to fresh what I remember.
It became a fairly large regex mostly because I also wanted to filter multi-line comments.
```
import re
reexpr = r"""
( # Capture code
"(?:\\.|[^"\\])*" # String literal
|
... |
In Python, how do I split a string and keep the separators? | 2,136,556 | 75 | 2010-01-25T23:41:13Z | 2,136,580 | 104 | 2010-01-25T23:45:19Z | [
"python",
"regex"
] | Here's the simplest way to explain this. Here's what I'm using:
```
re.split('\W', 'foo/bar spam\neggs')
-> ['foo', 'bar', 'spam', 'eggs']
```
Here's what I want:
```
someMethod('\W', 'foo/bar spam\neggs')
-> ['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
```
The reason is that I want to split a string into tokens,... | ```
>>> re.split('(\W)', 'foo/bar spam\neggs')
['foo', '/', 'bar', ' ', 'spam', '\n', 'eggs']
``` |
Error handling in SQLAlchemy | 2,136,739 | 24 | 2010-01-26T00:21:29Z | 2,137,389 | 40 | 2010-01-26T03:37:08Z | [
"python",
"sqlalchemy"
] | How do you handle errors in SQLAlchemy? I am relatively new to SQLAlchemy and do not know yet.
Before I used SQLAlchemy, I would do things like
```
status = db.query("INSERT INTO users ...")
if (!status):
raise Error, db.error
```
But now I am coding in SQLAlchemy and I do things like
```
user = User('Boda Cydo... | Your example says:
```
status = db.query("INSERT INTO users ...")
if (!status):
raise Error, db.error
```
That seems to mean that you want to raise an exception if there's some error on the query (with `raise Error, db.error`). However sqlalchemy already does that for you - so
```
user = User('Boda Cydo')
sessio... |
Creating an Instance of a Class with a variable in Python | 2,136,760 | 8 | 2010-01-26T00:26:26Z | 2,136,812 | 7 | 2010-01-26T00:34:01Z | [
"python"
] | I'm trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with.
I created a class `Toy` and want to create a function, `getNewToy(name, data1, data2, data3, data4, data5)`.
I want this function to create a new instance of the class `Toy`, and I want the function ... | If you haven't found it yet, here is [Dive into Python's chapter on object-oriented programming](http://diveintopython.net/object_oriented_framework/index.html).
Here are some more [examples](http://wiki.python.org/moin/SimplePrograms), scroll to BankAccount.
---
You can call a class directly to create an instance. ... |
Creating an Instance of a Class with a variable in Python | 2,136,760 | 8 | 2010-01-26T00:26:26Z | 2,136,854 | 12 | 2010-01-26T00:43:14Z | [
"python"
] | I'm trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with.
I created a class `Toy` and want to create a function, `getNewToy(name, data1, data2, data3, data4, data5)`.
I want this function to create a new instance of the class `Toy`, and I want the function ... | Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.
```
class Foo(object):
pass
class Bar(object):
pass
dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo
``` |
Process to convert simple Python script into Windows executable | 2,136,837 | 52 | 2010-01-26T00:39:11Z | 2,136,872 | 17 | 2010-01-26T00:48:36Z | [
"python",
"packaging",
"compilation",
"py2exe",
"software-distribution"
] | I wrote a script that will help a Windows user in her daily life. I want to simply send her the .exe and not ask her to install python, dlls or have to deal with any additional files.
I've read plenty of the stackoverflow entries regarding compiling Python scripts into executable files. I am a bit confused as there ar... | PyInstaller will create a single-file executable if you use the `--onefile` option (though what it actually does is extracts then runs itself).
There's a simple PyInstaller tutorial [here](http://bytes.com/topic/python/insights/579554-simple-guide-using-pyinstaller). If you have any questions about using it, please po... |
Process to convert simple Python script into Windows executable | 2,136,837 | 52 | 2010-01-26T00:39:11Z | 2,344,598 | 10 | 2010-02-26T20:26:44Z | [
"python",
"packaging",
"compilation",
"py2exe",
"software-distribution"
] | I wrote a script that will help a Windows user in her daily life. I want to simply send her the .exe and not ask her to install python, dlls or have to deal with any additional files.
I've read plenty of the stackoverflow entries regarding compiling Python scripts into executable files. I am a bit confused as there ar... | Using py2exe, include this in your setup.py:
```
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "YourScript.py"}],
zipfile = None,
)
```
then you can run it through command prompt / Idle, both work... |
Process to convert simple Python script into Windows executable | 2,136,837 | 52 | 2010-01-26T00:39:11Z | 14,022,642 | 7 | 2012-12-24T14:36:36Z | [
"python",
"packaging",
"compilation",
"py2exe",
"software-distribution"
] | I wrote a script that will help a Windows user in her daily life. I want to simply send her the .exe and not ask her to install python, dlls or have to deal with any additional files.
I've read plenty of the stackoverflow entries regarding compiling Python scripts into executable files. I am a bit confused as there ar... | i would recommend going to <http://sourceforge.net/projects/py2exe/files/latest/download?source=files> to download py2exe. Then make a python file named setup.py.
Inside it, type
```
from distutils.core import setup
import py2exe
setup(console=['nameoffile.py'])
```
Save in your user folder
Also save the file you wan... |
Can I unit test an inner function in python? | 2,136,910 | 8 | 2010-01-26T00:57:06Z | 2,136,939 | 7 | 2010-01-26T01:06:17Z | [
"python",
"unit-testing",
"doctest"
] | Is there any way to write `unittests` or `doctests` for `innerfunc`?
```
def outerfunc():
def innerfunc():
do_something()
return innerfunc()
``` | Only if you provide a way to extract the inner function object itself, e.g.
```
def outerfunc(calltheinner=True):
def innerfunc():
do_something()
if calltheinner:
return innerfunc()
else:
return innerfunc
```
If your outer function insists on hiding the inner one entirely inside it... |
Does a library to prevent duplicate form submissions exist for django? | 2,136,954 | 17 | 2010-01-26T01:10:52Z | 2,157,688 | 10 | 2010-01-28T20:24:25Z | [
"python",
"django",
"code-reuse"
] | I am trying to find a way to prevent users from double-submitting my forms. I have javascript that disables the submit button, but there is still an occasional user who finds a way to double-submit.
I have a vision of a re-usable library that I could create to protect from this.
In my ideal library, the code block wo... | You can use a session to store the hash
```
import hashlib
def contact(request):
if request.method == 'POST':
form = MyForm(request.POST)
#join all the fields in one string
hashstring=hashlib.sha1(fieldsstring)
if request.session.get('sesionform')!=hashstring:
if form.i... |
Scala equivalent to Python generators? | 2,137,619 | 39 | 2010-01-26T05:10:02Z | 2,139,849 | 25 | 2010-01-26T14:04:57Z | [
"python",
"scala"
] | Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
``... | While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want:
```
def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match {
case null => Stream.empty
case _ => (
clazz
#:: class... |
Scala equivalent to Python generators? | 2,137,619 | 39 | 2010-01-26T05:10:02Z | 2,146,456 | 10 | 2010-01-27T11:32:45Z | [
"python",
"scala"
] | Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called?
I wanted to have something like this to convert a recursive function into an iterator. Sort of like this:
``... | Another continuations plugin based solution, this time with a more or less encapsulated Generator type,
```
import scala.continuations._
import scala.continuations.ControlContext._
object Test {
def loopWhile(cond: =>Boolean)(body: =>(Unit @suspendable)): Unit @suspendable = {
if (cond) {
body
loop... |
Depth-First search in Python | 2,137,731 | 3 | 2010-01-26T06:00:34Z | 2,137,789 | 8 | 2010-01-26T06:17:07Z | [
"python",
"depth-first-search"
] | I'm trying to do a Depth-First search in Python but it's not working.
Basically we have a peg-solitaire board:
```
[1,1,1,1,1,0,1,1,1,1]
```
1's represent a peg, and 0 is an open spot. You must move a peg one at a time TWO SLOTS backwards or forward ONLY to an empty spot. If you jump over another peg in the process ... | The normal way to implement DFS in a situation where each step is a "move" from a "board position" to some possible next one, until a goal is reached, is as follows (pseudocode)
```
seenpositions = set()
currentpositions = set([startingposition])
while currentpositions:
nextpositions = set()
for p in currentpositi... |
Django - Store unescaped html in model | 2,137,736 | 10 | 2010-01-26T06:01:57Z | 2,137,790 | 15 | 2010-01-26T06:17:25Z | [
"python",
"django",
"django-models"
] | I am trying to store raw, unescaped HTML inside one of my Django models for display on my home page. However, when I store it in a TextField it gets escaped, and ends up just being displayed as raw text. How can I store raw HTML in a Django model?
\*\* EDIT \*\*
It seems as if its not getting escaped in the model lay... | You can use the `safe` filter to present unescaped text, or `escape` filter to present escaped text. You can also use `autoescape` tag to set a block. (`{% autoescape on %}` or `{% autoescape off %}`) |
Change class instance inside an instance method | 2,137,772 | 6 | 2010-01-26T06:13:28Z | 2,137,801 | 7 | 2010-01-26T06:20:31Z | [
"python",
"class",
"instance",
"hotswap"
] | Any idea if there is a way to make the following code to work
```
class Test(object):
def __init__(self, var):
self.var = var
def changeme(self):
self = Test(3)
t = Test(1)
assert t.var == 1
t.changeme()
assert t.var == 3
```
is something like the following safe to use for more complex obje... | `self = Test(3)` is re-binding the local name `self`, with no externally observable effects.
Assigning `self.__dict__` (unless you're talking about instances with `__slots__` or from classes with non-trivial metaclasses) is usually OK, and so is `self.__init__(3)` to re-initialize the instance. However I'd prefer to h... |
Cleanest way to get last item from Python iterator | 2,138,873 | 47 | 2010-01-26T10:53:07Z | 2,138,894 | 41 | 2010-01-26T10:56:42Z | [
"python",
"iterator"
] | What's the best way of getting the last item from an iterator in Python 2.6? For example, say
```
my_iter = iter(range(5))
```
What is the shortest-code / cleanest way of getting `4` from `my_iter`?
I could do this, but it doesn't seem very efficient:
```
[x for x in my_iter][-1]
``` | ```
item = defaultvalue
for item in my_iter:
pass
``` |
Cleanest way to get last item from Python iterator | 2,138,873 | 47 | 2010-01-26T10:53:07Z | 2,139,171 | 13 | 2010-01-26T11:59:14Z | [
"python",
"iterator"
] | What's the best way of getting the last item from an iterator in Python 2.6? For example, say
```
my_iter = iter(range(5))
```
What is the shortest-code / cleanest way of getting `4` from `my_iter`?
I could do this, but it doesn't seem very efficient:
```
[x for x in my_iter][-1]
``` | This is unlikely to be faster than the empty for loop due to the lambda, but maybe it will give someone else an idea
```
reduce(lambda x,y:y,my_iter)
```
If the iter is empty, a TypeError is raised |
Cleanest way to get last item from Python iterator | 2,138,873 | 47 | 2010-01-26T10:53:07Z | 2,211,077 | 15 | 2010-02-05T23:01:46Z | [
"python",
"iterator"
] | What's the best way of getting the last item from an iterator in Python 2.6? For example, say
```
my_iter = iter(range(5))
```
What is the shortest-code / cleanest way of getting `4` from `my_iter`?
I could do this, but it doesn't seem very efficient:
```
[x for x in my_iter][-1]
``` | Probably worth using `__reversed__` if it is available
```
if hasattr(my_iter,'__reversed__'):
last = next(reversed(my_iter))
else:
for last in my_iter:
pass
``` |
Cleanest way to get last item from Python iterator | 2,138,873 | 47 | 2010-01-26T10:53:07Z | 3,169,701 | 26 | 2010-07-02T23:39:12Z | [
"python",
"iterator"
] | What's the best way of getting the last item from an iterator in Python 2.6? For example, say
```
my_iter = iter(range(5))
```
What is the shortest-code / cleanest way of getting `4` from `my_iter`?
I could do this, but it doesn't seem very efficient:
```
[x for x in my_iter][-1]
``` | Use a [`deque`](https://docs.python.org/library/collections.html#collections.deque) of size 1.
```
from collections import deque
#aa is an interator
aa = iter('apple')
dd = deque(aa, maxlen=1)
last_element = dd.pop()
``` |
Build Python scripts and call methods from C# | 2,139,202 | 10 | 2010-01-26T12:03:25Z | 2,142,224 | 7 | 2010-01-26T20:02:38Z | [
"c#",
"python",
"ironpython"
] | Is there any way to make this scenario work?
There is a Python script. It is built into a DLL by running this script with IronPython:
```
import clr
clr.CompileModules("CompiledScript.dll", "script.py")
```
The goal is to call this DLL's methods from C# code. [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflec... | Sort of. You cannot access the Python methods directly from C# code. Unless you are playing with C# 4.0 and the dynamic keyword or you are very, very special ;). However, you can compile an IronPython class to a DLL and then use IronPython hosting in C# to access the methods (this is for IronPython 2.6 and .NET 2.0).
... |
breaking a 32-bit number into individual fields | 2,139,377 | 2 | 2010-01-26T12:43:40Z | 2,141,018 | 10 | 2010-01-26T16:59:03Z | [
"python"
] | Is there a quick way in python to split a 32-bit variable, say, `a1a2a3a4` into `a1`, `a2`, `a3`, `a4` quickly? I've done it by changing the value into hex and then splitting it, but it seems like a waste of time doing `int`->`string`->`int`. | Standard library module [struct](http://docs.python.org/library/struct.html?highlight=struct#module-struct) does short work of it:
```
>>> import struct
>>> x = 0xa1a2a3a4
>>> struct.unpack('4B', struct.pack('>I', x))
(161, 162, 163, 164)
```
"packing" with format `'>I'` makes `x` into a 4-byte string in big-endian o... |
How to read a CSV line with "? | 2,139,750 | 4 | 2010-01-26T13:52:03Z | 2,139,763 | 9 | 2010-01-26T13:53:48Z | [
"python",
"csv"
] | A trivial CSV line could be spitted using string split function. But some lines could have `"`, e.g.
```
"good,morning", 100, 300, "1998,5,3"
```
thus directly using string split would not solve the problem.
My solution is to first split out the line using `,` and then combining the strings with `"` at then begin or... | There's a [csv](http://docs.python.org/library/csv.html) module in Python, which handles this.
**Edit**: This task falls into "build a lexer" category. The standard way to do such tasks is to build a state machine (or use a lexer library/framework that will do it for you.)
The state machine for this task would probab... |
How to require login for django generic views? | 2,140,550 | 52 | 2010-01-26T15:59:27Z | 2,140,678 | 73 | 2010-01-26T16:12:51Z | [
"python",
"django"
] | I want to restrict access to urls serves by django generic views. For my views i know that login\_required decorator does the job. Also Create/update/delete generic views takes login\_requied argument but I couldn't find a way to do this for other generic views. | For Django < 1.5, you can add a decorator by wrapping the function in your urls, which allows you to wrap the generic views:
```
from django.contrib.auth.decorators import login_required
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^foo/$', login_required(direct_to_templ... |
How to require login for django generic views? | 2,140,550 | 52 | 2010-01-26T15:59:27Z | 2,140,680 | 9 | 2010-01-26T16:13:05Z | [
"python",
"django"
] | I want to restrict access to urls serves by django generic views. For my views i know that login\_required decorator does the job. Also Create/update/delete generic views takes login\_requied argument but I couldn't find a way to do this for other generic views. | If you don't want to write your own thin wrapper around the generic views in question (as Aamir suggested), you can also do something like this in your `urls.py` file:
```
from django.conf.urls.defaults import *
# Directly import whatever generic views you're using and the login_required
# decorator
from django.views... |
How to require login for django generic views? | 2,140,550 | 52 | 2010-01-26T15:59:27Z | 5,891,307 | 31 | 2011-05-05T00:17:20Z | [
"python",
"django"
] | I want to restrict access to urls serves by django generic views. For my views i know that login\_required decorator does the job. Also Create/update/delete generic views takes login\_requied argument but I couldn't find a way to do this for other generic views. | The generic views have changed from functions to objects with version 1.3 of Django. As such, there is a slight change needed for Will McCutchen and Will Hardy answers to work with version 1.3:
```
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
urlpatterns = pa... |
How to require login for django generic views? | 2,140,550 | 52 | 2010-01-26T15:59:27Z | 14,709,812 | 35 | 2013-02-05T14:27:03Z | [
"python",
"django"
] | I want to restrict access to urls serves by django generic views. For my views i know that login\_required decorator does the job. Also Create/update/delete generic views takes login\_requied argument but I couldn't find a way to do this for other generic views. | ## Django 1.9 or using django-braces
Django 1.9 has introduced a [LoginRequiredMixin](https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.mixins.LoginRequiredMixin) that is used thus:
```
from django.contrib.auth.mixins import LoginRequiredMixin
class MyView(LoginRequiredMixin, View):
... |
List Comprehension: why is this a syntax error? | 2,141,098 | 31 | 2010-01-26T17:10:11Z | 2,141,116 | 41 | 2010-01-26T17:12:17Z | [
"python",
"list-comprehension",
"python-2.6"
] | Why is `print(x)` here not valid (`SyntaxError`) in the following list-comprehension?
```
my_list=[1,2,3]
[print(my_item) for my_item in my_list]
```
To contrast - the following doesn't give a syntax error:
```
def my_func(x):
print(x)
[my_func(my_item) for my_item in my_list]
``` | Because print is not a function, it's a statement, and you can't have them in expressions. This gets more obvious if you use normal Python 2 syntax:
```
my_list=[1,2,3]
[print my_item for my_item in my_list]
```
That doesn't look quite right. :) The parenthesizes around my\_item tricks you.
This has changed in Pytho... |
Convert datetime fields in Chrome history file (sqlite) to readable format | 2,141,537 | 9 | 2010-01-26T18:08:46Z | 4,112,026 | 13 | 2010-11-06T05:15:02Z | [
"python",
"datetime",
"sqlite3"
] | Working on a script to collect users browser history with time stamps ( educational setting).
Firefox 3 history is kept in a sqlite file, and stamps are in UNIX epoch time... getting them and converting to readable format via a SQL command in python is pretty straightforward:
```
sql_select = """ SELECT datetime(moz_h... | Try this:
```
sql_select = """ SELECT datetime(last_visit_time/1000000-11644473600,'unixepoch','localtime'),
url
FROM urls
ORDER BY last_visit_time DESC
"""
get_hist = list(cursor.execute (sql_select))
```
Or something along those lines
seems to... |
Stored Procedures in Python for PostgreSQL | 2,141,589 | 9 | 2010-01-26T18:19:45Z | 2,142,128 | 8 | 2010-01-26T19:48:55Z | [
"python",
"postgresql",
"stored-procedures",
"plpgsql"
] | we are still pretty new to Postgres and came from Microsoft Sql Server.
We are wanting to write some stored procedures now. Well, after struggling to get something more complicated than a `hello world` to work in pl/pgsql, we decided it's better if we are going to learn a new language we might as well learn Python bec... | 1. Depends on what operations you're doing.
2. Well, combine that with a general Python documentation, and that's about what you have.
3. No. Again, depends on what you're doing. If you're only going to run a query once, no point in preparing it separately.
4. If you are using persistent connections, it might. But they... |
Pymedia installation on Windows with Python 2.6 | 2,141,701 | 6 | 2010-01-26T18:38:43Z | 3,670,423 | 8 | 2010-09-08T17:34:47Z | [
"python"
] | I am trying to install latest version of Pymedia from sources. I have Python2.6 and there is no binary available.
Started with:
```
python setup.py build
```
and got the following messages:
```
Using WINDOWS configuration...
Path for OGG not found.
Path for VORBIS not found.
Path for FAAD not found.
Path for MP... | Somebody has done it, if you're just after pymedia for python2.6 on windows:
Have a look here:
<http://www.lfd.uci.edu/~gohlke/pythonlibs/>
There's also a version for python2.7 |
Using Python to program MS Office macros? | 2,141,967 | 23 | 2010-01-26T19:23:23Z | 2,141,981 | 18 | 2010-01-26T19:26:33Z | [
"python",
"excel",
"vba",
"ms-office"
] | I've recently taken it as a project to teach myself how to program in Python. Overall, I must say that I'm impressed with it.
In the past I've typically stuck to programming in VBA mostly for MS Excel (but also a bit in MS Access and Word) and have struggled to find ways to make it do things that Python can easily do ... | Yes, absolutely. You want to use `win32com` module, which is part of pywin32 ([get it here](http://sourceforge.net/projects/pywin32/)).
I've found you can really simplify Python integration by writing a macro in VBA for Python to use, and then just have Python call the macro. It will look something like this:
```
fro... |
Using Python to program MS Office macros? | 2,141,967 | 23 | 2010-01-26T19:23:23Z | 2,142,695 | 7 | 2010-01-26T21:14:10Z | [
"python",
"excel",
"vba",
"ms-office"
] | I've recently taken it as a project to teach myself how to program in Python. Overall, I must say that I'm impressed with it.
In the past I've typically stuck to programming in VBA mostly for MS Excel (but also a bit in MS Access and Word) and have struggled to find ways to make it do things that Python can easily do ... | Or have a look at IronPython. IPy is a native .NET implementation of Python 2.6, you can find it at <http://www.codeplex.com/ironpython>.
We have used it for several projects. You can use it "from the outside" using COM or - as we do - write a Excel AddIn with a ScriptHost, which calls out to IronPython code giving yo... |
Using Python to program MS Office macros? | 2,141,967 | 23 | 2010-01-26T19:23:23Z | 2,142,749 | 7 | 2010-01-26T21:23:50Z | [
"python",
"excel",
"vba",
"ms-office"
] | I've recently taken it as a project to teach myself how to program in Python. Overall, I must say that I'm impressed with it.
In the past I've typically stuck to programming in VBA mostly for MS Excel (but also a bit in MS Access and Word) and have struggled to find ways to make it do things that Python can easily do ... | There is a set of cross platform Python utilities - called xlrd, xlwt, and xlutils - for reading & writing Excel files. There are some limitations (e.g. I don't think they can process macros), but they do allow you to work with Excel files on non-Windows platforms, if that's of use to you. See: <http://www.python-excel... |
Ranking within Django ORM or SQL? | 2,141,978 | 3 | 2010-01-26T19:25:55Z | 2,142,264 | 8 | 2010-01-26T20:09:21Z | [
"python",
"sql",
"django",
"django-models",
"django-orm"
] | **I have a huge list ranked by various values** (eg. scores)
So I grab the list ordered by these values:
```
players = Player.objects.order_by('-score', '-karma')
```
---
I would like to:
* Grab a player and get the **neighbouring players**
> P1 score:123
>
> P2 score:122
>
> **YOU**! score:**110**
>
> P3 score:9... | These sorts of things are always very difficult to do. You'll need multiple queries for each one.
So, to get the players just before and after your position when ordered by score, first you'll need to work out what that position is. (Note that this assumes that you can't have more than one person with the same score, ... |
Django: Best way to implement "status" field in modules | 2,142,055 | 22 | 2010-01-26T19:39:59Z | 2,142,268 | 24 | 2010-01-26T20:09:50Z | [
"python",
"django"
] | I have a field in my module that is used to hold the status of the object.
So far I have used:
```
ORDER_STATUS = ((0, 'Started'), (1, 'Done'), (2, 'Error'))
status = models.SmallIntegerField(choices=ORDER_STATUS)
```
Its easy to convert one way:
```
def status_str(self): return ORDER_STATUS[self.status][1]
```
The... | Maybe this question helps you: [Set Django IntegerField by choices=⦠name](http://stackoverflow.com/questions/1117564/set-django-integerfield-by-choices-name).
I quote from the accepted answer (with adjustments ;)):
Put this into your class (`STATUS_CHOICES` will be the list that is handed to the `choices` option... |
Strip whitespace in generated HTML using pure Python code | 2,142,108 | 8 | 2010-01-26T19:46:59Z | 2,142,194 | 8 | 2010-01-26T19:58:12Z | [
"python",
"html",
"whitespace",
"strip",
"jinja2"
] | I am using Jinja2 to generate HTML files which are typically very huge in size. I noticed that the generated HTML had a lot of whitespace. Is there a pure-Python tool that I can use to minimize this HTML? When I say "minimize", I mean remove unnecessary whitespace from the HTML (much like Google does -- look at the sou... | You might also investigate [Jinja's built-in whitespace control](http://jinja.pocoo.org/2/documentation/templates#whitespace-control), which might alleviate some of the need for manually removing whitespace after your templates have been rendered.
Quoting [the docs](http://jinja.pocoo.org/2/documentation/templates#whi... |
Handle 404 throw by code in appengine | 2,142,198 | 5 | 2010-01-26T19:58:47Z | 2,153,398 | 9 | 2010-01-28T09:19:58Z | [
"python",
"google-app-engine",
"http-status-code-404"
] | I manage the "real" 404 errors in this way:
```
application = webapp.WSGIApplication([
('/', MainPage),
#Some others urls
('/.*',Trow404) #I got the 404 page
],debug=False)
```
But in some parts of my code i throw a 404 error
```
self.error(404)
```
and i wanna show the same page that mentioned b... | The easiest way to do this is to override the error() method on your base handler (presuming you have one) to generate the 404 page, and call that from your regular handlers and your 404 handler. For example:
```
class BaseHandler(webapp.RequestHandler):
def error(self, code):
super(BaseHandler, self).error(code... |
What are acceptable use-cases for python's `assert` statement? | 2,142,202 | 22 | 2010-01-26T19:58:59Z | 2,142,233 | 16 | 2010-01-26T20:03:57Z | [
"python",
"assert"
] | I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the `-o`(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.
It feels much cleane... | **If being graceful is impossible, be dramatic**
Here is the correct version of your code:
```
if filename.endswith('.jpg'):
# convert it to the PNG we want
try:
filename = convert_jpg_to_png_tmpfile(filename)
except PNGCreateError:
# Tell the user their jpg was crap
print "Your jp... |
What are acceptable use-cases for python's `assert` statement? | 2,142,202 | 22 | 2010-01-26T19:58:59Z | 2,142,354 | 7 | 2010-01-26T20:23:26Z | [
"python",
"assert"
] | I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the `-o`(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.
It feels much cleane... | `assert` is best used for code that should be active during testing when you are surely going to run without `-o`
You may personally never run with `-o` but what happens if your code ends up in a larger system and the admin wants to run it with `-o`?
It's possible that the system will appear to run fine, but there ar... |
What are acceptable use-cases for python's `assert` statement? | 2,142,202 | 22 | 2010-01-26T19:58:59Z | 2,142,358 | 23 | 2010-01-26T20:23:51Z | [
"python",
"assert"
] | I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the `-o`(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.
It feels much cleane... | Assertions should be used for expressing **invariants**, or **preconditions**.
In your example, you are using them for checking unexpected input - and that's a completely different *class* of exceptions.
Depending on the requirements, it may be perfectly OK to raise an exception on wrong input, and stop the applicat... |
What are acceptable use-cases for python's `assert` statement? | 2,142,202 | 22 | 2010-01-26T19:58:59Z | 2,142,394 | 9 | 2010-01-26T20:26:59Z | [
"python",
"assert"
] | I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the `-o`(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case.
It feels much cleane... | Totally valid. The assertion is a formal claim about the state of your program.
You should use them for things which can't be proven. However, they're handy for things you *think* you can prove as a check on your logic.
Another example.
```
def fastExp( a, b ):
assert isinstance(b,(int,long)), "This algorithm ra... |
Python: Analysis on CSV files 100,000 lines x 40 columns | 2,142,415 | 11 | 2010-01-26T20:30:30Z | 2,142,469 | 12 | 2010-01-26T20:40:41Z | [
"python",
"numpy"
] | I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis.
I was wondering what issues should I expect wi... | I've found that Python + CSV is probably the fastest, and simplest way to do some kinds of statistical processing.
We do a fair amount of reformatting and correcting for odd data errors, so Python helps us.
The availability of Python's functional programming features makes this particularly simple. You can do samplin... |
getting list without k'th element efficiently and non-destructively | 2,142,453 | 17 | 2010-01-26T20:36:56Z | 2,142,467 | 46 | 2010-01-26T20:40:17Z | [
"python",
"list",
"copying"
] | I have a list in python and I'd like to iterate through it, and selectively construct a list that contains all the elements except the current k'th element. one way I can do it is this:
```
l = [('a', 1), ('b', 2), ('c', 3)]
for num, elt in enumerate(l):
# construct list without current element
l_without_num = cop... | ```
l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = l[:k] + l[(k + 1):]
```
Is this what you want? |
getting list without k'th element efficiently and non-destructively | 2,142,453 | 17 | 2010-01-26T20:36:56Z | 2,142,488 | 8 | 2010-01-26T20:45:09Z | [
"python",
"list",
"copying"
] | I have a list in python and I'd like to iterate through it, and selectively construct a list that contains all the elements except the current k'th element. one way I can do it is this:
```
l = [('a', 1), ('b', 2), ('c', 3)]
for num, elt in enumerate(l):
# construct list without current element
l_without_num = cop... | It would help if you explained more how you wanted to use it. But you can do the same with list comprehension.
```
l = [('a', 1), ('b', 2), ('c', 3)]
k = 1
l_without_num = [elt for num, elt in enumerate(l) if not num == k]
```
This is also more memory efficient to iterate over if you don't have to store it in l\_with... |
What's the best way to add a GUI to a Pygame application? | 2,142,912 | 8 | 2010-01-26T21:50:50Z | 2,146,629 | 8 | 2010-01-27T12:01:54Z | [
"python",
"user-interface",
"graphics",
"pygame"
] | Are there any good GUIs that support Pygame surfaces as a widget within the application?
If this isn't possible or practical, what GUI toolkit has the best graphics component? I'm looking to keep the speedy rendering made possible by a SDL wrapper. | Dont use wxPython, its very hard to get to work well with Pygame, as described over at the [GUI section](http://www.pygame.org/wiki/gui) of the Pygame wiki.
> First of all, pygame relies on the
> SDL, which means that it can only have
> one window at a time. Thus, trying to
> implement multiple Gtk, Qt, ...
> applicat... |
How to write a regular expression to match a string literal where the escape is a doubling of the quote character? | 2,143,235 | 6 | 2010-01-26T22:40:45Z | 2,143,267 | 17 | 2010-01-26T22:45:04Z | [
"python",
"regex",
"fortran",
"ply"
] | I am writing a parser using [ply](http://www.dabeaz.com/ply/) that needs to identify FORTRAN string literals. These are quoted with single quotes with the escape character being doubled single quotes. i.e.
`'I don''t understand what you mean'`
is a valid escaped FORTRAN string.
Ply takes input in regular expression.... | A string literal is:
1. An open single-quote, followed by:
2. Any number of doubled-single-quotes and non-single-quotes, then
3. A close single quote.
Thus, our regex is:
```
r"'(''|[^'])*'"
``` |
Python indentation issue? | 2,143,291 | 4 | 2010-01-26T22:48:49Z | 2,143,301 | 10 | 2010-01-26T22:50:50Z | [
"python"
] | I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get
> IndentationError: expected an indented
> block
What is wrong with this?
```
import random
class Individual:
alleles = (0,1)
length = 5
string = ""
def __init__(self):
#some... | All of those methods that consist of just a comment.
To fix it, for example, do this
```
def twoPointCrossover(self, partner):
#at two random(?) points, crossover.
pass
```
The comments don't count as compilable statements, so you have a bunch of empty blocks. That is why it gives you the indent erro... |
What's the easiest way to reproduce a randomly generated level in Python? | 2,143,463 | 2 | 2010-01-26T23:19:45Z | 2,143,487 | 7 | 2010-01-26T23:25:45Z | [
"python",
"random",
"pygame"
] | I'm making a game which uses procedurally generated levels, and when I'm testing I'll often want to reproduce a level. Right now I haven't made any way to save the levels, but I thought a simpler solution would be to just reuse the seed used by Python's random module. However I've tried using both `random.seed()` and `... | `random.seed` should work ok, but remember that it is not thread safe - if random numbers are being used elsewhere at the same time you may get different results between runs.
In that case you should use an instance of `random.Random()` to get a private random number generator
```
>>> import random
>>> seed=1234
>>> ... |
Undefined variable from import when using wxPython in pydev | 2,143,549 | 18 | 2010-01-26T23:40:20Z | 3,743,861 | 39 | 2010-09-18T22:59:21Z | [
"python",
"eclipse",
"wxpython",
"pydev"
] | I just downloaded wxPython, and was running some of the sample programs from [here](http://wiki.wxpython.org/Getting%20Started#First_steps). However, on every line that uses a variable from wx.\*, I get a "Undefined variable from import error"
For example, the following program generates five errors on lines 1,4,8, an... | This happened to me. I had installed PyDev and configured it and went on my merry way. A few months later, I installed wxPython and had this same problem. An easy way to fix is in eclipse:
Window -> Preferences -> Pydev -> Interpreter - Python
Just remove the default interpreter and add a new one (it can be the same ... |
Undefined variable from import when using wxPython in pydev | 2,143,549 | 18 | 2010-01-26T23:40:20Z | 3,945,589 | 7 | 2010-10-15T19:48:58Z | [
"python",
"eclipse",
"wxpython",
"pydev"
] | I just downloaded wxPython, and was running some of the sample programs from [here](http://wiki.wxpython.org/Getting%20Started#First_steps). However, on every line that uses a variable from wx.\*, I get a "Undefined variable from import error"
For example, the following program generates five errors on lines 1,4,8, an... | PyDev finds the references when you setup the interpreter in
> ```
> Window -> Preferences -> Pydev -> Interpreter - Python
> ```
If wxPython was not in your site-packages directory when you first setup the interpreter, then the references to the wx objects and names will not be known to the editor lookup function. T... |
How do I get a content-type of a file in Python? (with url..) | 2,143,674 | 6 | 2010-01-27T00:08:59Z | 2,143,704 | 12 | 2010-01-27T00:16:56Z | [
"python",
"http",
"url",
"content-type"
] | Suppose I haev a video file:
<http://mydomain.com/thevideofile.mp4>
How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file.
i want it to return:
```
video/mp4
```
Edit: this is what I did. What do you think?
```
f = urllib2.urlopen(url)
params['mi... | Like so:
```
>>> import httplib
>>> conn = httplib.HTTPConnection("mydomain.com")
>>> conn.request("HEAD", "/thevideofile.mp4")
>>> res = conn.getresponse()
>>> print res.getheaders()
```
That will only download and print the headers because it is making a [HEAD](http://en.wikipedia.org/wiki/HTTP#Request_methods) req... |
Find all decorated functions in a module | 2,144,109 | 5 | 2010-01-27T02:08:29Z | 2,144,135 | 9 | 2010-01-27T02:13:28Z | [
"python"
] | Is it possible to find out if a function is decorated at runtime? For example could I find all functions in a module that are decorated by "example"?
```
@example
def test1():
print "test1"
``` | In the general case it is not possible because the `example` decorator might not leave any trace that's detectable at runtime -- for example, it **could** be
```
def example(f):
return f
```
If you do control the source for `example`, it's of course easy to make it mark or record the functions it's decorating; if y... |
Find all decorated functions in a module | 2,144,109 | 5 | 2010-01-27T02:08:29Z | 2,144,413 | 7 | 2010-01-27T03:36:07Z | [
"python"
] | Is it possible to find out if a function is decorated at runtime? For example could I find all functions in a module that are decorated by "example"?
```
@example
def test1():
print "test1"
``` | Since you have indicated that you are have control of the wrapper code, here is a simple example
```
def example(f):
f.wrapped=True
return f
@example
def test1():
print "test1"
def test2():
print "test2"
print test1.wrapped
print hasattr(test2, 'wrapped')
``` |
assigning points to bins | 2,144,443 | 4 | 2010-01-27T03:49:16Z | 2,144,477 | 12 | 2010-01-27T03:59:54Z | [
"python",
"numpy",
"scipy",
"binning"
] | What is a good way to bin numerical values into a certain range? For example, suppose I have a list of values and I want to bin them into N bins by their range. Right now, I do something like this:
```
from scipy import *
num_bins = 3 # number of bins to use
values = # some array of integers...
min_val = min(values) -... | `numpy.histogram()` does exactly what you want.
The function signature is:
```
numpy.histogram(a, bins=10, range=None, normed=False, weights=None, new=None)
```
We're mostly interested in `a` and `bins`. `a` is the input data that needs to be binned. `bins` can be a number of bins (your `num_bins`), or it can be a s... |
Why can't I use 'django-admin.py makemessages -l cn' | 2,144,503 | 7 | 2010-01-27T04:06:27Z | 2,144,521 | 8 | 2010-01-27T04:13:16Z | [
"python",
"django"
] | print :
```
D:\zjm_code\register2>python D:\Python25\Lib\site-packages\django\bin\django-adm
in.py makemessages -l cn
Error: This script should be run from the Django SVN tree or your project or app
tree. If you did indeed run it from the SVN checkout or your project or applica
tion, maybe you are just missing the co... | 1. is `register2` your project or app tree?
2. did you make directory `register2\\locale`? |
Python C interoperability | 2,144,542 | 2 | 2010-01-27T04:18:49Z | 2,144,563 | 7 | 2010-01-27T04:24:56Z | [
"python",
"c",
"interop"
] | I wish to wrap an existing C (pure C that is. No C++) library into Python so that I can call it from Python scripts. Which approach among the various available (C Api, SWIG etc.) would be the most suitable? | go with Ctypes, it is part of standard distribution and works very well.
basically you can wrap C structures and types in python classes, as well as functions. Some types and functionality is already provided by library.
[ctypes](http://docs.python.org/library/ctypes.html)
couple caveats though: passing triple pointe... |
Is it safe to use sys.platform=='win32' check on 64-bit Python? | 2,144,748 | 32 | 2010-01-27T05:21:53Z | 2,145,582 | 27 | 2010-01-27T09:07:15Z | [
"python",
"windows",
"64bit",
"cross-platform",
"32bit-64bit"
] | The usual check to differentiate between running Python-application on Windows and on other OSes (Linux typically) is to use conditional:
```
if sys.platform == 'win32':
...
```
But I wonder is it safe to use today when 64-bit Python is more widely used in last years? Does 32 really means 32-bit, or basically it ... | `sys.platform` will be `win32` regardless of the bitness of the underlying Windows system, as you can see in `PC/pyconfig.h` (from the Python 2.6 source distribution):
```
#if defined(MS_WIN64)
/* maintain "win32" sys.platform for backward compatibility of Python code,
the Win64 API should be close enough to the Wi... |
How to know the encoding of a file in Python? | 2,144,815 | 15 | 2010-01-27T05:46:09Z | 2,144,852 | 17 | 2010-01-27T05:58:05Z | [
"python",
"encoding",
"character-encoding"
] | Does anybody know how to get the encoding of a file in Python. I know that you can use the codecs module to open a file with a specific encoding but you have to know it in advance.
```
import codecs
f = codecs.open("file.txt", "r", "utf-8")
```
Is there a way to detect automatically which encoding is used for a file?... | Unfortunately there is no 'correct' way to determine the encoding of a file by looking at the file itself. This is a universal problem, not limited to python or any particular file system.
If you're reading an XML file, the first line in the file *might* give you a hint of what the encoding is.
Otherwise, you will ha... |
Using Django, why would REMOTE_ADDR return 127.0.0.1 on a web server? | 2,144,848 | 7 | 2010-01-27T05:57:21Z | 2,144,938 | 9 | 2010-01-27T06:17:52Z | [
"python",
"django"
] | When getting the IP with `request.META['REMOTE_ADDR']` code. This works fine on the local system but when hosted on a web server the ip got is 127.0.0.1 - How can this be resolved? | Your web server is probably behind a load balancer. You can try using request.META['HTTP\_X\_FORWARDED\_FOR'].
Or better, look at the [django book, chapter 15](http://www.djangobook.com/en/1.0/chapter15/) - *Whatâs Middleware?* and *Reverse Proxy Support (X-Forwarded-For Middleware)* sections. |
Python: multiple calls to __init__() on the same instance | 2,144,988 | 9 | 2010-01-27T06:31:45Z | 2,145,048 | 9 | 2010-01-27T06:48:39Z | [
"python",
"initialization"
] | The `__init__()` function gets called when object is created.
Is it ok to call an object `__init__()` function again, after its been created?
```
instance = cls(p1=1, p2=2)
# some code
instance.__init__(p1=123, p2=234)
# some more code
instance.__init__(p1=23, p2=24)
```
why would anyone wanna call `__init__()` on an... | It's fine to call `__init__` more than once on an object, as long as `__init__` is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code `__init__` appropriately!-) is when your class's `__new__` method returns an instance of the class: that *does* cause ... |
Random is barely random at all? | 2,145,510 | 56 | 2010-01-27T08:50:51Z | 2,145,517 | 39 | 2010-01-27T08:51:38Z | [
"python",
"random",
"birthday-paradox"
] | I did this to test the randomness of randint:
```
>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500): # You can see I was optimistic.
... x = randint(500, 5000)
... if x in uniques:
... raise Exception('We duped %d at iteration number %d' % (x, i))
... uniques.append(x)
.... | Before blaming Python, you should really brush up some probability & statistics theory. Start by reading about the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_paradox)
By the way, the `random` module in Python uses the [Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_twister) PRNG, which is consid... |
Random is barely random at all? | 2,145,510 | 56 | 2010-01-27T08:50:51Z | 2,145,533 | 34 | 2010-01-27T08:54:45Z | [
"python",
"random",
"birthday-paradox"
] | I did this to test the randomness of randint:
```
>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500): # You can see I was optimistic.
... x = randint(500, 5000)
... if x in uniques:
... raise Exception('We duped %d at iteration number %d' % (x, i))
... uniques.append(x)
.... | If you don't want repetative one, generate sequential array and use [random.shuffle](http://docs.python.org/library/random.html#random.shuffle) |
Random is barely random at all? | 2,145,510 | 56 | 2010-01-27T08:50:51Z | 2,145,551 | 239 | 2010-01-27T08:58:59Z | [
"python",
"random",
"birthday-paradox"
] | I did this to test the randomness of randint:
```
>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500): # You can see I was optimistic.
... x = randint(500, 5000)
... if x in uniques:
... raise Exception('We duped %d at iteration number %d' % (x, i))
... uniques.append(x)
.... | ## The Birthday Paradox, or why PRNGs produce duplicates more often than you might think.
There are a couple of issues at play in the OP's problem. One is the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_problem) as mentioned above and the second is the nature of what you are generating, which does not inh... |
Random is barely random at all? | 2,145,510 | 56 | 2010-01-27T08:50:51Z | 2,145,600 | 14 | 2010-01-27T09:10:23Z | [
"python",
"random",
"birthday-paradox"
] | I did this to test the randomness of randint:
```
>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500): # You can see I was optimistic.
... x = randint(500, 5000)
... if x in uniques:
... raise Exception('We duped %d at iteration number %d' % (x, i))
... uniques.append(x)
.... | True randomness definitely includes repetition of values before the whole set of possible values is exhausted. It would not be random otherwise, as you would be able to predict for how long a value would not be repeated.
If you ever rolled dice, you surely got 3 sixes in row quite often... |
Random is barely random at all? | 2,145,510 | 56 | 2010-01-27T08:50:51Z | 2,161,698 | 25 | 2010-01-29T11:56:23Z | [
"python",
"random",
"birthday-paradox"
] | I did this to test the randomness of randint:
```
>>> from random import randint
>>>
>>> uniques = []
>>> for i in range(4500): # You can see I was optimistic.
... x = randint(500, 5000)
... if x in uniques:
... raise Exception('We duped %d at iteration number %d' % (x, i))
... uniques.append(x)
.... | As an answer to the answer of Nimbuz:
<http://xkcd.com/221/>
 |
Convert Unicode/UTF-8 string to lower/upper case using pure & pythonic library | 2,145,826 | 6 | 2010-01-27T09:51:40Z | 2,145,841 | 16 | 2010-01-27T09:54:02Z | [
"python",
"google-app-engine",
"case-conversion"
] | I use Google App Engine and cannot use any C/C++ extension, just pure & pythonic library to do conversion of Unicode/UTF-8 strings to lower/upper case. str.lower() and string.lowercase() don't. | `str` encoded in UTF-8 and `unicode` are two different types. Don't use `string`, use the appropriate method on the unicode object:
```
>>> print u'Ä'.upper()
Ä
```
Decode `str` to `unicode` before using:
```
>>> print 'Ä'.decode('utf-8').upper()
Ä
``` |
What is the equivalent of 'fread' from Matlab in Python? | 2,146,031 | 8 | 2010-01-27T10:25:25Z | 2,146,144 | 7 | 2010-01-27T10:44:25Z | [
"python",
"matlab",
"numpy",
"readline",
"fread"
] | I have practically no knowledge of Matlab, and need to translate some parsing routines into Python. They are for large files, that are themselves divided into 'blocks', and I'm having difficulty right from the off with the checksum at the top of the file.
What exactly is going on here in Matlab?
```
status = fseek(fi... | From the [documentation of `fread`](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/fread.html), it is a function to read binary data. The second argument specifies the size of the output vector, the third one the size/type of the items read.
In order to recreate this in Python, you can use the [`array`](htt... |
What is the equivalent of 'fread' from Matlab in Python? | 2,146,031 | 8 | 2010-01-27T10:25:25Z | 14,720,675 | 7 | 2013-02-06T02:36:52Z | [
"python",
"matlab",
"numpy",
"readline",
"fread"
] | I have practically no knowledge of Matlab, and need to translate some parsing routines into Python. They are for large files, that are themselves divided into 'blocks', and I'm having difficulty right from the off with the checksum at the top of the file.
What exactly is going on here in Matlab?
```
status = fseek(fi... | ## Python Code for Reading a 1-Dimensional Array
When replacing Matlab with Python, I wanted to read binary data into a [`numpy.array`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html), so I used [`numpy.fromfile`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html) to read th... |
__cmp__ method is this not working as expected in Python 2.x? | 2,146,225 | 5 | 2010-01-27T10:58:23Z | 2,146,246 | 9 | 2010-01-27T11:01:19Z | [
"python",
"python-2.x",
"cmp"
] | ```
class x:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def __cmp__(self,other):
print("cmp method called with self="+str(self)+",other="+str(other))
return self.name==other.name
# return False
instance1=x("hello")
instance2=x("ther... | `__cmp__(x,y)` should return a negative number (e.g. -1) if `x < y`, a positive number (e.g. 1) if `x > y` and 0 if `x == y`. You should never return a boolean with it.
What you're overloading is `__eq__(x, y)`. |
Use of meta class in django | 2,146,363 | 5 | 2010-01-27T11:19:54Z | 2,146,382 | 19 | 2010-01-27T11:21:50Z | [
"python",
"django",
"django-models"
] | Can someone please explain why is meta class used in the following example.
Ex:
```
Class Employee (models.Model):
name = models.ForeignKey(name)
Gender = models.IntegerField()
class Meta:
ordering = ["Gender"]
```
Thanks... | Django models use the `Meta` class to contain extra information about the model that would not necessarily be appropriate to contain within the model class itself. Note that this is *not* the same as Python's `metaclass`; that is a completely different topic. |
HTTPS connection Python | 2,146,383 | 27 | 2010-01-27T11:22:00Z | 2,146,399 | 9 | 2010-01-27T11:23:57Z | [
"python",
"ssl",
"https",
"httplib",
"pyopenssl"
] | I am trying to verify the that target exposes a https web service. I have code to connect via HTTP but I am not sure how to connect via HTTPS. I have read you use SSL but I have also read that it did not support certificate errors. The code I have got is from the python docs:
```
import httplib
conn = httplib.HTTPConn... | using
```
class httplib.HTTPSConnection
```
<http://docs.python.org/library/httplib.html#httplib.HTTPSConnection> |
HTTPS connection Python | 2,146,383 | 27 | 2010-01-27T11:22:00Z | 2,146,467 | 50 | 2010-01-27T11:33:53Z | [
"python",
"ssl",
"https",
"httplib",
"pyopenssl"
] | I am trying to verify the that target exposes a https web service. I have code to connect via HTTP but I am not sure how to connect via HTTPS. I have read you use SSL but I have also read that it did not support certificate errors. The code I have got is from the python docs:
```
import httplib
conn = httplib.HTTPConn... | <http://docs.python.org/library/httplib.html>:
> Note: HTTPS support is only available if the socket module was compiled with SSL support.
```
#!/usr/bin/env python
import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = resp... |
HTTPS connection Python | 2,146,383 | 27 | 2010-01-27T11:22:00Z | 2,146,907 | 7 | 2010-01-27T12:53:20Z | [
"python",
"ssl",
"https",
"httplib",
"pyopenssl"
] | I am trying to verify the that target exposes a https web service. I have code to connect via HTTP but I am not sure how to connect via HTTPS. I have read you use SSL but I have also read that it did not support certificate errors. The code I have got is from the python docs:
```
import httplib
conn = httplib.HTTPConn... | To check for [ssl support in Python 2.6+](http://docs.python.org/library/ssl.html):
```
try:
import ssl
except ImportError:
print "error: no ssl support"
```
To connect via [https](http://stackoverflow.com/questions/1935939/python-send-cmd-on-socket/1936923#1936923):
```
import urllib2
try:
response = u... |
How to do while loops with multiple conditions | 2,146,419 | 10 | 2010-01-27T11:27:32Z | 2,146,427 | 10 | 2010-01-27T11:28:54Z | [
"python",
"logic"
] | I have a while loop in python
```
condition1=False
condition1=False
val = -1
while condition1==False and condition2==False and val==-1:
val,something1,something2 = getstuff()
if something1==10:
condition1 = True
if something2==20:
condition2 = True
'
'
```
I want to break out of the lo... | Change the `and`s to `or`s. |
twisted http client | 2,147,148 | 13 | 2010-01-27T13:31:50Z | 2,147,398 | 17 | 2010-01-27T14:02:26Z | [
"python",
"http",
"client",
"twisted"
] | I am after an example describing the usage of Twisted's HTTP Client.
After reading the excellent [blog post on the internals of Twisted](http://krondo.com/blog/?page_id=1327), I understand how the "Factory" and "Protocol" components play their role but I am unclear on how to introduce "Request" in the overall Client f... | As of Twisted 9.0, there are actually two HTTP clients available. The older one has quite a few features, such as automatically following redirects, interpreting cookie headers, etc. You can find an example of its usage here:
<http://twistedmatrix.com/documents/current/web/examples/>
(`getpage.py` and `dlpage.py`)
U... |
Serializing list to JSON | 2,147,701 | 16 | 2010-01-27T14:42:07Z | 2,147,791 | 33 | 2010-01-27T14:53:03Z | [
"python",
"django",
"json",
"serialization"
] | I am sending information between client and Django server, and I would like to use JSON to this. I am sending simple information - list of strings. I tried using `django.core.serializers`, but when I did, I got
```
AttributeError: 'str' object has no attribute '_meta'
```
It seems this can be used only for Django obj... | You can use pure Python to do it:
```
import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'
``` |
How do I represent and work with n-bit vectors in Python? | 2,147,848 | 5 | 2010-01-27T14:59:13Z | 2,147,880 | 7 | 2010-01-27T15:02:15Z | [
"python",
"bit-manipulation",
"bitarray",
"bitvector"
] | In an assignment I am currently working on we need to work with bit vectors, but I am very unsure of how to do this in Python. They should be able to be from 4 bits to 20 bits. I have never worked with bit vector before, but I guess that one would one create arrays of unsigned bytes that you manipulated using the usual... | The [bitarray](http://pypi.python.org/pypi/bitarray) module does this efficiently with booleans. |
How to convert an xml string to a dictionary in Python? | 2,148,119 | 60 | 2010-01-27T15:28:49Z | 5,807,028 | 22 | 2011-04-27T15:58:19Z | [
"python",
"xml",
"json",
"dictionary",
"xml-deserialization"
] | I have a program that reads an xml document from a socket. I have the xml document stored in a string which I would like to convert directly to a Python dictionary, the same way it is done in Django's `simplejson` library.
Take as an example:
```
str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></per... | This is a great module that someone created. I've used it several times.
<http://code.activestate.com/recipes/410469-xml-as-dictionary/>
Here is the code from the website just in case the link goes bad.
```
import cElementTree as ElementTree
class XmlListConfig(list):
def __init__(self, aList):
for eleme... |
How to convert an xml string to a dictionary in Python? | 2,148,119 | 60 | 2010-01-27T15:28:49Z | 10,077,069 | 20 | 2012-04-09T17:23:43Z | [
"python",
"xml",
"json",
"dictionary",
"xml-deserialization"
] | I have a program that reads an xml document from a socket. I have the xml document stored in a string which I would like to convert directly to a Python dictionary, the same way it is done in Django's `simplejson` library.
Take as an example:
```
str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></per... | The following XML-to-Python-dict snippet parses entities as well as attributes following [this XML-to-JSON "specification"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is the most general solution handling all cases of XML.
```
from collections import defaultdict
def etree_to_dict(t)... |
How to convert an xml string to a dictionary in Python? | 2,148,119 | 60 | 2010-01-27T15:28:49Z | 10,199,714 | 142 | 2012-04-17T21:51:24Z | [
"python",
"xml",
"json",
"dictionary",
"xml-deserialization"
] | I have a program that reads an xml document from a socket. I have the xml document stored in a string which I would like to convert directly to a Python dictionary, the same way it is done in Django's `simplejson` library.
Take as an example:
```
str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></per... | [xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) does exactly that:
```
xmltodict.parse("""
<?xml version="1.0" ?>
<person>
<name>john</name>
<age>20</age>
</person>""")
# {u'person': {u'age': u'20', u'name': u'john'}}
``` |
Python: Embed Chaco in PyQt4 Mystery | 2,148,279 | 8 | 2010-01-27T15:47:33Z | 2,151,067 | 7 | 2010-01-27T23:17:07Z | [
"python",
"pyqt",
"pyqt4",
"chaco"
] | How do i go about adding Chaco to an existing PyQt4 application?
Hours of searches yielded little ([search for yourself](http://www.google.com/search?hl=en&q=filetype%3apy+chaco+pyqt4)). So far i've figured i need the following lines:
```
import os
os.environ['ETS_TOOLKIT']='qt4'
```
i could not find PyQt4-Chaco cod... | here is what you need:
```
import os, sys
os.environ['ETS_TOOLKIT'] = 'qt4'
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
from numpy import linspace, pi, sin
from enthought.enable.api import Component, Container, Window
from enthought.chaco.api import create_line_plot, \
a... |
Python: Embed Chaco in PyQt4 Mystery | 2,148,279 | 8 | 2010-01-27T15:47:33Z | 2,248,631 | 8 | 2010-02-11T23:40:36Z | [
"python",
"pyqt",
"pyqt4",
"chaco"
] | How do i go about adding Chaco to an existing PyQt4 application?
Hours of searches yielded little ([search for yourself](http://www.google.com/search?hl=en&q=filetype%3apy+chaco+pyqt4)). So far i've figured i need the following lines:
```
import os
os.environ['ETS_TOOLKIT']='qt4'
```
i could not find PyQt4-Chaco cod... | I just saw this today. It is absolutely possible and fairly straightforward to embed Chaco inside Qt as well as WX. In fact, all of the examples, when run with your ETS\_TOOLKIT environment var set to "qt4", are doing exactly this. (Chaco *requires* there to be an underlying GUI toolkit.)
I have written a small, stand... |
Python: Rar Brute Forcer | 2,148,393 | 4 | 2010-01-27T16:04:11Z | 2,148,444 | 7 | 2010-01-27T16:12:06Z | [
"python",
"performance"
] | I am trying to brute force a RAR archive which is protected by a password with 3 characters:
```
import os
Alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for a in range(0,26):
for b in range(0,26):
for c in range(0,26):
Brute = Alphabets[a] + Alphabets[b] + Alphabets[c]
os.popen4("Rar.exe x -p" + Brute + " Protecte... | You could use (or learn from) [rarcrack](http://sourceforge.net/projects/rarcrack/). It is written in C and compiles without problems on Linux (Windows with lots of changes).
In general, opening a process for every single tested password is very expensive. You should try and open the archive yourself, and then test ag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.