Example #1
0
    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)
Example #2
0
    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 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)
Example #4
0
    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)
Example #5
0
    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)
Example #6
0
    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)
Example #7
0
    def _repr_html_(self):
        """For IPython notebook, renders 3D pybel.Molecule webGL objects."""

        # Returning None defers to _repr_svg_
        if not ipython_3d:
            return None

        # If the javascript files have not yet been loaded, do so
        # IPython >=2.0 does this by copying into ~/.ipython/nbextensions
        filename = "imolecule.min.js"
        local_path = os.path.join("nbextensions", filename)
        remote_path = ("https://rawgit.com/openbabel/contributed/master/web/"
                       "imolecule/build/imolecule.min.js")

        # Try using IPython >=2.0 to install js locally from website
        try:
            from IPython.html.nbextensions import (install_nbextension,
                                                   check_nbextension)
            if not check_nbextension(local_path):
                install_nbextension(remote_path, verbose=0)
        except:
            pass

        # Some exposed parameters. Leaving this unfunctionalized for now.
        size = (400, 300)
        drawing_type = "ball and stick"
        camera_type = "perspective"

        # Clone molecule
        mol = self.clone

        # Infer structure in cases where the input format has no specification
        if not mol.OBMol.HasNonZeroCoords():
            mol.make3D()
        mol.OBMol.Center()

        # Convert the relevant parts of `self` into JSON for rendering
        table = ob.OBElementTable()
        atoms = [{"element": table.GetSymbol(atom.atomicnum),
                  "location": atom.coords}
                 for atom in mol.atoms]
        bonds = [{"atoms": [bond.GetBeginAtom().GetIndex(),
                            bond.GetEndAtom().GetIndex()],
                  "order": bond.GetBondOrder()}
                 for bond in ob.OBMolBondIter(mol.OBMol)]
        mol = {"atoms": atoms, "bonds": bonds}
        if hasattr(mol, "unitcell"):
            uc = mol.unitcell
            mol["unitcell"] = [[v.GetX(), v.GetY(), v.GetZ()]
                               for v in uc.GetCellVectors()]
            # Support for previous naming scheme
            mol["periodic_connections"] = mol["unitcell"]
        json_mol = json.dumps(mol, separators=(",", ":"))

        # Try using local copy. If that fails, use remote copy.
        div_id = uuid.uuid4()
        return """<div id="molecule_%s"></div>
               <script type="text/javascript">
               requirejs.config({baseUrl: "/",
                                 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);

                   $d.resizable({
                       aspectRatio: %d / %d,
                       resize: function (evt, ui) {
                           $d.imolecule.renderer.setSize(ui.size.width,
                                                         ui.size.height);
                       }
                   });
               });
               </script>""" % (div_id, local_path[:-3], remote_path[:-3],
                               div_id, size[0], size[1], drawing_type,
                               camera_type, json_mol, size[0], size[1])