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 |
|---|---|---|---|---|---|---|---|---|---|
How can I create new rows in a pandas data frame containing the words in a string of an existing row? | 15,403,004 | 8 | 2013-03-14T06:56:04Z | 15,407,768 | 12 | 2013-03-14T11:19:41Z | [
"python",
"pandas"
] | I have a `DataFrame` in `pandas` with a column called `df.strings` with strings of text. I would like to get the individual words of those strings on their own rows with identical values for the other columns. For example if I have 3 strings (and an unrelated column, Time):
```
Strings --- Time
"The dog" --- 4Pm... | Here is my code that doesn't use `groupby()`, I think it's faster.
```
import pandas as pd
import numpy as np
import itertools
df = pd.DataFrame({
"strings":["the dog", "lazy dog", "The fox jump"],
"value":["a","b","c"]})
w = df.strings.str.split()
c = w.map(len)
idx = np.repeat(c.index, c.values)
#words = np.conca... |
Possible conflicting python installations | 15,403,273 | 8 | 2013-03-14T07:13:33Z | 15,403,520 | 8 | 2013-03-14T07:30:41Z | [
"python",
"numpy"
] | I'm not sure if the default python installation is the one that I've been installing modules to, and if that may be the cause of a conflicting Unicode byte size compatibility error. In short, I've installed Numpy 1.7 using Python 2.7.3 and when I try to install this other program that uses Python and Numpy as dependenc... | The problem indeed seems to be a mismatch of Python and Numpy compile settings.
/usr/local/bin is where custom Python is installed, you should try to run using /usr/bin/python instead.
Another solution is to use a virtualenv. Try this:
```
virtualenv myproject
cd myproject
source bin/activate
pip install numpy
```
... |
Where do I put IPython configuration files? | 15,403,523 | 6 | 2013-03-14T07:30:53Z | 15,409,096 | 8 | 2013-03-14T12:17:49Z | [
"python",
"emacs",
"editor",
"ipython"
] | I have been trying to set my %edit editor to Emacs for a while and made very slow progress.
The IPython 0.13 docs were unclear about how to actually configure this. It told me to set EDITOR to the desired editor (in my case, "emacsclient") by adding
```
c = get_config()
c.InteractiveShell.editor = 'emacsclient'
```
... | I have `c.TerminalInteractiveShell.editor = 'emacsclient'` in `~/.config/ipython/profile_default/ipython_config.py` and it works.
If you have trouble finding config location, use `ipython locate profile` command:
<http://ipython.org/ipython-doc/rel-0.13/whatsnew/version0.13.html#new-top-level-locate-command>
But I th... |
Django - Custom Admin Actions Logging | 15,404,199 | 3 | 2013-03-14T08:17:45Z | 15,404,372 | 9 | 2013-03-14T08:28:45Z | [
"python",
"django"
] | All changes you do in Django Admin is logged in the table django\_admin\_table and you can also see your most recent changes in "Recent Actions".
But when you write own "Admin Actions" and make changes through them nothing is being logged by default.
Example:
```
def make_checked(modeladmin, request, queryset):
... | Look at the admin's [`LogEntry`](https://github.com/django/django/blob/master/django/contrib/admin/models.py#L23) model and more importantly the [`LogEntryManager`](https://github.com/django/django/blob/master/django/contrib/admin/models.py#L16). The model manager provides a `log_action` method which makes it easy to a... |
changing "type" of python objects | 15,404,256 | 9 | 2013-03-14T08:21:52Z | 15,404,554 | 10 | 2013-03-14T08:41:43Z | [
"python",
"python-3.x"
] | On this [python doc page](http://docs.python.org/3.3/reference/datamodel.html) it says:
> Like its identity, an objectâs type is also unchangeable.
And I try this script,
```
#!python3
class Foo:
num = 1
pass
class Bar:
num = 2
pass
f1,f2= Foo(), Foo()
f2.__class__ = Bar
print( type(f1), type(f2), f1... | The footnotes one that page says:
> [1] It is possible in some cases to change an objectâs type, under
> certain controlled conditions. It generally isnât a good idea though,
> since it can lead to some very strange behaviour if it is handled
> incorrectly.
If you try to change the `__class__` of f2 to `list`:
`... |
Django: No module named 'app' | 15,404,580 | 6 | 2013-03-14T08:43:01Z | 15,406,099 | 13 | 2013-03-14T09:59:56Z | [
"python",
"django",
"runtime-error"
] | Django barfs with
```
ImportError at /store/
No module named store
```
But right there is the debug message there is the setting
```
INSTALLED_APPS =
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.stati... | If it were not for version control, I would have never found this. As it was, it took me almost an hour to track it down.
The mistake was in store/urls.py:
```
urlpatterns = patterns('store.views',
url(r'^$', 'main'),
url(r'^new_delivery_user/$', 'new_delivery_user'),
...
url(r'^event_signal/$', 'stor... |
Python's argparse to show program's version with prog and version string formatting | 15,405,636 | 14 | 2013-03-14T09:37:22Z | 15,406,624 | 23 | 2013-03-14T10:25:43Z | [
"python",
"version",
"argparse"
] | What's the preferred way of specifying program name and version info within argparse?
```
__version_info__ = ('2013','03','14')
__version__ = '-'.join(__version_info__)
...
parser.add_argument('-V', '--version', action='version', version="%(prog)s ("+__version__+")")
```
* <http://argparse.googlecode.com/svn/trunk/do... | Yes, that's the accepted way. From <http://docs.python.org/dev/library/argparse.html#action>:
```
>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
```
You should of course be embedding the version number in your package in a standard way: [Standard way to embed version into python packag... |
Does Python go well with QML (Qt-Quick)? | 15,406,002 | 23 | 2013-03-14T09:55:52Z | 15,406,478 | 26 | 2013-03-14T10:17:54Z | [
"python",
"qml",
"qt-quick"
] | I am a beginner in Qt-Quick.
I am not aware of Qt which is a basis for QML.
And also I'm not familiar with C++ which is again main supported language for both Qt and QML.
I'm aware JS can do a lot of logic in QML layer itself. But if we need interactions with OS, then we have to use some base language. As I'm comfortab... | On a conceptual level, they go together very well. I've written a python/qml/js/opengl program that combines everything fairly nicely. That was with Qt4.7 and PySide.
If you're just using QML, you can minimise the amount of Qt you'll need to be exposed to (though, as always, more knowledge makes you more powerful). Es... |
How to customize Page not found (404) in django? | 15,406,507 | 2 | 2013-03-14T10:19:28Z | 15,406,550 | 7 | 2013-03-14T10:21:26Z | [
"python",
"html",
"django",
"templates"
] | How I customize the error page in Django and where do I put my html for this page. | Just create a `404.html` file in your project's root level `templates` directory. |
python if condition and "and" | 15,407,871 | 5 | 2013-03-14T11:24:03Z | 15,407,902 | 7 | 2013-03-14T11:25:51Z | [
"python"
] | ```
>>> def foo(a):
print "called the function"
if(a==1):
return 1
else:
return None
>>> a=1
>>> if(foo(a) != None and foo(a) ==1):
print "asdf"
called the function
called the function
asdf
```
Hi.
how can i avoid calling the function twice without using an extra ... | > how can i avoid calling the function twice without using an extra variable.
Here, you can simply replace
```
if(foo(a) != None and foo(a) ==1):
```
with
```
if foo(a) == 1:
```
The `foo(a) != None` is redundant: if `foo(a) == 1`, it is guaranteed to not be `None`. |
python if condition and "and" | 15,407,871 | 5 | 2013-03-14T11:24:03Z | 15,407,913 | 12 | 2013-03-14T11:26:15Z | [
"python"
] | ```
>>> def foo(a):
print "called the function"
if(a==1):
return 1
else:
return None
>>> a=1
>>> if(foo(a) != None and foo(a) ==1):
print "asdf"
called the function
called the function
asdf
```
Hi.
how can i avoid calling the function twice without using an extra ... | You can chain the comparisons like this
```
if None != foo(a) == 1:
```
This works like
```
if (None != foo(a)) and (foo(a) == 1):
```
except that it only evaluates foo(a) once. |
cannot import name LOOKUP_SEP | 15,408,255 | 4 | 2013-03-14T11:41:03Z | 16,810,060 | 16 | 2013-05-29T09:20:51Z | [
"python",
"django"
] | I'm using django and I'm trying to set up django-roa but when i'm trying to start my webserver I have this error `cannot import name LOOKUP_SEP`
If I remove `django_roa` from my INSTALLEDS\_APP it's okay but I want django-roa working and I don't know how resolve this problem.
And I don't know what kind of detail I ca... | This question is the top Google search result for "cannot import name LOOKUP\_SEP", therefore although it doesn't necessarily solve any other compatibility issues between `django-roa` and Django 1.5 I want to point out...
You can solve this (specific) error by replacing:
```
from django.db.models.sql.constants import... |
cumulative distribution plots python | 15,408,371 | 7 | 2013-03-14T11:46:39Z | 15,419,072 | 16 | 2013-03-14T20:02:08Z | [
"python",
"python-3.x",
"matplotlib"
] | I am doing a project using python where I have two arrays of data. Let's call them *pc* and *pnc*. I am required to plot a cumulative distribution of both of these on the same graph. For *pc* it is supposed to be a less than plot i.e. at (x,y), y points in *pc* must have value less than x. For *pnc* it is to be a more ... | You were close. You should not use plt.hist as numpy.histogram, that gives you both the values and the bins, than you can plot the cumulative with ease:
```
import numpy as np
import matplotlib.pyplot as plt
# some fake data
data = np.random.randn(1000)
# evaluate the histogram
values, base = np.histogram(data, bins=... |
cumulative distribution plots python | 15,408,371 | 7 | 2013-03-14T11:46:39Z | 22,588,814 | 7 | 2014-03-23T08:56:32Z | [
"python",
"python-3.x",
"matplotlib"
] | I am doing a project using python where I have two arrays of data. Let's call them *pc* and *pnc*. I am required to plot a cumulative distribution of both of these on the same graph. For *pc* it is supposed to be a less than plot i.e. at (x,y), y points in *pc* must have value less than x. For *pnc* it is to be a more ... | Using histograms is really unnecessarily heavy and imprecise (the binning makes the data fuzzy): you can just sort all the x values: the index of each value is the number of values that are smaller. This shorter and simpler solution looks like this:
```
import numpy as np
import matplotlib.pyplot as plt
# Some fake d... |
django doesn't load initial fixtures while syncdb | 15,409,978 | 2 | 2013-03-14T12:59:16Z | 17,301,246 | 7 | 2013-06-25T15:21:16Z | [
"python",
"django",
"django-fixtures"
] | I've got a django project with following structure:
```
/djninja # project dir
/djninja # main app dir
/bands # app dir
/fans # app dir
/lyrics # app dir
```
I've created a `initial_data.yaml` file to make `syncdb` load fixtures (I prefer YAML format). According to the [documentation](https://docs.djangoproje... | Apparently Django looks for fixtures in apps specified in `INSTALLED_APPS` that have a `models.py` in them.
So if your app is missing one, create an empty `models.py` and Django won't skip looking for fixtures in that app. |
Use list comprehension to build a tuple | 15,410,119 | 27 | 2013-03-14T13:05:40Z | 15,410,140 | 43 | 2013-03-14T13:06:49Z | [
"python"
] | How can I use list comprehension to build a tuple of 2-tuple from a list. It would be equivalent to
```
tup = ()
for element in alist:
tup = tup + ((element.foo, element.bar),)
``` | ```
tup = tuple((element.foo, element.bar) for element in alist)
```
Technically, it's a [generator expression](http://docs.python.org/2/reference/expressions.html#generator-expressions). It's like a list comprehension, but it's evaluated lazily and won't need to allocate memory for an intermediate list.
For complete... |
Pandas count(distinct) equivalent | 15,411,158 | 57 | 2013-03-14T13:50:03Z | 15,411,596 | 95 | 2013-03-14T14:09:06Z | [
"python",
"pandas",
"count",
"group-by",
"distinct"
] | I am using pandas as a db substitute as I have multiple databases (oracle, mssql, etc) and I am unable to make a sequence of commands to a SQL equivalent.
I have a table loaded in a DataFrame with some columns:
```
YEARMONTH, CLIENTCODE, SIZE, .... etc etc
```
In SQL, to count the amount of different clients per yea... | I believe this is what you want:
```
table.groupby('YEARMONTH').CLIENTCODE.nunique()
```
Example:
```
In [2]: table
Out[2]:
CLIENTCODE YEARMONTH
0 1 201301
1 1 201301
2 2 201301
3 1 201302
4 2 201302
5 2 201302
6 3 ... |
Pandas count(distinct) equivalent | 15,411,158 | 57 | 2013-03-14T13:50:03Z | 23,464,103 | 15 | 2014-05-05T02:59:28Z | [
"python",
"pandas",
"count",
"group-by",
"distinct"
] | I am using pandas as a db substitute as I have multiple databases (oracle, mssql, etc) and I am unable to make a sequence of commands to a SQL equivalent.
I have a table loaded in a DataFrame with some columns:
```
YEARMONTH, CLIENTCODE, SIZE, .... etc etc
```
In SQL, to count the amount of different clients per yea... | Interestingly enough, very often `len(unique())` is a few times (3x-15x) faster than `nunique()`. |
Do we need sconscript file in every source directory | 15,411,176 | 2 | 2013-03-14T13:50:38Z | 15,573,849 | 10 | 2013-03-22T15:17:33Z | [
"python",
"scons"
] | I am using scons to compile my project.
In my project source files are in different directories.
Do we need sconscript file in every directory to compile those project source files?
I tried to compile all directories with the single sconscript file. But all object files are adding to my source directory only.
I am us... | I prepared an example that shows how to compile a project like yours with just one SConstruct script (no subsidiary SConscripts) using the SCons VariantDir() function. I decided to do this in a separate answer so that it would be easier to read.
The VariantDir() function isnt documented very well, so the behavior you ... |
How can I check if code is executed in the IPython notebook? | 15,411,967 | 23 | 2013-03-14T14:25:44Z | 15,412,661 | 8 | 2013-03-14T14:56:28Z | [
"python",
"ipython",
"ipython-notebook"
] | I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.
How can I check from my Python code if it's running in the IPython notebook? | The question is what do you want execute differently.
We do our best in IPython prevent the kernel from knowing to which kind of frontend is connected, and actually you can even have a kernel connected to many differents frontends at the same time. Even if you can take a peek at the type of `stderr/out` to know wether... |
How can I check if code is executed in the IPython notebook? | 15,411,967 | 23 | 2013-03-14T14:25:44Z | 22,424,821 | 7 | 2014-03-15T14:05:07Z | [
"python",
"ipython",
"ipython-notebook"
] | I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.
How can I check from my Python code if it's running in the IPython notebook? | You can check whether python is in *interactive* mode using the following snippet [[1]](http://stackoverflow.com/questions/2356399/tell-if-python-is-in-interactive-mode):
```
def is_interactive():
import __main__ as main
return not hasattr(main, '__file__')
```
I have found this method very useful because I d... |
How can I check if code is executed in the IPython notebook? | 15,411,967 | 23 | 2013-03-14T14:25:44Z | 24,937,408 | 11 | 2014-07-24T15:04:56Z | [
"python",
"ipython",
"ipython-notebook"
] | I have some Python code example I'd like to share that should do something different if executed in the terminal Python / IPython or in the IPython notebook.
How can I check from my Python code if it's running in the IPython notebook? | To check if you're in a notebook, which can be important e.g. when determining what sort of progressbar to use, this worked for me:
```
def in_ipynb():
try:
cfg = get_ipython().config
if cfg['IPKernelApp']['parent_appname'] == 'ipython-notebook':
return True
else:
r... |
Is this not a tuple? | 15,412,055 | 6 | 2013-03-14T14:29:04Z | 15,412,081 | 14 | 2013-03-14T14:30:03Z | [
"python",
"django",
"tuples"
] | I can't figure out what I'm doing wrong here. My error is: ImproperlyConfigured at /admin/ '**CategoryAdmin.fields**' must be a list or tuple.
Isn't the CategoryAdmin.fields a tuple? Am I reading this wrong?
**admin.py**
..
```
class CategoryAdmin(admin.ModelAdmin):
fields = ('title')
list_display = ('id', '... | No, it is not. You need to add a comma:
```
fields = ('title',)
```
It is the *comma* that makes this a tuple. The parenthesis are really just optional here:
```
>>> ('title')
'title'
>>> 'title',
('title',)
```
The parenthesis are of course still a good idea, with parenthesis tuples are easier to spot visually, an... |
Linux - How can I copy files of the same extension located in several subdirectories into a single directly? | 15,412,107 | 4 | 2013-03-14T14:30:58Z | 15,412,190 | 9 | 2013-03-14T14:34:52Z | [
"python",
"linux",
"bash",
"csh"
] | I have a folder which has many subdirectories, each with a `*.nr` file in them. There are 1000 subdirectories, each containing at least one `*.nr` file. Is there a quick way to copy all those `*.nr` files into a single directory?
I can write a quick `python` script to iterate through the files, but this seems like ove... | something like
```
find /path/to/src -name "*.nr" -exec cp \{\} /path/to/dest \;
``` |
How can I increase the size of, and pad, a python list? | 15,412,906 | 3 | 2013-03-14T15:06:40Z | 15,412,974 | 12 | 2013-03-14T15:09:14Z | [
"python",
"list"
] | Say I have this list:
```
[1,2,3,4]
```
and I want:
```
[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4]
```
What is the best way of doing this?
My current method is to create a new list:
```
x = [1,2,3,4]
y = [[n]*4 for n in x]
```
This gives:
```
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]]
```
Which seems clos... | ```
>>> x = [1,2,3,4]
>>> [n for n in x for _ in range(4)]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
```
`itertools.repeat` is indeed semantically cleaner, thanks, Steven:
```
from itertools import repeat
[repeated for value in x for repeated in repeat(value, 4)]
``` |
Fitting 3D points python | 15,413,217 | 3 | 2013-03-14T15:18:45Z | 15,413,456 | 7 | 2013-03-14T15:29:20Z | [
"python",
"scipy"
] | I have python code that produces a list of 3-tuples of numbers x, y and z. I would like to fit z= f(x,y) using scipy curve\_fit. Here is some non-working code
```
A = [(19,20,24), (10,40,28), (10,50,31)]
def func(x,y,a, b):
return x*y*a + b
```
How can I get python to fit this function to the data in the list `A... | * The first argument to `func` must be the data (both x and y).
* The rest of the arguments to `func` represent the parameters.
So you need to modify your `func` a bit:
```
def func(data, a, b):
return data[:,0]*data[:,1]*a + b
```
---
* The first argument to `curve_fit` is the function.
* The second argument i... |
Multiprocessing.Pool makes Numpy matrix multiplication slower | 15,414,027 | 10 | 2013-03-14T15:54:06Z | 15,415,690 | 10 | 2013-03-14T17:05:16Z | [
"python",
"numpy",
"multiprocessing",
"pool"
] | So, I am playing around with `multiprocessing.Pool` and `Numpy`, but it seems I missed some important point. Why is the `pool` version much slower? I looked at `htop` and I can see several processes be created, but they all share one of the CPUs adding up to ~100%.
```
$ cat test_multi.py
import numpy as np
from time... | The unpredictable competition between communication overhead and computation speedup is definitely the issue here. What you are observing is perfectly fine. Whether you get a net speed-up depends on many factors and is something that has to be quantified properly (as you did).
**So why is `multiprocessing` so "unexpec... |
Multiprocessing.Pool makes Numpy matrix multiplication slower | 15,414,027 | 10 | 2013-03-14T15:54:06Z | 15,647,474 | 13 | 2013-03-26T21:09:54Z | [
"python",
"numpy",
"multiprocessing",
"pool"
] | So, I am playing around with `multiprocessing.Pool` and `Numpy`, but it seems I missed some important point. Why is the `pool` version much slower? I looked at `htop` and I can see several processes be created, but they all share one of the CPUs adding up to ~100%.
```
$ cat test_multi.py
import numpy as np
from time... | Regarding the fact that all of your processes are running on the same CPU, [see my answer here](http://stackoverflow.com/questions/15639779/python-what-determines-whether-different-processes-are-assigned-to-the-same-or/15641148#15641148).
During import, `numpy` changes the CPU affinity of the parent process, such that... |
Python-opencv: Read image data from stdin | 15,414,480 | 4 | 2013-03-14T16:11:17Z | 15,417,336 | 8 | 2013-03-14T18:27:58Z | [
"python",
"opencv"
] | How can I read image data from stdin rather than from a file?
With the C++ interface, it seems to be possible: <http://stackoverflow.com/a/5458035/908515>. The function `imdecode` is available in Python as well. But it expects a `numpy array` as (first) argument. I have no idea how to convert the stdin data.
This is ... | Looks like python stdin buffer is too small for images. You can run your program with `-u` flag in order to remove buffering. More details in [this](http://stackoverflow.com/a/3670470/723891) answer.
Second is that `numpy.asarray` probably not right way to get numpy array from the data, `numpy.frombuffer` works for me... |
Django template loop over dictionary.items with "items" as key | 15,416,662 | 8 | 2013-03-14T17:52:56Z | 15,416,865 | 7 | 2013-03-14T18:02:57Z | [
"python",
"django",
"django-templates"
] | I have a dictionary in my template that I want to loop through in the usual way
```
{% for key, value in dictionary.items %}
```
But in dictionary I have a key called `'items'`, so my loop return the value of dictionary['items'] and tries to unpack the result as key, value.
How can I tell Django to use the function ... | Call `dictionary.iteritems` instead? I don't think there's a better way.
If you have no control over dictionary keys, the only safe way is a custom tag for iterating over dicts. |
Python: syntax error with import | 15,417,415 | 2 | 2013-03-14T18:31:21Z | 15,417,432 | 7 | 2013-03-14T18:32:48Z | [
"python",
"python-import"
] | I have a python script technically named `/home/pi/Adafruit-Raspberry-Pi-Python-Code/Adafruit_BMP085/Adafruit_BMP085_example.py`
The first line of this script is
```
from Adafruit_BMP085 import BMP085
```
Also located in this directory is a python file named Adafruit\_BMP085 that has a function BMP085.
I want to cr... | You need to add the `/home/pi/Adafruit-Raspberry-Pi-Python-Code` path to the module search path in [`sys.path`](http://docs.python.org/2/library/sys.html#sys.path):
```
import sys
sys.path.append('/home/pi/Adafruit-Raspberry-Pi-Python-Code')
from Adafruit_BMP085 import BMP085
```
or move the `Adafruit_BMP085` packag... |
What is the fastest way to output large DataFrame into a CSV file? | 15,417,574 | 8 | 2013-03-14T18:40:11Z | 15,505,330 | 8 | 2013-03-19T16:38:18Z | [
"python",
"performance",
"pandas",
"output"
] | For python / pandas I find that df.to\_csv(fname) works at a speed of ~1 mln rows per min. I can sometimes improve performance by a factor of 7 like this:
```
def df2csv(df,fname,myformats=[],sep=','):
"""
# function is faster than to_csv
# 7 times faster for numbers if formats are specified,
# 2 times ... | Lev. Pandas has rewritten `to_csv` to make a big improvement in native speed. The process is now i/o bound, accounts for many subtle dtype issues, and quote cases. Here is our performance results vs. 0.10.1 (in the upcoming 0.11) release. These are in `ms`, lower ratio is better.
```
Results:
... |
pip won't install Python packages locally with --user | 15,418,949 | 10 | 2013-03-14T19:55:10Z | 20,304,268 | 8 | 2013-11-30T18:52:32Z | [
"python",
"package",
"pip",
"easy-install",
"pythonpath"
] | I'm trying to install packages locally with pip. It used to work with `--user` but now when I try it, it finds the version of the package in `/usr/local/lib/` and then does not install it locally. Normally it would install things in `~/.local` but now it just checks the system-wide dir for the package and if it's there... | [Citing](https://github.com/pypa/pip/issues/766#issuecomment-29544589) Marcus Smith (maintainer of pip):
> If you think the global site is out of date, and want the latest in
> the user site, then use:
> `pip install --upgrade --user SomePackage`
>
> If the global site is up to date, and you really just want the sam... |
Label name for ModelAdmin in Django | 15,419,617 | 5 | 2013-03-14T20:34:15Z | 15,419,734 | 10 | 2013-03-14T20:41:22Z | [
"python",
"django"
] | how can I give this class a label which is shown in the backend instead of "EditedAddress"?
```
class EditedAddressAdmin(admin.ModelAdmin):
list_display = ('comp_name','fam_name', 'fon')
search_fields = ['fam_name','comp_name']
admin.site.register(EditedAddress,EditedAddressAdmin)
``` | You can adjust the way your model name is displayed by adding a verbose\_name and/or verbose\_name\_plural to your model:
```
class EditedAddress(models.Model):
class Meta:
verbose_name = 'Edited Address'
verbose_name_plural = 'Edited Addresses'
``` |
Calling Custom functions from Python using rpy2 | 15,419,740 | 8 | 2013-03-14T20:41:47Z | 15,419,900 | 7 | 2013-03-14T20:50:39Z | [
"python",
"rpy2"
] | Is there a way to call functions defined in a file say myfunc.r
```
---------------myfunc.r --------------
myfunc = function(){
return(c(1,2,3,4,5,6,7,8,9,10))
}
getname = function(){
return("chart title")
}
---- Python
How to call getname() here ?
```
Any help would be greatly appreciated ? | You can do something like this ( python code here)
```
import rpy2.robjects as robjects
robjects.r('''
source('myfunc.r')
''')
r_getname = robjects.globalenv['getname']
```
then you call it
```
r_getname()
``` |
Calling Custom functions from Python using rpy2 | 15,419,740 | 8 | 2013-03-14T20:41:47Z | 15,434,486 | 8 | 2013-03-15T14:06:54Z | [
"python",
"rpy2"
] | Is there a way to call functions defined in a file say myfunc.r
```
---------------myfunc.r --------------
myfunc = function(){
return(c(1,2,3,4,5,6,7,8,9,10))
}
getname = function(){
return("chart title")
}
---- Python
How to call getname() here ?
```
Any help would be greatly appreciated ? | The are features in rpy2 that should help making this cleaner than dumping objects into the global workspace.
```
from rpy2.robjects.packages import STAP
# if rpy2 < 2.6.1 do:
# from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
# STAP = SignatureTranslatedAnonymousPackage
with open('myfunc.r', 'r'... |
Dealing with piecewise equations returned by sympy integrate | 15,420,816 | 7 | 2013-03-14T21:47:21Z | 15,438,302 | 7 | 2013-03-15T17:11:59Z | [
"python",
"sympy",
"symbolic-math",
"computer-algebra-systems",
"symbolic-computation"
] | In sympy I have an integral which returns a Piecewise object, e.g.
```
In [2]: from sympy.abc import x,y,z
In [3]: test = exp(-x**2/z**2)
In [4]: itest = integrate(test,(x,0,oo))
In [5]: itest
Out[5]:
â§ ___
⪠â²â± Ï â
z â â ... | In general, using `.args` is the correct way to access parts of an expression.
In this case, though, there is an option to `integrate` that will let you ignore convergence conditions
```
In [39]: integrate(test, (x, 0, oo), conds='none')
Out[39]:
___
â²â± Ï â
z
âââââââ
2
```
Also, if you expli... |
find the index of a string ignoring cases | 15,421,363 | 4 | 2013-03-14T22:24:06Z | 15,421,637 | 8 | 2013-03-14T22:45:45Z | [
"python"
] | I have a string that I need to find index in a list ignoring cases.
```
MG
['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
```
I want to find the index of MG in the following line as a list. | One of the more elegant ways you can do this is to use a generator:
```
>>> list = ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
>>> next(i for i,v in enumerate(list) if v.lower() == 'mg')
3
```
The above code makes a generator that yields the index of the next case insensitive occurrence of `... |
Matplotlib: Writing right-to-left text (Hebrew, Arabic, etc.) | 15,421,746 | 6 | 2013-03-14T22:54:21Z | 15,449,145 | 7 | 2013-03-16T12:16:02Z | [
"python",
"matplotlib",
"hebrew",
"right-to-left"
] | I'm trying to add some text to my plot which is RTL (in this case, Hebrew). After some work managed to get it to display the text, but it's displayed LTR (meaning, in the reverese order). I've dug into the reference and did extensive search online and nothing came up.
An example for what I'm using:
```
import matplot... | For whoever encounters the same problem, I found a partial solution.
The [bidi package](https://pypi.python.org/pypi/python-bidi) provides this functionality, so using:
```
from bidi import algorithm as bidialg
import matplotlib.pyplot as plt
text = bidialg.get_display(u'ש××× ×××ª× ×')
plt.text(0.5, 0.5, text... |
how to read a long multiline string line by line in python | 15,422,144 | 13 | 2013-03-14T23:31:07Z | 15,422,155 | 28 | 2013-03-14T23:32:36Z | [
"python"
] | I have a wallop of a string with many lines. How do I read the lines one by one with a `for` clause? Here is what I am trying to do and I get an error on the textData var referenced in the `for line in textData` line.
```
for line in textData
print line
lineResult = libLAPFF.parseLine(line)
```
The textData v... | What about using [`.splitlines()`](http://docs.python.org/2/library/stdtypes.html#str.splitlines)?
```
for line in textData.splitlines():
print(line)
lineResult = libLAPFF.parseLine(line)
``` |
scikits-learn pca dimension reduction issue | 15,422,487 | 3 | 2013-03-15T00:04:51Z | 15,422,640 | 12 | 2013-03-15T00:22:49Z | [
"python",
"numpy",
"scikit-learn",
"pca"
] | I have a problem with reduction dimension using scikit-learn and PCA.
I have two numpy matrices, one has size (1050,4096) and another has size (50,4096). I tried to reduce the dimensions of both to yield (1050, 399) and (50,399) but, after doing the pca I got (1050,399) and (50,50) matrices. One matrix is for knn trai... | Call `fit_transform()` on train, `transform()` on test:
```
from sklearn import decomposition
train = np.random.rand(1050, 4096)
test = np.random.rand(50, 4096)
pca = decomposition.PCA()
pca.n_components = 399
train_reduced = pca.fit_transform(train)
test_reduced = pca.transform(test)
``` |
Best practices: how do you list required dependencies in your setup.py? | 15,422,527 | 18 | 2013-03-15T00:09:33Z | 15,422,703 | 25 | 2013-03-15T00:31:57Z | [
"python"
] | This is how I do it currently:
```
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
'requests',
'mock',
'gunicorn',
'mongoengine',
]
setup(name='repoapi',
version='... | You can split up your requirements into "install" dependencies and "test" dependencies like this:
```
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
install_requires = [
'pyramid',
'pyramid_debugtoolbar',
'waitress',
'requests',
'gunicorn',
... |
Django model: Email field unique if not null/blank | 15,422,606 | 8 | 2013-03-15T00:19:50Z | 15,534,514 | 17 | 2013-03-20T20:54:46Z | [
"python",
"django"
] | Let's say you have a simple model:
```
Class Contact(models.Model):
email = models.EmailField(max_length=70,blank=True)
first = models.CharField(max_length=25,blank=True)
last = models.CharField(max_length=25,blank=True)
```
What I would like to do is set email to be unique, however, in doing so I necessa... | Unfortunately, it's not as simple as just setting null=True, unique=True, blank=True. Whenever you try to import using csv, or some other text based source, some part of Django, for the purpose of uniqueness treats "" as something that ought not to be duplicated.
The work-around, is to overwrite the save method, as fo... |
Region of Interest opencv python | 15,424,852 | 5 | 2013-03-15T04:38:11Z | 15,426,187 | 14 | 2013-03-15T06:32:34Z | [
"python",
"opencv",
"image-processing"
] | I am trying to get a region of an image (ROI) using opencv python. THe version of opencv used is 2.4.3. However when I try to call the API
```
cv2.SetImageROI
```
it returns me the error
```
AttributeError: 'module' object has no attribute 'SetImageROI'
```
Also on checking the documentation it seems to suggest thi... | Okay, On further analysis realized that the cv2 since it has been supporting numpy array structure, there is no longer any need for a API, the entire image can be manipulated in the array itself.
eg:
```
img = cv2.imread('image.png')
img = img[c1:c1+25,r1:r1+25]
```
Here c1 is the left side column pixel location, and... |
How to use the context manager to avoid the use of __del__ in python? | 15,427,361 | 4 | 2013-03-15T08:01:38Z | 15,427,892 | 11 | 2013-03-15T08:37:48Z | [
"python",
"contextmanager"
] | As it is common knowledge the python `__del__` method should not be used to clean up important things, as it is not guaranteed this method gets called. The alternative is the use of a context manager, as described in several threads.
But I do not quite understand how to rewrite a class to use a context manager. To ela... | I suggest using the contextlib.contextmanager class instead of writing a class that implements **enter** and **exit**. Here's how it would work:
```
class MyWrapper(object):
def __init__(self, device):
self.device = device
def open(self):
self.device.open()
def close(self):
self.d... |
Blender scripting: Indices of selected vertices | 15,429,796 | 7 | 2013-03-15T10:21:15Z | 16,126,597 | 7 | 2013-04-21T00:07:53Z | [
"python",
"blender"
] | **Q:** In Blender 2.64, I have a mesh in edit mode with some vertices selected. How can I get or generate a list of indices of the selected vertices in a Python script?
I find the Blender Python API reference utterly confusing to navigate, and Google mostly points to outdated APIs. This is hopefully trivial for the Bl... | Your code only works reliably if you switch to object mode before you execute it. The reason is that while in edit-mode, the mesh data is not synchronized with the mesh from object mode. This is done when you switch back to object mode. You can verify this by switching to edit mode, select some vertices from your objec... |
Vertical scroll not working in Eclipse/PyDev | 15,430,595 | 10 | 2013-03-15T10:57:14Z | 33,384,417 | 30 | 2015-10-28T06:36:00Z | [
"python",
"eclipse",
"pydev"
] | I updated today to the latest version of PyDev (2.7.2), everything went smooth, I restarted Eclipse and then the vertical scroll in the PyDev editor stoped working. The scrollbar is moving, but the text is not scrolling. The horizontal scroll works though. This happens only with python files. When I open a text file or... | Scrolling didn't work for me after updating to `Ubuntu 15.10` (Eclipse 4.5.1, and PyDev 4.4.0).
Resolved after setting: `Preferences --> PyDev --> Editor --> Overview Ruler Minimap --> Show vertical scrollbar` |
Can I set max_retries for requests.request? | 15,431,044 | 63 | 2013-03-15T11:19:02Z | 15,431,343 | 64 | 2013-03-15T11:33:22Z | [
"python",
"python-requests"
] | Python requests module is simple and elegant but one thing bugs me.
It is possible to get a *requests.exception.ConnectionError* with message containing smth like: **'Max retries exceeded with url...'**
This implies that requests can attempt to access the data several times. But there is not a single mention of this p... | It is the underlying `urllib3` library that does the retrying. To set a different maximum retry count, use [alternative transport adapters](http://docs.python-requests.org/en/latest/user/advanced/#transport-adapters):
```
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://stackoverflow.c... |
Can I set max_retries for requests.request? | 15,431,044 | 63 | 2013-03-15T11:19:02Z | 18,190,415 | 47 | 2013-08-12T15:03:10Z | [
"python",
"python-requests"
] | Python requests module is simple and elegant but one thing bugs me.
It is possible to get a *requests.exception.ConnectionError* with message containing smth like: **'Max retries exceeded with url...'**
This implies that requests can attempt to access the data several times. But there is not a single mention of this p... | Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.
You can do this instead:
```
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://w... |
Can I set max_retries for requests.request? | 15,431,044 | 63 | 2013-03-15T11:19:02Z | 35,504,626 | 32 | 2016-02-19T11:50:58Z | [
"python",
"python-requests"
] | Python requests module is simple and elegant but one thing bugs me.
It is possible to get a *requests.exception.ConnectionError* with message containing smth like: **'Max retries exceeded with url...'**
This implies that requests can attempt to access the data several times. But there is not a single mention of this p... | This will not only change the max\_retries but also enable a backoff strategy which makes requests to all *http://* addresses sleep for a period of time before retrying (to a total of 5 times):
```
import requests
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
s = req... |
Should a cookie header be set on every response? | 15,432,219 | 4 | 2013-03-15T12:15:42Z | 15,432,388 | 7 | 2013-03-15T12:23:32Z | [
"python",
"http",
"session",
"pyramid"
] | Let's say you're implementing sessions.
You check whether the browser presents a session cookie. If yes, you authenticate the cookie and find the user that the session is associated with, and move on processing the request.
If you didn't find a session cookie, you create a new session and send a cookie to the browser... | Generally, you don't need to set the cookie on each and every response. The browser already has the cookie and will continue sending it to the server as long as it is still valid.
Specifically, a Pyramid session cookie is set on every request because it contains a signed and timestamped secret that can expire separate... |
How to rearrange a python pandas dataframe? | 15,432,659 | 12 | 2013-03-15T12:36:02Z | 15,433,426 | 14 | 2013-03-15T13:13:10Z | [
"python",
"row",
"pandas",
"sequence",
"dataframe"
] | I have the following dataframe read in from a .csv file with the "Date" column being the index. The days are in the rows and the columns show the values for the hours that day.
```
> Date h1 h2 h3 h4 ... h24
> 14.03.2013 60 50 52 49 ... 73
```
I would like to arrange it like this, so that there is o... | I'm not the best at date manipulations, but maybe something like this:
```
import pandas as pd
from datetime import timedelta
df = pd.read_csv("hourmelt.csv", sep=r"\s+")
df = pd.melt(df, id_vars=["Date"])
df = df.rename(columns={'variable': 'hour'})
df['hour'] = df['hour'].apply(lambda x: int(x.lstrip('h'))-1)
com... |
Stepwise Regression in Python | 15,433,372 | 17 | 2013-03-15T13:10:24Z | 29,835,822 | 7 | 2015-04-23T22:59:30Z | [
"python",
"scipy",
"regression"
] | How to perform **stepwise regression** in **python**? There are methods for OLS in SCIPY but I am not able to do stepwise. Any help in this regard would be a great help. Thanks.
Edit: I am trying to build a linear regression model. I have 5 independent variables and using forward stepwise regression, I aim to select v... | Trevor Smith and I wrote a little forward selection function for linear regression with statsmodels: <http://planspace.org/20150423-forward_selection_with_statsmodels/> You could easily modify it to minimize a p-value, or select based on beta p-values with just a little more work. |
AttributeError: type object 'datetime.date' has no attribute 'now' | 15,434,793 | 4 | 2013-03-15T14:21:42Z | 15,435,110 | 15 | 2013-03-15T14:36:36Z | [
"python",
"django"
] | Using these lines of code:
```
from datetime import date
self.date_start_processing = date.now()
```
I'm getting this error:
**AttributeError: type object 'datetime.date' has no attribute 'now'**
How can I solve this?
Thanks. | You need to use
```
import datetime
now = datetime.datetime.now()
```
Or if you are using django 1.4+ and have timezone enabled you should use
```
django.utils.timezone.now()
``` |
python does not release filehandles to logfile | 15,435,652 | 7 | 2013-03-15T15:02:57Z | 15,474,586 | 15 | 2013-03-18T10:29:14Z | [
"python",
"logging"
] | I have an application which has to run a number of simulation runs. I want to setup a logging mechanisme where all logrecords are logged in a general.log, and all logs for a simulation run go to run00001.log, .... For this I have defined a class Run. in the `__init__()` a new filehandle is added for the runlog.
The pr... | You need to call `.close()` on the filehandler.
When your `Run` class completes, call:
```
handlers = self.log.handlers[:]
for handler in handlers:
handler.close()
self.log.removeHandler(handler)
``` |
Remove all occurrences of words in a string from a python list | 15,435,726 | 5 | 2013-03-15T15:06:07Z | 15,435,836 | 7 | 2013-03-15T15:11:33Z | [
"python",
"regex"
] | I'm trying to match and remove all words in a list from a string using a compiled regex but I'm struggling to avoid occurrences within words.
Current:
```
REMOVE_LIST = ["a", "an", "as", "at", ...]
remove = '|'.join(REMOVE_LIST)
regex = re.compile(r'('+remove+')', flags=re.IGNORECASE)
out = regex.sub("", text)
`... | One problem is that only the first `\b` is inside a raw string. The second gets interpreted as the backspace character (ASCII 8) rather than as a word boundary.
To fix, change
```
regex = re.compile(r'\b('+remove+')\b', flags=re.IGNORECASE)
```
to
```
regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE)
... |
Remove all occurrences of words in a string from a python list | 15,435,726 | 5 | 2013-03-15T15:06:07Z | 15,435,983 | 13 | 2013-03-15T15:19:03Z | [
"python",
"regex"
] | I'm trying to match and remove all words in a list from a string using a compiled regex but I'm struggling to avoid occurrences within words.
Current:
```
REMOVE_LIST = ["a", "an", "as", "at", ...]
remove = '|'.join(REMOVE_LIST)
regex = re.compile(r'('+remove+')', flags=re.IGNORECASE)
out = regex.sub("", text)
`... | here is a suggestion without using regex you may want to consider:
```
>>> sentence = 'word1 word2 word3 word1 word2 word4'
>>> remove_list = ['word1', 'word2']
>>> word_list = sentence.split()
>>> ' '.join([i for i in word_list if i not in remove_list])
'word3 word4'
``` |
What is PEP8's E128: continuation line under-indented for visual indent? | 15,435,811 | 129 | 2013-03-15T15:10:15Z | 15,435,837 | 217 | 2013-03-15T15:11:37Z | [
"python",
"sublimetext2",
"pep8"
] | Just opened a file with Sublime Text (with Sublime Linter) and noticed a PEP8 formatting error that I'd never seen before. Here's the text:
```
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'),
)
```
It's flagging the second argument, the line that starts `url(...)`
I was about to disabl... | [PEP-8 recommends](http://www.python.org/dev/peps/pep-0008/#indentation) you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:
```
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
```
... |
fast way to remove lowercase substrings from string? | 15,437,589 | 9 | 2013-03-15T16:34:27Z | 15,437,604 | 17 | 2013-03-15T16:35:18Z | [
"python",
"string",
"numpy"
] | What's an efficient way in Python (plain or using numpy) to remove all lowercase substring from a string `s`?
```
s = "FOObarFOOObBAR"
remove_lower(s) => "FOOFOOBAR"
``` | I'd use `str.translate`. Only the delete step is performed if you pass `None` for the translation table. In this case, I pass the `ascii_lowercase` as the letters to be deleted.
```
>>> import string
>>> s.translate(None,string.ascii_lowercase)
'FOOFOOOBAR'
```
I doubt you'll find a faster way, but there's always `ti... |
fast way to remove lowercase substrings from string? | 15,437,589 | 9 | 2013-03-15T16:34:27Z | 15,437,644 | 9 | 2013-03-15T16:37:11Z | [
"python",
"string",
"numpy"
] | What's an efficient way in Python (plain or using numpy) to remove all lowercase substring from a string `s`?
```
s = "FOObarFOOObBAR"
remove_lower(s) => "FOOFOOBAR"
``` | My first approach would be `''.join(x for x in s if not x.islower())`
If you need speed use mgilson answer, it is a lot faster.
```
>>> timeit.timeit("''.join(x for x in 'FOOBarBaz' if not x.islower())")
3.318969964981079
>>> timeit.timeit("'FOOBarBaz'.translate(None, string.ascii_lowercase)", "import string")
0.536... |
Matrix Multiplication of a Pandas DataFrame and Series | 15,438,952 | 4 | 2013-03-15T17:48:07Z | 15,439,161 | 8 | 2013-03-15T17:58:55Z | [
"python",
"pandas"
] | I want to do a matrix multiplcation of a pandas dataframe and a series
```
df = pandas.DataFrame({'a':[4,1,3], 'b':[5,2,4]},index=[1,2,3])
ser = pandas.Series([0.6,0.4])
```
df is,
```
a b
1 4 5
2 1 2
3 3 4
```
ser is,
```
0 0.6
1 0.4
```
My desired result is a matrix product, like so
ans is,
I ca... | pandas implicity aligns on the index of a series, use the dot function
```
In [3]: df = pd.DataFrame({'a' : [4,1,3], 'b' : [5,2,4]},index=[1,2,3])
In [4]: s = pd.Series([0.6,0.4],index=['a','b'])
In [5]: df.dot(s)
Out[5]:
1 4.4
2 1.4
3 3.4
``` |
Compare multiple unique strings in a list | 15,439,824 | 3 | 2013-03-15T18:37:41Z | 15,439,850 | 7 | 2013-03-15T18:39:18Z | [
"python",
"list",
"python-2.7"
] | Edit: I am using Python 2.7
I have a given 'matrix' as shown below which contains multiple lists of strings. I want to sort through matrix and only print out the row(s) which only contain a specific set of strings.
Can any one give me a hint on how to go about this?
What I have tried so far:
```
matrix = [("One", "... | Your test is incorrect, you want to test each string separately with `in`:
```
if "One" in data and "Three" in data and "Six" in data:
```
`and` does not group operands for the `in` test; each component is evaluated separately:
```
("One") and ("Three") and ("Six" in data):
```
which leads to the result of `"Six" i... |
Trouble writing a dictionary to csv with keys as headers and values as columns | 15,440,970 | 2 | 2013-03-15T19:49:35Z | 15,441,073 | 8 | 2013-03-15T19:56:03Z | [
"python",
"csv",
"dictionary"
] | I have a dictionary that looks like:
```
mydict = {"foo":[1,2], "bar":[3,4], "asdf":[5,6]}
```
I'm trying to write this to a CSV file so that it looks like:
```
foo,bar,asdf
1,3,5
2,4,6
```
I've spend the last hour looking for solutions, and the closest one I found suggested doing something like this:
```
headers ... | Instead of `zip(mydict.values())`, use `zip(*mydict.values())`. Here is the difference:
```
>>> zip(mydict.values())
[([1, 2],), ([3, 4],), ([5, 6],)]
>>> zip(*mydict.values())
[(1, 3, 5), (2, 4, 6)]
```
Basically the second version does the same thing as `zip([1, 2], [3, 4], [5, 6])`. This is called [Unpacking Argum... |
Cyclical indexing of lists in Python | 15,441,495 | 4 | 2013-03-15T20:26:15Z | 15,441,702 | 11 | 2013-03-15T20:39:23Z | [
"python",
"data-structures"
] | Say I have an array `foo` with e.g. elements `[1, 2, 3]`, and that I want to retrieve elements of `foo` as if `foo` had been "*infinitely concatenated*".
For example `foo[0:2]` would return (like a normal list):
`[1, 2]`
and `foo[0:5]` would return:
```
[1, 2, 3, 1, 2]
```
while `foo[7:13]` would return:
```
[2, ... | I'm afraid you'll have to implement it yourself. It isn't difficult though:
```
class cyclist(list):
def __getitem__(self, index):
return list.__getitem__(self, index % len(self))
def __getslice__(self, start, stop):
return [self[n] for n in range(start, stop)]
foo = cyclist([1, 2, 3])
print... |
Modify JSON response of Flask-Restless | 15,442,025 | 4 | 2013-03-15T21:00:50Z | 15,442,616 | 7 | 2013-03-15T21:46:09Z | [
"python",
"ember.js",
"flask",
"flask-restless"
] | I am trying to use Flask-Restless with Ember.js which isn't going so great. It's the GET responses that are tripping me up. For instance, when I do a `GET` request on `/api/people` for example Ember.js expects:
```
{
people: [
{ id: 1, name: "Yehuda Katz" }
]
}
```
But Flask-Restless responds with:
... | Flask extensions have [pretty readable source code](https://github.com/jfinkels/flask-restless/blob/master/flask_restless/views.py#L843). You can make a `GET_MANY` postprocessor:
```
def pagination_remover(results):
return {'people': results['objects']} if 'page' in results else results
manager.create_api(
..... |
How to store real-time chat messages in database? | 15,442,265 | 6 | 2013-03-15T21:19:17Z | 15,442,587 | 12 | 2013-03-15T21:43:58Z | [
"python",
"chat",
"real-time",
"tornado",
"mysql-python"
] | I am using `mysqldb` for my database currently, and I need to integrate a messaging feature that is in real-time. The `chat demo` that Tornado provides *does not* implement a database, (whereas the `blog` *does*.)
This messaging service also will also double as an email in the future (like how Facebook's message servi... | Tornado is a single threaded non blocking server.
What this means is that if you make any blocking calls on the main thread you will eventually kill performance. You might not notice this at first because each database call might only block for 20ms. But once you are making more than 200 database calls per seconds you... |
Converting RGB to HLS and back | 15,442,285 | 5 | 2013-03-15T21:20:55Z | 15,442,440 | 10 | 2013-03-15T21:32:14Z | [
"python",
"colors",
"rgb",
"color-space"
] | I'm using python's colorsys library to convert RGB color values to HLS. Just to verify, I tried converting back to RGB and got a different value back. I can understand minor differences because of precision issues, but these values are significantly different.
Here's my code:
```
import colorsys
r=192
g=64
b=1
hlsva... | Your values are way, way outside the bounds of the colorspace.
From [the docs](http://docs.python.org/2/library/colorsys.html):
> Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all o... |
Convert strings to int or float in python 3? | 15,444,945 | 8 | 2013-03-16T02:33:24Z | 15,444,965 | 11 | 2013-03-16T02:38:34Z | [
"python",
"string",
"python-3.x",
"integer",
"double"
] | ```
integer = input("Number: ")
rslt = int(integer)+2
print('2 + ' + integer + ' = ' + rslt)
double = input("Point Number: ")
print('2.5 + ' +double+' = ' +(float(double)+2.5))
```
Gives me
```
Traceback (most recent call last):
File "C:\...", line 13, in <module>
print('2 + ' + integer + ' = ' + rslt)
Typ... | You have to convert the integer into a string:
```
print('2 + ' + str(integer) + ' = ' + str(rslt))
```
Or pass it as an argument to `print` and print will do it for you:
```
print('2 +', integer, '=', rslt)
```
I would do it using string formatting:
```
print('2 + {} = {}'.format(integer, rslt))
``` |
rqworker timeout | 15,445,036 | 9 | 2013-03-16T02:51:46Z | 15,446,143 | 12 | 2013-03-16T06:03:09Z | [
"python",
"django",
"redis"
] | I am using django-rq to handle some long-running tasks on my django site. These tasks trip the 180 second timeout of the (I assume) rqworker:
```
JobTimeoutException: Job exceeded maximum timeout value (180 seconds).
```
How can I increase this timeout value? I've tried adding --timeout 360 to the rqworker command bu... | This seems to be the right way to approach the problem.
```
queue = django_rq.get_queue('default')
queue.enqueue(populate_trends, args=(self,), timeout=500)
```
If you need to pass kwargs,
```
queue = django_rq.get_queue('default')
queue.enqueue(populate_trends, args=(self,), kwargs={'x': 1,}, timeout=500)
```
Than... |
Given a list, How to count items in that list? | 15,445,119 | 3 | 2013-03-16T03:08:24Z | 15,445,129 | 10 | 2013-03-16T03:10:18Z | [
"python",
"list",
"python-3.x",
"count"
] | Given the list
```
List2 = ['Apple', 'Apple', 'Apple', 'Black', 'Black', 'Black', 'Green', 'Green', 'Red', 'Yellow']
```
I am trying to figure out how to count how many times each element in the list appears. This has to be incredibly simple but I can't figure it out. I read in my book about the count function and I ... | You can use [collections.Counter](http://docs.python.org/dev/library/collections#collections.Counter) which gives you a `dict` like object (in that it also has some additional functionality useful for *count* like purposes) that has key as the item, and a value as the number of occurrences.
```
from collections import... |
Help getting URL linked to by Reddit post With PRAW | 15,445,199 | 4 | 2013-03-16T03:21:35Z | 15,445,477 | 11 | 2013-03-16T04:12:38Z | [
"python",
"api",
"reddit"
] | Using Praw I am trying to get the post linked to in the title of a Reddit submission. For example the [submission](http://www.reddit.com/r/AdviceAnimals/comments/1adu71/apparently_people_still_need_to_hear_this/) links to this [image](http://i.qkme.me/3te2bn.jpg). I have tried figuring out a way to extract this informa... | ```
import praw
user_agent = praw.Reddit("my_cool_user_agent")
link = "http://www.reddit.com/r/AdviceAnimals/comments/" + \
"1adu71/apparently_people_still_need_to_hear_this/"
submission = user_agent.get_submission(link)
print submission.url
``` |
Finding intersection points of two ellipses (Python) | 15,445,546 | 4 | 2013-03-16T04:24:59Z | 15,446,492 | 11 | 2013-03-16T06:56:25Z | [
"python",
"geometry",
"intersection",
"shapes",
"ellipse"
] | I'm writing a basic 2D shape library in Python (primarily for manipulating SVG drawings), and I'm at a loss for how to efficiently calculate the intersection points of two ellipses.
Each ellipse is defined by the following variables (all floats):
```
c: center point (x, y)
hradius: "horizontal" radius
vradius: "verti... | In math, you need to express the ellipses as bivariate quadratic equations, and solve it. I found a [doucument](http://maptools.home.comcast.net/~maptools/BivariateQuadratics.pdf). All the calculations are in the document, but it may take a while to implement it in Python.
So another method is to approximate the ellip... |
How do I disable the security certificate check in Python requests | 15,445,981 | 44 | 2013-03-16T05:38:58Z | 15,445,989 | 74 | 2013-03-16T05:40:29Z | [
"python",
"https",
"python-requests"
] | I am using
```
import requests
requests.post(url='https://foo.com', data={'bar':'baz'})
```
but I get a request.exceptions.SSLError.
The website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me.
I would imagine there is an argument like 'verifiy=False' that I could use, but I... | From [the documentation](http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification):
> Requests can also ignore verifying the SSL certficate if you set
> `verify` to False.
>
> ```
> >>> requests.get('https://kennethreitz.com', verify=False)
> <Response [200]>
> ``` |
How do I disable the security certificate check in Python requests | 15,445,981 | 44 | 2013-03-16T05:38:58Z | 32,282,390 | 14 | 2015-08-29T03:20:26Z | [
"python",
"https",
"python-requests"
] | I am using
```
import requests
requests.post(url='https://foo.com', data={'bar':'baz'})
```
but I get a request.exceptions.SSLError.
The website has an expired certficate, but I am not sending sensitive data, so it doesn't matter to me.
I would imagine there is an argument like 'verifiy=False' that I could use, but I... | Use requests.packages.urllib3.disable\_warnings().
```
import requests
requests.packages.urllib3.disable_warnings()
requests.post(url='https://foo.com', data={'bar':'baz'})
``` |
main() function doesn't run when running script | 15,446,560 | 4 | 2013-03-16T07:07:05Z | 15,446,580 | 27 | 2013-03-16T07:08:55Z | [
"python"
] | ```
#! /usr/bin/python
def main():
print("boo")
```
This code does nothing when I try to run it in Python 3.3. No error or anything.
Whats's wrong
```
[tim@tim-arch ~]$ gvim script
[tim@tim-arch ~]$ sudo chmod 775 script
[tim@tim-arch ~]$ ./script
[tim@tim-arch ~]$
``` | You still have to *call* the function.
```
def main(): # declaring a function just declares it - the code doesn't run
print("boo")
main() # here we call the function
``` |
main() function doesn't run when running script | 15,446,560 | 4 | 2013-03-16T07:07:05Z | 15,446,612 | 12 | 2013-03-16T07:12:42Z | [
"python"
] | ```
#! /usr/bin/python
def main():
print("boo")
```
This code does nothing when I try to run it in Python 3.3. No error or anything.
Whats's wrong
```
[tim@tim-arch ~]$ gvim script
[tim@tim-arch ~]$ sudo chmod 775 script
[tim@tim-arch ~]$ ./script
[tim@tim-arch ~]$
``` | I assume what you wanted to do is call the print function when the script is executed from command line.
In python you can figure out if the script containing a piece of code is the same as the script which was launched initially by checking the `__name__` variable against `__main__`.
```
#! /usr/bin/python
if __nam... |
Why does my contextmanager-function not work like my contextmanager class in python? | 15,447,130 | 2 | 2013-03-16T08:19:15Z | 15,447,223 | 7 | 2013-03-16T08:30:53Z | [
"python",
"python-2.7",
"contextmanager"
] | In my code, I need to be able to open and close a device properly, and therefore see the need to use a context manager. While a context manager is usually defined as a class with `__enter__` and `__exit__` methods, there also seem to be the possibility to decorate a function for use with the context manager (see [a rec... | The example in the documentation for `contextmanager` is somewhat misleading. The portion of the function after `yield` does not really correspond to the `__exit__` of the context manager protocol. The key point in the documentation is this:
> If an unhandled exception occurs in the block, it is reraised inside the ge... |
How to add elements to 3 dimensional array in python | 15,448,594 | 5 | 2013-03-16T11:19:00Z | 15,448,639 | 10 | 2013-03-16T11:24:45Z | [
"python",
"arrays",
"multidimensional-array"
] | i am trying to store data in three dimensional array i.e, x[0][0][0] in python. how to initialize x. and add values to it. i tried this.
```
x=[]
x[0][0][0]=value1
x[0][0].append(value1)
```
both lines are giving out of range error. how to do it. i want it like. x[0][0][0]=value1, x[1][0][0]=value2, x[0][1][0]=value... | I recommend using `numpy` for multidimensional arrays. It makes it much more convenient, and much faster. This would look like
```
import numpy as np
x = np.zeros((10,20,30)) # Make a 10 by 20 by 30 array
x[0,0,0] = value1
```
Still, if you don't want to use `numpy`, or need non-rectangular multi-dimensional arrays, ... |
Does the `shell` in `shell=True` in subprocess means `bash`? | 15,449,428 | 6 | 2013-03-16T12:45:39Z | 15,449,462 | 20 | 2013-03-16T12:49:25Z | [
"python",
"shell",
"subprocess"
] | I was wondering whether `subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",shell=True)` will be interpreted by `sh` or`zsh` instead of `bash` in different server?
Anyone has ideas about this?
What should I do to make sure that it's interpreted by `bash`? | <http://docs.python.org/2/library/subprocess.html>
> ```
> On Unix with shell=True, the shell defaults to /bin/sh
> ```
Note that /bin/sh is often symlinked to something different, e.g. on ubuntu:
```
$ ls -la /bin/sh
lrwxrwxrwx 1 root root 4 Mar 29 2012 /bin/sh -> dash
```
You can use the `executable` argument to... |
When using modulus operator, I want the number not remainder 0 | 15,449,942 | 2 | 2013-03-16T13:38:16Z | 15,449,987 | 9 | 2013-03-16T13:42:56Z | [
"python",
"modulo"
] | First of all, I have to say that my English is so poor.
I could not find any better title for this article.
Anyway, I want to ask you guys, about Python.
Please look at the code below.
```
for i in range(1,11):
print(i,'-->',i%4)
```
Results in
```
1 --> 1
2 --> 2
3 --> 3
4 --> 0
5 --> 1
6 --> 2
7 --> 3
8 -... | ```
for i in range(1,11):
print(i,'-->',(i-1)%4+1)
``` |
Simple way to create matrix of random numbers | 15,451,958 | 16 | 2013-03-16T16:52:38Z | 15,451,996 | 8 | 2013-03-16T16:57:07Z | [
"python",
"random",
"coding-style"
] | I am trying to create a matrix of random numbers, but my solution is too long and looks ugly
```
random_matrix = [[random.random() for e in range(2)] for e in range(3)]
```
this looks ok, but in my implementation it is
```
weights_h = [[random.random() for e in range(len(inputs[0]))] for e in range(hiden_neurons)]
`... | Take a look at [numpy.random.rand](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand):
```
Docstring:
rand(d0, d1, ..., dn)
Random values in a given shape.
Create an array of the given shape and propagate it with
random samples from a uniform distribution
over ``[0, 1)``.
`... |
Simple way to create matrix of random numbers | 15,451,958 | 16 | 2013-03-16T16:52:38Z | 15,451,997 | 33 | 2013-03-16T16:57:09Z | [
"python",
"random",
"coding-style"
] | I am trying to create a matrix of random numbers, but my solution is too long and looks ugly
```
random_matrix = [[random.random() for e in range(2)] for e in range(3)]
```
this looks ok, but in my implementation it is
```
weights_h = [[random.random() for e in range(len(inputs[0]))] for e in range(hiden_neurons)]
`... | You can drop the `range(len())`:
```
weights_h = [[random.random() for e in inputs[0]] for e in range(hiden_neurons)]
```
But really, you should probably use numpy.
```
In [9]: numpy.random.random((3, 3))
Out[9]:
array([[ 0.37052381, 0.03463207, 0.10669077],
[ 0.05862909, 0.8515325 , 0.79809676],
[... |
Error while using listdir in Python | 15,452,099 | 5 | 2013-03-16T17:05:55Z | 15,452,633 | 8 | 2013-03-16T17:55:29Z | [
"python",
"file",
"directory",
"listdir"
] | I'm trying to get the list of files in a particular directory and count the number of files in the directory. I always get the following error:
```
WindowsError: [Error 3] The system cannot find the path specified: '/client_side/*.*'
```
My code is:
```
print len([name for name in os.listdir('/client_side/') if os.p... | This error occurs when you use `os.listdir` on a *path* which does not refer to an existing path.
For example:
```
>>> os.listdir('Some directory does not exist')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
WindowsError: [Error 3] : 'Some directory does not exist/*.*'
```
I... |
pydoc supported python metadata such as __version__ = '0.1' | 15,452,828 | 5 | 2013-03-16T18:12:29Z | 15,843,625 | 8 | 2013-04-05T21:10:12Z | [
"python",
"pydoc"
] | I'm not even really sure what these things are officially called, though, Python has metadata, usually at the top of the module files such as `__version__ = '0.1'`.
How can I find a list of all of the ones supported by PyDoc? | Any top-level private globals following a particular naming convention will be included under the `Data` section generated by **Pydoc**:
* All normal global variables are displayed there â you can see this simply by running **pydoc** on a module with some global variables that is otherwise empty.
* "Special" names ... |
extract data from a dictionary returned by pycurl | 15,453,608 | 3 | 2013-03-16T19:20:32Z | 15,453,651 | 8 | 2013-03-16T19:23:29Z | [
"python",
"dictionary",
"pycurl"
] | I have this:
```
import pycurl
import pprint
import json
c = pycurl.Curl()
c.setopt(c.URL, 'https://mydomainname.com')
c.perform()
```
the above code return a dictionary like this:
```
{"name":"steve", "lastvisit":"10-02-2012", "age":12}
```
I want to loop through that dictionary and get just the age:
```
age : ... | `c.perform()` doesn't return anything, you need to configure a file-like object to capture the value. A [`BytesIO` object](http://docs.python.org/3/library/io.html#io.BytesIO) would do, you can then call [`.getvalue()`](http://docs.python.org/3/library/io.html#io.BytesIO.getvalue) on that after the call completes:
```... |
How to add virtualenv to path | 15,453,793 | 8 | 2013-03-16T19:35:35Z | 15,490,253 | 10 | 2013-03-19T01:58:38Z | [
"python",
"osx",
"path",
"virtualenv",
"pip"
] | I am trying to find out why my `virtualenv` and/or `virtualenv` wrapper - installed using `pip` using `homebrew` - cannot be found. I think it's because it's not added to my PATH:
```
$ which virtualenv
$
```
and:
```
$ virtualenv someDir
$ -bash: virtualenv: command not found
```
I installed pip using `homebrew`, ... | It seems that I myself am the exception to the rule for almost all 'simple' installation procedures. For some reason, it WAS a path related issue:
I ran `brew info python`, which outputted a lot of information. At the bottom I found this:
```
Executable python scripts will be put in:
/usr/local/share/python
so you ma... |
How to reset db in Django? I get a command 'reset' not found error | 15,454,008 | 46 | 2013-03-16T19:56:10Z | 15,454,063 | 77 | 2013-03-16T20:00:52Z | [
"python",
"database",
"django",
"reset"
] | Following this Django by Example tutotrial here: <http://lightbird.net/dbe/todo_list.html>
The tutorial says:
> "This changes our table layout and weâll have to ask Django to reset
> and recreate tables:
>
> `manage.py reset todo; manage.py syncdb`"
though, when I run `manage.py reset todo`, I get the error:
```
... | `reset` has been replaced by `flush` with Django 1.5, see:
```
python manage.py help flush
``` |
How to reset db in Django? I get a command 'reset' not found error | 15,454,008 | 46 | 2013-03-16T19:56:10Z | 18,409,489 | 17 | 2013-08-23T18:26:51Z | [
"python",
"database",
"django",
"reset"
] | Following this Django by Example tutotrial here: <http://lightbird.net/dbe/todo_list.html>
The tutorial says:
> "This changes our table layout and weâll have to ask Django to reset
> and recreate tables:
>
> `manage.py reset todo; manage.py syncdb`"
though, when I run `manage.py reset todo`, I get the error:
```
... | It looks like the 'flush' answer will work for some, but not all cases. I needed not just to flush the values in the database, but to recreate the tables properly. I'm not using migrations yet (early days) so I really needed to drop all the tables.
On Heroku one can drop all the tables with pg:reset:
```
heroku pg:re... |
How to reset db in Django? I get a command 'reset' not found error | 15,454,008 | 46 | 2013-03-16T19:56:10Z | 18,542,131 | 12 | 2013-08-30T22:06:49Z | [
"python",
"database",
"django",
"reset"
] | Following this Django by Example tutotrial here: <http://lightbird.net/dbe/todo_list.html>
The tutorial says:
> "This changes our table layout and weâll have to ask Django to reset
> and recreate tables:
>
> `manage.py reset todo; manage.py syncdb`"
though, when I run `manage.py reset todo`, I get the error:
```
... | Similar to LisaD's answer, [Django Extensions](http://pythonhosted.org/django-extensions/) has a great reset\_db command that totally drops everything, instead of just truncating the tables like "flush" does. You have to specify a router, so it may look like:
`python ./manage.py reset_db --router=default`
Merely flus... |
How can a shell function know if it is running within a virtualenv? | 15,454,174 | 8 | 2013-03-16T20:10:09Z | 15,454,284 | 7 | 2013-03-16T20:20:04Z | [
"python",
"bash",
"shell",
"virtualenv"
] | How should a `bash` function test whether it is running inside a Python virtualenv?
The two approaches that come to mind are:
```
[[ "$(type -t deactivate)" != function ]]; INVENV=$?
```
or
```
[[ "x$(which python)" != "x$VIRTUAL_ENV/bin/python" ]]; INVENV=$?
```
(Note: wanting `$INVENV` to be 1 if we're inside a ... | ```
if [[ "$VIRTUAL_ENV" != "" ]]
then
INVENV=1
else
INVENV=0
fi
// or shorter if you like:
[[ "$VIRTUAL_ENV" == "" ]]; INVENV=$?
```
**EDIT**: as @ThiefMaster mentions in the comments, in certain conditions (for instance, when starting a new shell â perhaps in `tmux` or `screen` â from within an active virtua... |
How can a shell function know if it is running within a virtualenv? | 15,454,174 | 8 | 2013-03-16T20:10:09Z | 15,454,916 | 9 | 2013-03-16T21:28:41Z | [
"python",
"bash",
"shell",
"virtualenv"
] | How should a `bash` function test whether it is running inside a Python virtualenv?
The two approaches that come to mind are:
```
[[ "$(type -t deactivate)" != function ]]; INVENV=$?
```
or
```
[[ "x$(which python)" != "x$VIRTUAL_ENV/bin/python" ]]; INVENV=$?
```
(Note: wanting `$INVENV` to be 1 if we're inside a ... | Actually, I just found a similar question, from which one can easily derive an answer to this one:
[Python: Determine if running inside virtualenv](http://stackoverflow.com/questions/1871549)
E.g., a shell script can use something like
```
python -c 'import sys; print sys.real_prefix' 2>/dev/null && INVENV=1 || INVE... |
Stream data into hdfs directly without copying | 15,454,244 | 6 | 2013-03-16T20:15:57Z | 15,456,403 | 8 | 2013-03-17T00:39:09Z | [
"python",
"hadoop",
"hdfs"
] | I am looking for different options through which I can write data directly into hdfs using python without storing on the local node and then using copyfromlocal.
I would like to use hdfs file similar to local file and use write method with the line as the argument, something of the following:
```
hdfs_file = hdfs.... | Im not sure about a python hdfs library, but you can always stream via a hadoop fs put command and denote copying from stdin using '-' as the source filename:
```
hadoop fs -put - /path/to/file/in/hdfs.txt
``` |
Delimiter of numpy.savetxt | 15,454,880 | 4 | 2013-03-16T21:24:13Z | 15,455,693 | 8 | 2013-03-16T22:55:06Z | [
"python",
"python-3.x",
"file-io",
"numpy"
] | I am trying to write a numpy array to a `.txt` file using [`numpy.savetxt`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html). To the best I can tell, the following code follows the documentation:
```
z = np.array([1,2,3])
np.savetxt('testdata.txt',z,delimiter='hi')
```
However, the output file,... | You need 2D array, axis 0 is the row, and axis 1 is the column. So I use `z[None, :]` to convert it to 2D array:
```
from StringIO import StringIO
s = StringIO()
z = np.array([1,2,3])
np.savetxt(s,z[None, :],delimiter='hi')
s.getvalue()
```
output:
```
1.000000000000000000e+00hi2.000000000000000000e+00hi3.0000000000... |
Releasing memory in Python | 15,455,048 | 65 | 2013-03-16T21:44:59Z | 15,457,947 | 46 | 2013-03-17T05:46:25Z | [
"python",
"memory-management"
] | I have a few related questions regarding memory usage in the following example.
1. If I run in the interpreter,
```
foo = ['bar' for _ in xrange(10000000)]
```
the real memory used on my machine goes up to `80.9mb`. I then,
```
del foo
```
real memory goes down, but only to `30.4mb`. The in... | Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (`PyObject_Malloc`) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas,... |
Releasing memory in Python | 15,455,048 | 65 | 2013-03-16T21:44:59Z | 15,492,488 | 61 | 2013-03-19T06:00:32Z | [
"python",
"memory-management"
] | I have a few related questions regarding memory usage in the following example.
1. If I run in the interpreter,
```
foo = ['bar' for _ in xrange(10000000)]
```
the real memory used on my machine goes up to `80.9mb`. I then,
```
del foo
```
real memory goes down, but only to `30.4mb`. The in... | I'm guessing the question you really care about here is:
> Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?
No, there is not. But there is an easy workaround: child processes.
If you need 500MB of temporary storage for 5 minutes, but afte... |
Releasing memory in Python | 15,455,048 | 65 | 2013-03-16T21:44:59Z | 15,508,271 | 21 | 2013-03-19T19:04:01Z | [
"python",
"memory-management"
] | I have a few related questions regarding memory usage in the following example.
1. If I run in the interpreter,
```
foo = ['bar' for _ in xrange(10000000)]
```
the real memory used on my machine goes up to `80.9mb`. I then,
```
del foo
```
real memory goes down, but only to `30.4mb`. The in... | eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:
> Why does it release 50.5mb in particular - what is the amount that is released based on?
What it's based on is, ultimately, a whole series of coincidences inside Python and `malloc` that are very har... |
Dict of dicts of dicts to DataFrame | 15,455,388 | 10 | 2013-03-16T22:21:12Z | 15,455,455 | 12 | 2013-03-16T22:28:42Z | [
"python",
"json",
"dictionary",
"pandas"
] | I'd like to store JSON data in a Python Pandas DataFrame
my JSON data is a dict of dicts of dicts like this
```
d = {
"col1": {
"row1": {
"data1": "0.87",
"data2": "Title col1",
"data3": "14.4878",
"data4": "Title row1"
},
"row2": {
"data1": "15352.3",
"data2": "... | ```
df = pd.Panel.from_dict(d).to_frame()
```
output:
```
col1 col2
major minor
data1 row1 0.87 0.87
row2 15352.3 15352.3
row3 0 0
data2 row1 Title col1 Title col2
row2 Title col1 Title col2
ro... |
Python - Use 'set' to find the different items in list | 15,455,737 | 15 | 2013-03-16T22:59:41Z | 15,455,779 | 14 | 2013-03-16T23:05:45Z | [
"python",
"compare"
] | I need to compare two lists in Python, and I know about using the `set` command to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?
I would like to find the items that aren't in each one. Say list one is as follows:
```
[1, 2, 3, 4... | Looks like you need symmetric difference:
```
a = [1,2,3]
b = [3,4,5]
print(set(a)^set(b))
>>> [1,2,4,5]
``` |
Python - Use 'set' to find the different items in list | 15,455,737 | 15 | 2013-03-16T22:59:41Z | 15,455,820 | 12 | 2013-03-16T23:11:02Z | [
"python",
"compare"
] | I need to compare two lists in Python, and I know about using the `set` command to find similar items, but is there a another command I could use that would automatically compare them, instead of having to code for it?
I would like to find the items that aren't in each one. Say list one is as follows:
```
[1, 2, 3, 4... | The [docs](http://docs.python.org/2/library/stdtypes.html#set) are a good place to start. Here are a couple examples that might help you determine how you want to compare your sets.
To find the intersection (items that are in both sets):
```
>>> a = set([1, 2, 3, 4, 5, 6])
>>> b = set([4, 5, 6, 7, 8, 9])
>>> a & b
se... |
Remove preinstalled python from Mac OSX 10.8 | 15,456,386 | 3 | 2013-03-17T00:36:46Z | 15,456,431 | 15 | 2013-03-17T00:45:23Z | [
"python",
"osx",
"macports"
] | I want to move to python 3.0 and therefore remove the default python 2.7 (2.6,2.5...) installation on my mac. Including all the installed packages, $PATH,...
Does the python installer from python.org oder MacPorts installer provide an uninstaller, or is there a way to do this manually? | That's a *COMPLETELY TERRIBLE* idea, and you should never do that. You're likely to break dependencies and requirements for various software that expect to find the default Python in the default location.
Install your choice of Python 3 ( MacPorts, Python.org, whatever ). Update your local $PATH variables to use that ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.