instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Machine learning for monitoring servers
I'm looking at pybrain for taking server monitor alarms and determining the root cause of a problem. I'm happy with training it using supervised learning and curating the training data sets. The data is structured something like this: * Server Type **A** #1 * Alarm type 1 * Alarm type 2 * Server Type **A** #2 * Alarm type 1 * Alarm type 2 * Server Type **B** #1 * Alarm type **99** * Alarm type 2 So there are n servers, with x alarms that can be UP or DOWN. Both n and x are variable. If Server A1 has alarm 1 & 2 as DOWN, then we can say that service a is down on that server and is the cause of the problem. If alarm 1 is down on all servers, then we can say that service a is the cause. There can potentially be multiple options for the cause, so straight classification doesn't seem appropriate. I would also like to tie later sources of data to the net. Such as just scripts that ping some external service. All the appropriate alarms may not be triggered at once, due to serial service checks, so it can start with one server down and then another server down 5 minutes later. I'm trying to do some basic stuff at first: from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer INPUTS = 2 OUTPUTS = 1 # Build network # 2 inputs, 3 hidden, 1 output neurons net = buildNetwork(INPUTS, 3, OUTPUTS) # Build dataset # Dataset with 2 inputs and 1 output ds = SupervisedDataSet(INPUTS, OUTPUTS) # Add one sample, iterable of inputs and iterable of outputs ds.addSample((0, 0), (0,)) # Train the network with the dataset trainer = BackpropTrainer(net, ds) # Train 1000 epochs for x in xrange(10): trainer.train() # Train infinite epochs until the error rate is low trainer.trainUntilConvergence() # Run an input over the network result = net.activate([2, 1]) But I[m having a hard time mapping variable numbers of alarms to static numbers of inputs. For example, if we add an alarm to a server, or add a server, the whole net needs to be rebuilt. If that is something that needs to be done, I can do it, but want to know if there's a better way. Another option I'm trying to think of, is have a different net for each type of server, but I don't see how I can draw an environment-wide conclusion, since it will just make evaluations on a single host, instead of all hosts at once. Which type of algorithm should I use and how do I map the dataset to draw environment-wide conclusions as a whole with variable inputs? I'm very open to any algorithm that will work. Go is even better than python.
This is a challenging problem actually. Representation of labels It's difficult to represent your target labels for learning. As you pointed out, If Server A1 has alarm 1 & 2 as DOWN, then we can say that service a is down on that server and is the cause of the problem. If alarm 1 is down on all servers, then we can say that service a is the cause. There can potentially be multiple options for the cause ... I guess you need to list all possible options otherwise we cannot expect an ML algorithm to generalize. To make it simple, let's say you have only two possible causes of the problem: 1. Service problem 2. Server problem Site-wise binary classifier Suppose in your first ML model, the above are the only two causes. Then you are working on a site-wise binary classifier now. Probably logistic regression is better to get you started since it is easily interpretable. To find out which server is the problem or which service is the problem, this can be your second step. To solve the second step, based on your example, if it is a service problem, I think some decision rules can be manually derived so that the service name can be pinpointed. The idea is that you should see a significant amount of servers that are triggering the same alarm, right? Also see the advanced readings at the end to check more options. if it is a server problem, you can construct a second binary classifier (an individual server side classifier), which runs on each server using only features coming from that server and answers the question: "if i have problem". Features for the site-wise binary classifier I assume all those alarms are the best source of your features. I guess using some summary statistics data as features could help more for the site-wise classifier here. For example, the percentage of servers that are receiving alarm A as DOWN the average length of time across all servers whose alarm B is DOWN across all servers whose alarm B is DOWN, what is the percentage of them that also have alarm A down. ... Features for the server-side binary classifier You should explicitly use all alarm signals as the features for the server-side classifier. However, at training time, you should take all data from all of the servers. The labels are just "has-problem" or "has-no-problem". The training data will look like: alarm A On, alarm B On, alarm C on, ..., alarm Z on, has-problem YES, YES, NO, YES, YES NO, YES, NO, NO, NO ?, NO, YES, NO, NO Note I used "?" to indicate some possible alarms you might have missing data (unknown state), which can be used to describe the situation below: All the appropriate alarms may not be triggered at once, due to serial service checks, so it can start with one server down and then another server down 5 minutes later. Some advanced readings This problem is related to a few topics, e.g., alarm correlation, event correlation, fault diagnosis.
Ambiguity in Pandas Dataframe / Numpy Array "axis" definition
I've been very confused about how python axes are defined, and whether they refer to a DataFrame's rows or columns. Consider the code below: >>> df = pd.DataFrame([[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], columns=["col1", "col2", "col3", "col4"]) >>> df col1 col2 col3 col4 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 So if we call df.mean(axis=1), we'll get a mean across the rows: >>> df.mean(axis=1) 0 1 1 2 2 3 However, if we call df.drop(name, axis=1), we actually drop a column, not a row: >>> df.drop("col4", axis=1) col1 col2 col3 0 1 1 1 1 2 2 2 2 3 3 3 Can someone help me understand what is meant by an "axis" in pandas/numpy/scipy? A side note, DataFrame.mean just might be defined wrong. It says in the documentation for DataFrame.mean that axis=1 is supposed to mean a mean over the columns, not the rows...
It's perhaps simplest to remember it as 0=down and 1=across. This means: Use axis=0 to apply a method down each column, or to the row labels (the index). Use axis=1 to apply a method across each row, or to the column labels. Here's a picture to show the parts of a DataFrame that each axis refers to: It's also useful to remember that Pandas follows NumPy's use of the word axis. The usage is explained in NumPy's glossary of terms: Axes are defined for arrays with more than one dimension. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0), and the second running horizontally across columns (axis 1). [my emphasis] So, concerning the method in the question, df.mean(axis=1), seems to be correctly defined. It takes the mean of entries horizontally across columns, that is, along each individual row. On the other hand, df.mean(axis=0) would be an operation acting vertically downwards across rows. Similarly, df.drop(name, axis=1) refers to an action on column labels, because they intuitively go across the horizontal axis. Specifying axis=0 would make the method act on rows instead.
Django test runner fails in virtualenv on Ubuntu
I've been struggling with a problem with the Django test runner installed in a Python virtualenv on Ubuntu 14.04. The same software runs fine on MacOS, and I think it was fine on an earlier version of Ubuntu. The failure message is: ImportError: '<test>' module incorrectly imported from '<base-env>/local/lib/python2.7/site-packages/<package-dir>'. Expected '<base-env>/lib/python2.7/site-packages/<package-dir>'. Is this module globally installed? And the full stack trace from the error is: Traceback (most recent call last): File "/home/annalist/anenv/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line utility.execute() File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 50, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 71, in execute super(Command, self).execute(*args, **options) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/base.py", line 338, in execute output = self.handle(*args, **options) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 88, in handle failures = test_runner.run_tests(test_labels) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/test/runner.py", line 147, in run_tests suite = self.build_suite(test_labels, extra_tests) File "/home/annalist/anenv/local/lib/python2.7/site-packages/django/test/runner.py", line 96, in build_suite tests = self.test_loader.discover(start_dir=label, **kwargs) File "/usr/lib/python2.7/unittest/loader.py", line 206, in discover tests = list(self._find_tests(start_dir, pattern)) File "/usr/lib/python2.7/unittest/loader.py", line 287, in _find_tests for test in self._find_tests(full_path, pattern): File "/usr/lib/python2.7/unittest/loader.py", line 287, in _find_tests for test in self._find_tests(full_path, pattern): File "/usr/lib/python2.7/unittest/loader.py", line 267, in _find_tests raise ImportError(msg % (mod_name, module_dir, expected_dir)) ImportError: 'test_entity' module incorrectly imported from '/home/annalist/anenv/local/lib/python2.7/site-packages/annalist_root/annalist/tests'. Expected '/home/annalist/anenv/lib/python2.7/site-packages/annalist_root/annalist/tests'. Is this module globally installed? The test cases run fine in the development environment, and they also run fine when installed from a source distribution kit into a new virtualenv environment on the MAcOS development host. But when I install the same package into a new virtualenv on an Ubuntu 14.04 host, the test runner fails with the above message. The problems came up in a management utility I created that invokes some functions of django-admin (as well as some other stuff). Web searches revealed reports of bugs with virtualenv and posix compatibility, which have been addressed relatively recently (2013/14) in Ubuntu distributions by creating a local directory in the virtual environment which in turn contains symlinks to directories that are also accessible from the top-level virtual environment directory. The paths shown in the error message correspond to these aliased directory paths. (I'm posting this as a question so I can post the outcome and answer from my investigations, in the hope that it might be useful to others. Hence, I'm not trying to give a detailed description of my particular software setup.)
I had exactly the same problem and couldn't figure out what was going on. Finally it was a stupid thing: I had a layout similar to this one: my_app/ __init__.py tests.py tests/ __init__.py test_foo.py The problem was generated by having both a "tests.py" module and a "tests" package in the same folder. Just deleting the "tests.py" file solved the problem for me. Hope it helps.
Cython Numpy warning about NPY_NO_DEPRECATED_API when using MemoryView
I am converting a Cython memoryview to a numpy array (to be able to use it in pure Python code): from libc.stdlib cimport realloc cimport numpy as np DTYPE = np.float64 ctypedef np.float64_t DTYPE_t cpdef np.ndarray[DTYPE_t] compute(DTYPE_t[:,::1] data): cdef unsigned int Nchannels = data.shape[0] cdef unsigned int Ndata = data.shape[1] cdef DTYPE_t* output = NULL cdef DTYPE_t[::1] mv output = <DTYPE_t*>realloc(output, Ndata*sizeof(output)) if not output: raise MemoryError() mv = <DTYPE_t[:Ndata]>output mv[10:Ndata-10] = 0.0 # various calculations... return np.asarray(mv, dtype=DTYPE, order='C') It compiles, but the compiler gives the following warning: /Users/vlad/anaconda/lib/python2.7/site-packages/numpy/core/include /nump/npy_1_7_deprecated_api.h:15:2: warning: "Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-W#warnings] I added the suggested directive in setup.py: from distutils.core import setup, Extension from Cython.Build import cythonize import numpy filename = 'agents3.pyx' agents_module = Extension( 'Agents', sources = [filename], define_macros = [('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION')], include_dirs = [numpy.get_include()], ) setup (name = 'Agents', ext_modules = cythonize(agents_module) ) Now it wouldn't compile, it says: Vlads-MacBook-Pro:program vlad$ python setup.py build_ext --inplace Compiling agents3.pyx because it changed. Cythonizing agents3.pyx running build_ext building 'Agents' extension gcc -fno-strict-aliasing -I/Users/vlad/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION -I/Users/vlad/anaconda/lib/python2.7/site-packages/numpy/core/include -I/Users/vlad/anaconda/include/python2.7 -c agents3.c -o build/temp.macosx-10.5-x86_64-2.7/agents3.o agents3.c:2273:52: error: use of undeclared identifier 'NPY_C_CONTIGUOUS' __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); ^ agents3.c:2311:52: error: use of undeclared identifier 'NPY_F_CONTIGUOUS' __pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); ^ agents3.c:2474:42: error: no member named 'descr' in 'struct tagPyArrayObject' __pyx_t_4 = ((PyObject *)__pyx_v_self->descr); ~~~~~~~~~~~~ ^ agents3.c:4026:27: error: no member named 'base' in 'struct tagPyArrayObject' Py_XDECREF(__pyx_v_arr->base); ~~~~~~~~~~~ ^ /Users/vlad/anaconda/include/python2.7/object.h:823:34: note: expanded from macro 'Py_XDECREF' #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0) ^ agents3.c:4026:27: error: no member named 'base' in 'struct tagPyArrayObject' Py_XDECREF(__pyx_v_arr->base); ~~~~~~~~~~~ ^ /Users/vlad/anaconda/include/python2.7/object.h:823:64: note: expanded from macro 'Py_XDECREF' #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0) ^ /Users/vlad/anaconda/include/python2.7/object.h:772:24: note: expanded from macro 'Py_DECREF' --((PyObject*)(op))->ob_refcnt != 0) \ ^ agents3.c:4026:27: error: no member named 'base' in 'struct tagPyArrayObject' Py_XDECREF(__pyx_v_arr->base); ~~~~~~~~~~~ ^ /Users/vlad/anaconda/include/python2.7/object.h:823:64: note: expanded from macro 'Py_XDECREF' #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0) ^ /Users/vlad/anaconda/include/python2.7/object.h:775:34: note: expanded from macro 'Py_DECREF' _Py_Dealloc((PyObject *)(op)); \ ^ /Users/vlad/anaconda/include/python2.7/object.h:762:15: note: expanded from macro '_Py_Dealloc' (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) ^ /Users/vlad/anaconda/include/python2.7/object.h:115:47: note: expanded from macro 'Py_TYPE' #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) ^ agents3.c:4026:27: error: no member named 'base' in 'struct tagPyArrayObject' Py_XDECREF(__pyx_v_arr->base); ~~~~~~~~~~~ ^ /Users/vlad/anaconda/include/python2.7/object.h:823:64: note: expanded from macro 'Py_XDECREF' #define Py_XDECREF(op) do { if ((op) == NULL) ; else Py_DECREF(op); } while (0) ^ /Users/vlad/anaconda/include/python2.7/object.h:775:34: note: expanded from macro 'Py_DECREF' _Py_Dealloc((PyObject *)(op)); \ ^ /Users/vlad/anaconda/include/python2.7/object.h:762:45: note: expanded from macro '_Py_Dealloc' (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op))) ^ agents3.c:4035:16: error: no member named 'base' in 'struct tagPyArrayObject' __pyx_v_arr->base = __pyx_v_baseptr; ~~~~~~~~~~~ ^ agents3.c:4070:30: error: no member named 'base' in 'struct tagPyArrayObject' __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); ~~~~~~~~~~~ ^ agents3.c:4093:44: error: no member named 'base' in 'struct tagPyArrayObject' __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); ~~~~~~~~~~~ ^ agents3.c:1065:37: note: expanded from macro '__Pyx_INCREF' #define __Pyx_INCREF(r) Py_INCREF(r) ^ /Users/vlad/anaconda/include/python2.7/object.h:767:18: note: expanded from macro 'Py_INCREF' ((PyObject*)(op))->ob_refcnt++) ^ agents3.c:4094:41: error: no member named 'base' in 'struct tagPyArrayObject' __pyx_r = ((PyObject *)__pyx_v_arr->base); ~~~~~~~~~~~ ^ 11 errors generated. error: command 'gcc' failed with exit status 1 Vlads-MacBook-Pro:program vlad$ What should I do? Is it OK to leave the deprecated API call as it is? It tries to acces the base field -- but I am not doing it, it's Cython's fault. I simply converted a memoryview to a numpy array. Is there another, cleaner/safer way of doing it?
Just for a further reference, cython online docs says this is because Cython is using a deprecated Numpy API, and for the time being, it's just a warning that we can ignore.
How to hide in IPython notebook
I am plotting a NumPy array of values, I, using IPython notebook in %matplotlib inline mode with the plot command plt.plot(I,'o'). The resulting output is: <matplotlib.figure.Figure at 0x119e6ead0> Out[159]: [<matplotlib.lines.Line2D at 0x11ac57090>, <matplotlib.lines.Line2D at 0x11ac57310>, <matplotlib.lines.Line2D at 0x11ac57510>, <matplotlib.lines.Line2D at 0x11ac57690>, <matplotlib.lines.Line2D at 0x11ac57810>, <matplotlib.lines.Line2D at 0x11ac57990>, <matplotlib.lines.Line2D at 0x11ac57b10>, .... .... ] Then my plot shows up below these lines of output. Is there a way to just show the plot and hide the <matplotlib.lines.Line2D at ...> from the output?
Using a semi-colon ; to end the line suppresses the unwanted output when generating plots: plt.plot(I,'o'); In general, using a semi-colon stops IPython from outputting a value (e.g. the line In [1]: 1+1; would not have a corresponding output 2). An alternative way would be to bind a variable to the plot: _ = plt.plot(a) This way, IPython only shows you the plots and the name _ is bound to the unwanted output.
Row and column headers in matplotlib's subplots
What's the best practise to add a row and a column header to a grid of subplots generated in a loop in matplotlib? I can think of a couple, but not particularly neat: For columns, with a counter to your loop you can use set_title() for the first row only. For rows this doesn't work. You would have to draw text outside of the plots. You add an extra row of subplots on top and an extra column of subplots on the left, and draw text in the middle of that subplot. Can you suggest a better alternative?
There are several ways to do this. The easy way is to exploit the y-labels and titles of the plot and then use fig.tight_layout() to make room for the labels. Alternatively, you can place additional text in the right location with annotate and then make room for it semi-manually. If you don't have y-labels on your axes, it's easy to exploit the title and y-label of the first row and column of axes. import matplotlib.pyplot as plt cols = ['Column {}'.format(col) for col in range(1, 4)] rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']] fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8)) for ax, col in zip(axes[0], cols): ax.set_title(col) for ax, row in zip(axes[:,0], rows): ax.set_ylabel(row, rotation=0, size='large') fig.tight_layout() plt.show() If you do have y-labels, or if you prefer a bit more flexibility, you can use annotate to place the labels. This is more complicated, but allows you to have individual plot titles, ylabels, etc in addition to the row and column labels. import matplotlib.pyplot as plt from matplotlib.transforms import offset_copy cols = ['Column {}'.format(col) for col in range(1, 4)] rows = ['Row {}'.format(row) for row in ['A', 'B', 'C', 'D']] fig, axes = plt.subplots(nrows=4, ncols=3, figsize=(12, 8)) plt.setp(axes.flat, xlabel='X-label', ylabel='Y-label') pad = 5 # in points for ax, col in zip(axes[0], cols): ax.annotate(col, xy=(0.5, 1), xytext=(0, pad), xycoords='axes fraction', textcoords='offset points', size='large', ha='center', va='baseline') for ax, row in zip(axes[:,0], rows): ax.annotate(col, xy=(0, 0.5), xytext=(-ax.yaxis.labelpad - pad, 0), xycoords=ax.yaxis.label, textcoords='offset points', size='large', ha='right', va='center') fig.tight_layout() # tight_layout doesn't take these labels into account. We'll need # to make some room. These numbers are are manually tweaked. # You could automatically calculate them, but it's a pain. fig.subplots_adjust(left=0.15, top=0.95) plt.show()
List insert at index that is well out of range - behaves like append
I had a list a = [1, 2, 3] when I did a.insert(100, 100) [1, 2, 3, 100] as list was originally of size 4 and I was trying to insert value at index 100 , it behaved like append instead of throwing any errors as I was trying to insert in an index that did not even existed . Should it not throw IndexError: list assignment index out of range exception as it throws when I attempt doing a[100] = 100 Question : 1. Any idea Why has it been designed to silently handle this instead of informing the user with an exception ? Personal Opinion : Lets see how other languages behave in such a situation : Ruby : > a = [1, 2] > a[100] = 100 > a => [1, 2, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, 100] The way ruby handles this is pretty clear and sounds meaningful at least to me . Java : In java the method .add(index, value) if applied with index that is out of range(on arraylist , linkedlist for example) will throw java.lang.IndexOutOfBoundsException . So what I felt was either it should throw exception(as java does) or insert null in the range in between (as ruby handles it ). But the silent way of handling in python is just flummoxing . UPDATE (16 Sep 2014 IST 8:30 AM) : As suggested by one of the answerers I posted this question in python-dev and I got a response . It can be seen in this python dev mailing list thread . If you find that the thread link has changed, you can find the answer by doing a google search for the title of question appended at the beginning with python dev.
From the docs: list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x). So technically when you're doing a.insert(100, 100) it ensures that 100 will be inserted at a index before 100 which happens to be, in this case, index 3. Further, we can have a look at the implementation: static int ins1(PyListObject *self, Py_ssize_t where, PyObject *v) { Py_ssize_t i, n = Py_SIZE(self); PyObject **items; if (v == NULL) { PyErr_BadInternalCall(); return -1; } if (n == PY_SSIZE_T_MAX) { PyErr_SetString(PyExc_OverflowError, "cannot add more objects to list"); return -1; } if (list_resize(self, n+1) == -1) return -1; if (where < 0) { where += n; if (where < 0) where = 0; } if (where > n) // <-- Here the implementation handles indexes > list-len where = n; items = self->ob_item; for (i = n; --i >= where; ) items[i+1] = items[i]; Py_INCREF(v); items[where] = v; return 0; }
ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?
I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears. So, python 2 pickle can not load the file dumped by python 3 pickle? If I want it? How to do?
You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2. Check the protocolparameter in pickle.dump. Your resulting code will look like this. pickle.dump(your_object, your_file, protocol=2) There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.
How to compare two JSON objects with the same elements in a different order equal?
How can I test whether two JSON objects are equal in python, disregarding the order of lists? For example ... JSON document a: { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": "name"} ], "success": false } JSON document b: { "success": false, "errors": [ {"error": "required", "field": "name"}, {"error": "invalid", "field": "email"} ] } a and b should compare equal, even though the order of the "errors" lists are different.
If you want two objects with the same elements but in a different order to compare equal, then the obvious thing to do is compare sorted copies of them - for instance, for the dictionaries represented by your JSON strings a and b: import json a = json.loads(""" { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": "name"} ], "success": false } """) b = json.loads(""" { "success": false, "errors": [ {"error": "required", "field": "name"}, {"error": "invalid", "field": "email"} ] } """) >>> sorted(a.items()) == sorted(b.items()) False ... but that doesn't work, because in each case, the "errors" item of the top-level dict is a list with the same elements in a different order, and sorted() doesn't try to sort anything except the "top" level of an iterable. To fix that, we can define an ordered function which will recursively sort any lists it finds (and convert dictionaries to lists of (key, value) pairs so that they're orderable): def ordered(obj): if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj If we apply this function to a and b, the results compare equal: >>> ordered(a) == ordered(b) True
How do I set response headers in Flask?
This is my code: @app.route('/hello', methods=["POST"]) def hello(): resp = make_response() resp.headers['Access-Control-Allow-Origin'] = '*' return resp However, when I make a request from the browser to my server I get this error: XMLHttpRequest cannot load http://localhost:5000/hello. No 'Access-Control-Allow-Origin' header is present on the requested resource. I have also tried this approach, setting the response headers "after" the request: @app.after_request def add_header(response): response.headers['Access-Control-Allow-Origin'] = '*' return response No dice. I get the same error. Is there a way to just set the response headers in the route function? Something like this would be ideal: @app.route('/hello', methods=["POST"]) def hello(response): # is this a thing?? response.headers['Access-Control-Allow-Origin'] = '*' return response but I cant find anyway to do this. Please help. EDIT if I curl the url with a POST request like so: curl -iX POST http://localhost:5000/hello I get this response: HTTP/1.0 500 INTERNAL SERVER ERROR Content-Type: text/html Content-Length: 291 Server: Werkzeug/0.9.6 Python/2.7.6 Date: Tue, 16 Sep 2014 03:58:42 GMT <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>500 Internal Server Error</title> <h1>Internal Server Error</h1> <p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p> Any ideas?
You can do this pretty easily: @app.route("/") def home(): resp = flask.Response("Foo bar baz") resp.headers['Access-Control-Allow-Origin'] = '*' return resp Look at flask.Response and flask.make_response() But something tells me you have another problem, because the after_request should have handled it correctly too. EDIT I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are: curl -i http://127.0.0.1:5000/your/endpoint You should see > curl -i 'http://127.0.0.1:5000/' HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 11 Access-Control-Allow-Origin: * Server: Werkzeug/0.8.3 Python/2.7.5 Date: Tue, 16 Sep 2014 03:47:13 GMT Noting the Access-Control-Allow-Origin header. EDIT 2 As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem. For example: @app.route("/") def home(): resp = flask.Response("Foo bar baz") user.weapon = boomerang resp.headers['Access-Control-Allow-Origin'] = '*' return resp Gives a nicely formatted html error page, with this at the bottom (helpful for curl command) Traceback (most recent call last): ... File "/private/tmp/min.py", line 8, in home user.weapon = boomerang NameError: global name 'boomerang' is not defined
How to install Python MySQLdb module using pip?
How can I install the MySQLdb module for Python using pip?
It's easy to do, but hard to remember the correct spelling: pip install MySQL-python Note: Some dependencies might have to be in place when running the above command. Some hints on how to install these on various platforms: Ubuntu 14, Ubuntu 16, Debian 8.6 (jessie) sudo apt-get install python-pip python-dev libmysqlclient-dev Fedora 24: sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
Django 1.7 - How do I suppress "(1_6.W001) Some project unittests may not execute as expected."?
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 not execute as expected. HINT: Django 1.6 introduced a new default test runner. It looks like this project was generated using Django 1.5 or earlier. You should ensure your tests are all running & behaving as expected. See https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner for more information. The URL mentioned in the error message does detail the changes that have been made, but it does not give any hint as to why this warning is triggered or how to suppress it. Even though the warning message references Django 1.6, it only started appearing after upgrading to Django 1.7 I have checked that the same number of unit tests is being run under Django 1.7 as was being run under Django 1.6.1. For those interested, the application in question is an event management system called Kompassi that can be found on Github.
Found a blog post that reveals explicitly specifying TEST_RUNNER = 'django.test.runner.DiscoverRunner' in settings.py will stop this warning from occurring.
subsampling every nth entry in a numpy array
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 subsample this to start at a[1] and then sample every fourth point from there, to produce something like b = [2,2,2.....]
You can use numpy's slicing, 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 also reflect changes to the original array and keep the whole original array in memory: >>> a array([1, 2, 3, 4, 5]) >>> b = a[::2] # O(1), constant time >>> b[:] = 0 # modifying the view changes original array >>> a # original array is modified array([0, 2, 0, 4, 0]) so if either of the above things are a problem, you can make a copy explicitly: >>> a array([1, 2, 3, 4, 5]) >>> b = a[::2].copy() # explicit copy, O(n) >>> b[:] = 0 # modifying the copy >>> a # original is intact array([1, 2, 3, 4, 5]) This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.
Django - ImproperlyConfigured: Module "django.contrib.auth.middleware"
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 following error: ImproperlyConfigured: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class If anyone has any insight as to why I'm getting this error in the virtualenv, I'd appreciate it. I can get the server to run correctly in a non-virtualenv setup, though. Here is the full stack trace: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/wsgi.py", line 187, in __call__ self.load_middleware() File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/base.py", line 45, in load_middleware mw_class = import_by_path(middleware_path) File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/utils/module_loading.py", line 31, in import_by_path error_prefix, module_path, class_name)) ImproperlyConfigured: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class [16/Sep/2014 22:44:30] "GET / HTTP/1.1" 500 59 Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/wsgi.py", line 187, in __call__ self.load_middleware() File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/core/handlers/base.py", line 45, in load_middleware mw_class = import_by_path(middleware_path) File "/Users/jruecke/Python/JSON/lib/python2.7/site-packages/Django-1.6.5-py2.7.egg/django/utils/module_loading.py", line 31, in import_by_path error_prefix, module_path, class_name)) ImproperlyConfigured: Module "django.contrib.auth.middleware" does not define a "SessionAuthenticationMiddleware" attribute/class
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
AttributeError: 'Flask' object has no attribute 'user_options'
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 answer for this. If someone can shed some light on this, that would be really helpful.Thanks Code: from celery import Celery def make_celery(app): celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL']) celery.conf.update(app.config) TaskBase = celery.Task class ContextTask(TaskBase): abstract = True def __call__(self, *args, **kwargs): with app.app_context(): return TaskBase.__call__(self, *args, **kwargs) celery.Task = ContextTask return celery Example: from flask import Flask app = Flask(__name__) app.config.update( CELERY_BROKER_URL='redis://localhost:6379', CELERY_RESULT_BACKEND='redis://localhost:6379' ) celery = make_celery(app) @celery.task() def add_together(a, b): return a + b Traceback error: Traceback (most recent call last): File "/usr/local/bin/celery", line 11, in <module> sys.exit(main()) File "/usr/local/lib/python2.7/dist-packages/celery/__main__.py", line 30, in main main() File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/celery.py", line 769, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 305, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/usr/local/lib/python2.7/dist-packages/celery/bin/base.py", line 473, in setup_app_from_commandline user_preload = tuple(self.app.user_options['preload'] or ()) AttributeError: 'Flask' object has no attribute 'user_options' UPDATE: Fixed the issue. I was running the worker incorrectly.Thanks everyone for your help
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_application worker The your_application string has to point to your application’s package or module that creates the celery object. Assuming the code resides in application.py, explicitly pointing to the celery object (not just the module name) avoided the error: celery -A application.celery worker
DynamoDB : The provided key element does not match the schema
My question is about dynamodb There is a way to get item depending on a field that is not the hashkey ? Example My Table Users : id (HashKey) , name , email And I want to retrieve the user having email as 'test@mail.com' How this can be done ?? I try this with boto : user = users.get_item(email='john.doe@gmail.com') I get the following error : 'The provided key element does not match the schema'
To query on fields which are not the hash key you need to use a Global Secondary Index (GSI). Take a look at this AWS Post for more details on GSI's. UPDATE Feb 2015: It is now possible to add a GSI to an existing table. See the Amazon Docs for more details. Sadly you cannot add a GSI to an existing DynamoDB table so you'll need to create a new table and port your data if this is something you really need to query on. From the DynamoDB FAQ: Q: How do I create a global secondary index for a DynamoDB table? All GSIs associated with a table must be specified at table creation time. At this time, it is not possible to add a GSI after the table has been created. For detailed steps on creating a Table and its indexes, see here. You can create a maximum of 5 global secondary indexes per table. If you do not want to port your data you could consider creating a second DynamoDB table with the email as a hash key and the hash of the parent record to use as a lookup into your main data table but as you can imagine this isn't exactly an optimal solution and it comes with its own headaches of keeping it in synch with your master table.
Difference between `yield from foo()` and `for x in foo(): yield x`
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 do I have to know about the magic of yield from to avoid getting into a situation where the magic does something I don't expect? What advantages does the magic provide, that I should be aware of?
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. When you use the for loop, the yield x expression 'receives' the sent data; the foo() generator will never see this. But when you use yield from the sent data goes straight to whatever yield expression the delegated-to generator is currently paused at. In other words, yield from passes on the sent data so the delegated-to generator can receive it instead. You can also raise exceptions in a generator, with generator.throw(); with the for loop case, the exception is raised from the yield x line, while with yield from the exception is passed on again; the exception is raised inside foo() instead. Together, this means that yield from in essence replaces the current generator for the duration of the delegated iteration. The delegated-to generator also gets to communicate with the parent generator, when done the .value attribute of the StopIteration exception raised is returned as the value of the yield from expression. You can set the value of that exception by using return <expression> in the delegated-to foo() generator, or you can use raise StopIteration(<expression>) explicitly. yield from was introduced into the language with PEP 380: Syntax for Delegating to a Subgenerator.
Why does str(float) return more digits in Python 3 than Python 2?
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 insulates you from the slight differences between binary and decimal representation. Python 2 demo: http://ideone.com/OKJtxv print str(1.4*1.5) 2.1 print repr(1.4*1.5) 2.0999999999999996 In Python 3.2 it appears str and repr return the same thing. Python 3 demo: http://ideone.com/oAKRsb print(str(1.4*1.5)) 2.0999999999999996 print(repr(1.4*1.5)) 2.0999999999999996 Is there a PEP that describes the change, or some other statement from someone responsible?
No, there's no PEP. There's an issue in the bug tracker, and an associated discussion on the Python developers mailing list. While I was responsible for proposing and implementing the change, I can't claim it was my idea: it had arisen during conversations with Guido at EuroPython 2010. Some more details: as already mentioned in comments, Python 3.1 introduced a new algorithm for the string repr of a float, (later backported to the Python 2 series, so that it also appears in Python 2.7). As a result of this new algorithm, a "short" decimal number typed in at the prompt has a correspondingly short representation. This eliminated one of the existing reasons for the difference between str and repr, and made it possible to use the same algorithm for both str and repr. So for Python 3.2, following the discussion linked to above, str and repr were made identical. As to why: it makes the language a little bit smaller and cleaner, and it removes the rather arbitrary choice of 12 digits when outputting the string. (The choice of 17 digits used for the repr in Python versions prior to 2.7 is far from arbitrary, by the way: two distinct IEEE 754 binary64 floats will have distinct representations when converted to decimal with 17 significant digits, and 17 is the smallest integer with this property.) Apart from simplicity, there are some less obvious benefits. One aspect of the repr versus str distinction that's been confusing for users in the past is the fact that repr automatically gets used in containers. So for example in Python 2.7: >>> x = 1.4 * 1.5 >>> print x 2.1 >>> print [x] [2.0999999999999996] I'm sure there's at least one StackOverflow question asking about this phenomenon somewhere: here is one such, and another more recent one. With the simplification introduced in Python 3.2, we get this instead: >>> x = 1.4 * 1.5 >>> print(x) 2.0999999999999996 >>> print([x]) [2.0999999999999996] which is at least more consistent. If you do want to be able to hide imprecisions, the right way to do it remains the same: use string formatting for precise control of the output format. >>> print("{:.12g}".format(x)) 2.1 I hope that explains some of the reasoning behind the change. I'm not going to argue that it's universally beneficial: as you point out, the old str had the convenient side-effect of hiding imprecisions. But in my opinion (of course, I'm biased), it does help eliminate a few surprises from the language.
Python Django : No module named security
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/myproject/monarch/env/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__ return self.application(environ, start_response) File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 168, in __call__ self.load_middleware() File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 44, in load_middleware mw_class = import_string(middleware_path) File "/home/zat42/myproject/monarch/env/local/lib/python2.7/site-packages/django/utils/module_loading.py", line 26, in import_string module = import_module(module_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named security I don't know why there is this error my configuration works fine with a fresh install... But when I copy my current project, I got Error 500. I tried to deploy "part after part" but I can't find what's wrong. Tell me if you need more of my files because I don't really know where is the problem... Thank you.
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.
Ansible - Can I print information during module execution?
I would like to know if there is a way to print information while a module is executing -- primarily as a means to demonstrate that the process is working and has not hung. Specifically, I am trying to get feedback during the execution of the cloudformation module. I tried modifying the (Python) source code to include the following: def debug(msg): print json.dumps({ "DEBUG" : msg }) ... debug("The stack operation is still working...") What this did, of course, was store all this output and only print it all after the module had finished executing. So for particularly large cloudformation templates, this means that I wait around for 5 minutes or so, and then suddenly see a large amount of text appear on the screen at the end. What I was expecting was to see "The stack operation is still working..." printed every x seconds. It would seem that the Asynchronous Actions and Polling are what I'm looking for... but this didn't work, either. The entire task, "Launch CloudFormation for {{ stackname }}", was skipped entirely. See below for the relevant (YAML) snippet from my playbook: - name: Launch CloudFormation for {{ stackname }} cloudformation: > stack_name="{{ stackname }}" state=present region="{{ region }}" disable_rollback=true template="{{ template }}" register: cloud args: template_parameters: KeyName: "{{ keyName }}" Region: "{{ region }}" SecurityGroup: "{{ securityGroup }}" BootStrapper: "{{ bootStrapper }}" BootStrapCommand: "powershell.exe -executionpolicy unrestricted -File C:\\{{ bootStrapper }} {{ region }}" S3Bucket: "{{ s3Bucket }}" async: 3600 poll: 30 This tells me that async is meant for typical shell commands, and not complex modules such as cloudformation. OR -- I may have done something wrong. Could anyone shed some light on this situation? Again, for large cloudformation tasks that take a while, I would like some periodic indication that the task is still running, and not hanging. I appreciate the help!
The answer is simple - no. Ansible is a Continuous system that aims to handle ability to run over a bunch of servers and displaying real-time stdout results can be very unconvenient. But I think You can use some tricks if Your destination system can support execution in background. I see that Your system is windows, so You have to install cygwin onto it for ability to run background commands like "sleep 20 &" in the example below You can run this playbook with ansible-playbook -vv background.yml You can see that stdout changing. echo Test---- >> /tmp/test && tail /tmp/test is a demo command. You should output data to some file and tail it for ability to see the progress. Or You may look at file size of stdout file and display it. Use imagination ))) # @file background.yml - hosts: 127.0.0.1 connection: local gather_facts: no tasks: - name: Background operation shell: "sleep 20 & \ PPID=$! \ echo $PPID" register: bcktsk - name: Check PPID shell: "kill -0 {{ bcktsk.stdout | int + 2 }}" register: checkppid ignore_errors: true - name: Check if process still active shell: "echo Test---- >> /tmp/test && tail /tmp/test && kill -0 {{ bcktsk.stdout | int + 2 }}" register: test when: checkppid.rc == 0 until: test.rc ==1 delay: 2 retries: 10000 ignore_errors: true
Why do we have to use the __dunder__ methods instead of operators when calling via 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 is it that prevented super being implemented in a way that would allow the operator access? Subscriptable was just an example, I have the same question for __getattr__, __init__, etc. The docs attempt to explain why, but I don't understand it.
CPython's bug tracker's issue 805304, "super instances don't support item assignment", 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 caching of methods, whilst the proxied methods are found at runtime. He offers a patch that would give a subset of this functionality: + if (o->ob_type == &PySuper_Type) { + PyObject *result; + result = PyObject_CallMethod(o, "__setitem__", "(OO)", key, value); + if (result == NULL) + return -1; + Py_DECREF(result); + return 0; + } + so it is clearly possible. However, he concludes I've been thinking that this one could be left alone and just document that super objects only do their magic upon explicit attribute lookup. Otherwise, fixing it completely involves combing Python for every place that directly calls functions from the slots table, and then adding a followup call using attribute lookup if the slot is empty. When it comes to functions like repr(obj), I think we want the super object to identify itself rather than forwarding the call to the target object's __repr__() method. The argument seems to be that if __dunder__ methods are proxied, then either __repr__ is proxied or there is an inconsistency between them. super(), thus, might not want to proxy such methods lest it gets too near the programmer's equivalent of an uncanny valley.
How to iterate over pandas multiindex dataframe using index
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 835 9:16:00 123.776946 623 9:17:00 153.76646 624 9:18:00 463.276946 626 9:19:00 663.176934 622 9:20:00 763.77333 621 2012-11-04 9:15:00 115.449437 122 9:16:00 123.776946 555 9:17:00 153.76646 344 9:18:00 463.276946 212 I want to have do some complex process over daily data block. Psuedo code would look like for count in df(level 0 index) : new_df = get only chunk for count complex_process(new_df) So, first of all, I could not find a way to access only blocks for a date 2012-11-03 9:15:00 45.312814 835 9:16:00 123.776946 623 9:17:00 153.76646 624 9:18:00 463.276946 626 9:19:00 663.176934 622 9:20:00 763.77333 621 and then send it for processing. I am doing this in for loop as I am not sure if there is any way to do it without mentioning exact value of level 0 column. I did some basic search and able to get df.index.get_level_values(0), but it returns me all the values and that causes loop to run multiple times for a day. I want to create a dataframe per day and send it for processing.
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 Time 2012-11-02 9:15:00 79.373668 224 9:16:00 130.841316 477 observation1 observation2 date Time 2012-11-03 9:15:00 45.312814 835 9:16:00 123.776946 623 9:17:00 153.766460 624 9:18:00 463.276946 626 9:19:00 663.176934 622 9:20:00 763.773330 621 observation1 observation2 date Time 2012-11-04 9:15:00 115.449437 122 9:16:00 123.776946 555 9:17:00 153.766460 344 9:18:00 463.276946 212
How to send an email through gmail without enabling 'insecure access'?
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 me work out how to upgrade bits of code that look like this: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(GMAIL_USER, GMAIL_PASSWORD) server.sendmail(FROM, TO, MESSAGE) server.close() Sure, I'll go and turn on "Access for less secure apps", but if anyone has worked out what to replace this code with, I'll be grateful.
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 of writing, I couldn't find a published package for public consumption for Python 3. The python 2 experience was straight-forward (in comparison). Navigating the Google website is half the battle No doubt, over time, this will change. Ultimately you need to download a client_secret.json file. You can only (probably) do this setting up stuff via a web browser: You need a google account - either google apps or gmail. So, if you haven't got one, go get one. Get yourself to the developers console Create a new project, and wait 4 or 400 seconds for that to complete. Navigate to API's and Auth -> Credentials Under OAuth select Create New Client ID Choose Installed Application as the application type and Other You should now have a button Download JSON. Do that. It's your client_secret.json—the passwords so to speak But wait that's not all! You have to give your application a "Product Name" to avoid some odd errors. (see how much I suffered to give you this ;-) Navigate to API's & auth -> Consent Screen Choose your email Enter a PRODUCT NAME. It doesn't matter what it is. "Foobar" will do fine. Save Newsflash! Whoa. Now there's even more! Navigate to API's & auth -> APIs -> Gmail API Click the button Enable API Yay. Now we can update the emailing script. Python 2 You need to run the script interactively the first time. It will open a web browser on your machine and you'll grant permissions (hit a button). This exercise will save a file to your computer gmail.storage which contains a reusable token. [I had no luck transferring the token to a machine which has no graphical browser functionality—returns an HTTPError. I tried to get through it via the lynx graphical browser. That also failed because google have set the final "accept" button to "disabled"!? I'll raise another question to jump this hurdle (more grumbling)] First you need some libraries: pip install --upgrade google-api-python-client pip install --upgrade python-gflags you need to change the to and from addresses make sure you have the client_token.json file whereever the Storage instructions expect it the directory needs to be writable so it can save the gmail.storage file Finally some code: import base64 import httplib2 from email.mime.text import MIMEText from apiclient.discovery import build from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run # Path to the client_secret.json file downloaded from the Developer Console CLIENT_SECRET_FILE = 'client_secret.json' # Check https://developers.google.com/gmail/api/auth/scopes for all available scopes OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose' # Location of the credentials storage file STORAGE = Storage('gmail.storage') # Start the OAuth flow to retrieve credentials flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE) http = httplib2.Http() # Try to retrieve credentials from storage or run the flow to generate them credentials = STORAGE.get() if credentials is None or credentials.invalid: credentials = run(flow, STORAGE, http=http) # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery gmail_service = build('gmail', 'v1', http=http) # create a message to send message = MIMEText("Message goes here.") message['to'] = "yourvictim@goes.here" message['from'] = "you@go.here" message['subject'] = "your subject goes here" body = {'raw': base64.b64encode(message.as_string())} # send it try: message = (gmail_service.users().messages().send(userId="me", body=body).execute()) print('Message Id: %s' % message['id']) print(message) except Exception as error: print('An error occurred: %s' % error) Hopefully that gets us all started. Not as simple as the old way, but does look a lot less complicated now I can see it in the flesh.
How to break long string lines for PEP8 compliance?
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 code?
Using string literal concatenation: pic_url = ("http://graph.facebook.com/{0}/" "picture?width=100&height=100".format(me['id']))
Django 1.7 - "No migrations to apply" when run migrate after makemigrations
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 returns: Migrations for 'profiles': 0001_initial.py: - Create model RoadmapProfile When I run "migrate profiles": Operations to perform: Apply all migrations: profiles Running migrations: No migrations to apply. The issue is, when I try to open any page related to mezzanine.accounts (for example update account), it crashes with: OperationalError at /accounts/update/ no such column: profiles_roadmapprofile.fullname What I have done wrong?
In MySQL Database delete row 'profiles' from the table 'django_migrations'. Delete all migration files in migrations folder. Try again python manage.py makemigrations and python manage.py migrate command.
python pickle gives "AttributeError: 'str' object has no attribute 'write'"
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
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 is deprecated : If an application uses migrations, there is no automatic loading of fixtures. Since migrations will be required for applications in Django 2.0, this behavior is considered deprecated. If you want to load initial data for an app, consider doing it in a data migration. (https://docs.djangoproject.com/en/1.7/howto/initial-data/#automatically-loading-initial-data-fixtures) The official documentation does not have a clear example on how to do it, so my question is : What is the best way to import such initial data using data migrations : Write Python code with multiple calls to mymodel.create(...), Use or write a Django function (like calling loaddata) to load data from a JSON fixture file. I prefer the second option. I don't want to use South, as Django seems to be able to do it natively now.
Assuming you have a fixture file in <yourapp>/fixtures/initial_data.json 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_data Edit your migration file <yourapp>/migrations/0002_auto_xxx.py 2.1. Custom implementation, inspired by Django' loaddata (initial answer): import os from sys import path from django.core import serializers fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures')) fixture_filename = 'initial_data.json' def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) fixture = open(fixture_file, 'rb') objects = serializers.deserialize('json', fixture, ignorenonexistent=True) for obj in objects: obj.save() fixture.close() def unload_fixture(apps, schema_editor): "Brutally deleting all entries for this model..." MyModel = apps.get_model("yourapp", "ModelName") MyModel.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('yourapp', '0001_initial'), ] operations = [ migrations.RunPython(load_fixture, reverse_code=unload_fixture), ] 2.2. A simpler solution for load_fixture (per @juliocesar's suggestion): from django.core.management import call_command fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures')) fixture_filename = 'initial_data.json' def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) call_command('loaddata', fixture_file) Useful if you want to use a custom directory. 2.3. Simplest: calling loaddata with app_label will load fixtures from the <yourapp>'s fixtures dir automatically : from django.core.management import call_command fixture = 'initial_data' def load_fixture(apps, schema_editor): call_command('loaddata', fixture, app_label='yourapp') If you don't specify app_label, loaddata will try to load fixture filename from all apps fixtures directories (which you probably don't want). Run it python manage.py migrate <yourapp>
Is it a bug to omit an Accept */* header in an HTTP/1.0 Request for a REST API
I'm trying to determine whether it is a bug that Python's urllib.urlopen() function omits an HTTP Accept header when making simple REST API requests. The Facebook Graph API seems to notice whether the header is present or not: GET /zuck HTTP/1.0 Host: graph.facebook.com Accept: */* Without the accept header, the returned content-type of application/json; charset=UTF-8 becomes text/javascript; charset=UTF-8. That may be a bug in Facebook's REST API or it may be a legitimate response to a missing accept header. I notice the command-line tools like curl use Accept: */* by default: $ curl -v https://graph.facebook.com/zuck > GET /zuck HTTP/1.1 > User-Agent: curl/7.30.0 > Host: graph.facebook.com > Accept: */* Likewise, the Python requests package also uses Accept: */* as a default: def default_headers(): return CaseInsensitiveDict({ 'User-Agent': default_user_agent(), 'Accept-Encoding': ', '.join(('gzip', 'deflate')), 'Accept': '*/*', 'Connection': 'keep-alive', }) I presume that curl and requests add the default for a reason, but I'm not sure what that reason is. RFC 2616 for HTTP/1.1 says that */* indicates all media types and that if no Accept header field is present, then it is assumed that the client accepts all media types. This would seem to indicate that Accept: */* is optional and its omission would have no effect. That said, Python is using HTTP/1.0 and the RFCs are silent about the effect of omitting the header. I would like to determine whether the best practice is to include Accept: */* as curl and requests do or whether it is okay to omit is as Python's urllib.urlopen() does. The question is important because I'm in a position to fix urllib.urlopen() if it is determined to be buggy or if it is problematic for use with REST APIs as commonly implemented using HTTP/1.0: >>> import httplib >>> httplib.HTTPConnection.debuglevel = 1 >>> import urllib >>> u = urllib.urlopen('https://graph.facebook.com/zuck') send: 'GET /zuck HTTP/1.0\r\nHost: graph.facebook.com\r\nUser-Agent: Python-urllib/1.17\r\n\r\n' The related questions on StackOverflow aren't helpful for this question. What does 'Accept: */*' mean under Client section of Request Headers? asks what */* means (we already know that it means all media types) and Send a curl request with no Accept header? asks how to omit the accept header in a curl request. My question focuses on whether you should include */* and whether it is a bug to omit it.
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 accepts all media types. This means that omitting the header SHOULD be equivalently interpreted by the server as sending Accept: */* in the sense that the client acceptes all media types in both cases. It is interesting that the facebook response differs in both cases but I guess it is their failure of interpreting the protocol correctly. Though on the other side both responses are obviously correct responses to the request (Which I find a funny twist). I have some general thoughts on this issue (which might also contribute to the bugfix discussion): Following Postel Law Be conservative in what you do, be liberal in what you accept from others (often reworded as "Be conservative in what you send, be liberal in what you accept"). you could decide to be more precise and explicitly add Accept: */*. You would be more precise helping the server that he might have misinterpreted the protocol (like facebook probably did) that a missing header would be equivalent to Accept: */* Just adding header fields like Accept: */* which could be omitted increases network traffic by 11 Byte for every single request which might lead to performance issues. Having Accept: */* be default in the request might make it hard for developers to get it out of the header in order to save to 11 Byte. There is a difference between a specification (or a standard) and a de facto standard. Obviously omitting the header field is perfect according to the specification on the other hand a lot of libraries seem to include this and services like the facebook API behave differently this can be seen as a de facto standard being created and you could jump into the loop and be part of creating it. When speaking HTTP/1.1: Even though (1) und (3) speak for fixing the urllib I would probably follow the specification and the performance argument (2) and omit the header. As stated above the response of facebook in both cases is correct since they are allowed to set the media type to whatever they like. (even though this behaviour seems unintended, weird, and by mistake) When speaking HTTP/1.0: I would send the accept header since you said it is not specified in the HTTP/1.0 RFC and then I think Postel's law becomes more important. On the other side the Accept header is just optional in http 1.0. The Accept request-header field can be used to indicate a list of media ranges which are acceptable as a response to the request Why would you set an optional header by default?
How to read a 6 GB csv file with 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\parsers.pyc in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, na_fvalues, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format) 450 infer_datetime_format=infer_datetime_format) 451 --> 452 return _read(filepath_or_buffer, kwds) 453 454 parser_f.__name__ = name C:\Python27\lib\site-packages\pandas\io\parsers.pyc in _read(filepath_or_buffer, kwds) 242 return parser 243 --> 244 return parser.read() 245 246 _parser_defaults = { C:\Python27\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows) 693 raise ValueError('skip_footer not supported for iteration') 694 --> 695 ret = self._engine.read(nrows) 696 697 if self.options.get('as_recarray'): C:\Python27\lib\site-packages\pandas\io\parsers.pyc in read(self, nrows) 1137 1138 try: -> 1139 data = self._reader.read(nrows) 1140 except StopIteration: 1141 if nrows is None: C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader.read (pandas\parser.c:7145)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader._read_low_memory (pandas\parser.c:7369)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader._read_rows (pandas\parser.c:8194)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader._convert_column_data (pandas\parser.c:9402)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader._convert_tokens (pandas\parser.c:10057)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser.TextReader._convert_with_dtype (pandas\parser.c:10361)() C:\Python27\lib\site-packages\pandas\parser.pyd in pandas.parser._try_int64 (pandas\parser.c:17806)() MemoryError: Any help on this??
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 (by specifying the chunksize parameter): chunksize = 10 ** 6 for chunk in pd.read_csv(filename, chunksize=chunksize): process(chunk)
pip geoip installing in ubuntu gcc error
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 error: GeoIP.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 how to solve this problem in ubuntu
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: command 'x86_64-linux-gnu-gcc' failed with exit status 1 Returned 1. $ apt-cache search geoip ... libgeoip-dev - Development files for the GeoIP library ... andrew@refbuntu:~$ sudo apt-get install libgeoip-dev -y [sudo] password for andrew: Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: geoip-bin libgeoip-dev 0 upgraded, 2 newly installed, 0 to remove and 159 not upgraded. ... Setting up libgeoip-dev (1.5.1-1ubuntu1) ... andrew@refbuntu:~$ easy_install GeoIP ... Running GeoIP-1.3.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-rwdpkL/GeoIP-1.3.2/egg-dist-tmp-DLLeBT /usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg) warning: no files found matching 'ChangeLog' zip_safe flag not set; analyzing archive contents... Adding GeoIP 1.3.2 to easy-install.pth file Installed /home/andrew/.local/lib/python2.7/site-packages/GeoIP-1.3.2-py2.7-linux-x86_64.egg Processing dependencies for GeoIP Finished processing dependencies for GeoIP If you install the apt-file package, you can also search by filename for packages containing that file: $ apt-file search GeoIP.h libgeoip-dev: /usr/include/GeoIP.h This is really handy for any installation/compilation process that fails due to missing dependencies.
Pybrain time series prediction using LSTM recurrent nets
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 In the example above, the network is able to predict a sequence after its being trained. But the issue is, network takes in all the sequential data by feeding it in one go to the input layer. For example, if the training data has 10 features each, the 10 features will be simultaneously fed into 10 input nodes at one time. From my understanding, this is no longer a time series prediction am I right? Since there is no difference in terms of the time each feature is fed into the network? Correct me if I am wrong on this. Therefore, what I am trying to achieve is a recurrent network that has only ONE input node, and ONE output node. The input node is where all the time series data will be fed sequentially at different time steps. The network will be trained to reproduce the input at the output node. Could you please suggest or guide me in constructing the network I mentioned? Thank you very much in advance.
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(data) [1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2] Now put this timeseries into a supervised dataset, where the target for each sample is the next sample: from pybrain.datasets import SequentialDataSet from itertools import cycle ds = SequentialDataSet(1, 1) for sample, next_sample in zip(data, cycle(data[1:])): ds.addSample(sample, next_sample) Build a simple LSTM network with 1 input node, 5 LSTM cells and 1 output node: from pybrain.tools.shortcuts import buildNetwork from pybrain.structure.modules import LSTMLayer net = buildNetwork(1, 5, 1, hiddenclass=LSTMLayer, outputbias=False, recurrent=True) Train the network: from pybrain.supervised import RPropMinusTrainer from sys import stdout trainer = RPropMinusTrainer(net, dataset=ds) train_errors = [] # save errors for plotting later EPOCHS_PER_CYCLE = 5 CYCLES = 100 EPOCHS = EPOCHS_PER_CYCLE * CYCLES for i in xrange(CYCLES): trainer.trainEpochs(EPOCHS_PER_CYCLE) train_errors.append(trainer.testOnData()) epoch = (i+1) * EPOCHS_PER_CYCLE print("\r epoch {}/{}".format(epoch, EPOCHS), end="") stdout.flush() print() print("final error =", train_errors[-1]) Plot the errors (note that in this simple toy example, we are testing and training on the same dataset, which is of course not what you'd do for a real project!): import matplotlib.pyplot as plt plt.plot(range(0, EPOCHS, EPOCHS_PER_CYCLE), train_errors) plt.xlabel('epoch') plt.ylabel('error') plt.show() Now ask the network to predict the next sample: for sample, target in ds.getSequenceIterator(0): print(" sample = %4.1f" % sample) print("predicted next sample = %4.1f" % net.activate(sample)) print(" actual next sample = %4.1f" % target) print() (The code above is based on the example_rnn.py and the examples from the PyBrain documentation)
Is it possible to step backwards in 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 that you don’t want to run.
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 the thesis and here is the program and the code. I used epdb as a starting point to create a live reverse debugger as part of my MSc degree. The thesis is available online: Combining reverse debugging and live programming towards visual thinking in computer programming. In chapter 1 and 2 I also cover most of the historical approaches to reverse debugging.
How to format axis number format to thousands with a comma in 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 fig1 = plt.figure(1) fig1.set_figheight(15) fig1.set_figwidth(20) ax = fig1.add_subplot(2,1,1) x = 10000.21, 22000.32, 10120.54 y = 1, 4, 15 ax.plot(x, y) ax2 = fig1.add_subplot(2,1,2) x2 = 10434, 24444, 31234 y2 = 1, 4, 9 ax2.plot(x2, y2) fig1.show()
Use , as format specifier: >>> format(10000.21, ',') '10,000.21' Alternatively you can also use str.format instead of format: >>> '{:,}'.format(10000.21) '10,000.21' With matplotlib.ticker.FuncFormatter: ... ax.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) ax2.get_xaxis().set_major_formatter( matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))) fig1.show()
What is regex for currency symbol?
In java I can use the regex : \p{Sc} for detecting currency symbol in text. What is the equivalent in Python?
You can use the unicode category if you use 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'] >>> print _[1] ¢ UPDATE Alterantive way using unicodedata.category: >>> import unicodedata >>> [ch for ch in '$99.99 / €77' if unicodedata.category(ch) == 'Sc'] ['$', '€']
pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"
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. Python 2.7 was already installed, it came with ArcGIS. python and pip were not available from the command line until I installed 3.4.1. > pip search linkchecker works. Perhaps that is because pip search does not verify the site's SSL certificate. I am in a company network but we do not go through a proxy to reach the Internet. Each company computer (including mine) has a Trusted Root Certificate Authority that is used for various reasons including enabling monitoring TLS traffic to https://google.com. Not sure if that has anything to do with it. Here are the contents of my pip.log after running pip install linkchecker: Downloading/unpacking linkchecker Getting page https://pypi.python.org/simple/linkchecker/ Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598) Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker Getting page https://pypi.python.org/simple/ Could not fetch URL https://pypi.python.org/simple/: connection error: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ (Caused by <class 'http.client.CannotSendRequest'>: Request-sent) Will skip URL https://pypi.python.org/simple/ when looking for download links for linkchecker Cannot fetch index base URL https://pypi.python.org/simple/ URLs to search for versions for linkchecker: * https://pypi.python.org/simple/linkchecker/ Getting page https://pypi.python.org/simple/linkchecker/ Could not fetch URL https://pypi.python.org/simple/linkchecker/: connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598) Will skip URL https://pypi.python.org/simple/linkchecker/ when looking for download links for linkchecker Could not find any downloads that satisfy the requirement linkchecker Cleaning up... Removing temporary dir C:\Users\jcook\AppData\Local\Temp\pip_build_jcook... No distributions at all found for linkchecker Exception information: Traceback (most recent call last): File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main status = self.run(options, args) File "C:\Python34\lib\site-packages\pip\commands\install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "C:\Python34\lib\site-packages\pip\req.py", line 1177, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "C:\Python34\lib\site-packages\pip\index.py", line 277, in find_requirement raise DistributionNotFound('No distributions at all found for %s' % req) pip.exceptions.DistributionNotFound: No distributions at all found for linkchecker
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 workarounds that help in installing most of the python packages with ease would be: Using easy_install if you are really lazy and don't want to waste much time.But then there are some packages that would still either be not found or would give you small errors. The 2nd and most useful way would be download the Wheel of the python package from the link: Wheel and use the pip command 'pip install whell_package_name.whl' to install the package.
Iterate python Enum in definition order
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, in definition order". However, iteration is not happening in order for me: >>> from enum import Enum >>> class Shake(Enum): ... vanilla = 7 ... chocolate = 4 ... cookies = 9 ... mint = 3 ... >>> for s in Shake: ... print(s) ... Shake.mint Shake.chocolate Shake.vanilla Shake.cookies Am I misunderstanding something, or is iteration in definition order just not supported in the backported versions of Enums yet? Assuming the latter, is there an easy way to force it to happen in order?
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 ... mint = 3 ... >>> for s in Shake: ... print(s) ... Shake.vanilla Shake.chocolate Shake.cookies Shake.mint
Why does this take so long to match? Is it a bug?
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') The expected result would be that there were no matches. This expression, however, executes almost immediately (note the trailing slash): re.findall(r'(\d+(,)?)+/$', '12345121,223456,123123,3234,4523,523523/') Is this a bug?
There is some catastrophic backtracking 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 this wouldn't be a match with attempting all of the extraneous repetition). This is solved by optimizing the expression. The easiest way to accomplish this is to just look for 1+ digits or commas followed by a slash and the end of the string: [\d,]+/$. However, that is not perfect since it would allow for something like ,123,,4,5/. For this you can use a slightly optimized version of your initial try: (?:\d,?)+/$. First, I made your repeating group non-capturing ((?:...)) which isn't necessary but it provides for a "cleaner match". Next, and the only crucial step, I stopped repeating the \d inside of the group since the group is already repeating. Finally, I removed the unnecessary group around the optional , since ? only affects the last character. Pretty much this will look for one digit, maybe a comma, then repeat, and finally followed by a trailing /. This can still match an odd string 1,2,3,/, so for the heck of it I improved your original regex with a negative lookbehind: (?:\d,?)+(?<!,)/$. This will assert that there is no comma directly before the trailing /.
Scientific notation colorbar in matplotlib
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 color bar: import matplotlib as plot import numpy as np img = np.random.randn(300,300) myplot = plt.imshow(img) plt.colorbar(myplot) plt.show() When I do this, I get the following image: However, I would like to see the ticklabels in scientific notation... Is there any one line command to do this? Otherwise, is there any hint out there? Thanks!
You could use colorbar's format parameter: 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).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b) plt.colorbar(myplot, format=ticker.FuncFormatter(fmt)) plt.show()
Execute curl command within a Python script
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 recommendations to use pycurl, but I couldn't figure out how to apply it to mine. I tried using: subprocess.call([ 'curl', '-X', 'POST', '-d', flow_x, 'http://localhost:8080/firewall/rules/0000000000000001' ]) and it works, but is there a better way?
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 other program, from within my program, just to make a measly little web request?". That's crazy, there's got to be a better way right? Uxio's answer works, sure. But it hardly looks very Pythonic, does it? That's a lot of work just for one little request. Python's supposed to be about flying! Anyone writing that is probably wishing they just call'd curl! it works, but is there a better way? Yes, there is a better way! Requests: HTTP for Humans Things shouldn’t be this way. Not in Python. Let's GET this page: import requests res = requests.get('http://stackoverflow.com/questions/26000336') That's it, really! You then have the raw res.text, or res.json() output, the res.headers, etc. You can see the docs (linked above) for details of setting all the options, since I imagine OP has moved on by now, and you - the reader now - likely need different ones. But, for example, it's as simple as: url = http://example.tld payload = { 'key' : 'val' } headers = {} res = requests.post(url, data=payload, headers=headers) You can even use a nice Python dict to supply the query string in a GET request with params={}. Simple and elegant. Keep calm, and fly on.
Encrypted and secure docker containers
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 functions via network but no chance to touch the actual server where binaries and code are stored. Now we want to deliver the "local" version of our system. The app will be running on PCs that our users will physically own. We know that everything could be broken, but at least want to protect the app from possible copying and reverse-engineering as much as possible. I know that docker is a wonderful deployment tool so I wonder: it is possible to create encrypted docker containers where no one can see any data stored in the container's filesystem? Is there a known solution to this problem? Also, maybe there are well known solutions not based on docker?
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 file system or protecting RAM from debugging. Using obfuscation on a standard Linux box, you can make it harder to read the file system and RAM, but you can't make it impossible or the container cannot run. If you can control the hardware running the operating system, then you might want to look at the Trusted Platform Module which starts system verification as soon as the system boots. You could then theoretically do things before the root user has access to the system to hide keys and strongly encrypt file systems. Even then, given physical access to the machine, a determined attacker can always get the decrypted data.
ImportError: No module named datetime
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.
What is the difference between a pandas Series and a single-column DataFrame?
Why does pandas make a distinction between a Series and a single-column DataFrame? In other words: what is the reason of existence of the Series class? I'm mainly using time series with datetime index, maybe that helps to set the context.
Quoting the Pandas docs pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False) Two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure (Emphasis mine, sentence fragment not mine) So the Series is the datastructure for a single column of a DataFrame, not only conceptually, but literally i.e. the data in a DataFrame is actually stored in memory as a collection of Series. Analogously: We need both lists and matrices, because matrices are built with lists. Single row matricies, while equivalent to lists in functionality still cannot exists without the list(s) they're composed of. They both have extremely similar APIs, but you'll find that DataFrame methods always cater to the possibility that you have more than one column. And of course, you can always add another Series (or equivalent object) to a DataFrame, while adding a Series to another Series involves creating a DataFrame.
error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
When I try to install odoo-server I got the following error could anyone help me to resolve this? error: Setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Try installing these packages. sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev sudo easy_install greenlet sudo easy_install gevent
should pytest et al. go in tests_require[] or extras_require{testing[]}?
I am writing a python program which uses py.test for testing and now one test also depends on numpy. Where in my setup.py should I add those dependencies? Currently the relevant part of my setup.py looks something like this: [...] 'version': '0.0.1', 'install_requires': [], 'tests_require': ['pytest'], 'cmdclass': {'test': PyTest}, 'extras_require': { 'testing': ['pytest'], }, [...] Having pytest twice feels already somewhat strange and I'm not sure where to add numpy.
According to the docs tests_require are additional packages that are obtained when using setuptools's test command. They are not installed on the system. extras_require are optional additional packages grouped by the feature name. The list of packages are installed to use that feature and there are various ways to install them. See Does pip handle extras_requires from setuptools/distribute based sources? My interpretation tests_require should be packages that are used in the tests such as numpy and not packages that are used to conduct testing like pytest or nose. tests_require would need to be moved or copied to a "testing" feature in extras_require when testing outside of setuptools. Use extras_require to make a testing package such as pytest optional. Use setup_requires to require it. pytest and nose can be integrated with setuptools to take advantage of the convenience of tests_require, however, there may be drawbacks. nose warns that plugins may not be available when run through setuptools. See pytest integration with setuptools test commands and nosetests setuptools command. For example Testing with setuptools integration: setup.py [...] 'version': '0.0.1', 'install_requires': [], 'tests_require': ['numpy'], 'cmdclass': {'test': PyTest}, 'extras_require': { 'testing': ['pytest'], }, [...] sh (env) > python setup.py develop (env) > easy_install pytest (env) > python setup.py test -a "--pdb" Or, testing without setuptools integration: setup.py [...] 'version': '0.0.1', 'install_requires': [], 'extras_require': { 'testing': ['pytest', 'numpy'], }, [...] sh (env) > pip install -e .[testing] (env) > pytest.py --pdb
How to fix Selenium WebDriverException: The browser appears to have exited before we could connect?
I have installed firefox and Xvfb on my centos6.4 server to use selenium webdriver. But, when I run the code, I got an error. from selenium import webdriver browser = webdriver.Firefox() Error selenium.common.exceptions.WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: None' I read some related pages on stackoverflow and someone suggested to remove all files in tmp folder, so I did it. But, it still doesn't work. Could anyone please give me a help? Thank you in advance! Edit Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/webdriver.py", line 59, in __init__ self.binary, timeout), File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/extension_connection.py", line 47, in __init__ self.binary.launch_browser(self.profile) File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 64, in launch_browser self._wait_until_connectable() File "/usr/local/lib/python3.4/site-packages/selenium/webdriver/firefox/firefox_binary.py", line 103, in _wait_until_connectable self._get_firefox_output()) selenium.common.exceptions.WebDriverException: Message: 'The browser appears to have exited before we could connect. The output was: None'
for Googlers, this answer didn't work for me, and I had to use this answer instead. I am using AWS Ubuntu. Basically, I needed to install Xvfb and then pyvirtualdisplay: sudo apt-get install xvfb sudo pip install pyvirtualdisplay Once I had done that, this python code worked: #!/usr/bin/env python from pyvirtualdisplay import Display from selenium import webdriver display = Display(visible=0, size=(1024, 768)) display.start() browser = webdriver.Firefox() browser.get('http://www.ubuntu.com/') print browser.page_source browser.close() display.stop() Thanks to @That1Guy for the first answer
secret key not set in flask session
I am having 0 luck getting a session working in Flask (a Python module). Right now I am using a flask 3rd party library Flask-Session When I connect to my site, I get the following error: RuntimeError: the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. Below is my server code. from flask import Flask, session from flask.ext.session import Session SESSION_TYPE = 'memcache' app = Flask(__name__) sess = Session() nextId = 0 def verifySessionId(): global nextId if not 'userId' in session: session['userId'] = nextId nextId += 1 sessionId = session['userId'] print ("set userid[" + str(session['userId']) + "]") else: print ("using already set userid[" + str(session['userId']) + "]") sessionId = session.get('userId', None) return sessionId @app.route("/") def hello(): userId = verifySessionId() print("User id[" + str(userId) + "]") return str(userId) if __name__ == "__main__": app.secret_key = 'super secret key' sess.init_app(app) app.debug = True app.run() As you can see, I do set the app secret key. What am I doing wrong? Are there other session options? Other info: Running Python 2.7 on Linux Mint Full paste: Traceback (most recent call last): File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/sean/code/misc/session/sessiontest.py", line 27, in hello userId = verifySessionId() File "/home/sean/code/misc/session/sessiontest.py", line 16, in verifySessionId session['userId'] = nextId File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/werkzeug/local.py", line 341, in __setitem__ self._get_current_object()[key] = value File "/home/sean/code/misc/hangman/venv/lib/python2.7/site-packages/flask/sessions.py", line 126, in _fail raise RuntimeError('the session is unavailable because no secret ' RuntimeError: the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.
The exception is raised by the NullSessionInterface session implementation, which is the default session type when you use Flask-Session. That's because you don't ever actually give the SESSION_TYPE configuration to Flask; it is not enough to set it as a global in your module. This default doesn't make much sense with Flask 0.10; it may have made sense with Flask 0.8 or 0.9, but the current version is used as an error signal. In your case it gives you the wrong error message now. Set the SESSION_TYPE configuration option to something else. Pick one of redis, memcached, filesystem or mongodb. Setting it to filesystem is easiest; there is enough default configuration there to have that work without additional dependencies: if __name__ == "__main__": app.secret_key = 'super secret key' app.config['SESSION_TYPE'] = 'filesystem' sess.init_app(app) app.debug = True app.run()
ImproperlyConfigured: You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
I was trying to configure my django project to deploy to heroku. I am getting the following error and I don't really know how to fix it. Here is the full traceback and error: 22:46:15 web.1 | Traceback (most recent call last): 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/arbiter.py", line 495, in spawn_worker 22:46:15 web.1 | worker.init_process() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/workers/base.py", line 106, in init_process 22:46:15 web.1 | self.wsgi = self.app.wsgi() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/app/base.py", line 114, in wsgi 22:46:15 web.1 | self.callable = self.load() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 62, in load 22:46:15 web.1 | return self.load_wsgiapp() 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load_wsgiapp 22:46:15 web.1 | return util.import_app(self.app_uri) 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/gunicorn/util.py", line 354, in import_app 22:46:15 web.1 | __import__(module) 22:46:15 web.1 | File "/Users/nir/nirla/nirla/wsgi.py", line 12, in <module> 22:46:15 web.1 | from dj_static import Cling 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/dj_static.py", line 7, in <module> 22:46:15 web.1 | from django.contrib.staticfiles.handlers import StaticFilesHandler as DebugHandler 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 8, in <module> 22:46:15 web.1 | from django.contrib.staticfiles.views import serve 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/contrib/staticfiles/views.py", line 13, in <module> 22:46:15 web.1 | from django.views import static 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/views/static.py", line 96, in <module> 22:46:15 web.1 | template_translatable = ugettext_noop("Index of %(directory)s") 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 65, in gettext_noop 22:46:15 web.1 | return _trans.gettext_noop(message) 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/utils/translation/__init__.py", line 52, in __getattr__ 22:46:15 web.1 | if settings.USE_I18N: 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__ 22:46:15 web.1 | self._setup(name) 22:46:15 web.1 | File "/Users/nir/nirla/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 47, in _setup 22:46:15 web.1 | % (desc, ENVIRONMENT_VARIABLE)) 22:46:15 web.1 | ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here is my wsgi.py file: import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nirla.settings") #nirla is the name of the project application = Cling(get_wsgi_application()) And in case it was relevant, my manage.py file: import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nirla.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) Can anyone seem to understand the issue here? And if so, can you be so kind as to explain what is wrong? Thank you!
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found: export DJANGO_SETTINGS_MODULE=mysite.settings Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this: heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name> In my specific case I ran these two and everything worked out: export DJANGO_SETTINGS_MODULE=nirla.settings heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal Edit I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
Understanding NumPy's einsum
I'm struggling to understand exactly how einsum works. I've looked at the documentation and a few examples, but it's not seeming to stick. Here's an example we went over in class: C = np.einsum("ij,jk->ki", A, B) for two arraysA and B I think this would take A^T * B, but I'm not sure (it's taking the transpose of one of them right?). Can anyone walk me through exactly what's happening here (and in general when using einsum)?
(Note: this answer is based on a short blog post about einsum I wrote a while ago.) What does einsum do? Imagine that we have two multi-dimensional arrays, A and B. Now let's suppose we want to... multiply A with B in a particular way to create new array of products; and then maybe sum this new array along particular axes; and then maybe transpose the axes of the new array in a particular order. There's a good chance that einsum will help us do this faster and more memory-efficiently that combinations of the NumPy functions like multiply, sum and transpose will allow. How does einsum work? Here's a simple (but not completely trivial) example. Take the following two arrays: A = np.array([0, 1, 2]) B = np.array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) We will multiply A and B element-wise and then sum along the rows of the new array. In "normal" NumPy we'd write: >>> (A[:, np.newaxis] * B).sum(axis=1) array([ 0, 22, 76]) So here, the indexing operation on A lines up the first axes of the two arrays so that the multiplication can be broadcast. The rows of the array of products is then summed to return the answer. Now if we wanted to use einsum instead, we could write: >>> np.einsum('i,ij->i', A, B) array([ 0, 22, 76]) The signature string 'i,ij->i' is the key here and needs a little bit of explaining. You can think of it in two halves. On the left-hand side (left of the ->) we've labelled the two input arrays. To the right of ->, we've labelled the array we want to end up with. Here is what happens next: A has one axis; we've labelled it i. And B has two axes; we've labelled axis 0 as i and axis 1 as j. By repeating the label i in both input arrays, we are telling einsum that these two axes should be multiplied together. In other words, we're multiplying array A with each column of array B, just like A[:, np.newaxis] * B does. Notice that j does not appear as a label in our desired output; we've just used i (we want to end up with a 1D array). By omitting the label, we're telling einsum to sum along this axis. In other words, we're summing the rows of the products, just like .sum(axis=1) does. That's basically all you need to know to use einsum. It helps to play about a little; if we leave both labels in the output, 'i,ij->ij', we get back a 2D array of products (same as A[:, np.newaxis] * B). If we say no output labels, 'i,ij->, we get back a single number (same as doing (A[:, np.newaxis] * B).sum()). The great thing about einsum however, is that is does not build a temporary array of products first; it just sums the products as it goes. This can lead to big savings in memory use. A slightly bigger example (with pictures!) To explain the dot product, here are two new arrays: A = array([[1, 1, 1], [2, 2, 2], [5, 5, 5]]) B = array([[0, 1, 0], [1, 1, 0], [1, 1, 1]]) We will compute the dot product using np.einsum('ij,jk->ik', A, B). Here's a picture showing the labelling of the A and B and the output array that we get from the function: You can see that label j is repeated - this means we're multiplying the rows of A with the columns of B. Furthermore, the label j is not included in the output - we're summing these products. Labels i and k are kept for the output, so we get back a 2D array. It might be even clearer to compare this result with the array where the label j is not summed. Below, on the left you can see the 3D array that results from writing np.einsum('ij,jk->ijk', A, B) (i.e. we've kept label j): Summing axis j gives the expected dot product, shown on the right.
Is Python *with* statement exactly equivalent to a try - (except) - finally block?
I know this was widely discussed, but I still can't find an answer to confirm this: is the with statement identical to calling the same code in a try - (except) -finally block, where whatever one defines in the __exit__ function of the context manager is placed in the finally block? For example -- are these 2 code snippets doing exactly the same thing? import sys from contextlib import contextmanager @contextmanager def open_input(fpath): fd = open(fpath) if fpath else sys.stdin try: yield fd finally: fd.close() with open_input("/path/to/file"): print "starting to read from file..." the same as: def open_input(fpath): try: fd = open(fpath) if fpath else sys.stdin print "starting to read from file..." finally: fd.close() open_input("/path/to/file") Thanks!
I'm going to put aside mentions of scope, because it's really not very relevant. According to PEP 343, with EXPR as VAR: BLOCK translates to mgr = (EXPR) exit = type(mgr).__exit__ # Not calling it yet value = type(mgr).__enter__(mgr) exc = True try: try: VAR = value # Only if "as VAR" is present BLOCK except: # The exceptional case is handled here exc = False if not exit(mgr, *sys.exc_info()): raise # The exception is swallowed if exit() returns true finally: # The normal and non-local-goto cases are handled here if exc: exit(mgr, None, None, None) As you can see, type(mgr).__enter__ is called as you expect, but not inside the try. type(mgr).__exit__ is called on exit. The only difference is that when there is an exception, the if not exit(mgr, *sys.exc_info()) path is taken. This gives with the ability to introspect and silence errors unlike what a finally clause can do. contextmanager doesn't complicate this much. It's just: def contextmanager(func): @wraps(func) def helper(*args, **kwds): return _GeneratorContextManager(func, *args, **kwds) return helper Then look at the class in question: class _GeneratorContextManager(ContextDecorator): def __init__(self, func, *args, **kwds): self.gen = func(*args, **kwds) def __enter__(self): try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None def __exit__(self, type, value, traceback): if type is None: try: next(self.gen) except StopIteration: return else: raise RuntimeError("generator didn't stop") else: if value is None: value = type() try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") except StopIteration as exc: return exc is not value except: if sys.exc_info()[1] is not value: raise Unimportant code has been elided. The first thing to note is that if there are multiple yields, this code will error. This does not affect the control flow noticeably. Consider __enter__. try: return next(self.gen) except StopIteration: raise RuntimeError("generator didn't yield") from None If the context manager was well written, this will never break from what is expected. One difference is that if the generator throws StopIteration, a different error (RuntimeError) will be produced. This means the behaviour is not totally identical to a normal with if you're running completely arbitrary code. Consider a non-erroring __exit__: if type is None: try: next(self.gen) except StopIteration: return else: raise RuntimeError("generator didn't stop") The only difference is as before; if your code throws StopIteration, it will affect the generator and thus the contextmanager decorator will misinterpret it. This means that: from contextlib import contextmanager @contextmanager def with_cleanup(func): try: yield finally: func() def good_cleanup(): print("cleaning") with with_cleanup(good_cleanup): print("doing") 1/0 #>>> doing #>>> cleaning #>>> Traceback (most recent call last): #>>> File "", line 15, in <module> #>>> ZeroDivisionError: division by zero def bad_cleanup(): print("cleaning") raise StopIteration with with_cleanup(bad_cleanup): print("doing") 1/0 #>>> doing #>>> cleaning Which is unlikely to matter, but it could. Finally: else: if value is None: value = type() try: self.gen.throw(type, value, traceback) raise RuntimeError("generator didn't stop after throw()") except StopIteration as exc: return exc is not value except: if sys.exc_info()[1] is not value: raise This raises the same question about StopIteration, but it's interesting to note that last part. if sys.exc_info()[1] is not value: raise This means that if the exception is unhandled, the traceback will be unchanged. If it was handled but a new traceback exists, that will be raised instead. This perfectly matches the spec. TL;DR with is actually slightly more powerful than a try...finally in that the with can introspect and silence errors. Be careful about StopIteration, but otherwise you're fine using @contextmanager to create context managers.
Emmet - Notepad++ "Unknown exception"
Every time I'm trying to use Emmet's Expand Abbreviation it gives me errors. First a pop up with Unknown Exception and then another pop up with python script plugin did not accept the script. I tried reinstalling Notepad++ but that didn't help. I'm running Windows 8 x64 & Notepad++ 6.6.9. This is the first time I'm using Emmet, after recently used the old Zen Coding. (Which works flawlessly.) I have python 2.7 installed, if that necessary too.
I had the same problem as you. This is the solution which worked for me: emmetio/npp Bug ID #12: python script plugin did not accept the script Basically, the problem lies in the Python Script plugin which will be automatically installed with Emmet. Go to this link: http://sourceforge.net/projects/npppythonscript/files/Python%20Script%200.9.2.0/ and download PythonScript_full_0.9.2.0 package. Replace Notepad++'s Python package with PythonScript_full_0.9.2.0 and unpack the archive in Notepad++'s MAIN directory. (This is where notepad++.exe is.) (Do NOT unpack the archive inside the plugins directory. That will not work. The python27.dll file needs to be in the same directory where notepad++.exe is.) I am using Notepad++ v6.6.9 and it works now.
Why are tuples constructed from differently initialized sets equal?
I expected the following two tuples >>> x = tuple(set([1, "a", "b", "c", "z", "f"])) >>> y = tuple(set(["a", "b", "c", "z", "f", 1])) to compare unequal, but they don't: >>> x == y >>> True Why is that?
At first glance, it appears that x should always equal y, because two sets constructed from the same elements are always equal: >>> x = set([1, "a", "b", "c", "z", "f"]) >>> y = set(["a", "b", "c", "z", "f", 1]) >>> x {1, 'z', 'a', 'b', 'c', 'f'} >>> y {1, 'z', 'a', 'b', 'c', 'f'} >>> x == y True However, it is not always the case that tuples (or other ordered collections) constructed from two equal sets are equal. In fact, the result of your comparison is sometimes True and sometimes False, at least in Python >= 3.3. Testing the following code: # compare.py x = tuple(set([1, "a", "b", "c", "z", "f"])) y = tuple(set(["a", "b", "c", "z", "f", 1])) print(x == y) ... a thousand times: $ for x in {1..1000} > do > python3.3 compare.py > done | sort | uniq -c 147 False 853 True This is because, since Python 3.3, the hash values of strings, bytes and datetimes are randomized as a result of a security fix. Depending on what the hashes are, "collisions" may occur, which will mean that the order items are stored in the underlying array (and therefore the iteration order) depends on the insertion order. Here's the relevant bit from the docs: Security improvements: Hash randomization is switched on by default. — https://docs.python.org/3/whatsnew/3.3.html EDIT: Since it's mentioned in the comments that the True/False ratio above is superficially surprising ... Sets, like dictionaries, are implemented as hash tables - so if there's a collision, the order of items in the table (and so the order of iteration) will depend both on which item was added first (different in x and y in this case) and the seed used for hashing (different across Python invocations since 3.3). Since collisions are rare by design, and the examples in this question are smallish sets, the issue doesn't arise as often as one might initially suppose. For a thorough explanation of Python's implementation of dictionaries and sets, see The Mighty Dictionary.
matplotlib get ylim values
I'm using matplotlib to plot data (using plot and errorbar functions) from Python. I have to plot a set of totally separate and independent plots, and then adjust they're ylim values so they can be easily visually compared. How can I retrieve the ylim values from each plot, so that I can take the min and max of the lower and upper ylim values, respectively, and adjust the plots so they can be visually compared? Of course, I could just analyze the data and come up with my own custom ylim values... but I'd like to use matplotlib to do that for me. Any suggestions on how to easily (and efficiently) do this? Here's my Python function that plots using matplotlib: import matplotlib.pyplot as plt def myplotfunction(title, values, errors, plot_file_name): # plot errorbars indices = range(0, len(values)) fig = plt.figure() plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.') # axes axes = plt.gca() axes.set_xlim([-0.5, len(values) - 0.5]) axes.set_xlabel('My x-axis title') axes.set_ylabel('My y-axis title') # title plt.title(title) # save as file plt.savefig(plot_file_name) # close figure plt.close(fig)
Just use axes.get_ylim(), it is very similar to set_ylim. From the docs: get_ylim() Get the y-axis range [bottom, top]
Why does tuple(set([1,"a","b","c","z","f"])) == tuple(set(["a","b","c","z","f",1])) 85% of the time with hash randomization enabled?
Given Zero Piraeus' answer to another question, we have that x = tuple(set([1, "a", "b", "c", "z", "f"])) y = tuple(set(["a", "b", "c", "z", "f", 1])) print(x == y) Prints True about 85% of the time with hash randomization enabled. Why 85%?
I'm going to assume any readers of this question to have read both: Zero Piraeus' answer and My explanation of CPython's dictionaries. The first thing to note is that hash randomization is decided on interpreter start-up. The hash of each letter will be the same for both sets, so the only thing that can matter is if there is a collision (where order will be affected). By the deductions of that second link we know the backing array for these sets starts at length 8: _ _ _ _ _ _ _ _ In the first case, we insert 1: _ 1 _ _ _ _ _ _ and then insert the rest: α 1 ? ? ? ? ? ? Then it is rehashed to size 32: 1 can't collide with α as α is an even hash ↓ so 1 is inserted at slot 1 first ? 1 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? In the second case, we insert the rest: ? β ? ? ? ? ? ? And then try to insert 1: Try to insert 1 here, but will ↓ be rehashed if β exists ? β ? ? ? ? ? ? And then it will be rehashed: Try to insert 1 here, but will be rehashed if β exists and has ↓ not rehashed somewhere else ? β ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? So whether the iteration orders are different depends solely on whether β exists. The chance of a β is the chance that any of the 5 letters will hash to 1 modulo 8 and hash to 1 modulo 32. Since anything that hashes to 1 modulo 32 also hashes to 1 modulo 8, we want to find the chance that of the 32 slots, one of the five is in slot 1: 5 (number of letters) / 32 (number of slots) 5/32 is 0.15625, so there is a 15.625% chance¹ of the orders being different between the two set constructions. Not very strangely at all, this is exactly what Zero Piraeus measured. ¹Technically even this isn't obvious. We can pretend every one of the 5 hashes uniquely because of rehashing, but because of linear probing it's actually more likely for "bunched" structures to occur... but because we're only looking at whether a single slot is occupied, this doesn't actually affect us.
Microsoft Visual C++ Compiler for Python 2.7
I downloaded Microsoft Visual C++ Compiler for Python 2.7 , and install it, the full path of vcvarsall.bat is: C:\Users\UserName\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat But the following code can't return the path of it: from distutils import msvc9compiler msvc9compiler.find_vcvarsall(9.0) The installer doesn't write the install information to the registry, and from the source code of find_vcvarsall(), it seems that it can't find the vcvarsall.bat file from VS90COMNTOOLS setting, because it requires that the name of the folder that contains vcvarsall.bat is VC: productdir = os.path.join(toolsdir, os.pardir, os.pardir, "VC") How can I use the compiler without modify registry or folder name?
Update setuptools to 6.0 or greater. In those version setuptools can autodetect Microsoft Visual C++ Compiler for Python 2.7 with the vcvarsall.bat. Please reference to: https://pypi.python.org/pypi/setuptools/6.1#id4 https://bitbucket.org/pypa/setuptools/issue/258
How to draw random planes
I am using the following code to draw random planes in 3d that go through the origin. from __future__ import division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #Number of hyperplanes n = 20 #Dimension of space d = 3 plt3d = plt.figure().gca(projection='3d') for i in xrange(n): #Create random point on unit sphere v = np.random.normal(size = d) v = v/np.sqrt(np.sum(v**2)) # create x,y xx, yy = np.meshgrid(range(-5,5), range(-5,5)) z = (-v[0] * xx - v[1] * yy)/v[2] # plot the surface plt3d.plot_surface(xx, yy, z, alpha = 0.5) plt.show() But looking at the picture I don't believe they are uniformly chosen. What am I doing wrong?
I suggest you check your axes. Your calculation makes the Z axis way too large, which means that you have an absurdly biased point of view. First check that your normals are evenly distributed on the circle: from __future__ import division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #Number of hyperplanes n = 1000 #Dimension of space d = 3 plt3d = plt.figure().gca(projection='3d') for i in xrange(n): #Create random point on unit sphere v = np.random.normal(size = d) v = v/np.sqrt(np.sum(v**2)) v *= 10 plt3d.scatter(v[0], v[1], v[2]) plt3d.set_aspect(1) plt3d.set_xlim(-10, 10) plt3d.set_ylim(-10, 10) plt3d.set_zlim(-10, 10) plt.show() Then check that your plane is being created correctly: from __future__ import division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #Number of hyperplanes n = 1 #Dimension of space d = 3 plt3d = plt.figure().gca(projection='3d') for i in xrange(n): #Create random point on unit sphere v = np.random.normal(size = d) v = v/np.sqrt(np.sum(v**2)) v *= 10 # create x,y xx, yy = np.meshgrid(np.arange(-5,5,0.3), np.arange(-5,5,0.3)) xx = xx.flatten() yy = yy.flatten() z = (-v[0] * xx - v[1] * yy)/v[2] # Hack to keep the plane small filter = xx**2 + yy**2 + z**2 < 5**2 xx = xx[filter] yy = yy[filter] z = z[filter] # plot the surface plt3d.scatter(xx, yy, z, alpha = 0.5) for i in np.arange(0.1, 1, 0.1): plt3d.scatter(i*v[0], i*v[1], i*v[2]) plt3d.set_aspect(1) plt3d.set_xlim(-10, 10) plt3d.set_ylim(-10, 10) plt3d.set_zlim(-10, 10) plt.show() Then you can see that you've actually got good results! from __future__ import division import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #Number of hyperplanes n = 100 #Dimension of space d = 3 plt3d = plt.figure().gca(projection='3d') for i in xrange(n): #Create random point on unit sphere v = np.random.normal(size = d) v = v/np.sqrt(np.sum(v**2)) v *= 10 # create x,y xx, yy = np.meshgrid(np.arange(-5,5,0.3), np.arange(-5,5,0.3)) xx = xx.flatten() yy = yy.flatten() z = (-v[0] * xx - v[1] * yy)/v[2] # Hack to keep the plane small filter = xx**2 + yy**2 + z**2 < 5**2 xx = xx[filter] yy = yy[filter] z = z[filter] # plot the surface plt3d.scatter(xx, yy, z, alpha = 0.5) plt3d.set_aspect(1) plt3d.set_xlim(-10, 10) plt3d.set_ylim(-10, 10) plt3d.set_zlim(-10, 10) plt.show()
Why is the asyncio library slower than threads for this I/O-bound operation?
I'm writing a python program used to enumerate a site's domain name.For example,'a.google.com'. First, I used the threading module to do this: import string import time import socket import threading from threading import Thread from queue import Queue ''' enumerate a site's domain name like this: 1-9 a-z + .google.com 1.google.com 2.google.com . . 1a.google.com . . zz.google.com ''' start = time.time() def create_host(char): ''' if char is '1-9a-z' create char like'1,2,3,...,zz' ''' for i in char: yield i for i in create_host(char): if len(i)>1: return False for c in char: yield c + i char = string.digits + string.ascii_lowercase site = '.google.com' def getaddr(): while True: url = q.get() try: res = socket.getaddrinfo(url,80) print(url + ":" + res[0][4][0]) except: pass q.task_done() NUM=1000 #thread's num q=Queue() for i in range(NUM): t = Thread(target=getaddr) t.setDaemon(True) t.start() for host in create_host(char): q.put(host+site) q.join() end = time.time() print(end-start) ''' used time: 9.448670148849487 ''' Later, I read a book which said in some cases coroutines are faster than threads. So, I rewrote the code to use asyncio: import asyncio import string import time start = time.time() def create_host(char): for i in char: yield i for i in create_host(char): if len(i)>1: return False for c in char: yield c + i char = string.digits + string.ascii_lowercase site = '.google.com' @asyncio.coroutine def getaddr(loop, url): try: res = yield from loop.getaddrinfo(url,80) print(url + ':' + res[0][4][0]) except: pass loop = asyncio.get_event_loop() coroutines = asyncio.wait([getaddr(loop, i+site) for i in create_host(char)]) loop.run_until_complete(coroutines) end = time.time() print(end-start) ''' time 120.42313003540039 ''' Why is the asyncio version of getaddrinfo is so slow? Am I misusing the coroutines somehow?
First, I can't reproduce a performance difference nearly as large as the one you're seeing on my Linux machine. I'm consistently seeing about 20-25 seconds for the threaded version, and between 24-34 seconds for the asyncio version. Now, why is asyncio slower? There are a few things that contribute to this. First, the asyncio version has to print sequentially, but the threaded version doesn't. Printing is I/O, so the GIL can be released while it's happening. That means potentially two or more threads can print at the exact same time, though in practice it may not happen often, and probably doesn't make all that much difference in performance. Second, and much more importantly, the asyncio version of getaddrinfo is actually just calling socket.getaddrinfo in a ThreadPoolExecutor: def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0): if self._debug: return self.run_in_executor(None, self._getaddrinfo_debug, host, port, family, type, proto, flags) else: return self.run_in_executor(None, socket.getaddrinfo, host, port, family, type, proto, flags) It's using the default ThreadPoolExecutor for this, which only has five threads: # Argument for default thread pool executor creation. _MAX_WORKERS = 5 That's not nearly as much parallelism you want for this use-case. To make it behave more like the threading version, you'd need to use a ThreadPoolExecutor with 1000 threads, by setting it as the default executor via loop.set_default_executor: loop = asyncio.get_event_loop() loop.set_default_executor(ThreadPoolExecutor(1000)) coroutines = asyncio.wait([getaddr(loop, i+site) for i in create_host(char)]) loop.run_until_complete(coroutines) Now, this will make the behavior more equivalent to threading, but the reality here is you're really not using asynchronous I/O - you're just using threading with a different API. So the best you can do here is identical performance to the threading example. Finally, you're not really running equivalent code in each example - the threading version is using a pool of workers, which are sharing a queue.Queue, while the asyncio version is spawning a coroutine for every single item in the url list. If I make the asyncio version to use a asyncio.Queue and pool of coroutines, in addition to the removing the print statements and making a larger default executor, I get essentially identical performance with both versions. Here's the new asyncio code: import asyncio import string import time from concurrent.futures import ThreadPoolExecutor start = time.time() def create_host(char): for i in char: yield i for i in create_host(char): if len(i)>1: return False for c in char: yield c + i char = string.digits + string.ascii_lowercase site = '.google.com' @asyncio.coroutine def getaddr(loop, q): while True: url = yield from q.get() if not url: break try: res = yield from loop.getaddrinfo(url,80) except: pass @asyncio.coroutine def load_q(loop, q): for host in create_host(char): yield from q.put(host+site) for _ in range(NUM): yield from q.put(None) NUM = 1000 q = asyncio.Queue() loop = asyncio.get_event_loop() loop.set_default_executor(ThreadPoolExecutor(NUM)) coros = [asyncio.async(getaddr(loop, q)) for i in range(NUM)] loop.run_until_complete(load_q(loop, q)) loop.run_until_complete(asyncio.wait(coros)) end = time.time() print(end-start) And Output of each: dan@dandesk:~$ python3 threaded_example.py 20.409344911575317 dan@dandesk:~$ python3 asyncio_example.py 20.39924192428589 Note that there is some variability due to the network, though. Both of them will sometimes be a few seconds slower than this.
Convert a simple one line string to RDD in Spark
I have a simple line: line = "Hello, world" I would like to convert it to an RDD with only one element. I have tried sc.parallelize(line) But it get: sc.parallelize(line).collect() ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd'] Any ideas?
try using List as parameter: sc.parallelize(List(line)).collect() it returns res1: Array[String] = Array(hello,world)
Python slow read performance issue
Following an earlier thread I boiled down my problem to it's bare bones, in migrating from a Perl script to a Python one I found a huge performance issue with slurping files in Python. Running this on Ubuntu Server. NB: this is not a X vs. Y thread I need to know fundamentally if this is how it is or if I'm doing something stupid. I created my test data, 50,000 10kb files (this mirrors the avg file size of what I'm processing): mkdir 1 cd 1 for i in {1..50000}; do dd if=/dev/zero of=$i.xml bs=1 count=10000; done cd .. cp -r 1 2 Created my 2 scripts as simply as possible: Perl foreach my $file (<$ARGV[0]/*.xml>){ my $fh; open($fh, "< $file"); my $contents = do { local $/; <$fh> }; close($fh); } Python import glob, sys for file in glob.iglob(sys.argv[1] + '/*.xml'): with open(file) as x: f = x.read() I then cleared the caches and ran my 2 slurp scripts, between each run I cleaned the caches again using: sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' Then monitored to ensure it was reading everything from disk each time: sudo iotop -a -u me I tried this on a physical machine with RAID 10 disks and on a brand new VM I setup where the VM is on RAID 1 SSDs, have just included the test runs from my VM as the physical server was much the same just faster. $ time python readFiles.py 1 real 5m2.493s user 0m1.783s sys 0m5.013s $ time perl readFiles.pl 2 real 0m13.059s user 0m1.690s sys 0m2.471s $ time perl readFiles.pl 2 real 0m13.313s user 0m1.670s sys 0m2.579s $ time python readFiles.py 1 real 4m43.378s user 0m1.772s sys 0m4.731s I noticed on iotop when Perl was running DISK READ was around 45 M/s and IOWAIT approx 70%, when running Python DISK READ was 2M/s and IOWAIT 97%. I'm not sure where to go from here having boiled them down to as simple as I can get. In case it is relevant $ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 $ perl -v This is perl 5, version 18, subversion 2 (v5.18.2) built for x86_64-linux-gnu-thread-multi FURTHER INFO AS REQUESTED I ran strace and grabbed the info for file 1000.xml but all seem to do the same things: Perl $strace -f -T -o trace.perl.1 perl readFiles.pl 2 32303 open("2/1000.xml", O_RDONLY) = 3 <0.000020> 32303 ioctl(3, SNDCTL_TMR_TIMEBASE or SNDRV_TIMER_IOCTL_NEXT_DEVICE or TCGETS, 0x7fff7f6f7b90) = -1 ENOTTY (Inappropriate ioctl for device) <0.000016> 32303 lseek(3, 0, SEEK_CUR) = 0 <0.000016> 32303 fstat(3, {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000016> 32303 fcntl(3, F_SETFD, FD_CLOEXEC) = 0 <0.000017> 32303 fstat(3, {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000030> 32303 read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192) = 8192 <0.005323> 32303 read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192) = 1808 <0.000022> 32303 read(3, "", 8192) = 0 <0.000019> 32303 close(3) = 0 <0.000017> Python $strace -f -T -o trace.python.1 python readFiles.py 1 32313 open("1/1000.xml", O_RDONLY) = 3 <0.000021> 32313 fstat(3, {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000017> 32313 fstat(3, {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000019> 32313 lseek(3, 0, SEEK_CUR) = 0 <0.000018> 32313 fstat(3, {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000018> 32313 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fa18820a000 <0.000019> 32313 lseek(3, 0, SEEK_CUR) = 0 <0.000018> 32313 read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 8192) = 8192 <0.006795> 32313 read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 1808 <0.000031> 32313 read(3, "", 4096) = 0 <0.000018> 32313 close(3) = 0 <0.000027> 32313 munmap(0x7fa18820a000, 4096) = 0 <0.000022> One difference I noticed, not sure if it's relevant, is that Perl appears to run this against all files before it starts opening them whereas python doesn't: 32303 lstat("2/1000.xml", {st_mode=S_IFREG|0664, st_size=10000, ...}) = 0 <0.000022> Also ran strace with -c (just took top few calls): Perl $ time strace -f -c perl readFiles.pl 2 % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 44.07 3.501471 23 150018 read 12.54 0.996490 10 100011 fstat 9.47 0.752552 15 50000 lstat 7.99 0.634904 13 50016 open 6.89 0.547016 11 50017 close 6.19 0.491944 10 50008 50005 ioctl 6.12 0.486208 10 50014 3 lseek 6.10 0.484374 10 50001 fcntl real 0m37.829s user 0m6.373s sys 0m25.042s Python $ time strace -f -c python readFiles.py 1 % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 42.97 4.186173 28 150104 read 15.58 1.518304 10 150103 fstat 10.51 1.023681 20 50242 174 open 10.12 0.986350 10 100003 lseek 7.69 0.749387 15 50047 munmap 6.85 0.667576 13 50071 close 5.90 0.574888 11 50073 mmap real 5m5.237s user 0m7.278s sys 0m30.736s Did some parsing of the strace output with -T turned on and counted the first 8192 byte read for each file and it's clear this is where the time is going, below is the total time spent for the 50000 first reads of a file followed by the average time for each read. 300.247128000002 (0.00600446220302379) - Python 11.6845620000003 (0.000233681892724297) - Perl Not sure if that helps! UPDATE 2 Updated code in Python to use os.open and os.read and just do a single read of first 4096 bytes (that would work for me as info I want is in top part of file), also eliminates all the other calls in strace: 18346 open("1/1000.xml", O_RDONLY) = 3 <0.000026> 18346 read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 4096) = 4096 <0.007206> 18346 close(3) = 0 <0.000024> $ time strace -f -c python readFiles.py 1 % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 55.39 2.388932 48 50104 read 22.86 0.986096 20 50242 174 open 20.72 0.893579 18 50071 close real 4m48.751s user 0m3.078s sys 0m12.360s Total Time (avg read call) 282.28626 (0.00564290374812595) Still no better...next up I'm going to create a VM on Azure and try there for another example!! UPDATE 3 - Apologies for the size of this!! Ok some interesting results using your (@J.F.Sebastian) script on 3 setups, stripped the output at start for brevity and also removed all the tests which just run super fast from cache and look like: 0.23user 0.26system 0:00.50elapsed 99%CPU (0avgtext+0avgdata 9140maxresident)k 0inputs+0outputs (0major+2479minor)pagefaults 0swaps Azure A2 Standard VM (2 cores 3.5GB RAM Disk Unknown but slow) $ uname -a Linux servername 3.13.0-35-generic #62-Ubuntu SMP Fri Aug 15 01:58:42 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux $ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 $ perl -v This is perl 5, version 18, subversion 2 (v5.18.2) built for x86_64-linux-gnu-thread-multi (with 41 registered patches, see perl -V for more detail) + /usr/bin/time perl slurp.pl 1 1.81user 2.95system 3:11.28elapsed 2%CPU (0avgtext+0avgdata 9144maxresident)k 1233840inputs+0outputs (20major+2461minor)pagefaults 0swaps + clearcache + sync + sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' + /usr/bin/time python slurp.py 1 1.56user 3.76system 3:06.05elapsed 2%CPU (0avgtext+0avgdata 8024maxresident)k 1232232inputs+0outputs (14major+52273minor)pagefaults 0swaps + /usr/bin/time perl slurp.pl 2 1.90user 3.11system 6:02.17elapsed 1%CPU (0avgtext+0avgdata 9144maxresident)k 1233776inputs+0outputs (16major+2465minor)pagefaults 0swaps Comparable first slurp results for both, not sure what was going on during the 2nd Perl slurp? My VMWare Linux VM (2 cores 8GB RAM Disk RAID1 SSD) $ uname -a Linux servername 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux $ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 $ perl -v This is perl 5, version 18, subversion 2 (v5.18.2) built for x86_64-linux-gnu-thread-multi (with 41 registered patches, see perl -V for more detail) + /usr/bin/time perl slurp.pl 1 1.66user 2.55system 0:13.28elapsed 31%CPU (0avgtext+0avgdata 9136maxresident)k 1233152inputs+0outputs (20major+2460minor)pagefaults 0swaps + clearcache + sync + sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' + /usr/bin/time python slurp.py 1 2.10user 4.67system 4:45.65elapsed 2%CPU (0avgtext+0avgdata 8012maxresident)k 1232056inputs+0outputs (14major+52269minor)pagefaults 0swaps + /usr/bin/time perl slurp.pl 2 2.13user 4.11system 5:01.40elapsed 2%CPU (0avgtext+0avgdata 9140maxresident)k 1233264inputs+0outputs (16major+2463minor)pagefaults 0swaps This time, as before, Perl is way faster on first slurp, unsure what is happening on second Perl slurp though not seen this behaviour before. Ran measure.sh again and result was exactly the same give or take a few seconds. I then did what any normal person would do and updated the kernel to match the Azure machine 3.13.0-35-generic and ran measure.sh again and made no difference to results. Out of curiosity I then swapped the 1 and 2 parameter in measure.sh and something strange happened..Perl slowed down and Python sped up! + /usr/bin/time perl slurp.pl 2 1.78user 3.46system 4:43.90elapsed 1%CPU (0avgtext+0avgdata 9140maxresident)k 1234952inputs+0outputs (21major+2458minor)pagefaults 0swaps + clearcache + sync + sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' + /usr/bin/time python slurp.py 2 1.19user 3.09system 0:10.67elapsed 40%CPU (0avgtext+0avgdata 8012maxresident)k 1233632inputs+0outputs (14major+52269minor)pagefaults 0swaps + /usr/bin/time perl slurp.pl 1 1.36user 2.32system 0:13.40elapsed 27%CPU (0avgtext+0avgdata 9136maxresident)k 1232032inputs+0outputs (17major+2465minor)pagefaults 0swaps This has just confused me even further :-( Physical Server (32 cores 132 GB RAM Disk RAID10 SAS) $ uname -a Linux servername 3.5.0-23-generic #35~precise1-Ubuntu SMP Fri Jan 25 17:13:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux $ python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 $ perl -v This is perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi (with 55 registered patches, see perl -V for more detail) + /usr/bin/time perl slurp.pl 1 2.22user 2.60system 0:15.78elapsed 30%CPU (0avgtext+0avgdata 43728maxresident)k 1233264inputs+0outputs (15major+2984minor)pagefaults 0swaps + clearcache + sync + sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' + /usr/bin/time python slurp.py 1 2.51user 4.79system 1:58.53elapsed 6%CPU (0avgtext+0avgdata 34256maxresident)k 1234752inputs+0outputs (16major+52385minor)pagefaults 0swaps + /usr/bin/time perl slurp.pl 2 2.17user 2.95system 0:06.96elapsed 73%CPU (0avgtext+0avgdata 43744maxresident)k 1232008inputs+0outputs (14major+2987minor)pagefaults 0swaps Here Perl seems to win every time. baffled Given the oddity on my local VM, when I swapped directories, which is the machine I have most control over I'm going to try a binary approach on all the possible options of running python vs perl using 1 or 2 as the data directory and try to run them multiple times for consistency but it'll take a while and I'm going a little crazy so break may be required first! All I want is consistency :-( UPDATE 4 - Consistency (Below is run on an ubuntu-14.04.1-server VM, Kernel is 3.13.0-35-generic #62-Ubuntu) I think I've found some consistency, running the tests every way possible for Python/Perl slurp on data dir 1/2 I found the following: Python is always slow on created files (i.e. created by dd) Python is always fast on copied files (i.e. created by cp -r) Perl is always fast on created files (i.e. created by dd) Perl is always slow on copied files (i.e. created by cp -r) So I looked at OS level copying and it seems like on Ubuntu 'cp' behaves in the same way as Python, i.e. slow on original files and fast on copied files. This is what I ran and the results, I did this a few times on a machine with a single SATA HD and on a RAID10 system, results: $ mkdir 1 $ cd 1 $ for i in {1..50000}; do dd if=/dev/urandom of=$i.xml bs=1K count=10; done $ cd .. $ cp -r 1 2 $ sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' $ time strace -f -c -o trace.copy2c cp -r 2 2copy real 0m28.624s user 0m1.429s sys 0m27.558s $ sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' $ time strace -f -c -o trace.copy1c cp -r 1 1copy real 5m21.166s user 0m1.348s sys 0m30.717s Trace results show where time is being spent $ head trace.copy1c trace.copy2c ==> trace.copy1c <== % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 60.09 2.541250 25 100008 read 12.22 0.516799 10 50000 write 9.62 0.406904 4 100009 open 5.59 0.236274 2 100013 close 4.80 0.203114 4 50004 1 lstat 4.71 0.199211 2 100009 fstat 2.19 0.092662 2 50000 fadvise64 0.72 0.030418 608 50 getdents ==> trace.copy2c <== % time seconds usecs/call calls errors syscall ------ ----------- ----------- --------- --------- ---------------- 47.86 0.802376 8 100008 read 13.55 0.227108 5 50000 write 13.02 0.218312 2 100009 open 7.36 0.123364 1 100013 close 6.83 0.114589 1 100009 fstat 6.31 0.105742 2 50004 1 lstat 3.38 0.056634 1 50000 fadvise64 1.62 0.027191 544 50 getdents So it seems copying copies is much faster than copying original files, my current guess is that when copied the files get aligned on disk better than when they were originally created making them more efficient to read? Interestingly 'rsyn' and 'cp' seem to work in opposite ways speedwise, much like Perl and Python! $ rm -rf 1copy 2copy; sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'; echo "Rsync 1"; /usr/bin/time rsync -a 1 1copy; sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'; echo "Rsync 2"; /usr/bin/time rsync -a 2 2copy Rsync 1 3.62user 3.76system 0:13.00elapsed 56%CPU (0avgtext+0avgdata 5072maxresident)k 1230600inputs+1200000outputs (13major+2684minor)pagefaults 0swaps Rsync 2 4.87user 6.52system 5:06.24elapsed 3%CPU (0avgtext+0avgdata 5076maxresident)k 1231832inputs+1200000outputs (13major+2689minor)pagefaults 0swaps $ rm -rf 1copy 2copy; sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'; echo "Copy 1"; /usr/bin/time cp -r 1 1copy; sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'; echo "Copy 2"; /usr/bin/time cp -r 2 2copy Copy 1 0.48user 6.42system 5:05.30elapsed 2%CPU (0avgtext+0avgdata 1212maxresident)k 1229432inputs+1200000outputs (6major+415minor)pagefaults 0swaps Copy 2 0.33user 4.17system 0:11.13elapsed 40%CPU (0avgtext+0avgdata 1212maxresident)k 1230416inputs+1200000outputs (6major+414minor)pagefaults 0swaps
I will focus on only one of your examples, because rest things should be analogical: What I think, may matter in this situation is Read-Ahead (or maybe another technique related to this) feature: Let consider such example: I have created 1000 xml files in "1" dir (names 1.xml to 1000.xml) as you did by dd command and then I copied orginal dir 1 to dir 2 $ mkdir 1 $ cd 1 $ for i in {1..1000}; do dd if=/dev/urandom of=$i.xml bs=1K count=10; done $ cd .. $ cp -r 1 2 $ sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' $ time strace -f -c -o trace.copy2c cp -r 2 2copy $ sync; sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' $ time strace -f -c -o trace.copy1c cp -r 1 1copy In the next step I debugged cp command (by strace) to found out in what order data are copied: So cp does it in following order (only first 4 files, because I saw that the second read from original directory is more time consuming that second read from copied directory) 100.xml 150.xml 58.xml 64.xml ... * in my example Now, take a look on filesystem blocks which are used by these files (debugfs output - ext3 fs): Original directory: BLOCKS: (0-9):63038-63047 100.xml (0-9):64091-64100 150.xml (0-9):57926-57935 58.xml (0-9):60959-60968 64.xml .... Copied directory: BLOCKS: (0-9):65791-65800 100.xml (0-9):65801-65810 150.xml (0-9):65811-65820 58.xml (0-9):65821-65830 64.xml .... As you can see, in the "Copied directory" the block are adjacent, so it means that during reading of the first file 100.xml the "Read Ahead" technique (controller or system settings) can increase performance. dd create file in order 1.xml to 1000.xml, but cp command copies it in another order (100.xml, 150.xml, 58.xml,64.xml). So when you execute: cp -r 1 1copy to copy this dir to another, the blocks of files which you are copied are not adjacent, so read of such files take more time. When you copy dir which you copied by cp command (so files are not created by dd command), then file are adjacent so creating: cp -r 2 2copy copy of the copy is faster. Summary: So to test performance python/perl you should use the same dir (or two dirs copied by cp command) and also you can use option O_DIRECT to read bypassing all kernel buffers and read data from disk directly. Please remember, that results can be different on different type of kernel, system, disk controller, system settings, fs and so on. Additions: [debugfs] [root@dhcppc3 test]# debugfs /dev/sda1 debugfs 1.39 (29-May-2006) debugfs: cd test debugfs: stat test.xml Inode: 24102 Type: regular Mode: 0644 Flags: 0x0 Generation: 3385884179 User: 0 Group: 0 Size: 4 File ACL: 0 Directory ACL: 0 Links: 1 Blockcount: 2 Fragment: Address: 0 Number: 0 Size: 0 ctime: 0x543274bf -- Mon Oct 6 06:53:51 2014 atime: 0x543274be -- Mon Oct 6 06:53:50 2014 mtime: 0x543274bf -- Mon Oct 6 06:53:51 2014 BLOCKS: (0):29935 TOTAL: 1 debugfs:
python Named tuple to dictionary
I have a named tuple class in python class Town(collections.namedtuple('Town', [ 'name', 'population', 'coordinates', 'population', 'capital', 'state_bird'])): # ... What I'd like to do is turn this into a dictionary. I'll admit python is not one of my stronger languages. The key is that I dont want it to be rigidly tied to the name or numbers of the fields I have. Is there a way to write it such that I could add more fields, or pass an entirely different named tuple in and get a dictionary. Edit: I cant not alter the original class definition as its in someone elses code. So I need to take an instance of a Town and convert it to a dictionary.
TL;DR: there's a method _asdict provided for this. Here is a demonstration of the usage: >>> fields = ['name', 'population', 'coordinates', 'capital', 'state_bird'] >>> Town = collections.namedtuple('Town', fields) >>> funkytown = Town('funky', 300, 'somewhere', 'lipps', 'chicken') >>> funkytown._asdict() OrderedDict([('name', 'funky'), ('population', 300), ('coordinates', 'somewhere'), ('capital', 'lipps'), ('state_bird', 'chicken')]) This is a documented method of namedtuples, i.e. unlike the usual convention in python the leading underscore on the method name isn't there to discourage use. Along with the other methods added to namedtuples, _make, _replace, _source, _fields, it has the underscore only to try and prevent conflicts with possible field names. Note: For some 2.7.5 < python version < 3.5.0 code out in the wild, you might see this version: >>> vars(funkytown) OrderedDict([('name', 'funky'), ('population', 300), ('coordinates', 'somewhere'), ('capital', 'lipps'), ('state_bird', 'chicken')]) For a while the documentation had mentioned that _asdict was obsolete (see here), and suggested to use the built-in method vars. That advice is now outdated; in order to fix a bug related to subclassing, the __dict__ property which was present on namedtuples has again been removed by this commit.
Why does a class definition always produce the same bytecode?
Say I do: #!/usr/bin/env python # encoding: utf-8 class A(object): pass Now I disassemble it: python -m dis test0.py 4 0 LOAD_CONST 0 ('A') 3 LOAD_NAME 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 1 (<code object A at 0x1004ebb30, file "test0.py", line 4>) 12 MAKE_FUNCTION 0 15 CALL_FUNCTION 0 18 BUILD_CLASS 19 STORE_NAME 1 (A) 22 LOAD_CONST 2 (None) 25 RETURN_VALUE Now I add some statements in the class definition: #!/usr/bin/env python # encoding: utf-8 class A(object): print 'hello' 1+1 pass And I disassemble again: 4 0 LOAD_CONST 0 ('A') 3 LOAD_NAME 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 1 (<code object A at 0x1004ebb30, file "test0.py", line 4>) 12 MAKE_FUNCTION 0 15 CALL_FUNCTION 0 18 BUILD_CLASS 19 STORE_NAME 1 (A) 22 LOAD_CONST 2 (None) 25 RETURN_VALUE What don't the new statements appear in the new bytecode?
The new statements are stored in nested bytecode. You can see in your disassembly that another code object is loaded: 9 LOAD_CONST 1 (<code object A at 0x1004ebb30, file "test0.py", line 4>) You need to inspect that code object instead. That's because the class body is executed just like a function object, and the local namespace that call produces is then used to form the class members. Demo: >>> import dis >>> def wrapper(): ... class A(object): ... pass ... >>> dis.dis(wrapper) 2 0 LOAD_CONST 1 ('A') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (<code object A at 0x104b99930, file "<stdin>", line 2>) 12 MAKE_FUNCTION 0 15 CALL_FUNCTION 0 18 BUILD_CLASS 19 STORE_FAST 0 (A) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE >>> dis.dis(wrapper.__code__.co_consts[2]) 2 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_LOCALS 7 RETURN_VALUE This is the same setup as your first sample; the class body is accessed via the wrapper.__code__.co_consts tuple, which is what the LOAD_CONST byte code refers to; the index is given as 2. Now we can add a class body: >>> def wrapper(): ... class A(object): ... print 'hello' ... 1+1 ... pass ... >>> dis.dis(wrapper) 2 0 LOAD_CONST 1 ('A') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (<code object A at 0x104b4adb0, file "<stdin>", line 2>) 12 MAKE_FUNCTION 0 15 CALL_FUNCTION 0 18 BUILD_CLASS 19 STORE_FAST 0 (A) 22 LOAD_CONST 0 (None) 25 RETURN_VALUE >>> dis.dis(wrapper.__code__.co_consts[2]) 2 0 LOAD_NAME 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_CONST 0 ('hello') 9 PRINT_ITEM 10 PRINT_NEWLINE 4 11 LOAD_CONST 2 (2) 14 POP_TOP 5 15 LOAD_LOCALS 16 RETURN_VALUE Now the class body appears; we can see the byte code that'll be executed when the class body is loaded. Of note are the LOAD_NAME and STORE_NAME bytecodes executed for each class body; those retrieve the module name and store those as a new local name __module__, so that your class will end up with a __module__ attribute once created. The LOAD_LOCALS bytecode then gathers all the local names produced in this 'function' and returns that to the caller, so that the BUILD_CLASS bytecode can use that together with the 'A' string and the object bases tuple (created with BUILD_TUPLE) can produce your new class object.
How to use NOT IN clause in sqlalchemy ORM query
how do i convert the following mysql query to sqlalchemy? SELECT * FROM `table_a` ta, `table_b` tb where 1 AND ta.id = tb.id AND ta.id not in (select id from `table_c`) so far i have this for sqlalchemy: query = session.query(table_a, table_b) query = query.filter(table_a.id == table_b.id)
Try this: subquery = session.query(table_c.id) query = query.filter(~table_a.id.in_(subquery)) Note: table_a, table_b and table_c should be mapped classes, not Table instances.
How does \v differ from \x0b or \x0c?
Typing string.whitespace gives you a string containing all whitespace characters defined by Python's string module: '\t\n\x0b\x0c\r ' Both \x0b and \x0c seem to give a vertical tab. >>> print 'first\x0bsecond' first second \v gives the same effect. How are these three different? Why does the string module use \x0b or \x0c over the simpler \v?
\v is \x0b: >>> '\v' '\x0b' but the string literal representation in Python is using the \x0b notation instead. The Python string literal representation only ever uses \n, \r and \t, everything else that is not a printable ASCII character is represented using the \xhh notation instead. \x0c is a form feed; it forces a printer to move to the next sheet of paper. You can also express it as \f in Python: >>> '\f' '\x0c' In terminals the effects of \v and \f are often the same.
You are trying to add a non-nullable field 'new_field' to userprofile without a default
I know that from Django 1.7 I don't need to use South or any other migration system, so I am just using simple command python manage.py makemigrations However, all I get is this error: You are trying to add a non-nullable field 'new_field' to userprofile without a default; we can't do that (the database needs something to populate existing rows). Here is models.py: class UserProfile(models.Model): user = models.OneToOneField(User) website = models.URLField(blank=True) new_field = models.CharField(max_length=140) What are options?
If you are in early development cycle and don't care about your current database data you can just remove it and than migrate. But first you need to clean migrations dir rm your_app/migrations/* rm db.sqlite3 python manage.py makemigrations python manage.py migrate
Parallelize apply after pandas groupby
I have used rosetta.parallel.pandas_easy to parallelize apply after group by, for example: from rosetta.parallel.pandas_easy import groupby_to_series_to_frame df = pd.DataFrame({'a': [6, 2, 2], 'b': [4, 5, 6]},index= ['g1', 'g1', 'g2']) groupby_to_series_to_frame(df, np.mean, n_jobs=8, use_apply=True, by=df.index) However, has anyone figured out how to parallelize a function that returns a dataframe? This code fails for rosetta, as expected. def tmpFunc(df): df['c'] = df.a + df.b return df df.groupby(df.index).apply(tmpFunc) groupby_to_series_to_frame(df, tmpFunc, n_jobs=1, use_apply=True, by=df.index)
This seems to work, although it really should be built in to pandas import pandas as pd from joblib import Parallel, delayed import multiprocessing def tmpFunc(df): df['c'] = df.a + df.b return df def applyParallel(dfGrouped, func): retLst = Parallel(n_jobs=multiprocessing.cpu_count())(delayed(func)(group) for name, group in dfGrouped) return pd.concat(retLst) if __name__ == '__main__': df = pd.DataFrame({'a': [6, 2, 2], 'b': [4, 5, 6]},index= ['g1', 'g1', 'g2']) print 'parallel version: ' print applyParallel(df.groupby(df.index), tmpFunc) print 'regular version: ' print df.groupby(df.index).apply(tmpFunc) print 'ideal version (does not work): ' print df.groupby(df.index).applyParallel(tmpFunc)
Cython: are typed memoryviews the modern way to type numpy arrays?
Let's say I'd like to pass a numpy array to a cdef function: cdef double mysum(double[:] arr): cdef int n = len(arr) cdef double result = 0 for i in range(n): result = result + arr[i] return result Is this the modern way to handle typing numpy arrays? Compare with this question: cython / numpy type of an array What if I want to do the following: cdef double[:] mydifference(int a, int b): cdef double[:] arr_a = np.arange(a) cdef double[:] arr_b = np.arange(b) return arr_a - arr_b This will return an error because - is not defined for memoryviews. So, should that case have been handled as follows? cdef double[:] mydifference(int a, int b): arr_a = np.arange(a) arr_b = np.arange(b) return arr_a - arr_b
I will quote from the docs the docs Memoryviews are similar to the current NumPy array buffer support (np.ndarray[np.float64_t, ndim=2]), but they have more features and cleaner syntax. This indicates that the developers of Cython consider memory views to be the modern way. Memory views offer some big advantages over the np.ndarray notation primarily in elegance and interoperability, however they are not superior in performance. Performance: First it should be noted that boundscheck sometimes fails to work with memory views resulting in artificially fast figures for memoryviews with boundscheck=True (i.e. you get fast, unsafe indexing), if you're relying on boundscheck to catch bugs this could be a nasty surprise. For the most part once compiler optimizations have been applied, memory views and numpy array notation are equal in performance, often precisely so. When there is a difference it is normally no more than 10-30%. Performance benchmark The number is the time in seconds to perform 100,000,000 operations. Smaller is faster. ACCESS+ASSIGNMENT on small array (10000 elements, 10000 times) Results for `uint8` 1) memory view: 0.0415 +/- 0.0017 2) np.ndarray : 0.0531 +/- 0.0012 3) pointer : 0.0333 +/- 0.0017 Results for `uint16` 1) memory view: 0.0479 +/- 0.0032 2) np.ndarray : 0.0480 +/- 0.0034 3) pointer : 0.0329 +/- 0.0008 Results for `uint32` 1) memory view: 0.0499 +/- 0.0021 2) np.ndarray : 0.0413 +/- 0.0005 3) pointer : 0.0332 +/- 0.0010 Results for `uint64` 1) memory view: 0.0489 +/- 0.0019 2) np.ndarray : 0.0417 +/- 0.0010 3) pointer : 0.0353 +/- 0.0017 Results for `float32` 1) memory view: 0.0398 +/- 0.0027 2) np.ndarray : 0.0418 +/- 0.0019 3) pointer : 0.0330 +/- 0.0006 Results for `float64` 1) memory view: 0.0439 +/- 0.0037 2) np.ndarray : 0.0422 +/- 0.0013 3) pointer : 0.0353 +/- 0.0013 ACCESS PERFORMANCE (100,000,000 element array): Results for `uint8` 1) memory view: 0.0576 +/- 0.0006 2) np.ndarray : 0.0570 +/- 0.0009 3) pointer : 0.0061 +/- 0.0004 Results for `uint16` 1) memory view: 0.0806 +/- 0.0002 2) np.ndarray : 0.0882 +/- 0.0005 3) pointer : 0.0121 +/- 0.0003 Results for `uint32` 1) memory view: 0.0572 +/- 0.0016 2) np.ndarray : 0.0571 +/- 0.0021 3) pointer : 0.0248 +/- 0.0008 Results for `uint64` 1) memory view: 0.0618 +/- 0.0007 2) np.ndarray : 0.0621 +/- 0.0014 3) pointer : 0.0481 +/- 0.0006 Results for `float32` 1) memory view: 0.0945 +/- 0.0013 2) np.ndarray : 0.0947 +/- 0.0018 3) pointer : 0.0942 +/- 0.0020 Results for `float64` 1) memory view: 0.0981 +/- 0.0026 2) np.ndarray : 0.0982 +/- 0.0026 3) pointer : 0.0968 +/- 0.0016 ASSIGNMENT PERFORMANCE (100,000,000 element array): Results for `uint8` 1) memory view: 0.0341 +/- 0.0010 2) np.ndarray : 0.0476 +/- 0.0007 3) pointer : 0.0402 +/- 0.0001 Results for `uint16` 1) memory view: 0.0368 +/- 0.0020 2) np.ndarray : 0.0368 +/- 0.0019 3) pointer : 0.0279 +/- 0.0009 Results for `uint32` 1) memory view: 0.0429 +/- 0.0022 2) np.ndarray : 0.0427 +/- 0.0005 3) pointer : 0.0418 +/- 0.0007 Results for `uint64` 1) memory view: 0.0833 +/- 0.0004 2) np.ndarray : 0.0835 +/- 0.0011 3) pointer : 0.0832 +/- 0.0003 Results for `float32` 1) memory view: 0.0648 +/- 0.0061 2) np.ndarray : 0.0644 +/- 0.0044 3) pointer : 0.0639 +/- 0.0005 Results for `float64` 1) memory view: 0.0854 +/- 0.0056 2) np.ndarray : 0.0849 +/- 0.0043 3) pointer : 0.0847 +/- 0.0056 Benchmark Code (Shown only for access+assignment) # cython: boundscheck=False # cython: wraparound=False # cython: nonecheck=False import numpy as np cimport numpy as np cimport cython # Change these as desired. data_type = np.uint64 ctypedef np.uint64_t data_type_t cpdef test_memory_view(data_type_t [:] view): cdef Py_ssize_t i, j, n = view.shape[0] for j in range(0, n): for i in range(0, n): view[i] = view[j] cpdef test_ndarray(np.ndarray[data_type_t, ndim=1] view): cdef Py_ssize_t i, j, n = view.shape[0] for j in range(0, n): for i in range(0, n): view[i] = view[j] cpdef test_pointer(data_type_t [:] view): cdef Py_ssize_t i, j, n = view.shape[0] cdef data_type_t * data_ptr = &view[0] for j in range(0, n): for i in range(0, n): (data_ptr + i)[0] = (data_ptr + j)[0] def run_test(): import time from statistics import stdev, mean n = 10000 repeats = 100 a = np.arange(0, n, dtype=data_type) funcs = [('1) memory view', test_memory_view), ('2) np.ndarray', test_ndarray), ('3) pointer', test_pointer)] results = {label: [] for label, func in funcs} for r in range(0, repeats): for label, func in funcs: start=time.time() func(a) results[label].append(time.time() - start) print('Results for `{}`'.format(data_type.__name__)) for label, times in sorted(results.items()): print('{: <14}: {:.4f} +/- {:.4f}'.format(label, mean(times), stdev(times))) These benchmarks indicate that on the whole there is not much difference in performance. Sometimes the np.ndarray notation is a little faster, and sometimes vice-verca. One thing to watch out for with benchmarks is that when the code is made a little bit more complicated or 'realistic' the difference suddenly vanishes, as if the compiler loses confidence to apply some very clever optimization. This can be seen with the performance of floats where there is no difference whatsoever presumably as some fancy integer optimizations can't be used. Ease of use Memory views offer significant advantages, for example you can use a memory view on numpy array, CPython array, cython array, c array and more, both present and future. There is also the simple parallel syntax for casting anything to a memory view: cdef double [:, :] data_view = <double[:256, :256]>data Memory views are great in this regard, because if you type a function as taking a memory view then it can take any of those things. This means you can write a module that doesn't have a dependency on numpy, but which can still take numpy arrays. On the other hand, np.ndarray notation results in something that is still a numpy array and you can call all the numpy array methods on it. It's not a big deal to have both a numpy array and a view on the array though: def dostuff(arr): cdef double [:] arr_view = arr # Now you can use 'arr' if you want array functions, # and arr_view if you want fast indexing Having both the array and the array view works fine in practise and I quite like the style, as it makes a clear distinction between python-level methods and c-level methods. Conclusion Performance is very nearly equal and there is certainly not enough difference for that to be a deciding factor. The numpy array notation comes closer to the ideal of accelerating python code without changing it much, as you can continue to use the same variable, while gaining full-speed array indexing. On the other hand, the memory view notation probably is the future. If you like the elegance of it, and use different kinds of data containers than just numpy arrays, there is very good reason for using memory views for consistency's sake.
Calculate weighted average using a pandas/dataframe
I have the following table. I want to calculate a weighted average grouped by each date based on the formula below. I can do this using some standard conventional code, but assuming that this data is in a pandas dataframe, is there any easier way to achieve this rather than through iteration? Date ID wt value w_avg 01/01/2012 100 0.50 60 0.791666667 01/01/2012 101 0.75 80 01/01/2012 102 1.00 100 01/02/2012 201 0.50 100 0.722222222 01/02/2012 202 1.00 80 01/01/2012 w_avg = 0.5 * ( 60/ sum(60,80,100)) + .75 * (80/ sum(60,80,100)) + 1.0 * (100/sum(60,80,100)) 01/02/2012 w_avg = 0.5 * ( 100/ sum(100,80)) + 1.0 * ( 80/ sum(100,80))
I think I would do this with two groupbys. First to calculate the "weighted average": In [11]: g = df.groupby('Date') In [12]: df.value / g.value.transform("sum") * df.wt Out[12]: 0 0.125000 1 0.250000 2 0.416667 3 0.277778 4 0.444444 dtype: float64 If you set this as a column, you can groupby over it: In [13]: df['wa'] = df.value / g.value.transform("sum") * df.wt Now the sum of this column is the desired: In [14]: g.wa.sum() Out[14]: Date 01/01/2012 0.791667 01/02/2012 0.722222 Name: wa, dtype: float64 or potentially: In [15]: g.wa.transform("sum") Out[15]: 0 0.791667 1 0.791667 2 0.791667 3 0.722222 4 0.722222 Name: wa, dtype: float64
ProgrammingError: relation "django_session" does not exist error after installing Psycopg2
I started to develop a Django base web application. Everything were fine until I installed Psycopg2 for my database which I created in PstgreSql. Now when I'm trying to open any page in my site, it throws ProgrammingError: relation "django_session" does not exist error. Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 1.7 Exception Type: ProgrammingError Exception Value: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ Exception Location: /home/alex/.virtualenvs/startDjango/local/lib/python2.7/site-packages/django/db/backends/utils.py in execute, line 65 Python Executable: /home/alex/.virtualenvs/startDjango/bin/python This is my database setting in Setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myDB', 'USER': 'alex', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } I'm developing in virtualenvs Any idea how to fix this? Thanks
If you change the database, you should create database for the new database. Use manage.py migrate command. (or manage.py syncdb if you used it for old database).
Pandas concat gives error ValueError: Plan shapes are not aligned
I am quite new to pandas, I am attempting to a set of dataframes and I am getting this error: ValueError: Plan shapes are not aligned My understanding of concat is that it will join where columns are the same, but for those that it can't find it will fill with NA. This doesn't seem to be the case here. Heres the concat statement dfs = [npo_jun_df, npo_jul_df,npo_may_df,npo_apr_df,npo_feb_df, ] alpha = pd.concat(dfs)
In case it helps, I have also hit this error when I tried to concatenate two data frames (and as of the time of writing this is the only related hit I can find on google other than the source code). I don't know whether this answer would have solved the OP's problem (since they didn't post enough information), but for me, this was caused when I tried to concat dataframe df1 with columns ['A', 'B', 'B' 'C'] (see the duplicate column headings?) with dataframe df2 with columns ['A', 'B']. Understandably the duplication caused pandas to throw a wobbly. Change df1 to ['A', 'B', 'C'] (i.e. drop one of the duplicate columns) and everything works fine.
Pip build option to use multicore
I found that pip only use single core when it compiles packages. Since some python packages takes some time to build using pip, I'd like to utilize multicore on the machine. When using Makefile, I can do that like following command: make -j4 How can I achieve same thing for pip?
Use: --install-option="--jobs=6". pip3 install --install-option="--jobs=6" PyXXX I have the same demand that use pip install to speed the compile progress. My target pkg is PySide. At first I use pip3 install pyside, it takes me nearly 30 minutes (AMD 1055T 6-cores, 10G RAM), only one core take 100% load. There are no clues in pip3 --help, but I found lots of options like pip install -u pyXXX, but I didn't know what is '-u' and this parameter was not in pip --help too. I tried 'pip3 install --help' and there came the answer: --install-option. I read the code of PySide's code and found another clue: OPTION_JOBS = has_option('jobs'), I put ipdb.set_trace() there and finally understand how to use multicore to compile by using pip install. it took me about 6 minutes.
Scapy installation fails on osx with dnet import error
Having trouble installing Scapy and it's required dependancies. I have spent some time Googling for a solution but all 'solutions' seem to affect older versions of Python, or simply do not work. Script: #!/usr/bin/python import threading import Queue import time from scapy.all import * class WorkerThread(threading.Thread) : def __init__(self, queue, tid) : threading.Thread.__init__(self) self.queue = queue self.tid = tid print 'Worker: %d' %self.tid def run(self) : total_ports = 0 while True : port = 0 try : port = self.queue.get(timeout=1) except Queue.Empty : print 'Worker %d exiting. %d ports scanned' %(self.tid, total_ports) return #Scanning begins ip = sys.argv[1] response = sr1(IP(dst=ip)/TCP(dport=port, flags='S'), verbose=False, timeout=.2) if response : if response[TCP].flags == 18 : print 'ThreadID: %d: Got port no. %d status: OPEN' %(self.tid, port) self.queue.task_done() total_ports += 1 queue = Queue.Queue() threads = [] for i in range(1, 10) : print 'Creating WorkerThread : %d' %i worker = WorkerThread(queue, i) worker.setDaemon(True) worker.start() threads.append(worker) print 'WorkerThread %d created' %i for j in range(1, 100) : queue.put(j) queue.join() for item in threads : item.join() print 'Scanning complete' Python version is 2.7.5 and path to Python verified. which python /usr/bin/python When script is executed I am getting the following error: ./multi-threaded-scanner.py Traceback (most recent call last): File "./multi-threaded-scanner.py", line 6, in <module> from scapy.all import * File "/Library/Python/2.7/site-packages/scapy/all.py", line 16, in <module> from arch import * File "/Library/Python/2.7/site-packages/scapy/arch/__init__.py", line 75, in <module> from bsd import * File "/Library/Python/2.7/site-packages/scapy/arch/bsd.py", line 12, in <module> from unix import * File "/Library/Python/2.7/site-packages/scapy/arch/unix.py", line 20, in <module> from pcapdnet import * File "/Library/Python/2.7/site-packages/scapy/arch/pcapdnet.py", line 160, in <module> import dnet ImportError: No module named dnet I can use both the Scapy and Python interactive interpreters and running import scapy in the Python interpreter produces no errors. When the script was run initially the pcapy module was missing, however I installed that and then the issue switched to dnet, which I cannot find a solution for. A similar post, seems to describe the same issue but the workarounds have no effect. Can anybody shed any more light on this issue? Commands used to install pcapy and libdnet: libdnet-1.11.tar.gz (01-19-2005) ` ~/Downloads/libdnet-1.11  chmod a+x configure ~/Downloads/libdnet-1.11  ./configure && make` Exits successfully Pcapy: Latest stable release (0.10.8), updated August 26, 2010 ~/Downloads/pcapy-0.10.8  sudo python setup.py install Password: running install running build running build_ext running build_scripts running install_lib running install_scripts changing mode of /usr/local/bin/96pings.pcap to 777 changing mode of /usr/local/bin/pcapytests.py to 777 running install_data running install_egg_info Removing /Library/Python/2.7/site-packages/pcapy-0.10.8-py2.7.egg-info Writing /Library/Python/2.7/site-packages/pcapy-0.10.8-py2.7.egg-info ~/Downloads/pcapy-0.10.8  Results for compiling with new flags ~/Downloads/libdnet-1.12  sudo CFLAGS='-arch i386 -arch x86_64' ./configure --prefix=/usr and archargs='-arch i386 -arch x86_64' make configure: WARNING: you should use --build, --host, --target configure: WARNING: you should use --build, --host, --target checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes /Users/richardcurteis/Downloads/libdnet-1.12/config/missing: Unknown `--is-lightweight' option Try `/Users/richardcurteis/Downloads/libdnet-1.12/config/missing --help' for more information configure: WARNING: 'missing' script is too old or missing checking for a thread-safe mkdir -p... config/install-sh -c -d checking for gawk... no checking for mawk... no checking for nawk... no checking for awk... awk checking whether make sets $(MAKE)... yes checking whether make supports nested variables... yes checking whether to enable maintainer-specific portions of Makefiles... no checking build system type... Invalid configuration `and': machine `and' not recognized configure: error: /bin/sh config/config.sub and failed ~/Downloads/libdnet-1.12 
EDIT - This answer below states that all mentioned issues were fixed, and provides a much simpler installation method. However, its comments suggest that although it seems to work on OS X 10.10 Yosemite and OS X 10.11 El Capitan, it might fail for certain other versions. You have not completed the installation of libdnet and its Python wrapper, as stated in Scapy's installation guide: $ wget http://libdnet.googlecode.com/files/libdnet-1.12.tgz $ tar xfz libdnet-1.12.tgz $ ./configure $ make $ sudo make install $ cd python $ python2.5 setup.py install If your system is 64 bit, use these compilation commands instead: $ CFLAGS='-arch i386 -arch x86_64' ./configure $ archargs='-arch i386 -arch x86_64' make Moreover, please verify that you've installed the correct version, i.e. 1.12 rather than 1.11. If that fails as well, try installing via macports and use its dnet.so file, as described here: $ port selfupdate $ port upgrade outdated $ port install py27-libdnet $ port install libdnet $ cp /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dnet.so /Library/Python/2.7/site-packages That link also recommends changing some code in /Library/Python/2.7/site-packages/scapy/arch/unix.py (fix OSError: Device not configured). Change line 34 from: f=os.popen("netstat -rn") # -f inet to: f=os.popen("netstat -rn | grep -v vboxnet") # -f inet as follows: def read_routes(): if scapy.arch.SOLARIS: # f=os.popen("netstat -rvn") # -f inet f=os.popen("netstat -rn | grep -v vboxnet") # -f inet If you still get the error OSError: Device not configured, then try performing similar changes to the other branches of the if clause (specifically, to its else branch), as described in this answer.
How to run bash command inside python script?
In a bash script I am trying to run python and bash command both. In some where I want to execute some bash command inside a python loop. #!/bin/bash python << END for i in range(1000): #execute‬ some bash command such as echoing i END how can I do this?
The simplest way, not recommendable: import os # ... os.system(commandString) Better use subprocess, e.g.: import subprocess # ... subprocess.call(["echo", i], shell=True) Note that shell escaping is your job with these functions and they're a security hole if passed unvalidated user input. If you do not need shell features (such as variable expansion, wildcards, ...), never use shell=True. Then you don't need to do escaping yourself etc. There is another function like subprocess.call: subprocess.check_call. It is exactly like call, just that it throws an exception if the command executed returned with a non-zero exit code. This is often feasible behaviour in scripts and utilities.
How to change the Python Interpreter that gdb uses?
I'm using ubuntu 14.04, where python3 is a default system package. I want to debug Python2.7 programs with gdb, but I seem to encounter this issue: When i'm in gdb, using the py command puts me in an interpreter, so i ran these commands in the interpreter: First I check the interpreter version: (gdb) py >import sys >print(sys.version) >end 3.4.0 (default, Apr 11 2014, 13:08:40) [GCC 4.8.2] Then I check what interpreter executable is being used (gdb) py >import sys >print(sys.executable) >end /usr/bin/python (gdb) Then in bash, I check the interpreter: 12:34]hostname ~ $ls -l /usr/bin/python lrwxrwxrwx 1 root root 9 Dec 21 2013 /usr/bin/python -> python2.7 So although gdb says it's using my 2.7 interpreter, it's actually using another one. I need a 2.7 interpreter to be able to use it with the python specific extensions that the ubuntu package 'python2.7-dbg' provides, because as far as i know there's no such package for python 3.4 yet, and even if there was, the programs that i want to debug run python 2.7 My question is how do i make it use the interpreter I want? [EDIT] Do not uninstall python3 btw. I did it on ubuntu 14.04 and it wrecked my system. Couldn't manage to get it up again. I'm currently using it with no window-manager (it's cool and 1337), but you get the idea.
So although gdb says it's using my 2.7 interpreter GDB doesn't say that. It says it's using 3.4.0, and that interpreter is linked into GDB, in the form of libpython3.4.a or libpython3.4.so. Since there is no actual Python binary involved, the (minor) bug here is that sys.executable returns /usr/bin/python. It would possibly be better for it to return /usr/bin/gdb instead. I need a 2.7 interpreter In that case, you'll have to rebuild gdb from source, after configuring it with appropriate --with-python value.
How to analyze all duplicate entries in this Pandas DataFrame?
I'd like to be able to compute descriptive statistics on data in a Pandas DataFrame, but I only care about duplicated entries. For example, let's say I have the DataFrame created by: import pandas as pd data={'key1':[1,2,3,1,2,3,2,2],'key2':[2,2,1,2,2,4,2,2],'data':[5,6,2,6,1,6,2,8]} frame=pd.DataFrame(data,columns=['key1','key2','data']) print frame key1 key2 data 0 1 2 5 1 2 2 6 2 3 1 2 3 1 2 6 4 2 2 1 5 3 4 6 6 2 2 2 7 2 2 8 As you can see, rows 0,1,3,4,6, and 7 are all duplicates (using 'key1' and 'key2'. However, if I index this DataFrame like so: frame[frame.duplicated(['key1','key2'])] I get key1 key2 data 3 1 2 6 4 2 2 1 6 2 2 2 7 2 2 8 (i.e., the 1st and 2nd rows do not show up because they are not indexed to True by the duplicated method). That is my first problem. My second problems deals with how to extract the descriptive statistics from this information. Forgetting the missing duplicate for the moment, let's say I want to compute the .min() and .max() for the duplicate entries (so that I can get a range). I can use groupby and these methods on the groupby object like so: a.groupby(['key1','key2']).min() which gives key1 key2 data key1 key2 1 2 1 2 6 2 2 2 2 1 The data I want is obviously here, but what's the best way for me to extract it? How do I index the resulting object to get what I want (which is the key1,key2,data info)?
EDIT for Pandas 0.17 or later: As the take_last argument of the duplicated() method was deprecated in favour of the new keep argument since Pandas 0.17, please refer to this answer for the correct approach: Invoke the duplicated() method with keep=False, i.e. frame.duplicated(['key1', 'key2'], keep=False). Therefore, in order to extract the required data for this specific question, the following suffices: In [81]: frame[frame.duplicated(['key1', 'key2'], keep=False)].groupby(('key1', 'key2')).min() Out[81]: data key1 key2 1 2 5 2 2 1 [2 rows x 1 columns] Interestingly enough, this change in Pandas 0.17 may be partially attributed to this question, as referred to in this issue. For versions preceding Pandas 0.17: We can play with the take_last argument of the duplicated() method: take_last: boolean, default False For a set of distinct duplicate rows, flag all but the last row as duplicated. Default is for all but the first row to be flagged. If we set take_last's value to True, we flag all but the last duplicate row. Combining this along with its default value of False, which flags all but the first duplicate row, allows us to flag all duplicated rows: In [76]: frame.duplicated(['key1', 'key2']) Out[76]: 0 False 1 False 2 False 3 True 4 True 5 False 6 True 7 True dtype: bool In [77]: frame.duplicated(['key1', 'key2'], take_last=True) Out[77]: 0 True 1 True 2 False 3 False 4 True 5 False 6 True 7 False dtype: bool In [78]: frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2']) Out[78]: 0 True 1 True 2 False 3 True 4 True 5 False 6 True 7 True dtype: bool In [79]: frame[frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2'])] Out[79]: key1 key2 data 0 1 2 5 1 2 2 6 3 1 2 6 4 2 2 1 6 2 2 2 7 2 2 8 [6 rows x 3 columns] Now we just need to use the groupby and min methods, and I believe the output is in the required format: In [81]: frame[frame.duplicated(['key1', 'key2'], take_last=True) | frame.duplicated(['key1', 'key2'])].groupby(('key1', 'key2')).min() Out[81]: data key1 key2 1 2 5 2 2 1 [2 rows x 1 columns]
How to count the Nan values in the column in Panda Data frame
I have data, in which I want to find number of NaN, so that if it is less than some threshold, I will drop this columns. I looked, but didn't able to find any function for this. there is count_values(), but it would be slow for me, because most of values are distinct and I want count of NaN only.
You can use the isnull() method and then sum to count the nan values. For one column: In [1]: s = pd.Series([1,2,3, np.nan, np.nan]) In [4]: s.isnull().sum() Out[4]: 2 For several columns, it also works: In [5]: df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]}) In [6]: df.isnull().sum() Out[6]: a 1 b 2 dtype: int64
How do you catch this exception?
This code is in django/db/models/fields.py It creates/defines an exception? class ReverseSingleRelatedObjectDescriptor(six.with_metaclass(RenameRelatedObjectDescriptorMethods)): # This class provides the functionality that makes the related-object # managers available as attributes on a model class, for fields that have # a single "remote" value, on the class that defines the related field. # In the example "choice.poll", the poll attribute is a # ReverseSingleRelatedObjectDescriptor instance. def __init__(self, field_with_rel): self.field = field_with_rel self.cache_name = self.field.get_cache_name() @cached_property def RelatedObjectDoesNotExist(self): # The exception can't be created at initialization time since the # related model might not be resolved yet; `rel.to` might still be # a string model reference. return type( str('RelatedObjectDoesNotExist'), (self.field.rel.to.DoesNotExist, AttributeError), {} ) This is in django/db/models/fields/related.py it raises the said exception above: def __get__(self, instance, instance_type=None): if instance is None: return self try: rel_obj = getattr(instance, self.cache_name) except AttributeError: val = self.field.get_local_related_value(instance) if None in val: rel_obj = None else: params = dict( (rh_field.attname, getattr(instance, lh_field.attname)) for lh_field, rh_field in self.field.related_fields) qs = self.get_queryset(instance=instance) extra_filter = self.field.get_extra_descriptor_filter(instance) if isinstance(extra_filter, dict): params.update(extra_filter) qs = qs.filter(**params) else: qs = qs.filter(extra_filter, **params) # Assuming the database enforces foreign keys, this won't fail. rel_obj = qs.get() if not self.field.rel.multiple: setattr(rel_obj, self.field.related.get_cache_name(), instance) setattr(instance, self.cache_name, rel_obj) if rel_obj is None and not self.field.null: raise self.RelatedObjectDoesNotExist( "%s has no %s." % (self.field.model.__name__, self.field.name) ) else: return rel_obj The problem is that this code: try: val = getattr(obj, attr_name) except related.ReverseSingleRelatedObjectDescriptor.RelatedObjectDoesNotExist: val = None # Does not catch the thrown exception isinstance(foo, related.FieldDoesNotExist) False except Exception as foo: print type(foo) # Catches here, not above won't catch that exception >>>print type(foo) <class 'django.db.models.fields.related.RelatedObjectDoesNotExist'> and except related.RelatedObjectDoesNotExist: Raises an AttributeError: 'module' object has no attribute 'RelatedObjectDoesNotExist' >>>isinstance(foo, related.ReverseSingleRelatedObjectDescriptor.RelatedObjectDoesNotExist) Traceback (most recent call last): File "<string>", line 1, in <fragment> TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types which is probably why.
If your related model is called Foo you can just do: except Foo.DoesNotExist: Django is amazing when its not terrifying. RelatedObjectDoesNotExist is a property that returns a type that is figured out dynamically at runtime. That type uses self.field.rel.to.DoesNotExist as a base class. According to Django documentation: ObjectDoesNotExist and DoesNotExist exception DoesNotExist The DoesNotExist exception is raised when an object is not found for the given parameters of a query. Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found and to allow you to catch a particular model class with try/except. This is the magic that makes that happen. Once the model has been built up, self.field.rel.to.DoesNotExist is the does-not-exist exception for that model.
What are the Spark transformations that causes a Shuffle?
I have trouble to find in the Spark documentation operations that causes a shuffle and operation that does not. In this list, which ones does cause a shuffle and which ones does not? Map and filter does not. However, I am not sure with the others. map(func) filter(func) flatMap(func) mapPartitions(func) mapPartitionsWithIndex(func) sample(withReplacement, fraction, seed) union(otherDataset) intersection(otherDataset) distinct([numTasks])) groupByKey([numTasks]) reduceByKey(func, [numTasks]) aggregateByKey(zeroValue)(seqOp, combOp, [numTasks]) sortByKey([ascending], [numTasks]) join(otherDataset, [numTasks]) cogroup(otherDataset, [numTasks]) cartesian(otherDataset) pipe(command, [envVars]) coalesce(numPartitions)
It is actually extremely easy to find this out, without the documentation. For any of these functions just create an RDD and call to debug string, here is one example you can do the rest on ur own. scala> val a = sc.parallelize(Array(1,2,3)).distinct scala> a.toDebugString MappedRDD[5] at distinct at <console>:12 (1 partitions) MapPartitionsRDD[4] at distinct at <console>:12 (1 partitions) **ShuffledRDD[3] at distinct at <console>:12 (1 partitions)** MapPartitionsRDD[2] at distinct at <console>:12 (1 partitions) MappedRDD[1] at distinct at <console>:12 (1 partitions) ParallelCollectionRDD[0] at parallelize at <console>:12 (1 partitions) So as you can see distinct creates a shuffle. It is also particularly important to find out this way rather than docs because there are situations where a shuffle will be required or not required for a certain function. For example join usually requires a shuffle but if you join two RDD's that branch from the same RDD spark can sometimes elide the shuffle.
Pandas to_html() truncates string contents
I have a Python Pandas DataFrame object containing textual data. My problem is, that when I use to_html() function, it truncates the strings in the output. For example: import pandas df = pandas.DataFrame({'text': ['Lorem ipsum dolor sit amet, consectetur adipiscing elit.']}) print (df.to_html()) The output is truncated at adapis... <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>text</th> </tr> </thead> <tbody> <tr> <th>0</th> <td> Lorem ipsum dolor sit amet, consectetur adipis...</td> </tr> </tbody> </table> There is a related question on SO, but it uses placeholders and search/replace functionality to postprocess the HTML, which I would like to avoid: Writing full contents of Pandas dataframe to HTML table Is there a simpler solution to this problem? I could not find anything related from the documentation.
What you are seeing is pandas truncating the output for display purposes only. The default max_colwidth value is 50 which is what you are seeing. You can set this value to whatever you desire or you can set it to -1 which effectively turns this off: pd.set_option('display.max_colwidth', -1) Although I would advise against this, it would be better to set it to something that can be displayed easily in your console or ipython. A list of the options can be found here: http://pandas.pydata.org/pandas-docs/stable/options.html
Unexpected result with += on NumPy arrays
I am creating symmetric matrices/arrays in Python with NumPy, using a standard method: x = rand(500,500) x = (x+x.T) all(x==x.T) > True Now let's be clever: x = rand(500,500) x += x.T all(x==x.T) > False Wait, what? x==x.T > array([[ True, True, True, ..., False, False, False], [ True, True, True, ..., False, False, False], [ True, True, True, ..., False, False, False], ..., [False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True]], dtype=bool) The upper left and lower right segments are symmetrical. What if I chose a smaller array? x = rand(50,50) x += x.T all(x==x.T) > True OK.... x = rand(90,90) x += x.T all(x==x.T) > True x = rand(91,91) x += x.T all(x==x.T) > False And just to be sure... x = rand(91,91) x = (x+x.T) all(x==x.T) > True Is this a bug, or am I about to learn something crazy about += and NumPy arrays?
The transpose operation returns a view of the array, which means that no new array is allocated. Which, in turn, means that you are reading and modifying the array at the same time. It's hard to tell why some sizes or some areas of the result work, but most likely it has to do with how numpy deals with array addition (maybe it makes copies of submatrices) and/or array views (maybe for small sizes it does create a new array). The x = x + x.T operation works because there you are creating a new array and then assigning to x, of course.
How to use ipdb.set_trace in a forked process
I use ipdb.set_trace() whenever I need to set a break point in my code. Right now, I'm trying to use it in a process that I've created using multiprocessing, while the code does stop, I can't type anything to continue debugging. Is there any way to get my stdin directed properly? Ideally, I would like to imagine a new console opening everytime a forked process is stopped for debugging, however I don't think this is possible.
Sometimes for debugging You can change your code to use multiprocessing.dummy . This way, no fork will be done, it will work with threads and be easier to debug. Later on (after the bug is squashed...) you can switch back to multiprocessing multiprocessing.dummy - should offer the same API as multiprocessing so its an easy change...
Django testing model with ImageField
I need to test the Photo model of my Django application. How can I mock the ImageField with a test image file? tests.py class PhotoTestCase(TestCase): def test_add_photo(self): newPhoto = Photo() newPhoto.image = # ?????? newPhoto.save() self.assertEqual(Photo.objects.count(), 1)
For future users, I've solved the problem. You can mock an ImageField with an SimpleUploadedFile instance. test.py from django.core.files.uploadedfile import SimpleUploadedFile newPhoto.image = SimpleUploadedFile(name='test_image.jpg', content=open(image_path, 'rb').read(), content_type='image/jpeg')
Python Mixed Integer Linear Programming
Are there any Mixed Integer Linear Programming(MILP) solver for Python? Can GLPK python solve MILP problem? I read that it can solve Mixed integer problem. I am very new to linear programming problem. So i am rather confused and cant really differentiate if Mixed Integer Programming is different from Mixed Integer Linear programming(MILP).
Pulp is a python modeling interface that hooks up to solvers like the open source CBC, CPLEX, Gurobi, XPRESS-MP and YALMIP(open source). You can also use Pyomo to model the optimization problem and then call an external solver, namely CPLEX, Gurobim GLPK and the AMPL solver library. You can also call GLPK from GLPK/Python, PyGLPK or PyMathProg. Yet another modelling language is CMPL, which has a python interface for MIP solvers (for linear programs only). All the above solvers solve Mixed Integer Linear Programs, while some of them (CPLEX, GUROBI and XRESS-MP for sure) can solve Mixed Integer Quadratic Programs and Quadratically constrained quadratic programs (and also conic programs but this probably goes beyond the scope of this question). MIP refers to Mixed integer programs, but it is commonly used to refer to linear programs only. To make the terminology more precise, one should always refer to MILP or MINLP (Mixed integer non-linear programming). Note that CPLEX and GUROBI have their own python APIs as well, but they (and also) XPRESS-MP are commercial products, but free for academic research. CyLP is similar to Pulp above but interfaces with the COIN-OR solvers CBC and CGL and CLP. Note that there is a big difference in the performance of commercial and free solvers: the latter are falling behind the former by a large margin. SCIP is perhaps the best non-commercial solver. Its python interface, PySCIPOpt, is here. Also, have a look at this SO question. Finally, if you are interested at a simple constraint solver (not optimization) then have a look at python-constraint. I hope this helps!
Why is the dict literal syntax preferred over the dict constructor?
Why is the Python dict constructor slower than the using literal syntax? After hot debate with my colleague, I did some comparison and got the following statistics: python2.7 -m timeit "d = dict(x=1, y=2, z=3)" 1000000 loops, best of 3: 0.47 usec per loop python2.7 -m timeit "d = {'x': 1, 'y': 2, 'z': 3}" 10000000 loops, best of 3: 0.162 usec per loop What is the reason the constructor is slower? And in what situations, if any, would it be faster?
The constructor is slower because it creates the object by calling the dict() function, whereas the compiler turns the dict literal into BUILD_MAP bytecode, saving the function call.
OperationalError, no such column. Django
I am very new to django and was able to finish the tutorial on djangoproject.com without any errors. I am now going through the Django REST framework tutorial found at http://www.django-rest-framework.org/ I am almost finished with it and just added authentication. Now I am getting : OperationalError at /snippets/ no such column: snippets_snippet.owner_id Request Method: GET Request URL: http://localhost:8000/snippets/ Django Version: 1.7 Exception Type: OperationalError Exception Value: no such column: snippets_snippet.owner_id Exception Location: /Users/taylorallred/Desktop/env/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 485 Python Executable: /Users/taylorallred/Desktop/env/bin/python Python Version: 2.7.5 Python Path: ['/Users/taylorallred/Desktop/tutorial', '/Users/taylorallred/Desktop/env/lib/python27.zip', '/Users/taylorallred/Desktop/env/lib/python2.7', '/Users/taylorallred/Desktop/env/lib/python2.7/plat-darwin', '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac', '/Users/taylorallred/Desktop/env/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/taylorallred/Desktop/env/Extras/lib/python', '/Users/taylorallred/Desktop/env/lib/python2.7/lib-tk', '/Users/taylorallred/Desktop/env/lib/python2.7/lib-old', '/Users/taylorallred/Desktop/env/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/taylorallred/Desktop/env/lib/python2.7/site-packages'] Server time: Sat, 11 Oct 2014 07:02:34 +0000 I have looked in several places on the web, not just stackoverflow for the solution, it seems like in general that the problem is with my database and need to delete it then remake it, I have done this several times, the tutorial even has me delete the database and remake it at point. Here is my models.py: from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) class Snippet(models.Model): owner = models.ForeignKey('auth.User', related_name='snippets') highlighted = models.TextField() created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ('created',) def save(self, *args, **kwargs): """ Use the 'pygments' library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = self.linenos and 'table' or False options = self.title and {'title': self.title} or {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=true, **options) self.highlighted = highlight(self.code, lexer, formatter) super(Snippet, self).save(*args, **kwargs) My serializers.py: from django.forms import widgets from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES from django.contrib.auth.models import User class SnippetSerializer(serializers.ModelSerializer): owner = serializers.Field(source='owner.username') class Meta: model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner') class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = User fields = ('id', 'username', 'snippets') My views.py: from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework import generics from django.contrib.auth.models import User from snippets.serializers import UserSerializer from rest_framework import permissions class SnippetList(generics.ListCreateAPIView): """ List all snippets, or create a new snippet. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer def pre_save(self, obj): obj.owner = self.request.user permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): """ Retrieve, update or delete a nippet instance. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer def pre_save(self, obj): obj.owner = self.request.user permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer And finally my urls.py from django.conf.urls import include from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = patterns('', url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()), url(r'^users/$', views.UserList.as_view()), url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()), ) urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ) I apologize if I posted a bunch of unnecessary info. Thanks in advance guys. Edit: DB Schema: CREATE TABLE "snippets_snippet" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "created" datetime NOT NULL, "title" varchar(100) NOT NULL, "code" text NOT NULL, "linenos" bool NOT NULL, "language" varchar(100) NOT NULL, "style" varchar(100) NOT NULL); After doing some digging I found that when deleting and recreating the db (as the tutorial says to) instead of using the makemigrations command it would not only NOT add the columns but it would also not tell me something was wrong, when running the makemigrations command it tells me: You are trying to add a non-nullable field 'highlighted' to snippet without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows) 2) Quit, and let me add a default in models.py If I comment out the highlighted section in models.py it will post the same message above but for the owner line. So it wants a default for both highlighted and owner, but I am not sure what to use as it. As well as the tutorial isn't helping me either on it.
As you went through the tutorial you must have come across the section on migration, as this was one of the major changes in django 1.7 Prior to django 1.7, the syncdb command never made any change that had a chance to destroy data currently in the database. This meant that if you did syncdb for a model, then added a new row to the model (a new column, effectively), syncdb would not affect that change in the database. So either you dropped that table by hand and then ran syncdb again (to recreate it from scratch, losing any data), or you manually entered the correct statements at the database to add only that column. Then a project came along called south which implemented migrations. This meant that there was a way to migrate forward (and reverse, undo) any changes to the database and preserve the integrity of data. In django 1.7, the functionality of south was integrated directly into django. When working with migrations, the process is a bit different. Make changes to models.py (as normal). Create a migration. This generates code to go from the current state, to the next state of your model. This is done with the makemigrations command. This command is smart enough to detect what has changed, and will create a script to effect that change to your database. Next, you apply that migration with migrate. This command applies all migrations in order. So your normal syncdb is now a two step process, python manage.py makemigrations followed by python manage.py migrate. Now, on to your specific problem: class Snippet(models.Model): owner = models.ForeignKey('auth.User', related_name='snippets') highlighted = models.TextField() created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) In this model, you have two fields highlighted and code that are required (they cannot be null). Had you added these fields from the start, there wouldn't be a problem because the table has no existing rows. However, if the table has already been created and you add a field that cannot be null, you have to define a default value to provide for any existing rows - otherwise the database will not accept your changes because they would violate the data integrity constraints. This is what the command is prompting you about. You can tell django to apply a default during migration, or you can give it a "blank" default highlighted = models.TextField(default='') in the model itself.
numpy subtract every row of matrix by vector
So I have a n x d matrix and an n x 1 vector. I'm trying to write a code to subtract every row in the matrix by the vector. I currently have a for loop that iterates through and subtracts the i-th row in the matrix by the vector. Is there a way to simply subtract an entire matrix by the vector? Thanks! Current code: for i in xrange( len( X1 ) ): X[i,:] = X1[i,:] - X2 This is where X1 is the matrix's i-th row and X2 is vector. Can I make it so that I don't need a for loop?
That works in numpy but only if the trailing axes have the same dimension. Here is an example of successfully subtracting a vector from a matrix: In [27]: print m; m.shape [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] Out[27]: (4, 3) In [28]: print v; v.shape [0 1 2] Out[28]: (3,) In [29]: m - v Out[29]: array([[0, 0, 0], [3, 3, 3], [6, 6, 6], [9, 9, 9]]) This worked because the trailing axis of both had the same dimension (3). In your case, the leading axes had the same dimension. Here is an example, using the same v as above, of how that can be fixed: In [35]: print m; m.shape [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Out[35]: (3, 4) In [36]: (m.transpose() - v).transpose() Out[36]: array([[0, 1, 2, 3], [3, 4, 5, 6], [6, 7, 8, 9]]) The rules for broadcasting axes are explained in depth here.
Effective 1-5 grams extraction with python
I have a huge files of 3,000,000 lines and each line have 20-40 words. I have to extract 1 to 5 ngrams from the corpus. My input files are tokenized plain text, e.g.: This is a foo bar sentence . There is a comma , in this sentence . Such is an example text . Currently, I am doing it as below but this don't seem to be a efficient way to extract the 1-5grams: #!/usr/bin/env python -*- coding: utf-8 -*- import io, os from collections import Counter import sys; reload(sys); sys.setdefaultencoding('utf-8') with io.open('train-1.tok.en', 'r', encoding='utf8') as srcfin, \ io.open('train-1.tok.jp', 'r', encoding='utf8') as trgfin: # Extract words from file. src_words = ['<s>'] + srcfin.read().replace('\n', ' </s> <s> ').split() del src_words[-1] # Removes the final '<s>' trg_words = ['<s>'] + trgfin.read().replace('\n', ' </s> <s> ').split() del trg_words[-1] # Removes the final '<s>' # Unigrams count. src_unigrams = Counter(src_words) trg_unigrams = Counter(trg_words) # Sum of unigram counts. src_sum_unigrams = sum(src_unigrams.values()) trg_sum_unigrams = sum(trg_unigrams.values()) # Bigrams count. src_bigrams = Counter(zip(src_words,src_words[1:])) trg_bigrams = Counter(zip(trg_words,trg_words[1:])) # Sum of bigram counts. src_sum_bigrams = sum(src_bigrams.values()) trg_sum_bigrams = sum(trg_bigrams.values()) # Trigrams count. src_trigrams = Counter(zip(src_words,src_words[1:], src_words[2:])) trg_trigrams = Counter(zip(trg_words,trg_words[1:], trg_words[2:])) # Sum of trigram counts. src_sum_trigrams = sum(src_bigrams.values()) trg_sum_trigrams = sum(trg_bigrams.values()) Is there any other way to do this more efficiently? How to optimally extract different N ngrams simultaneously? From Fast/Optimize N-gram implementations in python, essentially this: zip(*[words[i:] for i in range(n)]) when hard-coded is this for bigrams, n=2: zip(src_words,src_words[1:]) and is this for trigrams, n=3: zip(src_words,src_words[1:],src_words[2:])
If you are interested only in the most common (frequent) n-grams (which is your case I suppose), you can reuse the central idea of the Apriori algorithm. Given s_min, a minimal support which can be thought as the number of lines that a given n-gram is contained in, it efficiently searches for all such n-grams. The idea is as follows: write a query function which takes an n-gram and tests how many times it is contained in the corpus. After you have such a function prepared (may be optimized as discussed later), scan the whole corpus and get all the 1-grams, i.e. bare tokens, and select those which are contained at least s_min times. This gives you subset F1 of frequent 1-grams. Then test all the possible 2-grams by combining all the 1-grams from F1. Again, select those which hold the s_min criterion and you'll get F2. By combining all the 2-grams from F2 and selecting the frequent 3-grams, you'll get F3. Repeat for as long as Fn is non-empty. Many optimizations can be done here. When combining n-grams from Fn, you can exploit the fact that n-grams x and y may only be combined to form (n+1)-gram iff x[1:] == y[:-1] (may be checked in constant time for any n if proper hashing is used). Moreover, if you have enough RAM (for your corpus, many GBs), you can extremely speed up the query function. For each 1-gram, store a hash-set of line indices containing the given 1-gram. When combining two n-grams into an (n+1)-gram, use intersection of the two corresponding sets, obtaining a set of lines where the (n+1)-gram may be contained. The time complexity grows as s_min decreases. The beauty is that infrequent (and hence uninteresting) n-grams are completely filtered as the algorithm runs, saving computational time for the frequent ones only.
Meaning of "with" statement without "as" keyword
I'm familiar with using python's with statement as a means of ensuring finalization of an object in the event of an exception being thrown. This usually looks like with file.open('myfile.txt') as f: do stuff... which is short-hand for f = file.open('myfile.txt'): try: do stuff... finally: f.close() or whatever other finalization routine a class may present. I recently came across a piece of code dealing with OpenGL that presented this: with self.shader: (Many OpenGL commands) Note that absence of any as keyword. Does this indicate that the __enter__ and __exit__ methods of the class are still to be called, but that the object is never explicitly used in the block (i.e., it works through globals or implicit references)? Or is there some other meaning that is eluding me?
The context manager can optionally return an object, to be assigned to the identifier named by as. And it is the object returned by the __enter__ method that is assigned by as, not necessarily the context manager itself. Using as <identifier> helps when you create a new object, like the open() call does, but not all context managers are created just for the context. They can be reusable and have already been created, for example. Take a database connection. You create the database connection just once, but many database adapters let you use the connection as a context manager; enter the context and a transaction is started, exit it and the transaction is either committed (on success), or rolled back (when there is an exception): with db_connection: # do something to the database No new objects need to be created here, the context is entered with db_connection.__enter__() and exited again with db_connection.__exit__(), but we already have a reference to the connection object. Now, it could be that the connection object produces a cursor object when you enter. Now it makes sense to assign that cursor object in a local name: with db_connection as cursor: # use cursor to make changes to the database db_connection still wasn't called here, it already existed before, and we already have a reference to it. But whatever db_connection.__enter__() produced is now assigned to cursor and can be used from there on out. This is what happens with file objects; open() returns a file object, and fileobject.__enter__() returns the file object itself, so you can use the open() call in a with statement and assign a reference to the newly created object in one step, rather than two. Without that little trick, you'd have to use: f = open('myfile.txt') with f: # use `f` in the block Applying all this to your shader example; you already have a reference to self.shader. It is quite probable that self.shader.__enter__() returns a reference to self.shader again, but since you already have a perfectly serviceable reference, why create a new local for that?
Drop multiple columns pandas
I am trying to drop multiple columns (column 2 and 70 in my data set, indexed as 1 and 69 respectively) by index number in a pandas data frame with the following code: df.drop([df.columns[[1, 69]]], axis=1, inplace=True) I get the following error: TypeError: unhashable type: 'Index' And in my code the [1, 69] is highlighted and says: Expected type 'Integral', got 'list[int]' instead The following code does what I want it to do successfully, but on two lines of repetitive code (first dropping col index 69, then 1, and order does matter because dropping earlier columns changes the index of later columns). I thought I could specify more than one column index simply as a list, but perhaps I have something wrong above? df.drop([df.columns[69]], axis=1, inplace=True) df.drop([df.columns[1]], axis=1, inplace=True) Is there a way that I can do this on one line similar to the first code snippet above?
You don't need to wrap it in a list with [..], just provide the subselection of the columns index: df.drop(df.columns[[1, 69]], axis=1, inplace=True) as the index object is already regarded as list-like.
How to know the version of pip itself
which shell command gives me the actual version of pip I am using? pip gives with pip show all version of modules that are installed but excludes itself.
You can do this: pip -V or pip --version
Recursive pattern in regex
This is very much related to Regular Expression to match outer brackets however, I specifically want to know how or whether it's possible to do this regex's recursive pattern? I'm yet to find a python example using this strategy so think this ought to be a useful question! I've seen some claims that recursive patterns can be used to match balanced parenthesis, but no examples using python's regex package (Note: re does not support recursive pattern, you need to use regex). One claim is that syntax is b(?:m|(?R))*e where: b is what begins the construct, m is what can occur in the middle of the construct, and e is what can occur at the end of the construct I want to extract matches for the outer braces in the following: "{1, {2, 3}} {4, 5}" ["1, {2, 3}", "4, 5"] # desired Note that this is easy to do the same for inner braces: re.findall(r"{([^{}]*)}", "{1, {2, 3}} {4, 5}") ['2, 3', '4, 5'] (In my example I was using finditer (over match objects), see here.) So I had hoped that the following, or some variation, would work: regex.findall(r"{(:[^{}]*|?R)}", "{1, {2, 3}} {4, 5}") regex.findall(r"({(:[^{}]*|?R)})", "{1, {2, 3}} {4, 5}") regex.findall(r"({(:.*|(?R))*})", "{1, {2, 3}} {4, 5}") regex.findall(r"({(:.*)|(?R)*})", "{1, {2, 3}} {4, 5}") regex.findall(r"({(:[^{}])|(?R)})", "{1, {2, 3}} {4, 5}") but I'm scuppered by either [] or error: too much backtracking. Is it possible to extract match objects for the outer parenthesis using regex's recursion? Obviously, I run the risk of being shot down with: don't parse html with regex do this with pyparse write a proper lexer & parser e.g. using ply I want to emphasis this is about how to use the recursive pattern (which if my understanding is correct, takes us outside of regular language parsing, so may can actually be possible!). If it can be done, this ought to be a cleaner solution.
The pattern is: {((?>[^{}]+|(?R))*)} You can see this works for your example: regex.findall("{((?>[^{}]+|(?R))*)}", "{1, {2, 3}} {4, 5}") # ['1, {2, 3}', '4, 5'] Explanation: The m part needs to exclude the brackets. The use of an atomic group is needed if you want at the same time to allow a quantifier for [^{}] and to repeat the group without catastropic backtracking problems. To be more clear, if the last closing curly bracket is missing this regex engine will backtrack atomic group by atomic group instead of character by character. To drive home this point, you can make the quantifier possessive like that: {((?>[^{}]+|(?R))*+)} (or {((?:[^{}]+|(?R))*+)} since the atomic group is no more useful). The atomic group (?>....) and the possessive quantifier ?+, *+, ++ are the two sides of the same feature. This feature forbids the regex engine to backtrack inside the group of characters that becomes an "atom". The basic examples are the following two patterns that always fail for the string aaaaaaaaaab: (?>a+)ab a++ab that is: regex.match("a++ab", "aaaaaaaaaab") regex.match("(?>a+)ab", "aaaaaaaaaab") When you use (?:a+) or a+ the regex engine (by default) records (in prevision) all backtracking positions for all characters. But when you use an atomic group or a possessive quantifier, theses backtracking positions are no more recorded (except for the begining of the group). So when the backtracking mechanism occurs the last "a" character can't be given back. Only the entire group can be given back. [EDIT]: the pattern can be written in a more efficient way if you use an "unrolled" subpattern to describe the content between brackets: {([^{}]*+(?:(?R)[^{}]*)*+)}
Ansible creating a virtualenv
How do you create a virtualenv for a specific python version using ansible. Is there a command in the ansible standard library? I would like something like: - virtualenv: dest=venv python_version:/usr/bin/python3
I have at times experienced some erratic behaviour with specifying virtualenv_command (e.g.: getting a python 2.7 executable in my virtualenv even though I specified to run the command with virtualenv-3.4. If you experience that problem, you can create the virtualenv manually with the command module: - name: Manually create the initial virtualenv command: virtualenv /user/home/venvs/myenv -p python3.4 creates="/user/home/venvs/myenv" (note: by specifying creates this command will only run in the case that a virtualenv does not exist at /user/home/venvs/myenv). Then you can install your requirements as normal with the pip command: - name: Install requirements pip: requirements=/my_app/requirements.txt virtualenv=/user/home/venvs/myenv Update I've found that specifying the virtualenv_python (available in Ansible 2.0+) also seems to work in the case stated above. For example: - name: Install requirements pip: requirements: /my_app/requirements.txt virtualenv: /user/home/venvs/myenv virtualenv_python: python3.4 (with this you shouldn't need to manually create the virtualenv first)
What is under the hood of x = 'y' 'z' in Python?
If you run x = 'y' 'z' in Python, you get x set to 'yz', which means that some kind of string concatenation is occurring when Python sees multiple strings next to each other. But what kind of concatenation is this? Is it actually running 'y' + 'z' or is it running ''.join('y','z') or something else?
The Python parser interprets that as one string. This is well documented in the Lexical Analysis documentation: String literal concatenation Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". The compiled Python code sees just the one string object; you can see this by asking Python to produce an AST of such strings: >>> import ast >>> ast.dump(ast.parse("'hello' 'world'", mode='eval').body) "Str(s='helloworld')" In fact, it is the very act of building the AST that triggers the concatenation, as the parse tree is traversed, see the parsestrplus() function in the AST C source. The feature is specifically aimed at reducing the need for backslashes; use it to break up a string across physical lines when still within a logical line: print('Hello world!', 'This string is spans just one ' 'logical line but is broken across multiple physical ' 'source lines.') Multiple physical lines can implicitly be joined into one physical line by using parentheses, square brackets or curly braces. This string concatenation feature was copied from C, but Guido van Rossum is on record regretting adding it to Python. That post kicked of a long and very interesting thread, with a lot of support for removing the feature altogether.
How to add trendline in python matplotlib dot (scatter) graphs?
How could I add trendline to a dot graph drawn using matplotlib.scatter?
as explained here With help from numpy one can calculate for example a linear fitting. # plot the data itself pylab.plot(x,y,'o') # calc the trendline z = numpy.polyfit(x, y, 1) p = numpy.poly1d(z) pylab.plot(x,p(x),"r--") # the line equation: print "y=%.6fx+(%.6f)"%(z[0],z[1])
Renaming a file in PyCharm
In PyCharm 3.4, I want to rename a file on the file tree that appears on the left of the IDE. If I right-click on a file, there is an option to delete it, but not to rename it. Similarly, there is no way of renaming it from the File or Edit menus. Is there a fundamental reason why PyCharm does not allow this from within the IDE, or have I missed the correct way of doing it?
Renaming files in PyCharm is simple. You simply select Refactor > Rename when right-clicking on a file in the tree. This will open a popup where you can type in the new filename. There are additional options when renaming, such as searching for references and in comments, strings, etc.
PIP Install Numpy throws an error "ascii codec can't decode byte 0xe2"
I have a freshly installed Ubuntu on a freshly built computer. I just installed python-pip using apt-get. Now when I try to pip install Numpy and Pandas, it gives the following error. I've seen this error mentioned in quite a few places on SO and Google, but I haven't been able to find a solution. Some people mention it's a bug, some threads are just dead... What's going on? Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> load_entry_point('pip==1.5.4', 'console_scripts', 'pip')() File "/usr/lib/python2.7/dist-packages/pip/__init__.py", line 185, in main return command.main(cmd_args) File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 161, in main text = '\n'.join(complete_log) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 72: ordinal not in range(128)
I had this exact problem recently and used apt-get install python-numpy This adds numpy to your system python interpreter. I may have had to do the same for matplotlib. To use in a virtualenv, you have to create your environment using the --system-site-packages option http://www.scipy.org/install.html
Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
I was creating a virtualenv with a clean install of python 3.3, 64-bit version. (Note: I have several installs of python on my computer including WinPython but want to set up clean and small virtualenvs for several projects that I am working on. The WinPython version works just fine.) When I used pip to try to install packages, I got an error message (can include pip log if requested). Ultimately, the last lines of the error message were: File "c:\python33-b\Lib\distutils\msvc9compiler.py", line 287, in query_vcvarsall raise ValueError(str(list(result.keys()))) ValueError: ['path'] I investigated the results from the function query_vcvarsall in the msvc9compiler.py. I found out that this function was looking for the path of vcvarsall from MS Visual Studio 10 Express on my computer. It is looking for 4 components: INCLUDE=, PATH=, LIB=, and LIBPATH=. These were specific for MS VS 2010. My install sent an argument of "amd64" to this function. It did not find anything but the PATH= statement but it did find the vcvarsall.bat file. When I tricked this function to use the "x86" argument, it found all of the 4 statements and appeared as if it would run fine. I spent some time researching this on the web. I found that MS VS Express 2010 installs by default as 32-bit. One has to set it to run as 64-bit (which means it will set the statements needed above.) Apparently there was a bug and the 64-bit tools were not installed with this version. So I installed MS SDK in order to install the 64-bit tools. I then found there was a fix to this and installed that (listed below in links). There were several methods outlined to create the paths for the 64-bit VS. One was to run vcvarsall amd64 on the command line for MS VS. This resulted in a message saying the tools were not installed on my computer. These tools were to reside in the C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 directory. The file that it apparently is looking for is vcvars64.bat (or something similar). I have the directory but not the batch file. (There was a recommendation to use the x86_amd64 method but it has all of the same issues.) The second recommendation was to run setenv /x64 from the SDK command line. I ran that and it seemed to run correctly. However, when I went I tried to install packages via pip, I got the same error message. My question ultimately is how to get pip running smoothly? Just to mention, yes, I did reboot before I tested pip again after each install and attempt at fixing this. Here are some sites that helped me get this far: 1) Launching a 64-bit command prompt from Visual Studio 2010 2) Setting the Path and Environment Variables for MS VS 2010 Command-Line Builds: http://msdn.microsoft.com/en-us/library/f2ccy3wt.aspx 3) VS2010 Express and missing x64 compiler: https://social.msdn.microsoft.com/Forums/en-US/e0ef4613-d90f-4eec-90db-41339ed31367/vs2010-express-and-missing-x64-compiler?forum=Vsexpressinstall 4) FIX: Visual C++ compilers are removed when you upgrade Visual Studio 2010 Professional or Visual Studio 2010 Express to Visual Studio 2010 SP1 if Windows SDK v7.1 is installed: http://support.microsoft.com/kb/2519277 5) msvc9compiler.py: ValueError when trying to compile with VC Express: http://bugs.python.org/issue7511
Ultimately I was able to get pip running. In a nutshell (and redundant from info above) here is what I did to intall 64-bit packages for python 3.3: 1) Installed Microsoft Visual C++ 2010 Express Download Here (http://www.visualstudio.com/downloads/download-visual-studio-vs) 2) Installed Microsoft SDK 7.1 (Windows 7) (http://www.microsoft.com/en-us/download/details.aspx?id=8279) 3) Built/enabled the 64-bit tools in SDK. Go to start menu and under Microsoft Windows SDK v7.1 folder, select Windows SDK 7.1 Command Prompt. A shell will come up. Type the following command setenv /x64. 4) I installed a fix (don't know if it was ultimately needed.) (http://support.microsoft.com/kb/2519277) 5) Created a new vcvars64.bat file under C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64. Inside of that new batch file I included only the line CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64. I am assuming what this does is forces distutils to use the C++ compiler from the SDK. Pip installed correctly after this. As I understand, the C++ compiler has to be the same as that used to compile python 3.3. From my research, it seems that the SDK as installed is that same compiler but just doesn't require that the original vcvars64.bat file be present. This information came from: http://www.w7forums.com/threads/vcvarsall-bat-no-64bit-support-vcvars64-bat-missing.6606/ . Please correct me if I am creating problems down the road with this solution. Thanks.
Extracting text from a PDF file using PDFMiner in python?
Python Version 2.7 I am looking for documentation or examples on how to extract text from a PDF file using PDFMiner with Python. It looks like PDFMiner updated their API and all the relevant examples I have found contain outdated code(classes and methods have changed). The libraries I have found that make the task of extracting text from a PDF file easier are using the old PDFMiner syntax so I'm not sure how to do this. As it is, I'm just looking at source-code to see if I can figure it out.
Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016) from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO def convert_pdf_to_txt(path): rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) fp = file(path, 'rb') interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos=set() for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True): interpreter.process_page(page) text = retstr.getvalue() fp.close() device.close() retstr.close() return text PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.
Pandas - pandas.DataFrame.from_csv vs pandas.read_csv
What's the difference between: pandas.DataFrame.from_csv, doc link: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_csv.html and pandas.read_csv, doc link: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html
There is no real difference (both are based on the same underlying function), but as noted in the comments, they have some different default values (index_col is 0 or None, parse_dates is True or False for read_csv and DataFrame.from_csv respectively) and read_csv supports more arguments (in from_csv they are just not passed through). Apart from that, it is recommended to use pd.read_csv. DataFrame.from_csv exists merely for historical reasons and to keep backwards compatibility (plans are to deprecate it, see here), but all new features are only added to read_csv (as you can see in the much longer list of keyword arguments). Actually, this should be made more clear in the docs.
PyCharm: "Simplify Chained Comparison"
I have an integer value x, and I need to check if it is between a start and end values, so I write the following statements: if x >= start and x <= end: # do stuff This statement gets underlined, and the tooltip tells me that I must simplify chained comparison As far as I can tell, that comparison is about as simple as they come. What have I missed here?
In Python you can "chain" comparison operations which just means they are "and"ed together. In your case, it'd be like this: if start <= x <= end: Reference: https://docs.python.org/2/reference/expressions.html#not-in
Why does Django generate migrations for help_text and verbose_name changes?
When I change help_text or verbose_name for any of my model fields and run python manage.py makemigrations, it detects these changes and creates a new migration, say, 0002_xxxx.py. I am using PostgreSQL and I think these changes are irrelevant to my database (I wonder if a DBMS for which these changes are relevant exists at all). Why does Django generate migrations for such changes? Is it an option to ignore them? Can I apply the changes from 0002_xxxx.py to the previous migration (0001_initial.py) manually and safely delete 0002_xxxx.py? Is there a way to update previous migration automatically?
This ticket addressed the problem. If you have changed only help_text & django generates a new migration; then you can apply changes from latest migration to previous migration and delete the latest migration. Just change the help_text in the previous migration to help_text present in latest migration and delete the latest migration file. Make sure to remove corresponding *.pyc file if it is present. Otherwise an exception will be raised.
Evaluate math equations from unsafe user input in Python
I have a website where the user enters math equations (expressions) and then those equations are evaluated against data (constants) provided by the website. The math operations needed include symbols, arithmetic operations, min(), max() and some other basic functions. A sample equation could be: max(a * b + 100, a / b - 200) One could simply eval() this using Python, but as we all know this leads compromising the site. What would be the safe approach of doing math equation evaluation? What math equation parsing and evaluation engines there are for Python If one chooses to use Python itself to evaluate the expression are there any Python sandboxes which would limit the Python, so that only user supplier operators and functions are available. Full-fledged Python, like defining functions, should be totally disabled. Subprocesses are ok (see PyPy sandbox). Specially, for loops and other holes for exploiting memory and CPU usage should be closed. Any other approaches e.g. by using a command line binary (bc)?
There is a relatively easy of doing this in Python without third party packages. Using compile() to prepare a single-line Python expression to be bytecode for eval() Not running the bytecode through eval(), but instead run it in your custom opcode loop and only implement opcodes which you really need. E.g. no built-ins, no attribute access, so the sandbox cannot escaped. However there are some gotchas, like preparing for CPU exhaustion and memory exhaustion, which are not specific to this method and are issue on other approaches too. Here is a full blog post about the topic. Here is a related gist. Below is shortened sample code. """" The orignal author: Alexer / #python.fi """ import opcode import dis import sys import multiprocessing import time # Python 3 required assert sys.version_info[0] == 3, "No country for old snakes" class UnknownSymbol(Exception): """ There was a function or constant in the expression we don't support. """ class BadValue(Exception): """ The user tried to input dangerously big value. """ MAX_ALLOWED_VALUE = 2**63 class BadCompilingInput(Exception): """ The user tried to input something which might cause compiler to slow down. """ def disassemble(co): """ Loop through Python bytecode and match instructions with our internal opcodes. :param co: Python code object """ code = co.co_code n = len(code) i = 0 extended_arg = 0 result = [] while i < n: op = code[i] curi = i i = i+1 if op >= dis.HAVE_ARGUMENT: # Python 2 # oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg oparg = code[i] + code[i+1] * 256 + extended_arg extended_arg = 0 i = i+2 if op == dis.EXTENDED_ARG: # Python 2 #extended_arg = oparg*65536L extended_arg = oparg*65536 else: oparg = None # print(opcode.opname[op]) opv = globals()[opcode.opname[op].replace('+', '_')](co, curi, i, op, oparg) result.append(opv) return result # For the opcodes see dis.py # (Copy-paste) # https://docs.python.org/2/library/dis.html class Opcode: """ Base class for out internal opcodes. """ args = 0 pops = 0 pushes = 0 def __init__(self, co, i, nexti, op, oparg): self.co = co self.i = i self.nexti = nexti self.op = op self.oparg = oparg def get_pops(self): return self.pops def get_pushes(self): return self.pushes def touch_value(self, stack, frame): assert self.pushes == 0 for i in range(self.pops): stack.pop() class OpcodeArg(Opcode): args = 1 class OpcodeConst(OpcodeArg): def get_arg(self): return self.co.co_consts[self.oparg] class OpcodeName(OpcodeArg): def get_arg(self): return self.co.co_names[self.oparg] class POP_TOP(Opcode): """Removes the top-of-stack (TOS) item.""" pops = 1 def touch_value(self, stack, frame): stack.pop() class DUP_TOP(Opcode): """Duplicates the reference on top of the stack.""" # XXX: +-1 pops = 1 pushes = 2 def touch_value(self, stack, frame): stack[-1:] = 2 * stack[-1:] class ROT_TWO(Opcode): """Swaps the two top-most stack items.""" pops = 2 pushes = 2 def touch_value(self, stack, frame): stack[-2:] = stack[-2:][::-1] class ROT_THREE(Opcode): """Lifts second and third stack item one position up, moves top down to position three.""" pops = 3 pushes = 3 direct = True def touch_value(self, stack, frame): v3, v2, v1 = stack[-3:] stack[-3:] = [v1, v3, v2] class ROT_FOUR(Opcode): """Lifts second, third and forth stack item one position up, moves top down to position four.""" pops = 4 pushes = 4 direct = True def touch_value(self, stack, frame): v4, v3, v2, v1 = stack[-3:] stack[-3:] = [v1, v4, v3, v2] class UNARY(Opcode): """Unary Operations take the top of the stack, apply the operation, and push the result back on the stack.""" pops = 1 pushes = 1 class UNARY_POSITIVE(UNARY): """Implements TOS = +TOS.""" def touch_value(self, stack, frame): stack[-1] = +stack[-1] class UNARY_NEGATIVE(UNARY): """Implements TOS = -TOS.""" def touch_value(self, stack, frame): stack[-1] = -stack[-1] class BINARY(Opcode): """Binary operations remove the top of the stack (TOS) and the second top-most stack item (TOS1) from the stack. They perform the operation, and put the result back on the stack.""" pops = 2 pushes = 1 class BINARY_POWER(BINARY): """Implements TOS = TOS1 ** TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] print(TOS1, TOS) if abs(TOS1) > BadValue.MAX_ALLOWED_VALUE or abs(TOS) > BadValue.MAX_ALLOWED_VALUE: raise BadValue("The value for exponent was too big") stack[-2:] = [TOS1 ** TOS] class BINARY_MULTIPLY(BINARY): """Implements TOS = TOS1 * TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 * TOS] class BINARY_DIVIDE(BINARY): """Implements TOS = TOS1 / TOS when from __future__ import division is not in effect.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 / TOS] class BINARY_MODULO(BINARY): """Implements TOS = TOS1 % TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 % TOS] class BINARY_ADD(BINARY): """Implements TOS = TOS1 + TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 + TOS] class BINARY_SUBTRACT(BINARY): """Implements TOS = TOS1 - TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 - TOS] class BINARY_FLOOR_DIVIDE(BINARY): """Implements TOS = TOS1 // TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 // TOS] class BINARY_TRUE_DIVIDE(BINARY): """Implements TOS = TOS1 / TOS when from __future__ import division is in effect.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 / TOS] class BINARY_LSHIFT(BINARY): """Implements TOS = TOS1 << TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 << TOS] class BINARY_RSHIFT(BINARY): """Implements TOS = TOS1 >> TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 >> TOS] class BINARY_AND(BINARY): """Implements TOS = TOS1 & TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 & TOS] class BINARY_XOR(BINARY): """Implements TOS = TOS1 ^ TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 ^ TOS] class BINARY_OR(BINARY): """Implements TOS = TOS1 | TOS.""" def touch_value(self, stack, frame): TOS1, TOS = stack[-2:] stack[-2:] = [TOS1 | TOS] class RETURN_VALUE(Opcode): """Returns with TOS to the caller of the function.""" pops = 1 final = True def touch_value(self, stack, frame): value = stack.pop() return value class LOAD_CONST(OpcodeConst): """Pushes co_consts[consti] onto the stack.""" # consti pushes = 1 def touch_value(self, stack, frame): # XXX moo: Validate type value = self.get_arg() assert isinstance(value, (int, float)) stack.append(value) class LOAD_NAME(OpcodeName): """Pushes the value associated with co_names[namei] onto the stack.""" # namei pushes = 1 def touch_value(self, stack, frame): # XXX moo: Get name from dict of valid variables/functions name = self.get_arg() if name not in frame: raise UnknownSymbol("Does not know symbol {}".format(name)) stack.append(frame[name]) class CALL_FUNCTION(OpcodeArg): """Calls a function. The low byte of argc indicates the number of positional parameters, the high byte the number of keyword parameters. On the stack, the opcode finds the keyword parameters first. For each keyword argument, the value is on top of the key. Below the keyword parameters, the positional parameters are on the stack, with the right-most parameter on top. Below the parameters, the function object to call is on the stack. Pops all function arguments, and the function itself off the stack, and pushes the return value.""" # argc pops = None pushes = 1 def get_pops(self): args = self.oparg & 0xff kwargs = (self.oparg >> 8) & 0xff return 1 + args + 2 * kwargs def touch_value(self, stack, frame): argc = self.oparg & 0xff kwargc = (self.oparg >> 8) & 0xff assert kwargc == 0 if argc > 0: args = stack[-argc:] stack[:] = stack[:-argc] else: args = [] func = stack.pop() assert func in frame.values(), "Uh-oh somebody injected bad function. This does not happen." result = func(*args) stack.append(result) def check_for_pow(expr): """ Python evaluates power operator during the compile time if its on constants. You can do CPU / memory burning attack with ``2**999999999999999999999**9999999999999``. We mainly care about memory now, as we catch timeoutting in any case. We just disable pow and do not care about it. """ if "**" in expr: raise BadCompilingInput("Power operation is not allowed") def _safe_eval(expr, functions_and_constants={}, check_compiling_input=True): """ Evaluate a Pythonic math expression and return the output as a string. The expr is limited to 1024 characters / 1024 operations to prevent CPU burning or memory stealing. :param functions_and_constants: Supplied "built-in" data for evaluation """ # Some safety checks assert len(expr) < 1024 # Check for potential bad compiler input if check_compiling_input: check_for_pow(expr) # Compile Python source code to Python code for eval() code = compile(expr, '', 'eval') # Dissect bytecode back to Python opcodes ops = disassemble(code) assert len(ops) < 1024 stack = [] for op in ops: value = op.touch_value(stack, functions_and_constants) return value