def test_create_nbextensions(self): with TemporaryDirectory() as ipdir: install_nbextension(self.src, ipython_dir=ipdir) self.assert_installed( pjoin(basename(self.src), u'ƒile'), ipdir )
def __init__(self, install_assets=False, *args, **kwargs): ''' Each time an instance is created: - if the nbextension is not installed... - copy all assets in `static` to the current profile's nbextensions - automagically load any css ''' if install_assets or not check_nbextension([nbextension]): # copy the static files to a namespaced location in `nbextensions` install_nbextension(static, user=True) # magically-named files css/SomeWidgetView.css magic_style = os.path.join(static, 'css', '%s.css' % self._view_name) styles = getattr(self, '_view_styles', []) if os.path.exists(magic_style): styles.append('css/%s.css' % self._view_name) styles = [ '/nbextensions/%s/%s' % (nbextension, style) for style in styles ] # tell the front-end to request the assets display(Javascript('', css=styles)) # always call the parent constructor! super(InstallerMixin, self).__init__(*args, **kwargs)
def __init__(self, install_assets=False, *args, **kwargs): ''' Each time an instance is created: - if the nbextension is not installed... - copy all assets in `static` to the current profile's nbextensions - automagically load any css ''' if install_assets or not check_nbextension([nbextension]): # copy the static files to a namespaced location in `nbextensions` install_nbextension(static) # magically-named files css/SomeWidgetView.css magic_style = os.path.join(static, 'css', '%s.css' % self._view_name) styles = getattr(self, '_view_styles', []) if os.path.exists(magic_style): styles.append('css/%s.css' % self._view_name) styles = [ '/nbextensions/%s/%s' % (nbextension, style) for style in styles ] # tell the front-end to request the assets display(Javascript('', css=styles)) # always call the parent constructor! super(InstallerMixin, self).__init__(*args, **kwargs)
def test_quiet(self): stdout = StringIO() stderr = StringIO() with mock.patch.object(sys, "stdout", stdout), mock.patch.object(sys, "stderr", stderr): install_nbextension(self.src, verbose=0) self.assertEqual(stdout.getvalue(), "") self.assertEqual(stderr.getvalue(), "")
def __init__(self, *args, **kwargs): ''' This will be called each time an implementing class is instantiated ''' # as a good citizen extension = os.path.basename(self._view_static) # copy the static files to a namespaced location in `nbextensions` install_nbextension(os.path.abspath(self._view_static), verbose=0) # this assumes your extension takes care of its own dependencies... script = 'IPython.load_extensions("%s/%s");' % ( extension, self._view_module ) # again, assume that you have put the style in the extension's folder styles = [] try: styles = ['/nbextensions/%s/%s.css' % (extension, self._view_style)] except: pass # tell the front-end to request the assets display(Javascript(script, css=styles)) # always call the parent constructor! super(InstallerMixin, self).__init__(*args, **kwargs)
def _install_js(): install_nbextension(EXT_DIR, overwrite=True, user=True, verbose=2) cm = ConfigManager() print('Enabling extension for notebook') cm.update("notebook", {"load_extensions": {"nbexamples/submit-example-button": True}}) cm.update("tree", {"load_extensions": {"nbexamples/main": True}})
def test_create_nbextensions_system(self): with TemporaryDirectory() as td: nbextensions.SYSTEM_NBEXTENSIONS_INSTALL_DIR = self.system_nbext = pjoin( td, u'nbextensions') install_nbextension(self.src, user=False) self.assert_installed(pjoin(basename(self.src), u'ƒile'), user=False)
def test_install_zip(self): path = pjoin(self.src, "myjsext.zip") with zipfile.ZipFile(path, 'w') as f: f.writestr("a.js", b"b();") f.writestr("foo/a.js", b"foo();") install_nbextension(path) self.assert_installed("a.js") self.assert_installed(pjoin("foo", "a.js"))
def _install_js(): install_nbextension(EXT_DIR, destination='nbexamples', overwrite=True, user=True, verbose=2) cm = ConfigManager() print('Enabling extension for notebook') cm.update("notebook", {"load_extensions": {"nbexamples/submit-example-button": True}}) cm.update("tree", {"load_extensions": {"nbexamples/main": True}})
def test_install_different_name(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) dest_f = u'ƒile.js' touch(src) install_nbextension({dest_f: src}) self.assert_installed(dest_f)
def test_create_nbextensions_user(self): with TemporaryDirectory() as td: self.ipdir = ipdir = pjoin(td, u'ipython') install_nbextension(self.src, user=True) self.assert_installed( pjoin(basename(self.src), u'ƒile'), user=True )
def test_create_ipython_dir(self): """install_nbextension when ipython_dir doesn't exist""" with TemporaryDirectory() as td: ipdir = pjoin(td, u'ipython') install_nbextension(self.src, ipython_dir=ipdir) self.assert_path_exists(ipdir) for file in self.files: self.assert_installed(pjoin(basename(self.src), file), ipdir)
def install(use_symlink=False, profile="default"): # Install the livereveal code. install_nbextension(livereveal_dir, symlink=use_symlink, overwrite=use_symlink) # Enable the extension in the given profile. profile_dir = locate_profile(profile) custom_js = os.path.join(profile_dir, "static", "custom", "custom.js") add_if_not_in_custom_js(custom_js, "LIVE_REVEAL", custom_js_entry)
def prepare_js(): """ This is needed to map js/css to the nbextensions folder """ pkgdir = os.path.join(os.path.dirname(__file__), "static") nbextensions.install_nbextension(pkgdir, symlink=True, user=True, destination='phyui')
def test_create_nbextensions_system(self): with TemporaryDirectory() as td: nbextensions.SYSTEM_NBEXTENSIONS_INSTALL_DIR = self.system_nbext = pjoin(td, u'nbextensions') install_nbextension(self.src, user=False) self.assert_installed( pjoin(basename(self.src), u'ƒile'), user=False )
def test_quiet(self): stdout = StringIO() stderr = StringIO() with mock.patch.object(sys, 'stdout', stdout), \ mock.patch.object(sys, 'stderr', stderr): install_nbextension(self.src, verbose=0) self.assertEqual(stdout.getvalue(), '') self.assertEqual(stderr.getvalue(), '')
def _install_js(): install_nbextension(EXT_DIR, destination='nbshared', overwrite=True, user=True, verbose=2) cm = ConfigManager() print('Enabling extension for notebook') cm.update("notebook", {"load_extensions": {"nbshared/submit-shared-button": True}}) cm.update("tree", {"load_extensions": {"nbshared/main": True}})
def test_create_ipython_dir(self): """install_nbextension when ipython_dir doesn't exist""" with TemporaryDirectory() as td: self.ipdir = ipdir = pjoin(td, u"ipython") install_nbextension(self.src, user=True) self.assert_dir_exists(ipdir) for file in self.files: self.assert_installed(pjoin(basename(self.src), file), ipdir)
def _prepare_js(self): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, '../js') install_nbextension(op.join(jsdir, 'processing.min.js'), user=True) ipythomic_js = op.join(jsdir, 'ipythomic.js') with open(ipythomic_js, 'r') as f: script = f.read() display(Javascript(script))
def test_install_destination_bad(self): with TemporaryDirectory() as d: zf = u"ƒ.zip" zsrc = pjoin(d, zf) with zipfile.ZipFile(zsrc, "w") as z: z.writestr("a.js", b"b();") with self.assertRaises(ValueError): install_nbextension(zsrc, destination="foo")
def __init__(self, *args, **kwargs): ''' Each time an instance is created: - copy ALL assets in `static` to the current profile's nbextensions - ensure that the view module has been required It also doesn't fix the race condition that can occur from a cell output being displayed that uses a widget before it has been required. This is inefficient, but can't be better until requirejs is used instead of WidgetManager. ''' # copy the static files to a namespaced location in `nbextensions` install_nbextension(static, verbose=0) # strip off the namespace try: view_ns, view_name = self._view_name.split("/") except: raise Exception("%s did not match the pattern `namespace/view`" % ( self._view_name )) # magically-named files js/SomeWidgetView.js and css/SomeWidgetView.css magic_module = os.path.join(static, 'js', '%s.js' % view_name) magic_style = os.path.join(static, 'css', '%s.css' % view_name) view_module = None if os.path.exists(magic_module): view_module = 'js/%s' % view_name view_module = getattr(self, '_view_module', view_module) if view_module is None: raise Exception( 'No JavaScript found for %(name)s: i.e. js/%(name)s.js' % { "name": view_name }) styles = getattr(self, '_view_styles', []) if os.path.exists(magic_style): styles.append('css/%s.css' % view_name) styles = [ '/nbextensions/%s/%s' % (nbextension, style) for style in styles ] # tell the front-end to request the assets display( Javascript('IPython.load_extensions("%s/%s");' % ( nbextension, view_module ), css=styles) ) # always call the parent constructor! super(InstallerMixin, self).__init__(*args, **kwargs)
def install(use_symlink=False, profile=default_profile, enable=True): # Install the livereveal code. install_nbextension(livereveal_dir, symlink=use_symlink, overwrite=use_symlink, user=True) if enable: # Enable the extension in the given profile. cm = get_config_manager(profile) cm.update('notebook', {"load_extensions": {"livereveal/main": True}})
def test_install_destination_bad(self): with TemporaryDirectory() as d: zf = u'ƒ.zip' zsrc = pjoin(d, zf) with zipfile.ZipFile(zsrc, 'w') as z: z.writestr("a.js", b"b();") with self.assertRaises(ValueError): install_nbextension(zsrc, destination='foo')
def _toJSON(mol): """For IPython notebook, renders 3D webGL objects.""" if not ipython_3d or not mol.GetNumConformers(): return None conf = mol.GetConformer() if not conf.Is3D(): return None mol = Chem.Mol(mol) try: Chem.Kekulize(mol) except: mol = Chem.Mol(mol) size = molSize_3d # center the molecule: atomps = numpy.array([list(conf.GetAtomPosition(x)) for x in range(mol.GetNumAtoms())]) avgP = numpy.average(atomps, 0) atomps -= avgP # If the javascript lib has not yet been loaded, do so. # IPython >=2.0 does this by copying the file into ~/.ipython/nbextensions # Fallback support provided by grabbing js from remote server local_path = "/nbextensions/imolecule.min" remote_path = ("https://raw.githubusercontent.com/patrickfuller/" "imolecule/master/build/imolecule.min") filepath = os.path.normpath(os.path.dirname(__file__)) install_nbextension([os.path.join(filepath, "imolecule.min.js")], verbose=0) # Convert the relevant parts of the molecule into JSON for rendering atoms = [{"element": atom.GetSymbol(), "location": list(atomps[atom.GetIdx()])} for atom in mol.GetAtoms()] bonds = [{"atoms": [bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()], "order": int(bond.GetBondTypeAsDouble())} for bond in mol.GetBonds()] mol = {"atoms": atoms, "bonds": bonds} json_mol = json.dumps(mol, separators=(",", ":")) div_id = uuid.uuid4() return """<div id="molecule_%s"></div> <script type="text/javascript"> requirejs.config({paths: {imolecule: ['%s', '%s']}}); require(['imolecule'], function () { var $d = $('#molecule_%s'); $d.width(%d); $d.height(%d); $d.imolecule = jQuery.extend({}, imolecule); $d.imolecule.create($d, {drawingType: '%s', cameraType: '%s'}); $d.imolecule.draw(%s); }); </script>""" % (div_id, local_path, remote_path, div_id, size[0], size[1], drawing_type_3d, camera_type_3d, json_mol)
def test_check_nbextension(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) touch(src) install_nbextension(src) assert check_nbextension(f, self.ipdir) assert check_nbextension([f], self.ipdir) assert not check_nbextension([f, pjoin('dne', f)], self.ipdir)
def _prepare_js(): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, '../../html/static/js/') install_nbextension([op.join(jsdir, 'vispy.min.js'), op.join(jsdir, 'jquery.mousewheel.min.js')]) backend_path = op.join(jsdir, 'webgl-backend.js') with open(backend_path, 'r') as f: script = f.read() display(Javascript(script))
def install(use_symlink=False, profile='default'): # Install the livereveal code. install_nbextension(livereveal_dir, symlink=use_symlink, overwrite=use_symlink) # Enable the extension in the given profile. profile_dir = locate_profile(profile) custom_js = os.path.join(profile_dir, 'static', 'custom', 'custom.js') add_if_not_in_custom_js(custom_js, 'LIVE_REVEAL', custom_js_entry)
def test_install_symlink(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) touch(src) install_nbextension(src, symlink=True) dest = pjoin(self.ipdir, u'nbextensions', f) assert os.path.islink(dest) link = os.readlink(dest) self.assertEqual(link, src)
def install(extension, use_symlink=False, profile='default', enable=True): # Install the livereveal code. ext_dir = os.path.join(base_dir, extension) install_nbextension(ext_dir, symlink=use_symlink, overwrite=use_symlink, user=True) # Enable/Disable the extension in the given profile. profile_dir = locate_profile(profile) cm = ConfigManager(profile_dir=profile_dir) cm.update('notebook', {"load_extensions": {extension + "/main": enable}})
def _prepare_js(force=False): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, "../../html/static/js/") # Make sure the JS files are installed to user directory (new argument # in IPython 3.0). if IPYTHON_MAJOR_VERSION >= 3: kwargs = {"user": True} else: kwargs = {} install_nbextension(jsdir, overwrite=force, destination="vispy", symlink=(os.name != "nt"), **kwargs)
def test_check_nbextension(self): with TemporaryDirectory() as d: f = u"ƒ.js" src = pjoin(d, f) touch(src) install_nbextension(src, user=True) assert check_nbextension(f, user=True) assert check_nbextension([f], user=True) assert not check_nbextension([f, pjoin("dne", f)], user=True)
def test_check_nbextension(self): with TemporaryDirectory() as d: f = u'ƒ.js' src = pjoin(d, f) touch(src) install_nbextension(src, user=True) nbext = pjoin(self.ipdir, u'nbextensions') assert check_nbextension(f, nbext) assert check_nbextension([f], nbext) assert not check_nbextension([f, pjoin('dne', f)], nbext)
def test_install_symlink_destination(self): with TemporaryDirectory() as d: f = u'ƒ.js' flink = u'ƒlink.js' src = pjoin(d, f) touch(src) install_nbextension(src, symlink=True, destination=flink) dest = pjoin(self.system_nbext, flink) assert os.path.islink(dest) link = os.readlink(dest) self.assertEqual(link, src)
def _prepare_js(force=False): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, '../../html/static/js/') # Make sure the JS files are installed to user directory (new argument # in IPython 3.0). if IPYTHON_MAJOR_VERSION >= 3: kwargs = {'user': True} else: kwargs = {} install_nbextension(jsdir, overwrite=force, destination='wetapy', symlink=(os.name != 'nt'), **kwargs)
def test_install_symlink_destination(self): with TemporaryDirectory() as d: f = u"ƒ.js" flink = u"ƒlink.js" src = pjoin(d, f) touch(src) install_nbextension(src, symlink=True, destination=flink) dest = pjoin(self.system_nbext, flink) assert os.path.islink(dest) link = os.readlink(dest) self.assertEqual(link, src)
def test_install_url(self): def fake_urlretrieve(url, dest): touch(dest) save_urlretrieve = nbextensions.urlretrieve nbextensions.urlretrieve = fake_urlretrieve try: install_nbextension("http://example.com/path/to/foo.js") self.assert_installed("foo.js") install_nbextension("https://example.com/path/to/another/bar.js") self.assert_installed("bar.js") finally: nbextensions.urlretrieve = save_urlretrieve
def __init__(self, *args, **kwargs): ''' Each time an instance is created: - copy ALL assets in `static` to the current profile's nbextensions - ensure that the view module has been required It also doesn't fix the race condition that can occur from a cell output being displayed that uses a widget before it has been required. This is inefficient, but can't be better until requirejs is used instead of WidgetManager. ''' # copy the static files to a namespaced location in `nbextensions` install_nbextension(static, verbose=0) # strip off the namespace try: view_ns, view_name = self._view_name.split("/") except: raise Exception("%s did not match the pattern `namespace/view`" % (self._view_name)) # magically-named files js/SomeWidgetView.js and css/SomeWidgetView.css magic_module = os.path.join(static, 'js', '%s.js' % view_name) magic_style = os.path.join(static, 'css', '%s.css' % view_name) view_module = None if os.path.exists(magic_module): view_module = 'js/%s' % view_name view_module = getattr(self, '_view_module', view_module) if view_module is None: raise Exception( 'No JavaScript found for %(name)s: i.e. js/%(name)s.js' % {"name": view_name}) styles = getattr(self, '_view_styles', []) if os.path.exists(magic_style): styles.append('css/%s.css' % view_name) styles = [ '/nbextensions/%s/%s' % (nbextension, style) for style in styles ] # tell the front-end to request the assets display( Javascript('IPython.load_extensions("%s/%s");' % (nbextension, view_module), css=styles)) # always call the parent constructor! super(InstallerMixin, self).__init__(*args, **kwargs)
def test_install_symlink_bad(self): with self.assertRaises(ValueError): install_nbextension("http://example.com/foo.js", symlink=True) with TemporaryDirectory() as d: zf = u'ƒ.zip' zsrc = pjoin(d, zf) with zipfile.ZipFile(zsrc, 'w') as z: z.writestr("a.js", b"b();") with self.assertRaises(ValueError): install_nbextension(zsrc, symlink=True)
def _prepare_js(): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, '../../html/static/js/') install_nbextension([ op.join(jsdir, 'vispy.min.js'), op.join(jsdir, 'jquery.mousewheel.min.js') ]) backend_path = op.join(jsdir, 'webgl-backend.js') with open(backend_path, 'r') as f: script = f.read() display(Javascript(script))
def install(use_symlink=False, profile='default', enable=True): # Install the livereveal code. install_nbextension(livereveal_dir, symlink=use_symlink, overwrite=use_symlink, user=True) if enable: # Enable the extension in the given profile. profile_dir = locate_profile(profile) cm = ConfigManager(profile_dir=profile_dir) cm.update('notebook', {"load_extensions": {"livereveal/main": True}})
def test_overwrite_dir(self): with TemporaryDirectory() as src: base = basename(src) fname = u'ƒ.js' touch(pjoin(src, fname)) install_nbextension(src) self.assert_installed(pjoin(base, fname)) os.remove(pjoin(src, fname)) fname2 = u'∂.js' touch(pjoin(src, fname2)) install_nbextension(src, overwrite=True) self.assert_installed(pjoin(base, fname2)) self.assert_not_installed(pjoin(base, fname))
def test_overwrite_dir(self): with TemporaryDirectory() as src: base = basename(src) fname = u"ƒ.js" touch(pjoin(src, fname)) install_nbextension(src) self.assert_installed(pjoin(base, fname)) os.remove(pjoin(src, fname)) fname2 = u"∂.js" touch(pjoin(src, fname2)) install_nbextension(src, overwrite=True) self.assert_installed(pjoin(base, fname2)) self.assert_not_installed(pjoin(base, fname))
def test_overwrite_dir(self): with TemporaryDirectory() as src: # src = py3compat.cast_unicode_py2(src) base = basename(src) fname = u'ƒ.js' touch(pjoin(src, fname)) install_nbextension(src) self.assert_installed(pjoin(base, fname)) os.remove(pjoin(src, fname)) fname2 = u'∂.js' touch(pjoin(src, fname2)) install_nbextension(src, overwrite=True) self.assert_installed(pjoin(base, fname2)) self.assert_not_installed(pjoin(base, fname))
def test_install_tar(self): def _add_file(f, fname, buf): info = tarfile.TarInfo(fname) info.size = len(buf) f.addfile(info, BytesIO(buf)) for i, ext in enumerate((".tar.gz", ".tgz", ".tar.bz2")): path = pjoin(self.src, "myjsext" + ext) with tarfile.open(path, 'w') as f: _add_file(f, "b%i.js" % i, b"b();") _add_file(f, "foo/b%i.js" % i, b"foo();") install_nbextension(path) self.assert_installed("b%i.js" % i) self.assert_installed(pjoin("foo", "b%i.js" % i))
def test_skip_old_file(self): with TemporaryDirectory() as d: fname = u'ƒ.js' src = pjoin(d, fname) mtime = touch(src) install_nbextension(src) self.assert_installed(fname) dest = pjoin(self.ipdir, u'nbextensions', fname) old_mtime = os.stat(dest).st_mtime mtime = touch(src, mtime - 100) install_nbextension(src) new_mtime = os.stat(dest).st_mtime self.assertEqual(new_mtime, old_mtime)
def enable_notebook(): """Enable IPython notebook widgets to be displayed. This function should be called before using TrajectoryWidget. """ libs = ['iview.js','surface.min.js','objexporter.js', 'TrackballControls.js', 'filesaver.js', 'base64-arraybuffer.js', 'context.js', 'molecularviewer.js', 'three.min.js', 'jquery-ui.min.js'] fns = [resource_filename('mdtraj', os.path.join('html', 'static', f)) for f in libs] install_nbextension(fns, verbose=0) display(_REQUIRE_CONFIG) widgets = ['widget_trajectory.js', 'widget_imagebutton.js', 'widget_gab.js'] for fn in widgets: fn = resource_filename('mdtraj', os.path.join('html', 'static', fn)) display(Javascript(filename=fn))
def test_overwrite_file(self): with TemporaryDirectory() as d: fname = u'ƒ.js' src = pjoin(d, fname) with open(src, 'w') as f: f.write('first') mtime = touch(src) dest = pjoin(self.ipdir, u'nbextensions', fname) install_nbextension(src) with open(src, 'w') as f: f.write('overwrite') mtime = touch(src, mtime - 100) install_nbextension(src, overwrite=True) with open(dest) as f: self.assertEqual(f.read(), 'overwrite')