copied code over from ipython notebook