def test_nbextensionpy_uninstall_files(self):
     self._inject_mock_extension()
     install_nbextension_python('mockextension', user=True)
     uninstall_nbextension_python('mockextension', user=True)
     
     assert not check_nbextension('_mockdestination/index.js')
     assert not check_nbextension(['_mockdestination/index.js'])
    def test_nbextensionpy_uninstall_files(self):
        self._inject_mock_extension()
        install_nbextension_python('mockextension', user=True)
        uninstall_nbextension_python('mockextension', user=True)

        assert not check_nbextension('_mockdestination/index.js')
        assert not check_nbextension(['_mockdestination/index.js'])
Beispiel #3
0
    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)
Beispiel #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)
     
     assert check_nbextension(f, user=True)
     assert check_nbextension([f], user=True)
     assert not check_nbextension([f, pjoin('dne', f)], user=True)
Beispiel #5
0
def nbinstall(overwrite=False, user=True):
    """
    Copies javascript dependencies to the '/nbextensions' folder in
    your IPython directory.

    Parameters
    ----------

    overwrite : bool
        If True, always install the files, regardless of what may already be
        installed.  Defaults to False.
    user : bool
        Whether to install to the user's .ipython/nbextensions directory.
        Otherwise do a system-wide install
        (e.g. /usr/local/share/jupyter/nbextensions).  Defaults to False.
    """
    if (check_nbextension('matplotlib')
            or check_nbextension('matplotlib', True)):
        return

    # Make a temporary directory so we can wrap mpl.js in a requirejs define().
    tempdir = mkdtemp()
    path = os.path.join(os.path.dirname(__file__), "web_backend")
    shutil.copy2(os.path.join(path, "nbagg_mpl.js"), tempdir)

    with open(os.path.join(path, 'mpl.js')) as fid:
        contents = fid.read()

    with open(os.path.join(tempdir, 'mpl.js'), 'w') as fid:
        fid.write('define(["jquery"], function($) {\n')
        fid.write(contents)
        fid.write('\nreturn mpl;\n});')

    install_nbextension(tempdir,
                        overwrite=overwrite,
                        symlink=False,
                        destination='matplotlib',
                        verbose=0,
                        **({
                            'user': user
                        } if version_info >= (3, 0, 0, '') else {}))
Beispiel #6
0
def nbinstall(overwrite=False, user=True):
    """
    Copies javascript dependencies to the '/nbextensions' folder in
    your IPython directory.

    Parameters
    ----------

    overwrite : bool
        If True, always install the files, regardless of what may already be
        installed.  Defaults to False.
    user : bool
        Whether to install to the user's .ipython/nbextensions directory.
        Otherwise do a system-wide install
        (e.g. /usr/local/share/jupyter/nbextensions).  Defaults to False.
    """
    if (check_nbextension('matplotlib') or
            check_nbextension('matplotlib', True)):
        return

    # Make a temporary directory so we can wrap mpl.js in a requirejs define().
    tempdir = mkdtemp()
    path = os.path.join(os.path.dirname(__file__), "web_backend")
    shutil.copy2(os.path.join(path, "nbagg_mpl.js"), tempdir)

    with open(os.path.join(path, 'mpl.js')) as fid:
        contents = fid.read()

    with open(os.path.join(tempdir, 'mpl.js'), 'w') as fid:
        fid.write('define(["jquery"], function($) {\n')
        fid.write(contents)
        fid.write('\nreturn mpl;\n});')

    install_nbextension(
        tempdir,
        overwrite=overwrite,
        symlink=False,
        destination='matplotlib',
        verbose=0,
        **({'user': user} if version_info >= (3, 0, 0, '') else {})
    )
def get_installed_versions(pyname, getversion):
    """ Check if the required NBExtensions are installed. If not, prompt user for action.
    """
    import importlib
    from notebook import nbextensions

    spec = importlib.import_module(pyname)._jupyter_nbextension_paths()[0]
    extname = spec['dest']
    require = spec['require']
    assert spec['section'] == 'notebook'

    search_paths = nbextension_ordered_paths()
    writable = location_writable()

    installed = {
        k: nbextensions.check_nbextension(extname, **EXTENSION_KWARGS[k])
        for k in search_paths.keys()
    }

    config_dirs = jupyter_config_dirs()
    paths = {}
    versions = {}
    enabled = {}
    active = {}
    found_active = False
    for location in EXTENSION_KWARGS:
        if not installed[location]:
            active[location] = False
            continue

        active[location] = not found_active
        found_active = True
        paths[location] = os.path.join(search_paths[location], 'nbextensions',
                                       extname)
        config = nbextensions.BaseJSONConfigManager(
            config_dir=config_dirs[location])
        enabled[location] = require in config.get('notebook').get(
            'load_extensions', {})

        if getversion:
            versionfile = os.path.join(paths[location], 'VERSION')
            if installed[location] and os.path.exists(versionfile):
                with open(versionfile, 'r') as pfile:
                    versions[location] = pfile.read().strip()
            else:
                versions[location] = 'pre-0.7'

    return {
        k: NbExtVersion(extname, installed[k], paths.get(k, None),
                        versions.get(k, None), enabled.get(k, False),
                        active[k], writable[k])
        for k in installed
    }
def get_installed_versions(pyname, getversion):
    """ Check if the required NBExtensions are installed. If not, prompt user for action.
    """
    import importlib
    from notebook import nbextensions

    spec = importlib.import_module(pyname)._jupyter_nbextension_paths()[0]
    extname = spec['dest']
    require = spec['require']
    assert spec['section'] == 'notebook'

    search_paths = nbextension_ordered_paths()
    writable = location_writable()

    installed = {k: nbextensions.check_nbextension(extname, **EXTENSION_KWARGS[k])
                 for k in search_paths.keys()}

    config_dirs = jupyter_config_dirs()
    paths = {}
    versions = {}
    enabled = {}
    active = {}
    found_active = False
    for location in EXTENSION_KWARGS:
        if not installed[location]:
            active[location] = False
            continue

        active[location] = not found_active
        found_active = True
        paths[location] = os.path.join(search_paths[location], 'nbextensions', extname)
        config = nbextensions.BaseJSONConfigManager(config_dir=config_dirs[location])
        enabled[location] = require in config.get('notebook').get('load_extensions', {})

        if getversion:
            versionfile = os.path.join(paths[location], 'VERSION')
            if installed[location] and os.path.exists(versionfile):
                with open(versionfile, 'r') as pfile:
                    versions[location] = pfile.read().strip()
            else:
                versions[location] = 'pre-0.7'

    return {k: NbExtVersion(extname,
                            installed[k],
                            paths.get(k, None),
                            versions.get(k, None),
                            enabled.get(k, False),
                            active[k],
                            writable[k])
            for k in installed}
Beispiel #9
0
def install_static(local_path=None, target_name=None, overwrite=False):
    """
    Write the javascript libraries to the given location.
    This utility is used by the IPython notebook tools to enable easy use
    of pyLDAvis with no web connection.
    Parameters
    ----------
    local_path: string (optional)
        the path to a file or a directory
    target_name: string (optional)
        the name of the target file or directory
    overwrite: boolean (optional)
        whether to overwrite if existing file or directory exists
    Returns
    -------
    The urls of the local_files
    """
    if IPYTHON_VERSION is None or IPYTHON_VERSION[0] < '2':
        raise ModuleNotFoundError(
            'IPython with version larger than 2.0 need to be installed!')
    if IPYTHON_VERSION[0] > '3':
        from notebook.nbextensions import install_nbextension, check_nbextension
    else:
        from IPython.html.nbextensions import install_nbextension, check_nbextension

    if local_path is None:
        local_path = STATIC_DIR
        target_name = VERSIONED_NAME
    if target_name is None:
        target_name = os.path.basename(local_path)

    if not os.path.exists(local_path):
        raise ValueError('%s not found at %s' % (target_name, local_path))

    if check_nbextension([target_name]):
        if overwrite:
            warnings.warn("Extension %s already exists. Overwriting..." %
                          target_name)
        else:
            # skipping
            return '/nbextensions/' + target_name
    else:
        full_url = install_nbextension(local_path,
                                       overwrite=overwrite,
                                       destination=target_name)
        print(full_url)
    return '/nbextensions/' + target_name
Beispiel #10
0
def valid_arborist_or_exception(**kwargs):
    from notebook import __version__ as notebook_version
    if notebook_version < '4.2.0':
        print(
            "Version of notebook package should be atleast 4.2.0 for Arborist, consider:"
        )
        print("    $ pip3 install --upgrade notebook")
        raise RuntimeError("Notebook too old for Arborist.")

    from notebook.serverextensions import validate_serverextension
    from notebook.nbextensions import check_nbextension
    warnings = validate_serverextension('tmtk.arborist')
    if warnings or not check_nbextension('transmart-arborist', **kwargs):
        print(
            'For the Arborist to work you need to install a jupyter serverextension using something like:'
        )
        print('  $ jupyter nbextension install --py tmtk.arborist')
        print('  $ jupyter serverextension enable --py tmtk.arborist')
        print('Then to verify installation run:')
        print('  $ jupyter serverextension list')
        raise RuntimeError('Transmart-arborist extension not found.')
Beispiel #11
0
from rdkit.Chem import AllChem as Chem

if TYPE_CHECKING:
    from rdkit.Chem import Mol

# Named tuple for storing serialized JSME widget value in several
# popular formats
JsmeValue = namedtuple("JsmeValue", ["jme", "molblock", "smiles"])

# Rel file path for Javascript source
JS_SOURCE = "jsme/jsme.nocache.js"

# Base URL for widget source javascript
BASE_URL = "/nbextensions/jupyter_jsme"

if check_nbextension("jupyter_jsme") is False:
    # Fallback option in case user didn't install Jupyter extension
    BASE_URL = "https://peter-ertl.com/jsme/JSME_2020-06-11"

_HTML_STR_FORMAT = '''
<script type="text/javascript" src="{base_url}/{js_source}"></script>
<script type="text/javascript">
function jsmeOnLoad() {{
    jsmeApp_{uid} = new JSApplet.JSME("JSApp_{uid}", \
        "{width}px", "{height}px", {{
        "options" : "{options}",
        "{data_type}": "{data}"
    }});
}}

function saveAs_{uid}(var_name) {{