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 |
|---|---|---|---|---|---|---|---|---|---|
Accessing LogCat from Android via Python | 11,524,586 | 3 | 2012-07-17T14:23:23Z | 11,524,887 | 7 | 2012-07-17T14:36:43Z | [
"android",
"python",
"events",
"logcat",
"android-logcat"
] | Is it possible to read information being sent over LogCat in python?
I have a program that is written in java.
Every draw frame it sends tag:"Fps: " message: number
I would like this message to fire an event that I can catch in my python script so I can draw a fps-meter. | Take a look at [subprocess](http://docs.python.org/library/subprocess.html). The following code was adapted from [Stefaan Lippens](http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading)
```
import Queue
import subprocess
import threading
class AsynchronousFileReader(threading.Thread):
'''
Hel... |
How can I tell if NumPy creates a view or a copy? | 11,524,664 | 33 | 2012-07-17T14:26:05Z | 11,524,746 | 34 | 2012-07-17T14:30:03Z | [
"python",
"numpy",
"copy"
] | For a minimal working example, let's digitize a 2D array. `numpy.digitize` requires a 1D array:
```
import numpy as np
N = 200
A = np.random.random((N, N))
X = np.linspace(0, 1, 20)
print np.digitize(A.ravel(), X).reshape((N, N))
```
Now the [documentation says](http://docs.scipy.org/doc/numpy/reference/generated/num... | This question is very similar to a [question](http://stackoverflow.com/q/11286864/748858) that I asked a while back:
You can check the `base` attribute.
```
a = np.arange(50)
b = a.reshape((5, 10))
print (b.base is a)
```
However, that's not perfect. You can also check to see if they share memory using `np.may_share... |
How can I tell if NumPy creates a view or a copy? | 11,524,664 | 33 | 2012-07-17T14:26:05Z | 14,271,298 | 10 | 2013-01-11T03:40:59Z | [
"python",
"numpy",
"copy"
] | For a minimal working example, let's digitize a 2D array. `numpy.digitize` requires a 1D array:
```
import numpy as np
N = 200
A = np.random.random((N, N))
X = np.linspace(0, 1, 20)
print np.digitize(A.ravel(), X).reshape((N, N))
```
Now the [documentation says](http://docs.scipy.org/doc/numpy/reference/generated/num... | In the documentation for [reshape](http://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html#numpy.reshape) there is some information about how to ensure an exception if a view cannot be made:
> It is not always possible to change the shape of an array without copying the data. If you want an error to be ... |
long text as String in python | 11,524,946 | 2 | 2012-07-17T14:39:19Z | 11,524,978 | 11 | 2012-07-17T14:40:45Z | [
"python",
"string",
"text"
] | Hey I would like to declare a String in Python which is a long text (with line breaks and paragraphs). Is this possible?
If I just copy-paste de text into quotations Python only recognizes the first line and I have to manually remove all the line breaks if I want the entire text. If this is possible would it still be p... | Use triple quotes :
```
mytext = """Some text
Some more text
etc...
"""
``` |
When does the App Engine scheduler use a new thread vs. a new instance? | 11,525,717 | 58 | 2012-07-17T15:23:33Z | 11,882,719 | 35 | 2012-08-09T11:47:01Z | [
"python",
"google-app-engine"
] | If I set `threadsafe: true` in my `app.yaml` file, what are the rules that govern when a new instance will be created to serve a request, versus when a new thread will be created on an existing instance?
If I have an app which performs something computationally intensive on each request, does multi-threading buy me an... | The following set of rules are currently used to determine if a given instance can accept a new request:
```
if processing more than N concurrent requests (today N=10): false
elif exceeding the soft memory limit: false
elif exceeding the instance class CPU limit: false
elif warming up: false
else true
```
The followi... |
How to share attributes without an is-a relationship in Python? | 11,526,499 | 3 | 2012-07-17T16:06:29Z | 11,526,559 | 7 | 2012-07-17T16:10:07Z | [
"python",
"properties"
] | I have a number of Python types that describe a hierarchy in the sense that they are increasingly specific in terms of their properties. Instead of trying to describe it in words, here is an example:
```
class A:
@property
def prop1(self):
return self._prop1
class B:
@property
def prop1(self):... | You can use a decorator:
```
def has_prop1(cls):
@property
def prop1(self):
return self._prop1
cls.prop1 = prop1
return cls
@has_prop1
class A(object):
pass
```
Compositing would go like this:
```
@has_prop1
@has_prop2
class B(object):
pass
```
Or even like this:
```
def has_many... |
set random seed programwide in python | 11,526,975 | 16 | 2012-07-17T16:36:58Z | 11,527,011 | 28 | 2012-07-17T16:38:43Z | [
"python",
"random",
"seed"
] | I have a rather big program, where I use functions from the `random` module in different files. I would like to be able to set the random seed once, at one place, to make the program always return the same results. Can that even be achieved in `python`? | The main python module that is run should `import random` and call `random.seed(n)` - this is shared between all other imports of `random` as long as somewhere else doesn't reset the seed. |
Python - inheriting from old-style classes | 11,527,921 | 18 | 2012-07-17T17:42:26Z | 11,527,947 | 29 | 2012-07-17T17:44:15Z | [
"python",
"inheritance",
"telnet"
] | I am trying to connect via telnet to a laboratory instrument. I'd like to extend the `Telnet` class from the `telnetlib` module in the standard library, to include functions specific to our instrument:
```
import telnetlib
class Instrument(telnetlib.Telnet):
def __init__(self, host=None, port=0, timeout=5):
... | You need to call the [constructor](http://docs.python.org/reference/datamodel.html#object.__init__) like this:
```
telnetlib.Telnet.__init__(self, host, port, timeout)
```
You need to add the explicit `self` since `telnet.Telnet.__init__` is not a *bound method* but rather an *unbound method*, i.e. witout an instance... |
Python - inheriting from old-style classes | 11,527,921 | 18 | 2012-07-17T17:42:26Z | 11,528,159 | 11 | 2012-07-17T17:57:05Z | [
"python",
"inheritance",
"telnet"
] | I am trying to connect via telnet to a laboratory instrument. I'd like to extend the `Telnet` class from the `telnetlib` module in the standard library, to include functions specific to our instrument:
```
import telnetlib
class Instrument(telnetlib.Telnet):
def __init__(self, host=None, port=0, timeout=5):
... | You have to inherit from `object`, and you must put it after the old-style class you are trying to inherit from (so that `object`'s methods aren't found first):
```
>>> class Instrument(telnetlib.Telnet,object):
... def __init__(self, host=None, port=0, timeout=5):
... super(Instrument,self).__init__(host,... |
Python ConfigParser: Checking for option existence | 11,527,939 | 14 | 2012-07-17T17:43:23Z | 11,528,082 | 15 | 2012-07-17T17:52:11Z | [
"python",
"configparser"
] | I'm using Python's ConfigParser to create a configuration file. I want to check if a section has a particular option defined and, if it does, get the value. If the option isn't defined, I just want to continue without any special behavior. There seem to be two ways of doing this.
```
if config.has_option('Options', 'm... | The choice between try/except and if-condition is a fuzzy line.
1. If you expect the exception to be quite rare, use try/except as it more closely models thinking
2. Conversely, "expected" exceptions like a configuration item missing, are part of the normal flow of control and the code should reflect that.
There is n... |
OpenCV: Converting from NumPy to IplImage in Python | 11,528,009 | 7 | 2012-07-17T17:48:12Z | 11,528,490 | 14 | 2012-07-17T18:18:13Z | [
"python",
"opencv"
] | I have an image that I load using cv2.imread(). This returns an NumPy array. However, I need to pass this into a 3rd party API that requires the data in IplImage format.
I've scoured everything I could and I've found instances of converting from IplImage to CvMat,and I've found some references to converting in C++, bu... | You can do like this.
```
source = cv2.imread() # source is numpy array
bitmap = cv.CreateImageHeader((source.shape[1], source.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring(),
source.dtype.itemsize * 3 * source.shape[1])
```
`bitmap` here is `cv2.cv.iplimage` |
Determining duplicate values in an array | 11,528,078 | 17 | 2012-07-17T17:52:00Z | 11,528,581 | 8 | 2012-07-17T18:25:45Z | [
"python",
"numpy",
"duplicates",
"unique"
] | Suppose I have an array
```
a = np.array([1, 2, 1, 3, 3, 3, 0])
```
How can I (efficiently, Pythonically) find which elements of `a` are duplicates (i.e., non-unique values)? In this case the result would be `array([1, 3, 3])` or possibly `array([1, 3])` if efficient.
I've come up with a few methods that appear to w... | I think this is most clear done outside of `numpy`. You'll have to time it against your `numpy` solutions if you are concerned with speed.
```
>>> import numpy as np
>>> from collections import Counter
>>> a = np.array([1, 2, 1, 3, 3, 3, 0])
>>> [item for item, count in Counter(a).iteritems() if count > 1]
[1, 3]
```
... |
Determining duplicate values in an array | 11,528,078 | 17 | 2012-07-17T17:52:00Z | 11,530,121 | 7 | 2012-07-17T20:10:22Z | [
"python",
"numpy",
"duplicates",
"unique"
] | Suppose I have an array
```
a = np.array([1, 2, 1, 3, 3, 3, 0])
```
How can I (efficiently, Pythonically) find which elements of `a` are duplicates (i.e., non-unique values)? In this case the result would be `array([1, 3, 3])` or possibly `array([1, 3])` if efficient.
I've come up with a few methods that appear to w... | People have already suggested `Counter` variants, but here's one which doesn't use a listcomp:
```
>>> from collections import Counter
>>> a = [1, 2, 1, 3, 3, 3, 0]
>>> (Counter(a) - Counter(set(a))).keys()
[1, 3]
```
[Posted not because it's efficient -- it's not -- but because I think it's cute that you can subtrac... |
Python hadoop streaming : Setting a job name | 11,528,429 | 7 | 2012-07-17T18:14:33Z | 11,528,661 | 10 | 2012-07-17T18:31:53Z | [
"python",
"hadoop",
"mapreduce",
"hadoop-streaming"
] | * I have a job that runs on my cluster using hadoop-streaming
* I have to start a new job for which I want to add a job name, how can I pass that option on command-line or file to setup a job name?
* In Java, you can do this by saying
> ```
> JobConf conf = new JobConf(WordCount.class);
> conf.setJobName("wordcount");... | Configure the property using the -D key=value notation:
```
-D mapred.job.name='My Job'
```
You can list a whole bunch of options by calling the streaming jar with just the `-info` argument |
Running Scrapy spiders in a Celery task | 11,528,739 | 28 | 2012-07-17T18:36:54Z | 11,657,239 | 27 | 2012-07-25T19:34:37Z | [
"python",
"django",
"scrapy",
"celery"
] | I have a Django site where a scrape happens when a user requests it, and my code kicks off a Scrapy spider standalone script in a new process. Naturally, this isn't working with an increase of users.
Something like this:
```
class StandAloneSpider(Spider):
#a regular spider
settings.overrides['LOG_ENABLED'] = Tr... | Okay here is how I got Scrapy working with my Django project that uses Celery for queuing up what to crawl. The actual workaround came primarily from joehillen's code located here <http://snippets.scrapy.org/snippets/13/>
First the `tasks.py` file
```
from celery import task
@task()
def crawl_domain(domain_pk):
... |
Running Scrapy spiders in a Celery task | 11,528,739 | 28 | 2012-07-17T18:36:54Z | 18,198,443 | 7 | 2013-08-12T23:43:37Z | [
"python",
"django",
"scrapy",
"celery"
] | I have a Django site where a scrape happens when a user requests it, and my code kicks off a Scrapy spider standalone script in a new process. Naturally, this isn't working with an increase of users.
Something like this:
```
class StandAloneSpider(Spider):
#a regular spider
settings.overrides['LOG_ENABLED'] = Tr... | I set [CELERYD\_MAX\_TASKS\_PER\_CHILD](http://docs.celeryproject.org/en/latest/configuration.html#std%3asetting-CELERYD_MAX_TASKS_PER_CHILD) to 1 in the settings file and that took care of the issue. The worker daemon starts a new process after each spider run and that takes care of the reactor. |
Why does Python say this Netscape cookie file isn't valid? | 11,529,428 | 6 | 2012-07-17T19:24:32Z | 11,536,599 | 10 | 2012-07-18T07:47:31Z | [
"python",
"cookies"
] | I'm writing a [Google Scholar](https://en.wikipedia.org/wiki/Google_Scholar) parser, and based on [this answer](http://stackoverflow.com/a/11485040/869912), I'm setting cookies before grabbing the HTML. This is the contents of my `cookies.txt` file:
```
# Netscape HTTP Cookie File
# http://curlm.haxx.se/rfc/cookie_spe... | I see nothing in your example code or copy of the cookies.txt file that is obviously wrong.
I've checked the source code for the [`MozillaCookieJar._really_load` method](http://hg.python.org/cpython/file/5470dc81caf9/Lib/http/cookiejar.py#l1989), which throws the exception that you see.
The first thing this method do... |
Flask SQLAlchemy query, specify column names | 11,530,196 | 30 | 2012-07-17T20:16:38Z | 11,535,992 | 8 | 2012-07-18T07:07:28Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | How do I specify the column that I want in my query using a model. (it selects all columns by default) I know how to do this with the sqlalchmey session: `session.query(self.col1)` but how do I do with with models. I can't do `SomeModel.query()`, is there a way? | It is the same:
```
session.query(SomeModel.col1)
``` |
Flask SQLAlchemy query, specify column names | 11,530,196 | 30 | 2012-07-17T20:16:38Z | 12,054,872 | 65 | 2012-08-21T12:29:42Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] | How do I specify the column that I want in my query using a model. (it selects all columns by default) I know how to do this with the sqlalchmey session: `session.query(self.col1)` but how do I do with with models. I can't do `SomeModel.query()`, is there a way? | You can use the `with_entities()` method to restrict which columns you'd like to return in the result. ([documentation](http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.with_entities))
```
result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)
```
Depending on your requir... |
Python Finding Index of Maximum in List | 11,530,799 | 7 | 2012-07-17T21:00:23Z | 11,530,835 | 16 | 2012-07-17T21:02:59Z | [
"python",
"list",
"indexing",
"max"
] | ```
def main():
a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
max = 0
for number in a:
if number > max:
max = number
print max
if __name__ == '__main__':
main()
```
I am able to get the maximum value in the array (**without using max()** of course...). How can I get the index (pos... | A simple one liner of:
```
max( (v, i) for i, v in enumerate(a) )[1]
```
This avoids having to `.index()` the list after. |
Python Finding Index of Maximum in List | 11,530,799 | 7 | 2012-07-17T21:00:23Z | 11,530,997 | 19 | 2012-07-17T21:15:49Z | [
"python",
"list",
"indexing",
"max"
] | ```
def main():
a = [2,1,5,234,3,44,7,6,4,5,9,11,12,14,13]
max = 0
for number in a:
if number > max:
max = number
print max
if __name__ == '__main__':
main()
```
I am able to get the maximum value in the array (**without using max()** of course...). How can I get the index (pos... | In my code I would use this:
```
>>> max(enumerate(a),key=lambda x: x[1])[0]
3
``` |
scons construction environment inheritance | 11,531,218 | 5 | 2012-07-17T21:35:37Z | 11,544,643 | 7 | 2012-07-18T15:15:06Z | [
"c++",
"python",
"c",
"build",
"scons"
] | I'm having a bit of an issue refactoring a build system based on scons. We have a C/C++ source tree with several different output objects (dlls, executables, test executables), and a somewhat heterogeneous layout for our source files (although most of it is in 'module' directories with `src/` and `inc/` directories).
... | The best way I know of is from your master SConstruct just do this:
```
env = Environment()
env.SConscript('src/SConscript', 'env')
```
Then in your src/SConscript file:
```
Import('env')
```
Then you can refer to the env variable as you would in your SConstruct file. If you don't want to mutate the SConstruct's e... |
Adding an attribute to a python dictionary from the standard library | 11,532,060 | 8 | 2012-07-17T23:04:26Z | 11,532,079 | 21 | 2012-07-17T23:06:18Z | [
"python",
"attributes",
"overloading",
"dictionary"
] | I was wondering if you could add an attibute to a python dictionary.
```
class myclass():
def __init__():
self.mydict = {} #initialize a regular dict
self.mydict.newattribute = "A description of what this dictionary will hold"
>>>AttributeError: 'dict' object has no attribute 'newattribute'
se... | Just derive from `dict`:
```
class MyDict(dict):
pass
```
Instances of `MyDict` can have custom attributes:
```
>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'
``` |
Reproduce the Unix cat command in Python | 11,532,980 | 6 | 2012-07-18T01:11:18Z | 11,533,066 | 9 | 2012-07-18T01:22:00Z | [
"python",
"cat"
] | I am currently reproducing the following Unix command:
```
cat command.info fort.13 > command.fort.13
```
in Python with the following:
```
with open('command.fort.13', 'w') as outFile:
with open('fort.13', 'r') as fort13, open('command.info', 'r') as com:
for line in com.read().split('\n'):
if line.stri... | The easiest way might be simply to forget about the lines, and just read in the entire file, then write it to the output:
```
with open('command.fort.13', 'wb') as outFile:
with open('command.info', 'rb') as com, open('fort.13', 'rb') as fort13:
outFile.write(com.read())
outFile.write(fort13.read()... |
How can I combine dictionaries with the same keys in python? | 11,533,274 | 4 | 2012-07-18T01:55:07Z | 11,533,303 | 9 | 2012-07-18T01:58:05Z | [
"python",
"dictionary"
] | Let's say I have a list of dictionaries like so:
```
dict[0] is
{'key_a': valuex1,
'key_b': valuex2,
'key_c': valuex3}
dict[1] is
{'key_a': valuey1,
'key_b': valuey2,
'key_c': valuey3}
dict[2] is
{'key_a': valuez1,
'key_b': valuez2,
'key_c': valuez3}
```
I would like to take these and construct a big dictiona... | ```
big_dict = {}
for k in dicts[0]:
big_dict[k] = [d[k] for d in dicts]
```
(I renamed your `dict` to `dicts` since dict is a built-in, and dicts makes more sense.)
Or, with a dict comprehension:
```
{ k:[d[k] for d in dicts] for k in dicts[0] }
```
or, for Python <2.7:
```
dict((k, [d[k] for d in dicts]) for... |
python multiprocessing pool retries | 11,533,405 | 5 | 2012-07-18T02:13:39Z | 11,624,927 | 7 | 2012-07-24T05:54:04Z | [
"python",
"multiprocessing"
] | Is there a way to re-send a piece of data for processing, if the original computation failed, using a simple pool?
```
import random
from multiprocessing import Pool
def f(x):
if random.getrandbits(1):
raise ValueError("Retry this computation")
return x*x
p = Pool(5)
# If one of these f(x) calls fails, ... | If you can (or don't mind) retrying immediately, use a decorator wrapping the function:
```
import random
from multiprocessing import Pool
from functools import wraps
def retry(f):
@wraps(f)
def wrapped(*args, **kwargs):
while True:
try:
return f(*args, **kwargs)
... |
PyInstaller won't load the PyQt's images to the GUI | 11,534,293 | 7 | 2012-07-18T04:26:45Z | 11,547,144 | 8 | 2012-07-18T17:36:40Z | [
"python",
"python-2.7",
"pyqt4",
"pyinstaller"
] | I've been having some complications to pass my script into an executable, but I finally managed to. The main problem is that PyInstaller doesn't load the images to the GUI.
This is how it should look like:

This is how it looks like:
![How it looks like]... | I was able to solve this, and this should help others as well:
* Create the .spec file with the following command:
> ```
> python Makespec.py --noconsole --icon="youricon.ico" --name="App name" program.py
> ```
* Open the .spec file (eg.: App name/App name.spec) and you should see something like this:
> ```
> a = A... |
How to fix "Attempted relative import in non-package" even with __init__.py | 11,536,764 | 338 | 2012-07-18T07:59:14Z | 11,536,794 | 264 | 2012-07-18T08:01:04Z | [
"python",
"python-import"
] | I'm trying to follow [PEP 328](http://www.python.org/dev/peps/pep-0328/), with the following directory structure:
```
pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py
```
In `core_test.py` I have the following import statement
```
from ..components.core import Ga... | Yes. You're not using it as a package.
```
python -m pkg.tests.core_test
``` |
How to fix "Attempted relative import in non-package" even with __init__.py | 11,536,764 | 338 | 2012-07-18T07:59:14Z | 11,537,218 | 354 | 2012-07-18T08:26:51Z | [
"python",
"python-import"
] | I'm trying to follow [PEP 328](http://www.python.org/dev/peps/pep-0328/), with the following directory structure:
```
pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py
```
In `core_test.py` I have the following import statement
```
from ..components.core import Ga... | To elaborate on @Ignacio's answer:
The Python import mechanism works relative to the `__name__` of the current file. When you execute a file directly, it doesn't have its usual name, but has `"__main__"` as its name instead. So relative imports don't work.
You can, as Igancio suggested, execute it using the `-m` opti... |
How to fix "Attempted relative import in non-package" even with __init__.py | 11,536,764 | 338 | 2012-07-18T07:59:14Z | 19,190,695 | 111 | 2013-10-04T21:00:02Z | [
"python",
"python-import"
] | I'm trying to follow [PEP 328](http://www.python.org/dev/peps/pep-0328/), with the following directory structure:
```
pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py
```
In `core_test.py` I have the following import statement
```
from ..components.core import Ga... | You can use `import components.core` directly if you append the current directory to `sys.path`:
```
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
``` |
How to fix "Attempted relative import in non-package" even with __init__.py | 11,536,764 | 338 | 2012-07-18T07:59:14Z | 27,876,800 | 71 | 2015-01-10T13:36:37Z | [
"python",
"python-import"
] | I'm trying to follow [PEP 328](http://www.python.org/dev/peps/pep-0328/), with the following directory structure:
```
pkg/
__init__.py
components/
core.py
__init__.py
tests/
core_test.py
__init__.py
```
In `core_test.py` I have the following import statement
```
from ..components.core import Ga... | It depends on how you want to launch your script.
If you want to [launch your UnitTest from the command line](https://docs.python.org/3/using/cmdline.html) in a classic way, that is:
```
python tests/core_test.py
```
Then, since in this case *'components'* and *'tests'* are siblings folders, you can import the relat... |
Matplotlib basemap: Popup box | 11,537,374 | 6 | 2012-07-18T08:38:09Z | 11,556,140 | 24 | 2012-07-19T07:46:18Z | [
"python",
"events",
"popup",
"matplotlib",
"matplotlib-basemap"
] | I want to know how to create a popup box in a basemap plot. When I hover my mouse over a location , it should trigger the popup box.
Is this possible? | Yes it is possible thanks to matplotlib's event handling framework. I couldn't find an already written example which does what you are particularly interested in so I wrote one (which I will put forward for inclusion in the matplotlib source).
I would read <http://matplotlib.sourceforge.net/users/event_handling.html> ... |
python pip install psycopg2 install error | 11,538,249 | 19 | 2012-07-18T09:27:04Z | 11,723,752 | 23 | 2012-07-30T14:40:05Z | [
"python",
"postgresql",
"pip"
] | I did a simple `pip install psycopg2` on mac system. It installed fine, but when I try to use psycopg2 I get the error:
```
Reason: Incompatible library version: _psycopg.so requires version 1.0.0 or later, but libssl.0.9.8.dylib provides version 0.9.8
```
`pip freeze` shows `psycopg2==2.4.5` just right. I have insta... | I ran into a similar problem after upgrading to Mountain Lion.
Instead of copying libssl.\* files per Slack's suggestion, make sure that `/usr/lib/libssl.dylib` is actually a soft link to the most up-to-date version of the library.
E.g., on my machine, `ls -l /usr/lib/libssl*` gives:
```
lrwxr-xr-x 1 root wheel ... |
python pip install psycopg2 install error | 11,538,249 | 19 | 2012-07-18T09:27:04Z | 12,397,173 | 50 | 2012-09-12T22:50:43Z | [
"python",
"postgresql",
"pip"
] | I did a simple `pip install psycopg2` on mac system. It installed fine, but when I try to use psycopg2 I get the error:
```
Reason: Incompatible library version: _psycopg.so requires version 1.0.0 or later, but libssl.0.9.8.dylib provides version 0.9.8
```
`pip freeze` shows `psycopg2==2.4.5` just right. I have insta... | The accepted answer here is correct (except I think it must be ln -fs , in fact I think it might even risk destabalizing your OS if not (?)). After bumping into this and dealing with it I just want to collect the full solution for this issue and the other lib problem (libcrypto.1.0.0.dylib) you will run into for Postgr... |
How to loop through a generator | 11,539,194 | 25 | 2012-07-18T10:21:46Z | 11,539,220 | 11 | 2012-07-18T10:23:46Z | [
"python",
"generator"
] | How can one loop through a generator? I thought about this way:
```
gen = function_that_returns_a_generator(param1, param2)
if gen: # in case the generator is null
while True:
try:
print gen.next()
except StopIteration:
break
```
Is there a more pythonic way? | ```
for item in function_that_returns_a_generator(param1, param2):
print item
```
You don't need to worry about the test to see if there is anything being returned by your function as if there's nothing returned you won't enter the loop. |
How to loop through a generator | 11,539,194 | 25 | 2012-07-18T10:21:46Z | 11,539,227 | 58 | 2012-07-18T10:24:11Z | [
"python",
"generator"
] | How can one loop through a generator? I thought about this way:
```
gen = function_that_returns_a_generator(param1, param2)
if gen: # in case the generator is null
while True:
try:
print gen.next()
except StopIteration:
break
```
Is there a more pythonic way? | Simply
```
for x in gen:
# whatever
```
will do the trick. Note that `if gen` always returns `True`. |
webdriver wait for one of a multiple elements to appear | 11,539,930 | 10 | 2012-07-18T11:09:18Z | 11,679,255 | 7 | 2012-07-26T23:00:15Z | [
"python",
"selenium",
"webdriver",
"selenium-webdriver",
"wait"
] | Is there a way to get a `webDriverWait` to wait for one of a number of elements to appear and to act accordingly based on which element appears?
At the moment I do a `WebDriverWait` within a try loop and if a timeout exception occurs I run the alternative code which waits for the other element to appear. This seems cl... | Create a function that takes a map of identifiers to xpath queries and returns the identifier that was matched.
```
def wait_for_one(self, elements):
self.waitForElement("|".join(elements.values())
for (key, value) in elements.iteritems():
try:
self.driver.find_element_by_xpath(value)
... |
File as command line argument for argparse - error message if argument is not valid | 11,540,854 | 24 | 2012-07-18T11:59:59Z | 11,541,450 | 33 | 2012-07-18T12:33:00Z | [
"python",
"argparse"
] | I am currently using argparse like this:
```
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
help="input file with two matrices", metavar="FILE")
args = parser.parse_args()
A, B = read(ar... | It's pretty easy actually. You just need to write a function which checks if the file is valid and writes an error otherwise. Use that function with the `type` option. Note that you could get more fancy and create a custom action by subclassing `argparse.Action`, but I don't think that is necessary here. In my example,... |
File as command line argument for argparse - error message if argument is not valid | 11,540,854 | 24 | 2012-07-18T11:59:59Z | 11,541,495 | 10 | 2012-07-18T12:34:58Z | [
"python",
"argparse"
] | I am currently using argparse like this:
```
import argparse
from argparse import ArgumentParser
parser = ArgumentParser(description="ikjMatrix multiplication")
parser.add_argument("-i", dest="filename", required=True,
help="input file with two matrices", metavar="FILE")
args = parser.parse_args()
A, B = read(ar... | I have just found this one:
```
def extant_file(x):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(x):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: x does not exist
raise argparse... |
How can I make a simple 3D line with Matplotlib? | 11,541,123 | 10 | 2012-07-18T12:14:22Z | 11,541,628 | 11 | 2012-07-18T12:40:48Z | [
"python",
"matplotlib"
] | I am new in python. I want to generate the lines, wich I get from an array in 3D.
Here is the code:
```
VecStart_x = [0,1,3,5]
VecStart_y = [2,2,5,5]
VecStart_z = [0,1,1,5]
VecEnd_x = [1,2,-1,6]
VecEnd_y = [3,1,-2,7]
VecEnd_z =[1,0,4,9]
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = p... | I guess, you want to plot 4 lines. Then you can try
```
for i in range(4):
ax.plot([VecStart_x[i], VecEnd_x[i]], [VecStart_y[i],VecEnd_y[i]],zs=[VecStart_z[i],VecEnd_z[i]])
```
As @Nicolas have suggested, do have a look at the matplotlib gallery. |
Basic query regarding bindtags in tkinter | 11,541,262 | 4 | 2012-07-18T12:23:22Z | 11,542,200 | 9 | 2012-07-18T13:10:32Z | [
"python",
"tkinter"
] | In the given example from [this post](http://stackoverflow.com/q/3501849/2596334), it was mentioned that if default bindtags are used then event value will not be visible inside definition (there will be lag by one).
There was some explanation regarding class binding.
I am a beginner, so would like to understand the... | When you do a binding on a widget, you aren't actually binding to a widget *per se*. When you do `mywidget.bind(...)`, what is actually happening is that the binding is associated with a *bind tag* with the same name as the widget.
When an event is detected, Tkinter first figures out which widget intercepted the event... |
Is SQLAlchemy still recommended if only used for raw sql query? | 11,543,266 | 13 | 2012-07-18T14:05:52Z | 11,543,303 | 16 | 2012-07-18T14:07:50Z | [
"python",
"orm",
"sqlalchemy",
"flask"
] | Using Flask, I'm curious to know if SQLAlchemy is still the best way to go for querying my database with raw SQL (direct `SELECT x FROM table WHERE ...`) instead of using the ORM or if there is an simpler yet powerful alternative ?
Thank for your reply. | I use SQLAlchemy for direct queries all the time.
Primary advantage: it gives you the best protection against SQL injection attacks. SQLAlchemy does the Right Thing whatever parameters you throw at it.
I find it works wonders for adjusting the generated SQL based on conditions as well. Displaying a result set with mu... |
Make all variables in a Python function global | 11,543,297 | 7 | 2012-07-18T14:07:27Z | 11,543,600 | 17 | 2012-07-18T14:24:34Z | [
"python",
"function",
"global-variables"
] | Is there a simple way to make all variables in a function global?
I have 20 odd variables in a function and naming them global one by one doesn't make nice code... to me anyway :) | There's no way to declare them all as global, and you really don't want to. Those 20 variables probably should be turned into an object with 20 attributes instead. |
Make all variables in a Python function global | 11,543,297 | 7 | 2012-07-18T14:07:27Z | 11,543,718 | 30 | 2012-07-18T14:29:25Z | [
"python",
"function",
"global-variables"
] | Is there a simple way to make all variables in a function global?
I have 20 odd variables in a function and naming them global one by one doesn't make nice code... to me anyway :) | ## Warning: Don't try this at home, you might burn it down.
There is no legitimate reason to do the following in the course of normal day-to-day programming. Please review the other answers to this question for more realistic alternatives.
I can barely imagine why you would want to do this, but here is a way to do it... |
Make all variables in a Python function global | 11,543,297 | 7 | 2012-07-18T14:07:27Z | 11,545,908 | 12 | 2012-07-18T16:19:08Z | [
"python",
"function",
"global-variables"
] | Is there a simple way to make all variables in a function global?
I have 20 odd variables in a function and naming them global one by one doesn't make nice code... to me anyway :) | The pythonic way to do this is either to keep the variables in local scope (i.e. define them within each function) and pass them between the functions as arguments / return values; or to keep your variables as attributes of an object or class making your "functions" methods in that class. Either way is OK, but the `glo... |
Python ASCII and Unicode decode error | 11,544,541 | 10 | 2012-07-18T15:09:48Z | 11,544,596 | 43 | 2012-07-18T15:12:47Z | [
"python",
"string",
"sqlite",
"character-encoding"
] | I got this very very frustrating error when inserting a certain string into my database. It said something like:
> Python cannot decode byte characters, expecting unicode"
After a lot of searching, I saw that I could overcome this error by encoding my string into [Unicode](http://en.wikipedia.org/wiki/Unicode). I try... | You need to take a disciplined approach. [Pragmatic Unicode, or How Do I Stop The Pain?](http://nedbatchelder.com/text/unipain.html) has everything you need.
If you get that error on that line of code, then the problem is that `string` is a byte string, and Python 2 is implicitly trying to decode it to Unicode for you... |
Python ASCII and Unicode decode error | 11,544,541 | 10 | 2012-07-18T15:09:48Z | 11,544,648 | 10 | 2012-07-18T15:15:25Z | [
"python",
"string",
"sqlite",
"character-encoding"
] | I got this very very frustrating error when inserting a certain string into my database. It said something like:
> Python cannot decode byte characters, expecting unicode"
After a lot of searching, I saw that I could overcome this error by encoding my string into [Unicode](http://en.wikipedia.org/wiki/Unicode). I try... | The `encode` method should be used on `unicode` objects to convert them to a `str` object with a given encoding. The `decode` method should be used on `str` objects of a given encoding to convert them `unicode` objects.
I suppose that your database store strings in UTF-8. So when you get strings from the database, con... |
Python dictionary list merging | 11,545,602 | 3 | 2012-07-18T16:04:26Z | 11,545,942 | 7 | 2012-07-18T16:20:48Z | [
"python",
"list",
"set",
"structure",
"dictionary"
] | I want to join the dictionaries in a list whose key 'user' are the same, but I don't realize how. for example:
```
[{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
```
would become:
```
[{'count2': 34, 'count4': 233, 'user': 2 },
{'count2': 234, 'use... | ```
from collections import defaultdict
dl = [{'count2': 34, 'user': 2},
{'count4': 233, 'user': 2},
{'count2': 234, 'user': 4},
{'count4': 344, 'user': 5}]
print dl
dd = defaultdict(dict)
for d in dl:
dd[d['user']].update(d)
print dd.values()
``` |
Is it possible to TDD when writing a test runner? | 11,545,759 | 2 | 2012-07-18T16:11:20Z | 11,546,149 | 10 | 2012-07-18T16:34:38Z | [
"python",
"django",
"testing",
"tdd",
"bootstrapping"
] | I am currently writing a new test runner for Django and I'd like to know if it's possible to TDD my test runner using my own test runner. Kinda like compiler bootstrapping where a compiler compiles itself.
Assuming it's possible, how can it be done? | Yes. One of the examples Kent Beck works through in his book "Test Driven Development: By Example" is a test runner. |
How to make db dumpfile in django | 11,546,151 | 7 | 2012-07-18T16:34:48Z | 11,546,254 | 9 | 2012-07-18T16:39:44Z | [
"python",
"django",
"django-models",
"django-commands"
] | I want to make a dump in django irrespective of database I am using and can be loaded later. The command 'dumpdata' is perfect for this, but it is printing output on console. More over I am calling it using call\_command function so I cannot store its content in any variable as it is printing output on console.
Please... | You just use it like that:
```
./manage.py dumpdata > data_dump.json
```
After that action, there will be `data_dump.json` file in the directory in which you executed that command.
There are multiple options coming with that, but you probably already know it. The thing you need to know is how to **redirect output fr... |
How to make db dumpfile in django | 11,546,151 | 7 | 2012-07-18T16:34:48Z | 11,546,881 | 14 | 2012-07-18T17:20:06Z | [
"python",
"django",
"django-models",
"django-commands"
] | I want to make a dump in django irrespective of database I am using and can be loaded later. The command 'dumpdata' is perfect for this, but it is printing output on console. More over I am calling it using call\_command function so I cannot store its content in any variable as it is printing output on console.
Please... | You *can* choose a file to put the output of dumpdata into if you call it from within Python using `call_command`, for example:
```
from django.core.management import call_command
output = open(output_filename,'w') # Point stdout at a file for dumping data to.
call_command('dumpdata','model_name',format='json',indent... |
Python multiprocessing keyword arguments | 11,546,858 | 8 | 2012-07-18T17:18:13Z | 11,546,979 | 12 | 2012-07-18T17:26:36Z | [
"python",
"arguments",
"multiprocessing",
"keyword-argument"
] | Here is a simple example of using keyword arguments in a function call. Nothing special.
```
def foo(arg1,arg2, **args):
print arg1, arg2
print (args)
print args['x']
args ={'x':2, 'y':3}
foo(1,2,**args)
```
Which prints, as expected:
```
1 2
{'y': 3, 'x': 2}
2
```
I am trying to pass the same style ke... | The dictionary you are using as keyword args should be passed in as the `kwargs` parameter to the `Process` object.
```
pool = [multiprocessing.Process(target=stretch, args= (shared_arr,slice(i, i+step)),kwargs=args) for i in range (0, y, step)]
``` |
Why is Python's "sorted()" slower than "copy, then .sort()" | 11,547,588 | 7 | 2012-07-18T18:04:14Z | 11,547,729 | 8 | 2012-07-18T18:13:14Z | [
"python",
"performance",
"sorting",
"optimization"
] | Here is the code I ran:
```
import timeit
print timeit.Timer('''a = sorted(x)''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').timeit(number = 1000)
print timeit.Timer('''a=x[:];a.sort()''', '''x = [(2, 'bla'), (4, 'boo'), (3, 4), (1, 2) , (0, 1), (4, 3), (2, 1) , (0, 0)]''').... | The difference you are looking at is miniscule, and completely goes away for longer lists. Simply adding `* 1000` to the definition of `x` gives the following results on my machine:
```
2.74775004387
2.7489669323
```
My best guess for the reason that `sorted()` was slightly slower for you is that `sorted()` needs to ... |
NumPy or Pandas: Keeping array type as integer while having a NaN value | 11,548,005 | 28 | 2012-07-18T18:30:02Z | 11,548,224 | 30 | 2012-07-18T18:43:27Z | [
"python",
"numpy",
"int",
"pandas",
"data-type-conversion"
] | Is there a preferred way to keep the data type of a NumPy array fixed as `int` (or `int64` or whatever), while still having an element inside listed as `numpy.NaN`?
In particular, I am converting an in-house data structure to a Pandas DataFrame. In our structure, we have integer-type columns that still have NaN's (but... | `NaN` can't be stored in an integer array. This is a known limitation of pandas at the moment; I have been waiting for progress to be made with NA values in NumPy (similar to NAs in R), but it will be at least 6 months to a year before NumPy gets these features, it seems:
<http://pandas.pydata.org/pandas-docs/stable/g... |
Check if key exists in dictionary. If not, append it | 11,548,302 | 5 | 2012-07-18T18:49:12Z | 11,548,328 | 12 | 2012-07-18T18:50:26Z | [
"python",
"dictionary"
] | I have a large python dict created from json data and am creating a smaller dict from the large one. Some elements of the large dictionary have a key called 'details' and some elements don't. What I want to do is check if the key exists in each entry in the large dictionary and if not, append the key 'details' with the... | You don't need a `collections.defaultdict`. You can use the `setdefault` method of dictionary objects.
```
d = {}
bar = d.setdefault('foo','bar') #returns 'bar'
print bar # bar
print d #{'foo': 'bar'}
```
As others have noted, if you don't want to add the key to the dictionary, you can use the `get` method.
here's ... |
logging.info doesn't show up on console but warn and error do | 11,548,674 | 10 | 2012-07-18T19:14:52Z | 11,548,754 | 17 | 2012-07-18T19:19:29Z | [
"python"
] | I am sure I have to make change somewhere, but not sure where; this is what is happening:
```
import logging
logging.info('I am info')
```
doesn't print on the terminal but:
```
import logging
logging.warn('I am warning')
```
does print `I am warning`.
Is there a environment level change that I can make so that th... | The root logger always defaults to WARNING level. Try calling
```
logging.getLogger().setLevel(logging.INFO)
```
and you should be fine. |
twisted get body of POST request | 11,548,682 | 5 | 2012-07-18T19:15:21Z | 11,549,600 | 11 | 2012-07-18T20:19:45Z | [
"python",
"http",
"post",
"twisted"
] | Ok,
This should be simple, since people do it all the time. I want to get the body of a POST request sent a twisted `Agent`. This is created with a twisted `FileBodyProducer`. On the server side, I get a `request` object for my `render_POST` method.
How do I retrieve the body?
server:
```
from twisted.web import se... | All right, so it's as simple as calling `request.content.read()`. This, as far as I can tell, is undocumented in the [API](http://twistedmatrix.com/documents/current/api/twisted.web.http.Request.html).
Here's the updated code for the client:
```
from twisted.internet import reactor
from twisted.web.client import Agen... |
python unit test: assertEqual on same objects throwing AssertionError | 11,549,309 | 4 | 2012-07-18T20:01:34Z | 11,549,365 | 12 | 2012-07-18T20:04:41Z | [
"python",
"django",
"unit-testing",
"django-unittest"
] | I have a class as
```
class PlaylistManager(models.Manager):
def add_playlist(self, name):
playlist = Playlist(name=name)
playlist.save()
return playlist
def get_playlist_with_id(self, id):
return super(PlaylistManager, self).get_query_set().filter(pk=id)
class Playlist(models... | `assertEqual()` uses the `==` operator to compare the classes. The default `==` operator of user-defined classes compares instances by object identity. This means two instances are only considered equal when they are the *same* instance. |
Pythonic way to calculate offsets of an array | 11,549,928 | 6 | 2012-07-18T20:38:21Z | 11,550,052 | 7 | 2012-07-18T20:46:34Z | [
"python",
"arrays",
"numpy"
] | I am trying to calculate the origin and offset of variable size arrays and store them in a dictionary. Here is the likely non-pythonic way that I am achieving this. I am not sure if I should be looking to use map, a lambda function, or list comprehensions to make the code more pythonic.
Essentially, I need to cut chun... | This code looks fine except for your use of `defaultdict`. A list seems like a much better data structure because:
* Your keys are sequential
* you are storing a list whose only element is another list in your dict.
One thing you could do:
* use the ternary operator (I'm not sure if this would be an improvement, but... |
Having more than one parameter with def in python | 11,550,285 | 3 | 2012-07-18T21:01:05Z | 11,550,319 | 7 | 2012-07-18T21:03:44Z | [
"python",
"function"
] | So in java you can do something like this if you don't know how many parameters you are going to get
```
private void testMethod(String... testStringArray){
}
```
How can I do something like this in python
as I can't do something like this right?
```
def testMethod(...listA):
``` | Are you talking about variable length argument lists? If so, take a look at `*args`, `**kwargs`.
See this [Basic Guide](http://basicpython.com/understanding-arguments-args-and-kwargs-in-python/) and [How to use \*args and \*\*kwargs in Python](http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python... |
Python date range generator over business days | 11,550,314 | 6 | 2012-07-18T21:03:21Z | 11,550,426 | 19 | 2012-07-18T21:11:58Z | [
"python"
] | I'm trying to create a generator function to iterate over business days (weekdays), skipping weekends (and holidays would be nice too!). So far, I only have a function that simply iterates over days:
```
def daterange(startDate, endDate):
for i in xrange(int((endDate - startDate).days)):
yield startDate + ... | I would strong recommend using the [dateutil](http://labix.org/python-dateutil) library for such tasks. A basic (*not* ignoring holidays) iterator over business days then simply is:
```
from dateutil.rrule import DAILY, rrule, MO, TU, WE, TH, FR
def daterange(start_date, end_date):
return rrule(DAILY, dtstart=start... |
Correct way to pause Python program | 11,552,320 | 62 | 2012-07-19T00:28:17Z | 11,552,350 | 97 | 2012-07-19T00:32:24Z | [
"python"
] | I've been using the input function as a way to pause my scripts
```
print("something")
wait = input("PRESS ENTER TO CONTINUE.")
print("something")
```
is there a formal way to do this? | Seems fine to me (or `raw_input()` in Python 2.X). Alternatively you could use `time.sleep()` if you want to pause for a certain number of seconds.
```
import time
print("something")
time.sleep(5.5) # pause 5.5 seconds
print("something")
``` |
Correct way to pause Python program | 11,552,320 | 62 | 2012-07-19T00:28:17Z | 11,552,356 | 16 | 2012-07-19T00:33:05Z | [
"python"
] | I've been using the input function as a way to pause my scripts
```
print("something")
wait = input("PRESS ENTER TO CONTINUE.")
print("something")
```
is there a formal way to do this? | I assume you want to pause without input
Use
[time.sleep(secs)](http://docs.python.org/library/time.html#time.sleep) |
Correct way to pause Python program | 11,552,320 | 62 | 2012-07-19T00:28:17Z | 32,909,325 | 7 | 2015-10-02T14:21:14Z | [
"python"
] | I've been using the input function as a way to pause my scripts
```
print("something")
wait = input("PRESS ENTER TO CONTINUE.")
print("something")
```
is there a formal way to do this? | use:
```
import os
os.system("pause")
``` |
Python 2.7: Setting I/O Encoding, âÃô? | 11,552,467 | 3 | 2012-07-19T00:46:02Z | 11,552,543 | 9 | 2012-07-19T00:56:32Z | [
"python",
"character-encoding"
] | Attempting to write a line to a text file in Python 2.7, and have the following code:
```
# -*- coding: utf-8 -*-
...
f = open(os.path.join(os.path.dirname(__file__), 'output.txt'), 'w')
f.write('Smithâs BaseBall Cap') // Note the strangely shaped apostrophe
```
However, in output.txt, I get `SmithâÃôs BaseBall... | You have declared your file to be encoded with UTF-8, so your byte-string literal is in UTF-8. The curly apostrophe is [U+2019](http://www.fileformat.info/info/unicode/char/2019/index.htm). In UTF-8, this is encoded as three bytes, \xE2\x80\x99. Those three bytes are written to your output file. Then, when you examine ... |
Why is `object() > 0` True in Python? | 11,553,862 | 5 | 2012-07-19T04:15:19Z | 11,553,877 | 12 | 2012-07-19T04:17:19Z | [
"python"
] | ```
In [32]: object() > 0
Out[32]: True
```
In fact, it's greater than any integer I've tried. | Because Python 2.x tried to make available comparison between objects of different types (even if they do not make sense).
It was fixed on Python 3:
```
>>> object() > 0
Traceback (most recent call last):
File "<pyshell#320>", line 1, in <module>
object() > 0
TypeError: unorderable types: object() > int()
```
... |
Mac OS X Lion Python Ctype CDLL error lib.so.6 : image not found | 11,554,355 | 4 | 2012-07-19T05:18:34Z | 11,554,403 | 10 | 2012-07-19T05:22:37Z | [
"python",
"osx",
"osx-lion"
] | I am a beginner in Python. When I tried the following Python sample code with type library on Mac OS X Lion:
```
#hello.py
from ctypes import *
cdll.LoadLibrary("libc.so.6")
libc = CDLL("libc.so.6")
message_string = "Hello World! Hello Python!\n"
libc.printf("Testing :%s",message_string)
//
```
An error occurred as f... | Shared libraries on Mac OS X tend to have the extension `.dylib` instead of `.so`. In this case, `/usr/lib/libc.dylib` is what you want so load `libc.dylib`. |
How should I read a file line-by-line in Python? | 11,555,468 | 72 | 2012-07-19T06:58:25Z | 11,555,506 | 13 | 2012-07-19T07:01:35Z | [
"python",
"python-3.x",
"python-2.7"
] | In pre-historic times (Python 1.4) we did:
```
fp = open('filename.txt')
while 1:
line = fp.readline()
if not line:
break
print line
```
after Python 2.1, we did:
```
for line in open('filename.txt').xreadlines():
print line
```
before we got the convenient iterator protocol in Python 2.3, a... | Yes,
```
with open('filename.txt') as fp:
for line in fp:
print line
```
is the way to go.
It is not more verbose. It is more safe. |
How should I read a file line-by-line in Python? | 11,555,468 | 72 | 2012-07-19T06:58:25Z | 11,555,509 | 111 | 2012-07-19T07:01:48Z | [
"python",
"python-3.x",
"python-2.7"
] | In pre-historic times (Python 1.4) we did:
```
fp = open('filename.txt')
while 1:
line = fp.readline()
if not line:
break
print line
```
after Python 2.1, we did:
```
for line in open('filename.txt').xreadlines():
print line
```
before we got the convenient iterator protocol in Python 2.3, a... | There is exactly one reason why the following is prefered:
```
with open('filename.txt') as fp:
for line in fp:
print line
```
We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close... |
How to check if a list exists in Python | 11,556,234 | 3 | 2012-07-19T07:53:23Z | 11,556,325 | 8 | 2012-07-19T07:58:10Z | [
"python"
] | What is the easiest way to check to see if a list or dict exists in python ?
Im using the following but this isn't working:
```
if len(list) == 0:
print "Im not here"
```
Thanks, | You can use a try/except block:
```
try:
#work with list
except NameError:
print "list isn't defined"
``` |
Sending data from HTML form to a Python script in Flask | 11,556,958 | 10 | 2012-07-19T08:37:36Z | 11,566,296 | 24 | 2012-07-19T17:35:54Z | [
"python",
"html",
"forms",
"input",
"flask"
] | I have the code below in my Python script:
```
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)
@app.route('/tx/index/')
def index():
"""Load start page where you select your pr... | You are new to html also. Form tag in html need two attributes set
1. Action - Where should form data be sent on clicking submit. It's an url.
2. Method - Either get request or post request.
index method in your example is called a view in flask (and other mvc frameworks). It can handle only GET requests.
Following c... |
Sending data from HTML form to a Python script in Flask | 11,556,958 | 10 | 2012-07-19T08:37:36Z | 30,699,653 | 12 | 2015-06-07T23:52:36Z | [
"python",
"html",
"forms",
"input",
"flask"
] | I have the code below in my Python script:
```
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)
@app.route('/tx/index/')
def index():
"""Load start page where you select your pr... | Let code talk!
You need your method that will receive data.
```
from flask import request
@app.route('/your_method_name', methods=['POST'])
def addRegion():
print("I got it!")
print(request.form['projectFilepath'])
...
```
And the HTML
```
<form action="your_method_name" method="post">
Project file... |
Python: sorting a dependency list | 11,557,241 | 8 | 2012-07-19T08:56:01Z | 11,564,323 | 11 | 2012-07-19T15:37:30Z | [
"python",
"sorting",
"topological-sort"
] | I'm trying to work out if my problem is solvable using the builtin sorted() function or if I need to do myself - old school using cmp would have been relatively easy.
My data-set looks like:
```
x = [
('business', Set('fleet','address'))
('device', Set('business','model','status','pack'))
('txn', Set('device','busine... | What you want is called a [topological sort](http://en.wikipedia.org/wiki/Topological_sorting). While it's possible to implement using the builtin `sort()`, it's rather awkward, and it's better to implement a topological sort directly in python.
Why is it going to be awkward? If you study the two algorithms on the wik... |
Tastypie, filtering many to many relationships | 11,557,790 | 6 | 2012-07-19T09:27:37Z | 11,610,355 | 7 | 2012-07-23T10:04:27Z | [
"python",
"django",
"tastypie"
] | I have two models that are linked by another model through a many to many relationship.
Here's the models themselves
```
class Posts(models.Model):
id = models.CharField(max_length=108, primary_key=True)
tags = models.ManyToManyField('Tags', through='PostTags')
class Tags(models.Model):
id = models.Char... | You can filter fields using lambda bundle attribute showing table name and field name.
```
tags = fields.ToManyField('django_app.api.TagsResource', attribute=lambda bundle: bundle.obj.tags.filter(tags__deleted=0))
``` |
Concatenating string and integer in python | 11,559,062 | 52 | 2012-07-19T10:41:07Z | 11,559,099 | 16 | 2012-07-19T10:42:49Z | [
"python",
"concatenation",
"string-concatenation"
] | In python say you have
```
s = "string"
i = 0
print s+i
```
will give you error
so you write
```
print s+str(i)
```
to not get error.
I think this is quite a clumsy way to handle int and string concatenation.
Even Java does not need explicit casting to String to do this sort
of concatenation.
Is there a better way... | String formatting, using the new-style `.format()` method (with the defaults [.format()](http://docs.python.org/library/stdtypes.html#str.format) provides):
```
'{}{}'.format(s, i)
```
Or the older, but "still sticking around", `%`-formatting:
```
'%s%d' %(s, i)
```
In both examples above there's *no* space betwe... |
Concatenating string and integer in python | 11,559,062 | 52 | 2012-07-19T10:41:07Z | 11,559,122 | 61 | 2012-07-19T10:43:47Z | [
"python",
"concatenation",
"string-concatenation"
] | In python say you have
```
s = "string"
i = 0
print s+i
```
will give you error
so you write
```
print s+str(i)
```
to not get error.
I think this is quite a clumsy way to handle int and string concatenation.
Even Java does not need explicit casting to String to do this sort
of concatenation.
Is there a better way... | Modern string formatting:
```
"{} and {}".format("string", 1)
``` |
Concatenating string and integer in python | 11,559,062 | 52 | 2012-07-19T10:41:07Z | 11,559,133 | 48 | 2012-07-19T10:44:18Z | [
"python",
"concatenation",
"string-concatenation"
] | In python say you have
```
s = "string"
i = 0
print s+i
```
will give you error
so you write
```
print s+str(i)
```
to not get error.
I think this is quite a clumsy way to handle int and string concatenation.
Even Java does not need explicit casting to String to do this sort
of concatenation.
Is there a better way... | No string formatting:
```
>> print 'Foo',0
Foo 0
``` |
__getattr__ on a class and not (or as well as) an instance | 11,559,120 | 4 | 2012-07-19T10:43:40Z | 11,559,173 | 7 | 2012-07-19T10:47:12Z | [
"python"
] | I know I can write code like:
```
class A :
def __getattr__ (self, name) :
return name
```
to trap access to undefined attributes on an instance of a class, so:
```
A().ATTR == 'ATTR'
```
is *True*. But is there any way to do this for the class itself? What I'd like to be able to is to have the followin... | You can use a [metaclass](http://docs.python.org/reference/datamodel.html#customizing-class-creation):
```
In [1]: class meta(type):
...: def __getattr__(self, name):
...: return name
...:
...:
In [2]: class A(object):
...: __metaclass__ = meta
...: def __getattr__(self... |
Pip freeze does not show repository paths for requirements file | 11,560,056 | 16 | 2012-07-19T11:39:02Z | 11,629,846 | 14 | 2012-07-24T11:25:09Z | [
"python",
"pip",
"dependency-management"
] | I've created an environment and added a package django-paramfield via git:
```
$ pip install git+https://bitbucket.org/DataGreed/django-paramfield.git
Downloading/unpacking git+https://bitbucket.org/DataGreed/django-paramfield.git
Cloning https://bitbucket.org/DataGreed/django-paramfield.git to /var/folders/9Z/9ZQZ1... | A simple but working workaround would be to install the package with the `-e` flag like `pip install -e git+https://bitbucket.org/DataGreed/django-paramfield.git#egg=django-paramfield`.
Than `pip freeze` shows the full source path of the package. It's not the best way it should be fixed in pip but it's working. The tr... |
R, Python: install packages on rpy2 | 11,561,258 | 2 | 2012-07-19T12:51:10Z | 25,322,360 | 8 | 2014-08-15T06:53:17Z | [
"python",
"import",
"package"
] | I'm using `R` in my Python script through the `rpy2` library and I need a [package](http://dirichletreg.r-forge.r-project.org) that is not in the default installation of R. How can I install it?
```
install.packages("DirichletReg", repos="http://r-forge.r-project.org")
```
won't work.
On Python:
```
>>> install.pac... | A lot has changed in the past two years, and Ricardo's answer didn't work for me. I recommend this method for installing from Python:
```
from rpy2.robjects.packages import importr
utils = importr('utils')
utils.install_packages('DirichletReg')
```
That `utils` package is the `R.utils` package whose documentation can... |
Django : What is the role of ModelState? | 11,561,722 | 14 | 2012-07-19T13:17:41Z | 11,562,044 | 15 | 2012-07-19T13:33:41Z | [
"python",
"django",
"django-models"
] | Sorry for not being this as programming question, but this caught my eye when I was trying to introspect my class objects.
I found this
```
{'user_id': 1, '_state': <django.db.models.base.ModelState object at 0x10ac2a750>, 'id': 2, 'playlist_id': 8}
```
What is the role of `_state` and what `ModelState` does? | From the Django source code, [\_state](https://github.com/django/django/blob/1.5/django/db/models/base.py#L330) is an instance variable defined in each Model instance that is an instance of [`ModelState`](https://github.com/django/django/blob/1.5/django/db/models/base.py#L311) that is defined as:
```
class ModelState(... |
Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works | 11,561,932 | 23 | 2012-07-19T13:28:36Z | 11,562,008 | 22 | 2012-07-19T13:31:36Z | [
"python",
"numpy",
"python-2.7"
] | I noticed this problem when a computer running Ubuntu was updated recently and the default version of Python changed to 2.7.
```
import json
import numpy as np
json.dumps(list(np.arange(5))) # Fails, throws a "TypeError: 0 is not JSON serializable"
json.dumps(np.arange(5).tolist()) # Works
```
Is there a difference ... | Because the elements of a NumPy array are not native ints, but of NUmPy's own types:
```
>>> type(np.arange(5)[0])
<type 'numpy.int64'>
```
You can use a custom [`JSONEncoder`](http://docs.python.org/library/json.html#json.JSONEncoder) to support the `ndarray` type returned by `arange`:
```
import numpy as np
import... |
Why does json.dumps(list(np.arange(5))) fail while json.dumps(np.arange(5).tolist()) works | 11,561,932 | 23 | 2012-07-19T13:28:36Z | 11,562,009 | 20 | 2012-07-19T13:31:37Z | [
"python",
"numpy",
"python-2.7"
] | I noticed this problem when a computer running Ubuntu was updated recently and the default version of Python changed to 2.7.
```
import json
import numpy as np
json.dumps(list(np.arange(5))) # Fails, throws a "TypeError: 0 is not JSON serializable"
json.dumps(np.arange(5).tolist()) # Works
```
Is there a difference ... | It looks like the `tolist()` method turns the numpy `int32` (or whatever size you have) back into an `int`, which JSON knows what to do with:
```
>>> list(np.arange(5))
[0, 1, 2, 3, 4]
>>> type(list(np.arange(5)))
<type 'list'>
>>> type(list(np.arange(5))[0])
<type 'numpy.int32'>
>>> np.arange(5).tolist()
[0, 1, 2, 3,... |
Is map(sum,zip(*list)) the fastest way to sum columns of list of arbitrary length? | 11,563,146 | 2 | 2012-07-19T14:35:23Z | 11,563,309 | 7 | 2012-07-19T14:43:35Z | [
"python",
"performance",
"list",
"optimization"
] | I would like to know if anyone can suggest a way to sum lists that is faster than map(sum, zip(\*list)).
Example:
```
import timeit
print timeit.Timer('''
[ (a[x]+b[x]+c[x]) for x in xrange(len(a)) ]
''', '''
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
''').timeit(number = 1000)
print timeit.Timer('''
map(... | How about this one?
```
print timeit.Timer('''
d.sum(axis=0)
''', '''
import numpy as np
a = range(200)
b = range(199,-1,-1)
c = range(1,201)
d = np.array([a,b,c])''').timeit(number = 1000)
```
Of course, this assumes that your lists contain some sort of numeric type... |
Python - switch alternative for non-discrete comparisons | 11,563,890 | 2 | 2012-07-19T15:14:21Z | 11,563,929 | 9 | 2012-07-19T15:16:40Z | [
"python",
"dictionary",
"switch-statement"
] | Maybe this question has been asked before, but I couldn't find it.
I am trying to implement something that determines what range a given value is in. In this example, x may be any real number.
```
def f(x):
if x < 0.1:
do_something_1()
elif 0.1 <= x < 1:
do_something_2()
elif 1 <= x < 10:
... | Use the [bisect](http://docs.python.org/release/2.5.2/lib/module-bisect.html) package to find the index where the value lies, and then call the appropriate function. In your example:
```
import bisect
def f(x):
funcs = [do_something_1, do_something_2, do_something_3, do_something_4]
funcs[bisect.bisect_left([... |
Python - switch alternative for non-discrete comparisons | 11,563,890 | 2 | 2012-07-19T15:14:21Z | 11,563,952 | 12 | 2012-07-19T15:18:01Z | [
"python",
"dictionary",
"switch-statement"
] | Maybe this question has been asked before, but I couldn't find it.
I am trying to implement something that determines what range a given value is in. In this example, x may be any real number.
```
def f(x):
if x < 0.1:
do_something_1()
elif 0.1 <= x < 1:
do_something_2()
elif 1 <= x < 10:
... | An easy way to improve this is not to repeat the lower bounds. Your code is equivalent to
```
if x < 0.1:
do_something_1()
elif x < 1:
do_something_2()
elif x < 10:
do_something_3()
else:
do_something_4()
```
If there are really many values, you might want to `bisect` instead, but with only four optio... |
Multiple re.sub() statements | 11,565,083 | 4 | 2012-07-19T16:20:16Z | 11,565,127 | 15 | 2012-07-19T16:22:54Z | [
"python",
"regex",
"string"
] | In my program, the user enters a term which I process before sending on. Part of this process is to change all instances of 'and','or' and 'not' to uppercase letters but leaving the rest intact.
I can't use `string.upper()` because it changes everything to uppercase; or `string.replace()` because if 'and' is in anothe... | You can pass a function substitution expression in `re.sub()`:
```
>>> term = "Lizards and Amphibians not salamander or newt"
>>> re.sub(r"\b(not|or|and)\b", lambda m: m.group().upper(), term)
'Lizards AND Amphibians NOT salamander OR newt'
```
However, I'd probably go with a non-regex solution:
```
>>> " ".join(s.u... |
passing variables to a template on a redirect in python | 11,565,313 | 5 | 2012-07-19T16:32:27Z | 11,566,057 | 11 | 2012-07-19T17:20:27Z | [
"python",
"google-app-engine",
"redirect",
"jinja2"
] | I am relatively new to Python so please excuse any naive questions.
I have a home page with 2 inputs, one for a "product" and one for an "email." When a user clicks submit they should be sent to "/success" where it will say:
You have requested "product"
You will be notified at "email"
I am trying to figure out the be... | When you do your redirect, include your email and product variables in the redirect. In Google appp engine, using webapp2, your current redirect probably looks like:
```
self.redirect('/sucess')
```
Instead, you can add the variables in the URL as follows:
```
self.redirect('/success?email=' + email + '&product=' + ... |
python: raise child_exception, OSError: [Errno 2] No such file or directory | 11,566,967 | 10 | 2012-07-19T18:19:46Z | 11,566,986 | 14 | 2012-07-19T18:21:07Z | [
"python",
"popen"
] | I execute a command in python using subprocess.popen() function like the following:
```
omp_cmd = 'cat %s | omp -h %s -u %s -w %s -p %s -X -' %(temp_xml, self.host_IP, self.username, self.password, self.port)
xmlResult = Popen(omp_cmd, stdout=PIPE, stderr=STDOUT)
```
In the shell it runs fine without error, but in py... | If you're going to pass the command as a string to `Popen` and if the commands have pipes to other commands in there, you need to use the `shell=True` keyword.
I'm not particularly familiar with the `omp` command, but this smells an awful lot like a useless use of cat. I would think that a better way to achieve this w... |
Count number of rows in a many-to-many relationship (SQLAlchemy) | 11,567,666 | 7 | 2012-07-19T19:08:31Z | 11,568,381 | 12 | 2012-07-19T20:01:12Z | [
"python",
"sqlalchemy"
] | I have a many-to-many relationship between say blog entries and tags. Now I want to know how many entries a specific tag has.
Imagine the following models (simplified):
```
rel_entries_tags = Table('rel_entries_tags', Base.metadata,
Column('entry_id', Integer, ForeignKey('entries.id')),
Column('tag_id', Integer, ... | ```
session.query(Entry).join(Entry.tags).filter(Tag.id==1).count()
```
or if you have a Tag already
```
session.query(Entry).with_parent(mytag, "entries").count()
``` |
javascript-readable json from python | 11,568,232 | 8 | 2012-07-19T19:50:28Z | 11,568,427 | 11 | 2012-07-19T20:04:26Z | [
"javascript",
"python",
"django",
"json"
] | My view computes a json and outputs a `json.dumps()`, and I'm passing this as the dictionary key `data`. I'm trying to pass this to a script element in my template, but when rendering, the browser gets it as a python-escaped string`{"nodes": [{"count":......` which isn't readable to the javascript. ... | If I understand well, you want to use a json in a template.
In order to do that, you have to disable the escaping, for exemple like this.
```
{% autoescape off %}
var x={{json_var}}
{% endautoescape %}
``` |
javascript-readable json from python | 11,568,232 | 8 | 2012-07-19T19:50:28Z | 11,569,300 | 11 | 2012-07-19T21:06:20Z | [
"javascript",
"python",
"django",
"json"
] | My view computes a json and outputs a `json.dumps()`, and I'm passing this as the dictionary key `data`. I'm trying to pass this to a script element in my template, but when rendering, the browser gets it as a python-escaped string`{"nodes": [{"count":......` which isn't readable to the javascript. ... | Note that instead of using
```
{% autoescape off %}
{{ my_json }}
{% endautoescape %}
```
You can simply use a filter :
```
{{ my_json|safe }}
``` |
Proper way to handle static files and templates for Django on Heroku | 11,569,144 | 28 | 2012-07-19T20:54:22Z | 11,590,401 | 49 | 2012-07-21T07:42:31Z | [
"python",
"django",
"heroku",
"static"
] | I'm moving over my django app to Heroku, and I was wondering what the proper way to handle static files is. Do I just push them via git to Heroku? Or should I be storing them on SW3 or something? Also, what should the STATIC\_ROOT and such be?
Thanks! | You should store them externally on a service like S3 - while Heroku *can* serve static files, it's not designed to.
Here's a good primer on getting started with S3:
<https://devcenter.heroku.com/articles/s3>
Use django-storages <http://django-storages.readthedocs.org/en/latest/index.html> to collect static files to... |
Python nested loop with generators does not work (in some cases)? | 11,569,535 | 7 | 2012-07-19T21:23:35Z | 11,569,572 | 20 | 2012-07-19T21:26:50Z | [
"python",
"generator",
"nested-loops"
] | Would somebody please explain the behavior of a nested loop using generators? Here is an example.
```
a = (x for x in range(3))
b = (x for x in range(2))
for i in a:
for j in b:
print (i,j)
```
The outer loop is not evaluated after the first iteration for some reason. The result is,
```
(0, 0)
(0, 1)
```... | It's because the `b` generator is exhausted during the first iteration of the outer for loop. Subsequent iterations will in effect have an empty inner loop (like `for x in ()`) so what's inside is never executed. This gives the false impression that it's the outer loop that fails, somehow.
Your second example works be... |
Python nested loop with generators does not work (in some cases)? | 11,569,535 | 7 | 2012-07-19T21:23:35Z | 11,569,725 | 8 | 2012-07-19T21:37:53Z | [
"python",
"generator",
"nested-loops"
] | Would somebody please explain the behavior of a nested loop using generators? Here is an example.
```
a = (x for x in range(3))
b = (x for x in range(2))
for i in a:
for j in b:
print (i,j)
```
The outer loop is not evaluated after the first iteration for some reason. The result is,
```
(0, 0)
(0, 1)
```... | @lazyr has answered this brilliantly, but I would point out for reference that when using nested generators it's worth knowing about `itertools.product`...
```
for i, j in itertools.product(range(3), range(2)):
print (i, j)
```
or (if you have *lots* of vals):
```
for vals in itertools.product(range(45), range(1... |
generator functions equivalent in Java | 11,570,132 | 22 | 2012-07-19T22:16:21Z | 20,971,237 | 23 | 2014-01-07T12:07:45Z | [
"java",
"python",
"iterator",
"generator"
] | I would like to implement an `Iterator` in Java that behaves somewhat like the following generator function in Python:
```
def iterator(array):
for x in array:
if x!= None:
for y in x:
if y!= None:
for z in y:
if z!= None:
yield z
```
x on the java ... | Had the same need so wrote a little class for it. Here are some examples:
```
Generator<Integer> simpleGenerator = new Generator<Integer>() {
public void run() throws InterruptedException {
yield(1);
// Some logic here...
yield(2);
}
};
for (Integer element : simpleGenerator)
System... |
generator functions equivalent in Java | 11,570,132 | 22 | 2012-07-19T22:16:21Z | 24,717,889 | 10 | 2014-07-12T22:30:27Z | [
"java",
"python",
"iterator",
"generator"
] | I would like to implement an `Iterator` in Java that behaves somewhat like the following generator function in Python:
```
def iterator(array):
for x in array:
if x!= None:
for y in x:
if y!= None:
for z in y:
if z!= None:
yield z
```
x on the java ... | Indeed Java has no yield, but you can now use Java 8 streams. IMO it's really a complicated iterator since it's backed by an array, not a function. Given it's a loop in a loop in a loop can be expressed as a Stream using filter (to skip the nulls) and flatMap to stream the inner collection. It's also about the size of ... |
is it possible to treat string methods as functions? | 11,570,426 | 2 | 2012-07-19T22:46:30Z | 11,570,441 | 8 | 2012-07-19T22:47:40Z | [
"python",
"function",
"methods"
] | is it possible to write a wrapper function for methods?
```
>>> lowtide = [ 'oh', 'i', 'do', 'like', 'to', 'be', 'beside', 'the', 'seaside' ]
>>> [ x.capitalize() for x in lowtide ]
['Oh', 'I', 'Do', 'Like', 'To', 'Be', 'Beside', 'The', 'Seaside']
>>> list(map(lambda x: x.capitalize(), lowtide))
['Oh', 'I', 'Do', 'L... | You can simply do
```
list(map(str.capitalize, lowtide))
```
In Python 3.x, `str.capitalize()` is a function taking the single argument `self`.
In Python 2.x, `str.capitalize()` is an "unbound method", but behaves similar to a function taking a single argument. |
Django Tastypie throws a 'maximum recursion depth exceeded' when full=True on reverse relation. | 11,570,443 | 6 | 2012-07-19T22:47:48Z | 11,570,683 | 13 | 2012-07-19T23:16:07Z | [
"python",
"django",
"tastypie"
] | I get a maximum recursion depth exceeded if a run the code below:
```
from tastypie import fields, utils
from tastypie.resources import ModelResource
from core.models import Project, Client
class ClientResource(ModelResource):
projects = fields.ToManyField(
'api.resources.ProjectResource', 'project_set',... | You would have to override `full_dehydrate` method on at least one resource to skip dehydrating related resource that is causing the recursion.
Alternatively you can define two types of resources that use the same model one with `full=True`and another with `full=False`. |
Flask/Werkzeug debugger, process model, and initialization code | 11,571,656 | 8 | 2012-07-20T01:29:15Z | 11,573,753 | 9 | 2012-07-20T06:09:49Z | [
"python",
"flask",
"wsgi",
"werkzeug"
] | I'm writing a Python web application using Flask. My application establishes a connection to another server at startup, and communicates with that server periodically in the background.
If I don't use Flask's builtin debugger (invoking app.run with debug=False), no problem.
If I do use the builtin debugger (invoking ... | I confirmed this behavior is due to Werkzeug, not Flask proper, and it is related to the reloader. You can see this in Werkzeug's serving.py -- in run\_simple(), if use\_reloader is true, it invokes make\_server via a helper function run\_with\_reloader() / restart\_with\_reloader() which does a subprocess.call(sys.exe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.