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
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."?
25,871,261
35
2014-09-16T14:20:05Z
26,573,049
10
2014-10-26T12:36:44Z
[ "python", "django", "python-2.7", "python-2.x", "django-1.7" ]
I have a Django application that has parts originally written in Django 1.2, and the application has been upgraded all the way up to 1.7. After upgrading to 1.7, I'm getting the following warning from `python manage.py check`: ``` System check identified some issues: WARNINGS: ?: (1_6.W001) Some project unittests may...
See <https://github.com/django/django/blob/1.7/django/core/checks/compatibility/django_1_6_0.py#L42> for the list of things it checks that gives you this error.
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."?
25,871,261
35
2014-09-16T14:20:05Z
28,069,285
8
2015-01-21T14:11:08Z
[ "python", "django", "python-2.7", "python-2.x", "django-1.7" ]
I have a Django application that has parts originally written in Django 1.2, and the application has been upgraded all the way up to 1.7. After upgrading to 1.7, I'm getting the following warning from `python manage.py check`: ``` System check identified some issues: WARNINGS: ?: (1_6.W001) Some project unittests may...
If everything's OK with your tests, you can simply turn the warning off by doing one (or all) of these steps: 1. Remove `SITE_ID` from your settings if you don't use sites framework anymore. 2. Add `BASE_DIR` variable to your settings. 3. Remove `MANAGERS` list form your setting if you don't use it. 4. Remove `XFrameO...
subsampling every nth entry in a numpy array
25,876,640
20
2014-09-16T19:11:25Z
25,876,672
32
2014-09-16T19:13:52Z
[ "python", "arrays", "numpy" ]
I am a beginner with numpy, and I am trying to extract some data from a long numpy array. What I need to do is start from a defined position in my array, and then subsample every nth data point from that position, until the end of my array. basically if I had ``` a = [1,2,3,4,1,2,3,4,1,2,3,4....] ``` I want to subsa...
You can use [numpy's slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing), simply `start:stop:step`. ``` >>> xs array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]) >>> xs[1::4] array([2, 2, 2]) ``` This creates a *view* of the the original data, so it's *constant time*. It'll al...
Check if certain operators are being used in a function
25,877,341
4
2014-09-16T19:55:00Z
25,878,033
10
2014-09-16T20:40:14Z
[ "python", "operators" ]
I want to prohibit certain operators being used in a function, for example, say I want to make sure the `**` power operator is not being used in the following function: ``` def pow(x, y): return x ** y ``` I have used `inspect.getsource` to get the source and checked if `"**"` is in the source but that will wrong...
I'd personally go for Ashwini's answer if you have 3.4 at hand, however, if you need to be a bit more compatible and don't mind parsing the source, then you can make use of `ast`, eg: ``` import inspect import ast def pow(x, y): return x ** y nodes = ast.walk(ast.parse(inspect.getsource(pow))) has_power = any(is...
How to login users with email and log them out with Django Rest Framework JSON web tokens?
25,878,583
3
2014-09-16T21:17:17Z
25,915,233
7
2014-09-18T14:19:50Z
[ "python", "django", "rest", "django-rest-framework" ]
I have an existing, working Django application that implements numerous Django-REST-framework APIs. I've just added user authentication with [**Django-rest-framework-JWT**](https://github.com/GetBlimp/django-rest-framework-jwt) and now I'm trying to learn it up. I have verified that it does issue me a token if I do the...
1. When using JWT for authentication you'd usually store the token in the browser's localstorage or sessionstorage. To logout you just remove the token. There's nothing else to invalidate. 2. One of the benefits of using this kind of approach for authentication is that tokens are not persisted in the database, so you d...
Django - ImproperlyConfigured: Module "django.contrib.auth.middleware"
25,879,725
18
2014-09-16T23:02:45Z
26,947,617
13
2014-11-15T15:51:13Z
[ "python", "django", "virtualenv" ]
I'm running a virtualenv to try to learn Django, but for whatever reason after installing Django and when I try to access the default Django start page, I get the following error in the browser: > A server error occurred. Please contact the administrator. In the terminal window where I am running the server says the ...
**easy solution** just remove ``` 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', ``` from ``` MIDDLEWARE_CLASSES = ( ... ... ) ``` in your project's **settings.py** then, it should work!
Django - ImproperlyConfigured: Module "django.contrib.auth.middleware"
25,879,725
18
2014-09-16T23:02:45Z
27,448,745
18
2014-12-12T17:16:40Z
[ "python", "django", "virtualenv" ]
I'm running a virtualenv to try to learn Django, but for whatever reason after installing Django and when I try to access the default Django start page, I get the following error in the browser: > A server error occurred. Please contact the administrator. In the terminal window where I am running the server says the ...
I was getting the same error. But i had forgotten to get into my VirtualEnv BEFORE running my server. So make sure that from terminal you first activate virtualenv: `source env/bin/activate` Then run: `python manage.py runserver`
Python.h not found using swig and Anaconda Python
25,882,150
2
2014-09-17T04:08:45Z
25,883,058
8
2014-09-17T05:41:23Z
[ "python", "c", "osx", "swig", "anaconda" ]
I'm trying to compile a simple python/C example following this tutorial: <http://www.swig.org/tutorial.html> I'm on MacOS using Anaconda python. however, when I run ``` gcc -c example.c example_wrap.c -I/Users/myuser/anaconda/include/ ``` I get: ``` example_wrap.c:130:11: fatal error: 'Python.h' file not found # ...
Use the option `-I/Users/myuser/anaconda/include/python2.7` in the `gcc` command. (That's assuming you are using python 2.7. Change the name to match the version of python that you are using.) You can use the command `python-config --cflags` to get the full set of recommended compilation flags: ``` $ python-config --c...
AttributeError: 'Flask' object has no attribute 'user_options'
25,884,951
18
2014-09-17T07:42:09Z
26,021,940
43
2014-09-24T16:25:36Z
[ "python", "flask", "celery" ]
So I am trying to setup this basic example from the following doc: > <http://flask.pocoo.org/docs/0.10/patterns/celery/> But so far I keep getting the below error: > AttributeError: 'Flask' object has no attribute 'user\_options' I am using celery 3.1.15. I did some search online but haven't found the correct answe...
I see the update that the original question has been solved, but I do not see the exact solution. For the sake of others who run into this error, here is some more info. The Flask Celery Based Background Tasks page (<http://flask.pocoo.org/docs/0.10/patterns/celery/>) suggests this to start celery: `celery -A your_ap...
pdist for theano tensor
25,886,374
5
2014-09-17T09:04:13Z
26,065,509
11
2014-09-26T17:53:15Z
[ "python", "matlab", "scipy", "theano" ]
I have a theano symbolic matrix ``` x = T.fmatrix('input') ``` `x` will be later on populated by `n` vectors of dim `d` (at train time). I would like to have the theano equivalent of `pdist` ([`scipy.spatial.distance.pdist`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist.html) of [`...
`pdist` from scipy is a collection of different functions - there doesn't exist a Theano equivalent for all of them at once. However, each specific distance, being a closed form mathematical expression, can be written down in Theano as such and then compiled. Take as a example the minkowski `p` norm distance (copy+pas...
What's the most Pythonic way to remove a number from start of a string?
25,887,716
2
2014-09-17T10:07:23Z
25,887,775
8
2014-09-17T10:09:35Z
[ "python" ]
I have various strings `123_dog` `2_fish` `56_cat` `45_cat_fish` There is always one number. Always a '\_' after the number. I need to remove the number and the underscore. I can use regex, but I wonder if there is some pythonic way that uses builtin methods? (I'm an experienced coder - but new to Python.)
Assuming that there is always an underscore after the number, and that there is always exactly a single number, you can do this: ``` s = '45_cat_fish' print s.split('_', 1)[1] # >>> cat_fish ``` The argument to `split` specifies the maximum number of splits to perform.
What does Thread Local Objects mean in Flask?
25,887,910
3
2014-09-17T10:15:44Z
25,888,107
9
2014-09-17T10:25:10Z
[ "python", "flask" ]
I am reading the Flask documentation and I read this - > One of the design decisions in Flask was that simple tasks should be simple; they should not take a lot of code and yet they should not limit you. Because of that, Flask has few design choices that some people might find surprising or unorthodox. For example, Fl...
A thread-local object is an object that is stored in a dedicated structure, tied to the current thread id. If you ask this structure for the object, it'll use the current thread identifier to give you data unique to the current thread. See [`threading.local`](https://docs.python.org/2/library/threading.html#threading.l...
Pandas join on field with different names?
25,888,207
3
2014-09-17T10:29:50Z
25,888,471
8
2014-09-17T10:43:08Z
[ "python", "join", "pandas", "field", "left-join" ]
According to [this documentation](http://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html#left-outer-join) I can only make a join between field having the same name. Do you know if it's possible to join two DataFrames on a field having different names? The equivalent in SQL would be: ``` SELECT * FROM d...
I think what you want is possible using `merge`. Pass in the keyword arguments for `left_on` and `right_on` to tell Pandas which column(s) from each DataFrame to use as keys: ``` pandas.merge(df1, df2, how='left', left_on=['id_key'], right_on=['fk_key']) ``` The documentation describes this in more detail on [this pa...
How To Get Latitude & Longitude with python
25,888,396
4
2014-09-17T10:39:14Z
25,890,585
9
2014-09-17T12:29:28Z
[ "python", "google-maps", "python-2.7" ]
I am trying to retrieve the longitude & latitude of a physical address ,through the below script .But I am getting the error. I have already installed googlemaps . kindly reply Thanks In Advance ``` #!/usr/bin/env python import urllib,urllib2 """This Programs Fetch The Address""" from googlemaps import GoogleMaps ...
googlemaps package you are using is not an official one and does not use google maps API v3 which is the latest one from google. You can use google's [geocode REST api](https://developers.google.com/maps/documentation/geocoding/) to fetch coordinates from address. Here's an example. ``` import requests response = re...
Difference between `yield from foo()` and `for x in foo(): yield x`
25,890,604
11
2014-09-17T12:30:19Z
25,890,821
12
2014-09-17T12:40:12Z
[ "python", "python-3.x", "generator", "yield", "yield-from" ]
In Python most examples of yield from explain it with saying that ``` yield from foo() ``` is similar to ``` for x in foo(): yield x ``` On the other hand it doesn't seem to be exactly the same and there's some magic thrown in. I feel a bit uneasy about using a function that does magic that I don't understand. What...
When `foo()` returns a regular iterable, the two are equivalent. The 'magic' comes into play when `foo()` is a *generator too*. At that moment, the `yield from foo()` and `for x in foo(): yield x` cases differ materially. A generator can be *sent* data too, using the [`generator.send()` method](https://docs.python.org...
Visitor pattern in python
25,891,637
6
2014-09-17T13:14:49Z
25,895,156
9
2014-09-17T15:54:55Z
[ "python", "visitor" ]
here is a simplified implementation of the visitor pattern in C++. Ist it possible to implement something like this in Python? I need it, because I will pass Objects from C++ code to a function in Python. My idea was to implement a visitor in Python to find out the type of the Object. My C++ code: ``` #include <iost...
The visitor pattern can be implemented in Python, I use it to implement a clean interface between my data and presentation layer. The data layer can determine the ordering of the data. and the presentation layer simply prints/formats it : In my data module I have : ``` class visited(object): .... def accep...
Python Pandas If value in column B = equals [X, Y, Z] replace column A with "T"
25,895,154
9
2014-09-17T15:54:50Z
25,895,239
12
2014-09-17T15:58:55Z
[ "python", "pandas", "comparison", "multiple-columns" ]
Say I have this array: ``` A, B 1, G 2, X 3, F 4, Z 5, I ``` If column B equals [X, Y or Z] replace column A with value "T" I've found how to change values within the same column but not across, any help would be most appreciated.
You can try this: ``` import pandas as pd df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': ['G', 'X', 'F', 'Z', 'I'] }) df.ix[df.B.isin(['X','Y','Z']), 'A'] = 'T' print df ``` Output: ``` A B 0 1 G 1 T X 2 3 F 3 T Z 4 5 I ``` Remember to use `ix` or `loc` to avoid setting values on ...
Pandas: Add column if does not exists
25,896,453
2
2014-09-17T17:08:01Z
25,896,592
7
2014-09-17T17:15:26Z
[ "python", "pandas" ]
I'm new to using pandas and am writing a script where I read in a dataframe and then do some computation on some of the columns. Sometimes I will have the column called "Met": ``` df = pd.read_csv(File, sep='\t', compression='gzip', header=0, names=["Chrom", "Site", "coverage", "Met"]) ``` Othertimes I will have: `...
You check it like this: ``` if 'Met' not in df: df['Met'] = df['freqC'] * df['coverage'] ```
Where should I write a user specific log file to (and be XDG base directory compatible)
25,897,836
5
2014-09-17T18:30:28Z
27,965,014
9
2015-01-15T13:56:36Z
[ "python", "logging", "pip" ]
By default, pip logs errors into "~/.pip/pip.log". Pip has an option to change the log path, and I'd like to put the log file somewhere besides ~/.pip so as not to clutter up my home directory. Where should I put it and be [XDG base dir compatible](http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html)...
This is, for the moment, unclear. Different software seem to handle this in different ways ([imsettings](https://code.google.com/p/imsettings/issues/detail?id=30) puts it in `$XDG_CACHE_HOME`, [profanity](https://groups.google.com/forum/#!msg/profanitydev/YQLDobYEfnA/kpodU-qckOIJ) in `$XDG_DATA_HOME`). [Debian](https...
Why does str(float) return more digits in Python 3 than Python 2?
25,898,733
15
2014-09-17T19:25:05Z
25,899,600
22
2014-09-17T20:17:58Z
[ "python", "python-2.7", "python-3.x", "floating-point-conversion" ]
In Python 2.7, `repr` of a `float` returns the nearest decimal number up to 17 digits long; this is precise enough to uniquely identify each possible IEEE floating point value. `str` of a `float` worked similarly, except that it limited the result to 12 digits; for most purposes this is a more reasonable result, and in...
No, there's no PEP. There's an [issue](http://bugs.python.org/issue9337) in the bug tracker, and an [associated discussion](https://mail.python.org/pipermail/python-dev/2010-July/102515.html) on the Python developers mailing list. While I was responsible for proposing and implementing the change, I can't claim it was m...
Python Django : No module named security
25,901,481
18
2014-09-17T22:39:47Z
25,909,386
9
2014-09-18T09:47:29Z
[ "python", "django", "module", "virtualenv" ]
When I deploy my project on an Ubuntu Server, using a virtualenv, I got this error : ``` [17/Sep/2014 22:29:00] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/zat42/myproj...
So, I found a solution : ``` 'django.middleware.security.SecurityMiddleware' ``` This line is in MIDDLEWARE\_CLASSES, from settings.py. When I delete this line I have no more problems with the security module but I guess this is not a good way to solve the problem ... I guess this line is in relation with the crsf to...
Python Django : No module named security
25,901,481
18
2014-09-17T22:39:47Z
27,025,300
7
2014-11-19T19:27:37Z
[ "python", "django", "module", "virtualenv" ]
When I deploy my project on an Ubuntu Server, using a virtualenv, I got this error : ``` [17/Sep/2014 22:29:00] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/zat42/myproj...
I ran into this same problem. It turned out that I was inadvertently using my machine's version of django-admin.py to start my Django project, rather than the one installed within the virtualenv. I ended up having to `source bin/activate` again after installing django within the virtualenv, before running any of the dj...
Python Django : No module named security
25,901,481
18
2014-09-17T22:39:47Z
27,251,293
41
2014-12-02T14:01:50Z
[ "python", "django", "module", "virtualenv" ]
When I deploy my project on an Ubuntu Server, using a virtualenv, I got this error : ``` [17/Sep/2014 22:29:00] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/home/zat42/myproj...
I met the same problem. Finnaly, I found I’m using django 1.7.1 to run a 1.8dev generated project. When I switch back to 1.7.1, and remove ‘django.middleware.security.SecurityMiddleware’ in setting.py, it seems ok.
How do I send data to a running python thread?
25,904,537
4
2014-09-18T05:08:36Z
25,904,681
8
2014-09-18T05:21:02Z
[ "python", "multithreading" ]
I have a class that is run in separate threads in my application. I can have multiple threads running at a time and the threads are daemons. After a period of time, *some* of these threads need to receive and process a message. How do I do this? A sample of my code looks like this: ``` import threading import time ...
You can use a [`Queue.Queue`](https://docs.python.org/2/library/queue.html#queue-objects) (or `queue.Queue` in Python 3) for this: ``` import threading import time from Queue import Queue print_lock = threading.Lock() class MyThread(threading.Thread): def __init__(self, queue, args=(), kwargs=None): thr...
How to remove duplicate values from a RDD[PYSPARK]
25,905,596
7
2014-09-18T06:23:01Z
25,915,033
11
2014-09-18T14:10:05Z
[ "python", "apache-spark", "rdd" ]
I have the following table as a RDD: ``` Key Value 1 y 1 y 1 y 1 n 1 n 2 y 2 n 2 n ``` I want to remove all the duplicates from `Value`. Output should come like this: ``` Key Value 1 y 1 n 2 y 2 n ``` While working in pyspark, output should come as list of key-value pairs like t...
I am afraid I have no knowledge about *python*, so all the references and code I provide in this answer are relative to *java*. However, it should not be very difficult to translate it into *python* code. You should take a look to the following [webpage](http://spark.apache.org/docs/latest/programming-guide.html#trans...
Missing data, insert rows in Pandas and fill with NAN
25,909,984
6
2014-09-18T10:17:23Z
25,916,109
8
2014-09-18T14:58:28Z
[ "python", "numpy", "pandas" ]
I'm new to Python and Pandas so there might be a simple solution which I don't see. I have a number of discontinuous datasets which look like this: ``` ind A B C 0 0.0 1 3 1 0.5 4 2 2 1.0 6 1 3 3.5 2 0 4 4.0 4 5 5 4.5 3 3 ``` I now look for a solution to get the following: ``...
`set_index` and `reset_index` are your friends. ``` df = DataFrame({"A":[0,0.5,1.0,3.5,4.0,4.5], "B":[1,4,6,2,4,3], "C":[3,2,1,0,5,3]}) ``` First move column A to the index: ``` In [64]: df.set_index("A") Out[64]: B C A 0.0 1 3 0.5 4 2 1.0 6 1 3.5 2 0 4.0 4 5 4.5 3 3 ``` Then reindex wit...
parallel generation of random forests using scikit-learn
25,914,320
7
2014-09-18T13:39:08Z
25,925,913
7
2014-09-19T03:29:09Z
[ "python", "scikit-learn", "random-forest", "elastic-map-reduce" ]
Main question: How do I combine different randomForests in python and scikit-learn? I am currently using the randomForest package in R to generate randomforest objects using elastic map reduce. This is to address a classification problem. Since my input data is too large to fit in memory on one machine, I sample the ...
Sure, just aggregate all the trees, for instance have look at this snippet from [pyrallel](https://github.com/pydata/pyrallel/blob/master/pyrallel/ensemble.py#L27): ``` def combine(all_ensembles): """Combine the sub-estimators of a group of ensembles >>> from sklearn.datasets import load_iris >>> ...
The lxml 'None' type is not None
25,918,190
3
2014-09-18T16:47:09Z
25,918,261
8
2014-09-18T16:51:56Z
[ "python", "lxml" ]
I want to compare a variable I set to `None`, which was a string element before, with `is` but it fails. When I compare this variable to `None` with `==`, it works. This is the variable I'm talking about: ``` print type(xml.a) -> <type 'lxml.objectify.StringElement'> ``` Because some libraries I use have `None` as ...
You are using the [`lxml.objectify` API](http://lxml.de/objectify.html#the-lxml-objectify-api); this API uses a *special object* to represent `None` values in the objectified XML tree. When you assigned `None` to `xml.a`, `lxml` stored that special object, so that it can transform that to a XML element in an XML docume...
Using Python to create a right triangle
25,921,016
3
2014-09-18T19:39:02Z
25,921,056
7
2014-09-18T19:41:31Z
[ "python", "python-3.x" ]
I'm confused and frustrated as to why my program is not executing the way it should. I am trying to create a right triangle using asterisks on python ver 3. I am using the exact code from the text book and it comes out as a straight line. Please enlighten me. example ``` size = 7 for row in range (size): for col...
In Python, indentation counts. The final `print` should be aligned with the second `for`. ``` size = 7 for row in range (size): for col in range (row + 1): print('*', end='') print() ``` Result: ``` * ** *** **** ***** ****** ******* ``` An empty `print` function effectively means "move to a new li...
Changes of clustering results after each time run in Python scikit-learn
25,921,762
2
2014-09-18T20:28:41Z
25,921,785
8
2014-09-18T20:30:51Z
[ "python", "scikit-learn", "cluster-analysis", "k-means", "spectral" ]
I have a bunch of sentences and I want to cluster them using scikit-learn spectral clustering. I've run the code and get the results with no problem. But, every time I run it I get different results. I know this is the problem with initiation but I don't know how to fix it. This is my a part of my code that runs on sen...
When using k-means, you want to set the `random_state` parameter in `KMeans` (see the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html)). Set this to either an int or a [`RandomState`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.RandomState.html) instance...
Element-wise matrix multiplication in NumPy
25,922,212
5
2014-09-18T20:58:52Z
25,922,418
8
2014-09-18T21:11:02Z
[ "python", "arrays", "image-processing", "numpy", "matrix-multiplication" ]
I'm making my first real foray into Python and NumPy to do some image processing. I have an image loaded as a 3 dimensional NumPy Array, where axis 0 represents image bands, while axes 1 and 2 represent columns and rows of pixels. From this, I need to take the 3x1 matrix representing each pixel and perform a few operat...
Numpy arrays use element-wise multiplication by default. Check out numpy.einsum, and numpy.tensordot. I think what you're looking for is something like this: ``` results = np.einsum('ij,jkl->ikl',factor,input) ```
Why do we have to use the __dunder__ methods instead of operators when calling via super?
25,924,548
33
2014-09-19T00:29:44Z
30,675,066
18
2015-06-05T20:14:30Z
[ "python", "super" ]
Why do we have to use `__getitem__` rather than the usual operator access? ``` class MyDict(dict): def __getitem__(self, key): return super()[key] ``` We get `TypeError: 'super' object is not subscriptable`. Instead we must use `super().__getitem__(key)`, but I never fully understood why - what exactly i...
CPython's bug tracker's [issue 805304, "super instances don't support item assignment",](http://bugs.python.org/issue805304) has Raymond Hettinger give a detailed explanation of perceived difficulties. The reason this doesn't work automatically is that such methods have to be defined on the class due to Python's cachi...
How to iterate over pandas multiindex dataframe using index
25,929,319
13
2014-09-19T08:15:06Z
25,935,024
15
2014-09-19T13:23:17Z
[ "python", "pandas" ]
I have a data frame df which looks like this. Date and Time are 2 multilevel index ``` observation1 observation2 date Time 2012-11-02 9:15:00 79.373668 224 9:16:00 130.841316 477 2012-11-03 9:15:00 45.312814 ...
One easy way would be to groupby the first level of the index - iterating over the groupby object will return the group keys and a subframe containing each group. ``` In [136]: for date, new_df in df.groupby(level=0): ...: print(new_df) ...: observation1 observation2 date ...
Upload large file nginx + uwsgi
25,932,624
3
2014-09-19T11:13:00Z
25,932,856
7
2014-09-19T11:26:56Z
[ "python", "nginx", "flask", "uwsgi" ]
stack: flask 0.10 + uwsgi 1.4.5 + nginx 1.2.3 I can upload small files (<100k) through my application but larger ones fail. uwsgi log shows: > Invalid (too big) CONTENT\_LENGTH. skip. nginx log does not show anything useful. I tried the following, without success: * [nginx conf] client\_max\_body\_size 0 or 20M * ...
Your problem in uwsgi `limit-post` params. Look at [source](https://github.com/unbit/uwsgi/blob/master/core/protocol.c#L429). This variable can be overridden by other configs. For example on debian config from `/usr/share/uwsgi/conf/default.ini` are also loaded.
Unique Salt per User using Flask-Security
25,942,092
4
2014-09-19T20:41:38Z
27,596,919
11
2014-12-22T05:15:13Z
[ "python", "encryption", "flask", "salt", "flask-security" ]
After reading here a bit about salting passwords, it seems that it's best to use a unique salt for each user. I'm working on implementing Flask-Security atm, and from the documentation it appears you can only set a global salt: ie SECURITY\_PASSWORD\_SALT = 'thesalt' Question: How would one go about making a unique sa...
Yes, Flask-Security does use per-user salts by design if using bcrypt (and other schemes such as des\_crypt, pbkdf2\_sha256, pbkdf2\_sha512, sha256\_crypt, sha512\_crypt). The config for 'SECURITY\_PASSWORD\_SALT' is only used for HMAC encryption. If you are using bcrypt as the hashing algorithm Flask-Security uses pa...
Generating all DNA kmers with Python
25,942,528
3
2014-09-19T21:20:48Z
25,942,623
8
2014-09-19T21:29:28Z
[ "python", "sequence", "permutation" ]
I'm having a little bit of trouble with this python code. I'm rather new to python and I would like to generate all possible DNA kmers of length k and add them to a list, however I cannot think of an elegant way to do it! Below is what I have for a kmer of length 8. Any suggestions would be very helpful. ``` bases=['...
``` In [58]: bases=['A','T','G','C'] In [59]: k = 2 In [60]: [''.join(p) for p in itertools.product(bases, repeat=k)] Out[60]: ['AA', 'AT', 'AG', 'AC', 'TA', 'TT', 'TG', 'TC', 'GA', 'GT', 'GG', 'GC', 'CA', 'CT', 'CG', 'CC'] In [61]: k = 3 In [62]: [''.join(p) for p in itertools.product(bases, repeat=k)] Out[62]: ['...
Django package to generate random alphanumeric string
25,943,850
8
2014-09-19T23:49:33Z
25,949,808
27
2014-09-20T14:30:27Z
[ "python", "django" ]
I'm building an app that has a separated front-end (Angular or some other JS library) and backend (Django). To ensure some security of requests being sent to the server, I want to append a url parameter say `server/someurl?unique_id=Something-unique`. I am storing this unique code on the machine's `localStorage` for a...
Django provides the function `get_random_string()` which will satisfy the alphanumeric string generation requirement. You don't need any extra package because it's in the `django.utils.crypto` module. ``` >>> from django.utils.crypto import get_random_string >>> unique_id = get_random_string(length=32) >>> unique_id u...
How to send an email through gmail without enabling 'insecure access'?
25,944,883
14
2014-09-20T03:24:58Z
25,949,203
20
2014-09-20T13:17:08Z
[ "python", "gmail" ]
Google are pushing us to improve the security of script access to their gmail smtp servers. I have no problem with that. In fact I'm happy to help. But they're not making it easy. It's all well and good to suggest we `Upgrade to a more secure app that uses the most up to date security measures`, but that doesn't help ...
This was painful, but I seem to have something going now... ### Python3 is not supported (yet) I don't think it will be too hard to attain, as I was stumbling through converting packages without hitting anything massive: just the usual 2to3 stuff. Yet after a couple of hours I got tired of swimming upstream. At time ...
Check if a OneToOne relation exists in Django
25,944,968
5
2014-09-20T03:44:09Z
27,042,585
7
2014-11-20T14:54:08Z
[ "python", "django", "model", "one-to-one" ]
Now I'm using django 1.6 I have two models relates with a `OneToOneField`. ``` class A(models.Model): pass class B(models.Model): ref_a = models.OneToOneField(related_name='ref_b', null=True) ``` --- First see my code that points out the problem: ``` a1 = A.objects.create() a2 = A.objects.create() b1 = B....
So you have a least two ways of checking that. First is to create try/catch block to get attribute, second is to use `hasattr`. ``` class A(models.Model): def get_B(self): try: return self.b except: return None class B(models.Model): ref_a = models.OneToOneField(related_name='r...
Is threading.local() a safe way to store variables for a single request in Google AppEngine?
25,949,059
5
2014-09-20T13:02:06Z
25,949,110
7
2014-09-20T13:07:14Z
[ "python", "multithreading", "google-app-engine", "global-variables", "python-multithreading" ]
I have a google appengine app where I want to set a global variable for that request only. Can I do this? In request\_vars.py ``` # request_vars.py global_vars = threading.local() ``` In another.py ``` # another.py from request_vars import global_vars get_time(): return global_vars.time_start ``` In main.py ...
Yes, using `threading.local` is an excellent method to set a per-request global. Your request will always be handled by one thread, on one instance in the Google cloud. That thread local value will be unique to that thread. Take into account that the thread *can* be reused for future requests, and always reset the val...
How to break long string lines for PEP8 compliance?
25,949,525
12
2014-09-20T13:55:54Z
25,949,550
15
2014-09-20T13:59:17Z
[ "python", "string", "pep8" ]
I have many long lines like this in the project and don't know how to break it to keep PEP8 happy. PEP8 shows warning from `.format(me['id'])` ``` pic_url = "http://graph.facebook.com/{0}/picture?width=100&height=100".format(me['id']) ``` How can I break the line to get rid of PEP8 warning and yet don't break the cod...
Using [string literal concatenation](https://docs.python.org/2/reference/lexical_analysis.html#string-literal-concatenation): ``` pic_url = ("http://graph.facebook.com/{0}/" "picture?width=100&height=100".format(me['id'])) ```
make the if else statement one liner in python
25,949,976
4
2014-09-20T14:49:02Z
25,949,986
9
2014-09-20T14:50:29Z
[ "python" ]
How can I make the if else statement as below one liner? ``` uly = '50' if '-' in uly: uly = uly.replace('-','S') else: uly = 'N'+uly print uly ``` My trial: ``` uly = [uly=uly.replace('-','S') if '-' in uly else uly = 'N'+uly] print uly ```
The following will do it: ``` uly = uly.replace('-', 'S') if '-' in uly else 'N' + uly ``` This uses the so-called [conditional expression](https://docs.python.org/2/reference/expressions.html#conditional-expressions) (similar to an `if` statement except that it's an expression and not a statement). What you have ri...
msgpack: haskell & python
25,950,447
4
2014-09-20T15:40:25Z
25,950,813
9
2014-09-20T16:19:14Z
[ "python", "haskell", "msgpack" ]
I'm confused by the differences between [haskell](https://github.com/msgpack/msgpack-haskell) and [python](https://github.com/msgpack/msgpack-python) clients for msgpack. This: ``` import Data.MessagePack as MP import Data.ByteString.Lazy as BL BL.writeFile "test_haskell" $ MP.pack (0, 2, 28, ()) ``` and this: ``` ...
The empty tuple `()` in Haskell is not like empty tuple or empty list in Python. It's similar to `None` in Python. (in the context of msgpack). So to get the same result, change the haskell program as: ``` MP.pack (0, 2, 28, []) -- empty list ``` Or change the python program as: ``` f.write(msgpack.packb([0, 2, 28...
Why is numba faster than numpy here?
25,950,943
9
2014-09-20T16:31:24Z
25,951,367
11
2014-09-20T17:20:53Z
[ "python", "numpy", "numba" ]
I can't figure out why numba is beating numpy here (over 3x). Did I make some fundamental error in how I am benchmarking here? Seems like the perfect situation for numpy, no? Note that as a check, I also ran a variation combining numba and numpy (not shown), which as expected was the same as running numpy without numba...
When you ask numpy to do: ``` x = x*2 - ( y * 55 ) ``` It is internally translated to something like: ``` tmp1 = y * 55 tmp2 = x * 2 tmp3 = tmp2 - tmp1 x = tmp3 ``` Each of those temps are arrays that have to be allocated, operated on, and then deallocated. Numba, on the other hand, handles things one item at a tim...
Why is numba faster than numpy here?
25,950,943
9
2014-09-20T16:31:24Z
25,952,400
10
2014-09-20T19:15:04Z
[ "python", "numpy", "numba" ]
I can't figure out why numba is beating numpy here (over 3x). Did I make some fundamental error in how I am benchmarking here? Seems like the perfect situation for numpy, no? Note that as a check, I also ran a variation combining numba and numpy (not shown), which as expected was the same as running numpy without numba...
I think this question highlights (somewhat) the limitations of calling out to precompiled functions from a higher level language. Suppose in C++ you write something like: ``` for (int i = 0; i != N; ++i) a[i] = b[i] + c[i] + 2 * d[i]; ``` The compiler sees all this at compile time, the whole expression. It can do a l...
Convert pandas.Series from dtype object to float, and errors to nans
25,952,790
2
2014-09-20T20:01:00Z
25,952,844
9
2014-09-20T20:06:35Z
[ "python", "pandas" ]
Consider the following situation: ``` In [2]: a = pd.Series([1,2,3,4,'.']) In [3]: a Out[3]: 0 1 1 2 2 3 3 4 4 . dtype: object In [8]: a.astype('float64', raise_on_error = False) Out[8]: 0 1 1 2 2 3 3 4 4 . dtype: object ``` I would have expected an option that allows conversion whil...
``` In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True) Out[30]: 0 1 1 2 2 3 3 4 4 NaN dtype: float64 ```
Django 1.7 - "No migrations to apply" when run migrate after makemigrations
25,958,708
24
2014-09-21T11:27:05Z
25,959,632
9
2014-09-21T13:20:41Z
[ "python", "django" ]
I use Django1.7 with Mezzanine. I create simple profile (according to Mezzanine documentation) stored in separate app "profiles": ``` class RoadmapProfile(models.Model): user = models.OneToOneField("auth.User") fullname = models.CharField(max_length=100, verbose_name="Full name") ``` Creation of migrations re...
Sounds like your initial migration was faked because the table already existed (probably with an outdated schema): <https://docs.djangoproject.com/en/1.7/topics/migrations/#adding-migrations-to-apps> > "This will make a new initial migration for your app. Now, when you > run migrate, **Django will detect that you hav...
Django 1.7 - "No migrations to apply" when run migrate after makemigrations
25,958,708
24
2014-09-21T11:27:05Z
27,650,735
55
2014-12-25T21:06:36Z
[ "python", "django" ]
I use Django1.7 with Mezzanine. I create simple profile (according to Mezzanine documentation) stored in separate app "profiles": ``` class RoadmapProfile(models.Model): user = models.OneToOneField("auth.User") fullname = models.CharField(max_length=100, verbose_name="Full name") ``` Creation of migrations re...
1. In MySQL Database delete row `'profiles'` from the table `'django_migrations'`. 2. Delete all migration files in migrations folder. 3. Try again `python manage.py makemigrations` and `python manage.py migrate` command.
python pickle gives "AttributeError: 'str' object has no attribute 'write'"
25,958,824
20
2014-09-21T11:43:06Z
25,958,825
34
2014-09-21T11:43:06Z
[ "python", "python-2.7", "pickle" ]
When I try to pickle something, I get an `AttributeError: 'str' object has no attribute 'write'` An example: ``` import pickle pickle.dump({"a dict":True},"a-file.pickle") ``` produces: ``` ... AttributeError: 'str' object has no attribute 'write' ``` What's wrong?
It's a trivial mistake: `pickle.dump(obj,file)` takes a `file` object, not a file name. What I need is something like: ``` with open("a-file.pickle",'wb') as f: pickle.dump({"a dict":True},f) ```
Loading initial data with Django 1.7 and data migrations
25,960,850
67
2014-09-21T15:37:13Z
25,981,899
63
2014-09-22T19:38:14Z
[ "python", "json", "django", "migration", "data-migration" ]
I recently switched from Django 1.6 to 1.7, and I began using migrations (I never used South). Before 1.7, I used to load initial data with a `fixture/initial_data.json` file, which was loaded with the `python manage.py syncdb` command (when creating the database). Now, I started using migrations, and this behavior i...
Assuming you have a fixture file in `<yourapp>/fixtures/initial_data.json` 1. Create your empty migration: In Django 1.7: ``` python manage.py makemigrations --empty <yourapp> ``` In Django 1.8+, you can provide a name: ``` python manage.py makemigrations --empty <yourapp> --name load_intial_d...
Loading initial data with Django 1.7 and data migrations
25,960,850
67
2014-09-21T15:37:13Z
28,285,161
8
2015-02-02T19:22:18Z
[ "python", "json", "django", "migration", "data-migration" ]
I recently switched from Django 1.6 to 1.7, and I began using migrations (I never used South). Before 1.7, I used to load initial data with a `fixture/initial_data.json` file, which was loaded with the `python manage.py syncdb` command (when creating the database). Now, I started using migrations, and this behavior i...
The best way to load initial data in migrated apps is through data migrations (as also recommended in the docs). The advantage is that the fixture is thus loaded in both during the tests as well as production. @n\_\_o suggested reimplementing `loaddata` command in the migration. In my tests, however, calling `loaddata...
Python: Are a,b=1,2 and a=1;b=2 strictly equivalent?
25,961,488
3
2014-09-21T16:44:46Z
25,961,519
10
2014-09-21T16:47:49Z
[ "python", "python-2.7", "loops", "syntax" ]
I am puzzled with the following: This works: ``` a, b = 1071, 1029 while(a%b != 0): a, b = b, a%b ``` But, the following snippet returns a **ZeroDivisionError** error message: ``` a, b = 1071, 1029 while(a%b != 0): a = b; b = a%b ``` while I expected both would be strictly equivalent. Can anyone throw the...
No. In ``` a, b = b, a%b ``` the right-hand side is evaluated into a tuple first, so `a%b` is calculated using the original value of `a`. In contrast, ``` a = b; b = a%b ``` `a%b` is calculated *after* `a` as been assigned the value of `b`, assigning a different result to `b`.
Is it a bug to omit an Accept */* header in an HTTP/1.0 Request for a REST API
25,961,997
14
2014-09-21T17:35:30Z
33,517,262
11
2015-11-04T08:44:02Z
[ "python", "rest", "http", "curl", "http-headers" ]
I'm trying to determine whether it is a bug that Python's [*urllib.urlopen()*](https://docs.python.org/2.7/library/urllib.html#urllib.urlopen) function omits an HTTP Accept header when making simple REST API requests. The [Facebook Graph API](https://developers.facebook.com/docs/graph-api) seems to notice whether the ...
the RFC states > The Accept request-header field can be used to specify certain media types which are acceptable for the response. This means that the header is optional because it says `can be used`. as you pointed out ther RFC also says: > If no Accept header field is present, then it is assumed that the client a...
How to read a 6 GB csv file with pandas
25,962,114
12
2014-09-21T17:46:43Z
25,962,187
32
2014-09-21T17:54:03Z
[ "python", "memory", "numpy", "pandas" ]
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting the following memory error: ``` MemoryError Traceback (most recent call last) <ipython-input-58-67a72687871b> in <module>() ----> 1 data=pd.read_csv('aphro.csv',sep=';') C:\Python27\lib\site-packages\pandas\io\...
The error shows that the machine does not have enough memory to read the entire CSV into a DataFrame at one time. Assuming you do not need the entire dataset in memory all at one time, one way to avoid the problem would be to [process the CSV in chunks](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.pa...
How to read a 6 GB csv file with pandas
25,962,114
12
2014-09-21T17:46:43Z
26,017,289
7
2014-09-24T12:46:23Z
[ "python", "memory", "numpy", "pandas" ]
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting the following memory error: ``` MemoryError Traceback (most recent call last) <ipython-input-58-67a72687871b> in <module>() ----> 1 data=pd.read_csv('aphro.csv',sep=';') C:\Python27\lib\site-packages\pandas\io\...
Thanks I proceeded the following way: ``` chunks=pd.read_table('aphro.csv',chunksize=1000000,sep=';',\ names=['lat','long','rf','date','slno'],index_col='slno',\ header=None,parse_dates=['date']) df=pd.DataFrame() %time df=pd.concat(chunk.groupby(['lat','long',chunk['date'].map(lambda x: x.year)])['rf'...
Check if float is close to any float stored in array
25,962,838
3
2014-09-21T19:07:01Z
25,962,971
9
2014-09-21T19:21:43Z
[ "python", "arrays", "numpy", "floating-point" ]
I need to check if a given float is close, within a given tolerance, to *any float* in an array of floats. ``` import numpy as np # My float a = 0.27 # The tolerance t = 0.01 # Array of floats arr_f = np.arange(0.05, 0.75, 0.008) ``` Is there a simple way to do this? Something like `if a in arr_f:` but allowing for ...
How about using [`np.isclose`](http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isclose.html)? ``` >>> np.isclose(arr_f, a, atol=0.01).any() True ``` `np.isclose` compares two objects element-wise to see if the values are within a given tolerance (here specified by the keyword argument `atol`). The funct...
pip geoip installing in ubuntu gcc error
25,963,409
11
2014-09-21T20:14:12Z
25,963,432
24
2014-09-21T20:16:57Z
[ "python", "gcc", "ubuntu-12.04", "pip" ]
i am try to install geoip in ubuntu in python pip...but there is same gcc error ``` pip install GeoIP gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes - fPIC -I/usr/include/python2.7 -c py_GeoIP.c -o build/temp.linux-i686-2.7/py_GeoIP.o -fno- strict-aliasing py_GeoIP.c:23:19: fatal...
You need to install the `libgeoip-dev` package. ``` $ easy_install GeoIP Searching for GeoIP Reading https://pypi.python.org/simple/GeoIP/ ... py_GeoIP.c:23:19: fatal error: GeoIP.h: No such file or directory #include "GeoIP.h" ^ compilation terminated. error: Setup script exited with error: comman...
Convert pandas series from string to unique int ids
25,963,431
2
2014-09-21T20:16:51Z
25,963,464
8
2014-09-21T20:21:16Z
[ "python", "pandas" ]
I have a categorical variable in a series. I want to assign integer ids to each unique value and create a new series with the ids, effectively turning a string variable into an integer variable. What is the most compact/efficient way to do this?
You could use [pandas.factorize](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.factorize.html): ``` In [32]: s = pd.Series(['a','b','c']) In [33]: labels, levels = pd.factorize(s) In [35]: labels Out[35]: array([0, 1, 2]) ```
Difference between every pair of columns of two numpy arrays (how to do it more efficiently)?
25,965,329
4
2014-09-22T00:45:03Z
25,965,635
7
2014-09-22T01:37:06Z
[ "python", "arrays", "performance", "numpy" ]
I am trying to optimize some code, and by profiling i noticed that this particular loop takes a lot of time. Can you help me write it faster? ``` import numpy as np rows_a, rows_v, cols = (10, 15, 3) a = np.arange(rows_a*cols).reshape(rows_a,cols) v = np.arange(rows_v*cols).reshape(rows_v,cols) c = 0 for i in range(...
``` import numpy as np rows_a, rows_v, cols = (10, 15, 3) a = np.arange(rows_a*cols).reshape(rows_a,cols) v = np.arange(rows_v*cols).reshape(rows_v,cols) def using_loop(): c = 0 for i in range(len(v)): D = ((a-v[i])**2).sum(axis=-1) c += D.min() return c def using_broadcasting(): retu...
Pybrain time series prediction using LSTM recurrent nets
25,967,922
15
2014-09-22T06:33:39Z
26,233,461
25
2014-10-07T10:04:06Z
[ "python", "neural-network", "time-series", "prediction", "pybrain" ]
I have a question in mind which relates to the usage of pybrain to do regression of a time series. I plan to use the LSTM layer in pybrain to train and predict a time series. I found an example code here in the link below [Request for example: Recurrent neural network for predicting next value in a sequence](http://s...
You can train an LSTM network with a single input node and a single output node for doing time series prediction like this: First, just as a good practice, let's use Python3's print function: ``` from __future__ import print_function ``` Then, make a simple time series: ``` data = [1] * 3 + [2] * 3 data *= 3 print(...
Python Multiprocessing Lib Error (AttributeError: __exit__)
25,968,518
4
2014-09-22T07:15:46Z
25,968,716
10
2014-09-22T07:28:54Z
[ "python", "multiprocessing", "pickle", "with-statement", "contextmanager" ]
Am getting this error when using the `pool.map(funct, iterable)`: ``` AttributeError: __exit__ ``` No Explanation, only stack trace to the pool.py file within the module. using in this way: ``` with Pool(processes=2) as pool: pool.map(myFunction, mylist) pool.map(myfunction2, mylist2) ``` I suspect there cou...
In Python 2.x and 3.0, 3.1 and 3.2, `multiprocessing.Pool()` objects are *not context managers*. You cannot use them in a `with` statement. Only in Python 3.3 and up can you use them as such. From the [Python 3 `multiprocessing.Pool()` documentation](https://docs.python.org/3/library/multiprocessing.html#module-multipr...
Redis scan command match option does not work in Python
25,970,315
2
2014-09-22T09:08:44Z
30,110,574
12
2015-05-07T19:58:49Z
[ "python", "redis" ]
I use python redis to match some infomation by using match option? but it doesn't work. ``` import redis import REDIS class UserCache(object): def __init__(self): self.rds = self._connectRds() def _connectRds(self): _db = REDIS['usercache'] pool = redis.ConnectionPool(host=_db['HOS...
Try the SCAN command like this : ``` r = Redis(....) #redis url for user in r.scan_iter(match='userinfo_*'): print(user) ```
Is it possible to step backwards in pdb?
25,972,979
18
2014-09-22T11:26:35Z
26,828,316
11
2014-11-09T12:45:06Z
[ "python", "pdb" ]
After I hit n to evaluate a line, I want to go back and then hit s to step into that function if it failed. Is this possible? The docs say: **j(ump) lineno** Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code t...
The GNU debugger, gdb: It is extremely slow, as it undoes single machine instruction at a time. The Python debugger, pdb: The `jump` command takes you backwards in the code, but does not reverse the state of the program. For Python, the extended python debugger prototype, epdb, was created for this reason. Here is th...
How to format axis number format to thousands with a comma in matplotlib
25,973,581
13
2014-09-22T11:58:33Z
25,973,637
17
2014-09-22T12:00:35Z
[ "python", "matplotlib" ]
another simple question, how can i change the format of the numbers in the x axis to be like 10,000 instead of 10000? Ideally i would just like to do something like this ``` x = format((10000.21, 22000.32, 10120.54), "#,###") ``` here is the code below ``` import matplotlib.pyplot as plt # create figure instance fi...
Use `,` as [format specifier](https://docs.python.org/2/library/string.html#formatstrings): ``` >>> format(10000.21, ',') '10,000.21' ``` Alternatively you can also use [`str.format`](https://docs.python.org/2/library/stdtypes.html#str.format) instead of [`format`](https://docs.python.org/2/library/functions.html#for...
Run bash script with python - TypeError: bufsize must be an integer
25,977,092
6
2014-09-22T14:54:31Z
25,977,145
13
2014-09-22T14:56:55Z
[ "python", "bash", "subprocess" ]
I'm trying to write python file, which wxtrac tar file in python. As I understand, `subprocess` is the appropriate tool for this mission. I write the following code: ``` from subprocess import call def tarfile(path): call(["tar"], path) if __name__ == "__main__": tarfile("/root/tryit/output.tar") ``` Whe...
You should specify the command as a list. Beside that, main option (`x`) is missing. ``` def tarfile(path): call(["tar", "xvf", path]) ``` BTW, Python has a [`tarfile` module](https://docs.python.org/2/library/tarfile.html): ``` import tarfile with tarfile.open("/root/tryit/output.tar") as tar: tar.extractal...
What is regex for currency symbol?
25,978,771
23
2014-09-22T16:25:09Z
25,978,807
36
2014-09-22T16:27:52Z
[ "python", "regex" ]
In java I can use the regex : [`\p{Sc}`](http://www.regular-expressions.info/unicode.html) for detecting currency symbol in text. What is the equivalent in Python?
You can use the unicode category if you use [`regex`](https://pypi.python.org/pypi/regex) package: ``` >>> import regex >>> regex.findall(r'\p{Sc}', '$99.99 / €77') # Python 3.x ['$', '€'] ``` --- ``` >>> regex.findall(ur'\p{Sc}', u'$99.99 / €77') # Python 2.x (NoteL unicode literal) [u'$', u'\xa2'] >>> prin...
What is regex for currency symbol?
25,978,771
23
2014-09-22T16:25:09Z
25,978,940
22
2014-09-22T16:34:19Z
[ "python", "regex" ]
In java I can use the regex : [`\p{Sc}`](http://www.regular-expressions.info/unicode.html) for detecting currency symbol in text. What is the equivalent in Python?
If you want to stick with [re](https://docs.python.org/2/library/re.html?highlight=re#module-re), supply the [characters from Sc manually](http://www.fileformat.info/info/unicode/category/Sc/list.htm): ``` u"[$¢£¤¥֏؋৲৳৻૱௹฿៛\u20a0-\u20bd\ua838\ufdfc\ufe69\uff04\uffe0\uffe1\uffe5\uffe6]" ``` will do...
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
25,981,703
53
2014-09-22T19:25:20Z
26,062,583
22
2014-09-26T14:59:52Z
[ "python", "windows", "ssl", "pip" ]
I am very new to Python and trying to `> pip install linkchecker` on Windows 7. Some notes: * pip install is failing no matter the package. For example, `> pip install scrapy` also results in the SSL error. * Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Pyt...
You can specify a cert with this param: ``` pip --cert /etc/ssl/certs/FOO_Root_CA.pem install linkchecker ``` See: [Docs » Reference Guide » pip](https://pip.readthedocs.io/en/latest/reference/pip/#cmdoption--cert) If specifying your company's root cert doesn't work maybe the cURL one will work: <http://curl.haxx....
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
25,981,703
53
2014-09-22T19:25:20Z
28,724,886
8
2015-02-25T16:53:57Z
[ "python", "windows", "ssl", "pip" ]
I am very new to Python and trying to `> pip install linkchecker` on Windows 7. Some notes: * pip install is failing no matter the package. For example, `> pip install scrapy` also results in the SSL error. * Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Pyt...
The most straightforward way I've found, is to download and use the "DigiCert High Assurance EV Root CA" from DigiCert at <https://www.digicert.com/digicert-root-certificates.htm#roots> You can visit <https://pypi.python.org/> to verify the cert issuer by clicking on the lock icon in the address bar, or increase your ...
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
25,981,703
53
2014-09-22T19:25:20Z
29,751,768
69
2015-04-20T15:13:41Z
[ "python", "windows", "ssl", "pip" ]
I am very new to Python and trying to `> pip install linkchecker` on Windows 7. Some notes: * pip install is failing no matter the package. For example, `> pip install scrapy` also results in the SSL error. * Vanilla install of Python 3.4.1 included pip 1.5.6. The first thing I tried to do was install linkchecker. Pyt...
# Update: You can ignore the `https` by using `index-url` and passing the `http` url as a parameter then set it as the trusted source. `pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org pythonPackage` ## Previous Answer: Most of the answers could pose a security issue. Two of the...
Iterate python Enum in definition order
25,982,212
13
2014-09-22T19:58:39Z
25,982,264
18
2014-09-22T20:01:53Z
[ "python", "python-2.7", "enums" ]
I'm using the backported Enum functionality from python 3.4 with python 2.7: ``` > python --version Python 2.7.6 > pip install enum34 # Installs version 1.0... ``` According to the documentation for Enums in python 3 (<https://docs.python.org/3/library/enum.html#creating-an-enum>), "Enumerations support iteration, **...
I found the answer here: <https://pypi.python.org/pypi/enum34#creating-an-enum>. For python <3.0, you need to specify an \_\_order\_\_ attribute: ``` >>> from enum import Enum >>> class Shake(Enum): ... __order__ = 'vanilla chocolate cookies mint' ... vanilla = 7 ... chocolate = 4 ... cookies = 9 ... ...
Why does this take so long to match? Is it a bug?
25,982,466
50
2014-09-22T20:14:52Z
25,982,568
53
2014-09-22T20:22:34Z
[ "python", "regex", "performance", "state-machines" ]
I need to match certain URLs in web application, i.e. `/123,456,789`, and wrote this regex to match the pattern: ``` r'(\d+(,)?)+/$' ``` I noticed that it does not seem to evaluate, even after several minutes when testing the pattern: ``` re.findall(r'(\d+(,)?)+/$', '12345121,223456,123123,3234,4523,523523') ``` Th...
There is some [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html) going on that will cause an exponential amount of processing depending on how long the non-match string is. This has to do with your nested repetitions and optional comma (even though some regex engines can determine that t...
Why does this take so long to match? Is it a bug?
25,982,466
50
2014-09-22T20:14:52Z
25,983,249
31
2014-09-22T21:17:40Z
[ "python", "regex", "performance", "state-machines" ]
I need to match certain URLs in web application, i.e. `/123,456,789`, and wrote this regex to match the pattern: ``` r'(\d+(,)?)+/$' ``` I noticed that it does not seem to evaluate, even after several minutes when testing the pattern: ``` re.findall(r'(\d+(,)?)+/$', '12345121,223456,123123,3234,4523,523523') ``` Th...
First off, I must say that **it is not a BUG**. its because of that , it tries all the possibilities, it takes time and computing resources. Sometimes it can gobble up a lot of time. When it gets really bad, it’s called **catastrophic backtracking**. This is the code of `findall` function in [**python source**](http...
Why does this take so long to match? Is it a bug?
25,982,466
50
2014-09-22T20:14:52Z
25,986,964
30
2014-09-23T04:33:50Z
[ "python", "regex", "performance", "state-machines" ]
I need to match certain URLs in web application, i.e. `/123,456,789`, and wrote this regex to match the pattern: ``` r'(\d+(,)?)+/$' ``` I noticed that it does not seem to evaluate, even after several minutes when testing the pattern: ``` re.findall(r'(\d+(,)?)+/$', '12345121,223456,123123,3234,4523,523523') ``` Th...
To avoid the catastrophic backtracking I suggest ``` r'\d+(,\d+)*/$' ```
Scientific notation colorbar in matplotlib
25,983,218
12
2014-09-22T21:14:58Z
25,983,372
19
2014-09-22T21:27:25Z
[ "python", "matplotlib", "scientific-notation", "colorbar" ]
I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1x10^0, 2x10^0, ..., 1x10^2, and so on) in the ticks of the color bar? Example, let's create and plot and image with its colo...
You could use [`colorbar`'s `format` parameter](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.colorbar): ``` import matplotlib.pyplot as plt import numpy as np import matplotlib.ticker as ticker img = np.random.randn(300,300) myplot = plt.imshow(img) def fmt(x, pos): a, b = '{:.2e}'.format(x...
Scientific notation colorbar in matplotlib
25,983,218
12
2014-09-22T21:14:58Z
25,983,384
11
2014-09-22T21:28:18Z
[ "python", "matplotlib", "scientific-notation", "colorbar" ]
I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1x10^0, 2x10^0, ..., 1x10^2, and so on) in the ticks of the color bar? Example, let's create and plot and image with its colo...
You can specify the format of the colorbar ticks as follows: ``` pl.colorbar(myplot, format='%.0e') ```
in and index function of list [Python]
25,984,798
10
2014-09-22T23:52:36Z
25,984,900
12
2014-09-23T00:05:23Z
[ "python", "python-2.7", "python-3.x", "data-structures" ]
I am trying to understand the internal working of the `in` command and `index()` of the list data structure. When I say: ``` if something not in some_list : print "do something" ``` Is it traversing the whole list internally, similar to a `for` loop or does it use, better approaches like `hashtables` etc. Also ...
Good question! Yes, both methods you mention will iterate the list, necessarily. **Python does not use hashtables for lists because there is no restriction that the list elements are hashable.** If you know about ["Big O" notation](http://en.wikipedia.org/wiki/Big_O_notation), the `list` data structure is designed for...
MFCC feature descriptors for audio classification using librosa
25,988,749
8
2014-09-23T06:54:40Z
25,989,406
11
2014-09-23T07:31:35Z
[ "python", "audio", "machine-learning" ]
I am trying to obtain single vector feature representations for audio files to use in a machine learning task (specifically, classification using a neural net). I have experience in computer vision and natural language processing, but I need some help getting up to speed with audio files. There are a variety of featur...
Check out [scikits.talkbox](http://scikits.appspot.com/talkbox). It has various functions that help you generate MFCC from audio files. Specifically you would wanna do something like this to generate MFCCs. ``` import numpy as np import scipy.io.wavfile from scikits.talkbox.features import mfcc sample_rate, X = scipy...
python all possible combinations of 0,1 of length k
25,991,292
7
2014-09-23T09:16:48Z
25,991,305
11
2014-09-23T09:17:34Z
[ "python", "combinations", "itertools" ]
I need all possible combinations of 0,1 of length k. Suppose k=2 I want `(0,0), (0,1), (1,0), (1,1)` I have tried different function in `itertools` but I did not find what I want. ``` >>> list(itertools.combinations_with_replacement([0,1], 2)) [(0, 0), (0, 1), (1, 1)] >>> list(itertools.product([0,1], [0,1])) #does ...
[`itertools.product()`](https://docs.python.org/2/library/itertools.html#itertools.product) takes a `repeat` keyword argument; set it to `k`: ``` product(range(2), repeat=k) ``` Demo: ``` >>> from itertools import product >>> for k in range(2, 5): ... print list(product(range(2), repeat=k)) ... [(0, 0), (0, 1),...
Python / Remove special character from string
25,991,612
6
2014-09-23T09:32:04Z
25,991,795
7
2014-09-23T09:40:55Z
[ "python" ]
I'm writing server side in python. I noticed that the client sent me one of the parameter like this: ``` "↵ tryit1.tar↵ " ``` I want to get rid of spaces (and for that I use the `replace` command), but I also want to get rid of the special character: "↵". How can ...
A regex would be good here: ``` re.sub('[^a-zA-Z0-9-_*.]', '', my_string) ```
Unable to log in to ASP.NET website with requests module of Python
25,996,921
5
2014-09-23T13:51:54Z
26,007,548
9
2014-09-24T02:27:37Z
[ "python", "asp.net", "django", "cookies", "python-requests" ]
I am trying to log in to an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) website using the `requests` module in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29). While logging in manually in the website I can see the following headers as well as cookies. **Request Headers:** ``` Accept:tex...
``` import requests from bs4 import BeautifulSoup URL="http://www11.davidsonsinc.com/Login/Login.aspx" headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"} username="username" password="password" s=requests.Session() s.headers.update(headers)...
How can I extract keywords from a Python format string?
25,996,937
2
2014-09-23T13:52:39Z
25,997,051
9
2014-09-23T13:58:39Z
[ "python", "string", "string-formatting" ]
I want to provide automatic string formatting in an API such that: ``` my_api("path/to/{self.category}/{self.name}", ...) ``` can be replaced with the values of attributes called out in the formatting string. --- How do I extract the keyword arguments from a Python format string: ``` "non-keyword {keyword1} {{esca...
String objects have a internal method, `str._formatter_parser()` that provides that information: ``` [fname for _, fname, _, _ in yourstring._formatter_parser() if fname] ``` The Python 3 equivalent is: ``` import _string [fname for _, fname, _, _ in _string.formatter_parser(yourstring) if fname] ``` or use the [`...
nltk download url authorization issue
25,998,742
4
2014-09-23T15:16:10Z
25,998,985
14
2014-09-23T15:26:44Z
[ "python", "python-2.7", "nltk" ]
I tried to update my nltk data with nltk.download() but I got HTTP Error 401: Authorization Required. When I traced the url in question, I found it in downloader.py > DEFAULT\_URL = '<http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml>' I then copied that URL and ran it in my browser to find out that it's aski...
NLTK have moved from their googlecode site. As noted [in this question](http://askubuntu.com/questions/527388/python-nltk-on-ubuntu-12-04-lts-nltk-downloadbrown-results-in-html-error-40), nltk's new data server is located at <http://nltk.github.com/nltk_data/>. Just update the URL to the new location, and it should ho...
What does colon equal (:=) in Python mean?
26,000,198
2
2014-09-23T16:31:10Z
26,000,366
7
2014-09-23T16:41:24Z
[ "python" ]
What does the `:=` operand mean, more specifically for Python? Can someone explain how to read this snippet of code? ``` node := root, cost = 0 frontier := priority queue containing node only explored := empty set ```
What you have found is **pseudocode** <http://en.wikipedia.org/wiki/Pseudocode> > **Pseudocode** is an informal high-level description of the operating > principle of a computer program or other algorithm. the `:=` operator is actually the assignment operator. In python this is simply the `=` operator. To translate...
Execute curl command within a Python script
26,000,336
11
2014-09-23T16:40:00Z
26,000,498
8
2014-09-23T16:49:26Z
[ "python", "python-2.7", "curl", "pycurl" ]
I am trying to execute a curl command within a python script. If I do it in the terminal, it looks like this: ``` curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001 ``` I've seen recomme...
If you are not tweaking the curl command too much you can also go and call the curl command directly ``` cmd = '''curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001''' args = cmd.split() p...
Execute curl command within a Python script
26,000,336
11
2014-09-23T16:40:00Z
26,000,778
9
2014-09-23T17:04:04Z
[ "python", "python-2.7", "curl", "pycurl" ]
I am trying to execute a curl command within a python script. If I do it in the terminal, it looks like this: ``` curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001 ``` I've seen recomme...
You could use urllib as @roippi said: ``` import urllib2 data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' url = 'http://localhost:8080/firewall/rules/0000000000000001' req = urllib2.Request(url, data, {'Content-Type': 'application/json'}) f = urllib2...
Execute curl command within a Python script
26,000,336
11
2014-09-23T16:40:00Z
31,764,155
36
2015-08-01T17:11:31Z
[ "python", "python-2.7", "curl", "pycurl" ]
I am trying to execute a curl command within a python script. If I do it in the terminal, it looks like this: ``` curl -X POST -d '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001 ``` I've seen recomme...
# Don't! I know, that's the "answer" nobody wants. But if something's worth doing, *it's worth doing right*, right? This seeming like a good idea probably stems from a fairly wide misconception that shell commands such as `curl` are anything other than programs themselves. So what you're asking is "how do I run this...
Manipulate URL fragment on redirect in Django
26,004,301
3
2014-09-23T20:35:46Z
26,004,488
8
2014-09-23T20:49:18Z
[ "python", "django", "redirect" ]
I have been using Django's auth module but recently had to switch off of it. The auth module handled session expirations by redirecting to the login page and setting the page you were logged out from as the `?next=/currentPage` parameter. So if my session expired on `#dashboard` I would be redirected to: ``` mydomain...
They're not removing it. Fragments are *never* sent to the backend: that's just how browsers work. Note that your original URL is not being interpreted as `next="/#dashboard"` at all, but `next="/"`, with a subsequent fragment of "dashboard". That is, the fragment is separate to the querystring, not part of it. What ...
What's a fast and pythonic/clean way of removing a sorted list from another sorted list in python?
26,005,454
5
2014-09-23T22:04:40Z
26,005,523
7
2014-09-23T22:12:32Z
[ "python", "list", "python-2.7", "sortedlist" ]
I am creating a fast method of generating a list of primes in the range(0, limit+1). In the function I end up removing all integers in the list named removable from the list named primes. I am looking for a fast and pythonic way of removing the integers, knowing that both lists are always sorted. I might be wrong, but...
This is quite fast and clean, it does `O(n)` set membership checks, and in amortized time it runs in `O(n)` (first line is `O(n)` amortized, second line is `O(n * 1)` amortized, because a membership check is `O(1)` amortized): ``` removable_set = set(removable) primes = [p for p in primes if p not in removable_set] ``...
Encrypted and secure docker containers
26,006,727
15
2014-09-24T00:35:10Z
26,108,342
12
2014-09-29T20:31:02Z
[ "python", "security", "encryption", "docker" ]
We all know situations when you cannot go open source and freely distribute software - and I am in one of these situations. I have an app that consists of a number of binaries (compiled from C sources) and python code that wraps it all into a system. This app used to work as a cloud solution so users had access to app...
The `root` user on the host machine (where the `docker` daemon runs) has full access to all the processes running on the host. That means the person who controls the host machine can always get access to the RAM of the application as well as the file system. That makes it impossible to hide a key for decrypting the fil...
convert xldate to python datetime
26,010,455
2
2014-09-24T06:55:41Z
26,010,799
9
2014-09-24T07:16:21Z
[ "python", "python-2.7" ]
I have a problem converting excel xldate to python datetime with the following code. Is this the right way to convert? ``` import xlrd from datetime import datetime book = xlrd.open_workbook("a.xls") sh = book.sheet_by_index(0) for rx in range(1,sh.nrows): a = sh.row(rx) print a year, month, day, hour, ...
`a[0]` is a [`xlrd.Cell`](http://www.lexicon.net/sjmachin/xlrd.html#xlrd.Cell-class), so you need to use `a[0].value` to access the cell content. Also, you can't unpack to `year, month, day, hour, minute` because there are more than five values in the tuple produced (what about `second`?) However, you can avoid that b...
efficient numpy.roll before numpy.sum() or mean()
26,019,315
7
2014-09-24T14:21:01Z
26,024,327
9
2014-09-24T18:52:36Z
[ "python", "numpy" ]
I have several (order of 1000) 3D-arrays of shape (1000, 800, 1024) I want to study. I need to calculate the mean along axis=0, but before I can do that, I have to roll the data along axis 2, until it is 'in the right place'. This sounds strange, so I'll try to explain. The 1D-sub-array of shape (1024,) is data from a...
I got bored and wrote your function in Cython. It runs about 10x faster than the code you posted, without allocating an intermediate array. ``` import numpy as np cimport numpy as np cimport cython from libc.math cimport sqrt @cython.boundscheck(False) @cython.wraparound(False) @cython.nonecheck(False) @cython.cdivis...
Include run-time dependencies in Python wheels
26,019,920
10
2014-09-24T14:47:01Z
26,143,487
7
2014-10-01T14:15:12Z
[ "python", "python-2.7", "python-wheel" ]
I'd like to distribute a whole virtualenv, or a bunch of Python wheels of exact versions with their runtime dependencies, for example: * pycurl + pycurl.so - libcurl.so * libz.so * libssl.so * libcrypto.so * libgssapi\_krb5.so + libkrb5.so - libresolv.so I suppose I cou...
AFAIK, there is no good standard way to portably install dependencies with your package. Continuum has [made conda for precisely this purpose](http://www.continuum.io/blog/conda). The numpy guys wrote their own distutils submodule in their package to install some complicated dependencies, and now [at least some of them...
Where to get sphinxcontrib.autohttp.flask?
26,026,084
3
2014-09-24T20:41:40Z
26,026,214
7
2014-09-24T20:49:47Z
[ "python", "flask" ]
I am looking to generate automatic documentation for the REST API of a Flask project. I can't locate the sphinx extension sphinxcontrib.autohttp.flask anywhere and it does not seem to come bundled with sphinx. When I run sphinx I get : ``` Extension error: Could not import extension sphinxcontrib.autohttp.flask (excep...
The `sphinxcontrib.autohttp.flask` module lives in the `sphinxcontrib.httpdomain` contrib extension which you can find here <https://bitbucket.org/birkenfeld/sphinx-contrib> or you can install it directly using pip like this: ``` pip install sphinxcontrib-httpdomain ```
Python code test in interview for junior dev
26,027,899
2
2014-09-24T22:58:49Z
26,027,914
9
2014-09-24T23:01:02Z
[ "python" ]
I went for a junior python developer interview this morning and had to come up with a more pythonic way of representing the following code. ``` dict = {} for i in range(a, b): if i % c == d: dict[i] = i/c ``` I didn't really know the answer what do you think he was looking for out of curiosity.
I guess most python devs would go with a dict comprehension. And we would avoid to name a variable `dict` because it shadows the built-in type. ``` dict_ = {i: i/c for i in range(a,b) if i % c == d} ``` They might also be impressed if you can find a way to rewrite it (hint: the result has some parallels with [divmod]...
ImportError: No module named datetime
26,031,160
22
2014-09-25T05:25:15Z
26,031,533
7
2014-09-25T05:53:16Z
[ "python", "ubuntu-12.04", "ubuntu-14.04" ]
When I upgrade my Ubuntu into 14.04 from 12.04, this time I get this error: ``` ImportError: No module named datetime ```
I tried to re-install it by these steps. ``` 1. remove the old version of venv 2. virtualenv venv 3. .venv/activate/bin 4. pip install -r requirements/ requirements.txt ``` And it works perfectly. Thanks guys :)
ImportError: No module named datetime
26,031,160
22
2014-09-25T05:25:15Z
26,499,478
41
2014-10-22T02:38:27Z
[ "python", "ubuntu-12.04", "ubuntu-14.04" ]
When I upgrade my Ubuntu into 14.04 from 12.04, this time I get this error: ``` ImportError: No module named datetime ```
This happened to me when I created a virtualenv and then upgraded from 12.04 to 14.04. I had to delete my virtualenv and recreate it, and after doing that, everything worked again.
ImportError: No module named datetime
26,031,160
22
2014-09-25T05:25:15Z
29,385,534
22
2015-04-01T07:52:11Z
[ "python", "ubuntu-12.04", "ubuntu-14.04" ]
When I upgrade my Ubuntu into 14.04 from 12.04, this time I get this error: ``` ImportError: No module named datetime ```
Just run this command. It worked like a charm! ``` $ cp /usr/bin/python2.7 $(which python2.7) ``` This just happened to me after the 14.10 update, and it seems to be because my virtual environments have old copies of `/usr/bin/python2.7` that — unlike the new binary — do not include `datetime` built-in, and so ge...
how to install setuptools in mac
26,032,836
7
2014-09-25T07:20:16Z
26,034,737
12
2014-09-25T09:13:37Z
[ "python", "django", "osx", "install", "pip" ]
I'm trying to install via `pip` some libraries but I'm having some problems. When I try to install some of them I require for my project I get this message: ``` $ sudo pip install dj-database-url==0.2.0 Downloading/unpacking dj-database-url==0.2.0 Downloading dj-database-url-0.2.0.tar.gz Cleaning up... setuptools m...
1) Download ez\_setup.py module from <https://pypi.python.org/pypi/setuptools> 2) Open a Terminal 3) cd to the directory where you put the 'ez\_setup.py' 4) type 'python ez\_setup.py' and run it. 5) You should have it then.
List of objects to JSON with Python
26,033,239
2
2014-09-25T07:46:20Z
26,033,300
13
2014-09-25T07:50:32Z
[ "python", "json", "object", "serialization" ]
I have a problem converting `Object` instances to JSON: ``` ob = Object() list_name = scaping_myObj(base_url, u, number_page) for ob in list_name: json_string = json.dumps(ob.__dict__) print json_string ``` In `list_name` I have a list of `Object` instances. `json_string` return, for example: ``` {"city": "...
You can use a list comprehension to produce a list of dictionaries, then convert that: ``` json_string = json.dumps([ob.__dict__ for ob in list_name]) ``` or use a `default` function; `json.dumps()` will call it for anything it cannot serialise: ``` def obj_dict(obj): return obj.__dict__ json_string = json.dump...