Python traitlets.default() Examples

The following are 30 code examples of traitlets.default(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module traitlets , or try the search function .
Example #1
Source File: pull.py    From nbgitpuller with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    """
    Synchronizes a github repository with a local repository.
    """
    logging.basicConfig(
        format='[%(asctime)s] %(levelname)s -- %(message)s',
        level=logging.DEBUG)

    parser = argparse.ArgumentParser(description='Synchronizes a github repository with a local repository.')
    parser.add_argument('git_url', help='Url of the repo to sync')
    parser.add_argument('branch_name', default='master', help='Branch of repo to sync', nargs='?')
    parser.add_argument('repo_dir', default='.', help='Path to clone repo under', nargs='?')
    args = parser.parse_args()

    for line in GitPuller(
        args.git_url,
        args.branch_name,
        args.repo_dir
    ).pull():
        print(line) 
Example #2
Source File: jupyter_widget.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _process_execute_error(self, msg):
        """Handle an execute_error message"""
        self.log.debug("execute_error: %s", msg.get('content', ''))

        content = msg['content']

        traceback = '\n'.join(content['traceback']) + '\n'
        if False:
            # FIXME: For now, tracebacks come as plain text, so we can't
            # use the html renderer yet.  Once we refactor ultratb to
            # produce properly styled tracebacks, this branch should be the
            # default
            traceback = traceback.replace(' ', ' ')
            traceback = traceback.replace('\n', '<br/>')

            ename = content['ename']
            ename_styled = '<span class="error">%s</span>' % ename
            traceback = traceback.replace(ename, ename_styled)

            self._append_html(traceback)
        else:
            # This is the fallback for now, using plain text with ansi
            # escapes
            self._append_plain_text(traceback, before_prompt=not self.from_here(msg)) 
Example #3
Source File: jupyter_widget.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_default_style(self, colors='lightbg'):
        """ Sets the widget style to the class defaults.

        Parameters
        ----------
        colors : str, optional (default lightbg)
            Whether to use the default light background or dark
            background or B&W style.
        """
        colors = colors.lower()
        if colors=='lightbg':
            self.style_sheet = styles.default_light_style_sheet
            self.syntax_style = styles.default_light_syntax_style
        elif colors=='linux':
            self.style_sheet = styles.default_dark_style_sheet
            self.syntax_style = styles.default_dark_syntax_style
        elif colors=='nocolor':
            self.style_sheet = styles.default_bw_style_sheet
            self.syntax_style = styles.default_bw_syntax_style
        else:
            raise KeyError("No such color scheme: %s"%colors)

    #---------------------------------------------------------------------------
    # 'JupyterWidget' protected interface
    #--------------------------------------------------------------------------- 
Example #4
Source File: future.py    From FeatureHub with MIT License 6 votes vote down vote up
def user_for_token(self, token, use_cache=True):
        """Ask the Hub to identify the user for a given token.
        Args:
            token (str): the token
            use_cache (bool): Specify use_cache=False to skip cached cookie values (default: True)
        Returns:
            user_model (dict): The user model, if a user is identified, None if authentication fails.
            The 'name' field contains the user's name.
        """
        return self._check_hub_authorization(
            url=url_path_join(self.api_url,
                "authorizations/token",
                quote(token, safe='')),
            cache_key='token:%s' % token,
            use_cache=use_cache,
        ) 
Example #5
Source File: imagespawner.py    From imagespawner with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def options_from_form(self, formdata):
        """Parse the submitted form data and turn it into the correct
           structures for self.user_options."""

        default = self.dockerimages[0]

        # formdata looks like {'dockerimage': ['jupyterhub/singleuser']}"""
        dockerimage = formdata.get('dockerimage', [default])[0]

        # Don't allow users to input their own images
        if dockerimage not in self.dockerimages: dockerimage = default

        # container_prefix: The prefix of the user's container name is inherited 
        # from DockerSpawner and it defaults to "jupyter". Since a single user may launch different containers
        # (even though not simultaneously), they should have different
        # prefixes. Otherwise docker will only save one container per user. We
        # borrow the image name for the prefix.
        options = {
            'container_image': dockerimage,
            'container_prefix': '{}-{}'.format(
                super().container_prefix, dockerimage.replace('/', '-')
            )
        }
        return options 
Example #6
Source File: app.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def start(self):
        config_file_dir = os.path.dirname(os.path.abspath(self.output))
        if not os.path.isdir(config_file_dir):
            self.exit(
                "%r does not exist. The destination directory must exist "
                "before generating config file." % config_file_dir
            )
        if os.path.exists(self.output) and not self.force:
            self.exit("Config file already exists, use `--force` to overwrite")

        config_text = DaskGateway.instance().generate_config_file()
        if isinstance(config_text, bytes):
            config_text = config_text.decode("utf8")
        print("Writing default config to: %s" % self.output)
        with open(self.output, mode="w") as f:
            f.write(config_text) 
Example #7
Source File: templateexporter.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, config=None, **kw):
        """
        Public constructor

        Parameters
        ----------
        config : config
            User configuration instance.
        extra_loaders : list[of Jinja Loaders]
            ordered list of Jinja loader to find templates. Will be tried in order
            before the default FileSystem ones.
        template : str (optional, kw arg)
            Template to use when exporting.
        """
        super(TemplateExporter, self).__init__(config=config, **kw)

        self.observe(self._invalidate_environment_cache,
                     list(self.traits(affects_environment=True)))
        self.observe(self._invalidate_template_cache,
                     list(self.traits(affects_template=True))) 
Example #8
Source File: registry.py    From binderhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _auth_config_url_default(self):
        url = urlparse(self.url)
        cfg = self._docker_config
        auths = cfg.get("auths", {})
        # check for our url in docker config.json
        # there can be some variation, so try a few things.

        # in ~all cases, the registry url will appear in config.json
        if self.url in auths:
            # this will
            return self.url
        # ...but the config key is allowed to lack https://, so check just hostname
        if url.hostname in auths:
            return url.hostname
        # default docker special-case, where auth and registry urls are different
        if ("." + url.hostname).endswith((".docker.io", ".docker.com")):
            return DEFAULT_DOCKER_AUTH_URL

        # url not found, leave the most likely default
        return self.url 
Example #9
Source File: registry.py    From binderhub with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _default_url(self):
        cfg = self._docker_config
        auths = cfg.get("auths", {})
        if not auths:
            return DEFAULT_DOCKER_REGISTRY_URL

        # default to first entry in docker config.json auths
        auth_config_url = next(iter(auths.keys()))
        if "://" not in auth_config_url:
            # auth key can be just a hostname,
            # which assumes https
            auth_config_url = "https://" + auth_config_url

        if auth_config_url.rstrip("/") == DEFAULT_DOCKER_AUTH_URL:
            # default docker config key is the v1 registry,
            # but we will talk to the v2 api
            return DEFAULT_DOCKER_REGISTRY_URL

        return auth_config_url 
Example #10
Source File: templateexporter.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _template_file_changed(self, change):
        new = change['new']
        if new == 'default':
            self.template_file = self.default_template
            return
        # check if template_file is a file path
        # rather than a name already on template_path
        full_path = os.path.abspath(new)
        if os.path.isfile(full_path):
            template_dir, template_file = os.path.split(full_path)
            if template_dir not in [ os.path.abspath(p) for p in self.template_path ]:
                self.template_path = [template_dir] + self.template_path
            self.template_file = template_file 
Example #11
Source File: execute.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _kernel_manager_class_default(self):
        """Use a dynamic default to avoid importing jupyter_client at startup"""
        try:
            from jupyter_client import KernelManager
        except ImportError:
            raise ImportError("`nbconvert --execute` requires the jupyter_client package: `pip install jupyter_client`")
        return KernelManager 
Example #12
Source File: google.py    From oauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _google_api_url(self):
        """get default google apis url from env"""
        google_api_url = os.getenv('GOOGLE_API_URL')

        # default to googleapis.com
        if not google_api_url:
            google_api_url = 'https://www.googleapis.com'

        return google_api_url 
Example #13
Source File: swarmspawner.py    From dockerspawner with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _default_network_name(self):
        # no default network for swarm
        # use internal networking by default
        return "" 
Example #14
Source File: frontend_widget.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _document_contents_change(self, position, removed, added):
        """ Called whenever the document's content changes. Display a call tip
            if appropriate.
        """
        # Calculate where the cursor should be *after* the change:
        position += added

        document = self._control.document()
        if position == self._get_cursor().position():
            self._auto_call_tip()

    #------ Trait default initializers ----------------------------------------- 
Example #15
Source File: jupyter_widget.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _syntax_style_changed(self, changed=None):
        """ Set the style for the syntax highlighter.
        """
        if self._highlighter is None:
            # ignore premature calls
            return
        if self.syntax_style:
            self._highlighter.set_style(self.syntax_style)
            self._ansi_processor.set_background_color(self.syntax_style)
        else:
            self._highlighter.set_style_sheet(self.style_sheet)

    #------ Trait default initializers ----------------------------------------- 
Example #16
Source File: templateexporter.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _create_environment(self):
        """
        Create the Jinja templating environment.
        """
        here = os.path.dirname(os.path.realpath(__file__))

        paths = self.template_path + \
            [os.path.join(here, self.default_template_path),
             os.path.join(here, self.template_skeleton_path)]

        loaders = self.extra_loaders + [
            ExtensionTolerantLoader(FileSystemLoader(paths), self.template_extension),
            DictLoader({self._raw_template_key: self.raw_template})
        ]
        environment = Environment(
            loader=ChoiceLoader(loaders),
            extensions=JINJA_EXTENSIONS
            )

        environment.globals['uuid4'] = uuid.uuid4

        # Add default filters to the Jinja2 environment
        for key, value in self.default_filters():
            self._register_filter(environment, key, value)

        # Load user filters.  Overwrite existing filters if need be.
        if self.filters:
            for key, user_filter in self.filters.items():
                self._register_filter(environment, key, user_filter)

        return environment 
Example #17
Source File: base.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_permissions(self, assignment_id: str, student_id: str) -> None:
        self.log.info("Setting destination file permissions to %s", self.permissions)
        dest = os.path.normpath(self._format_dest(assignment_id, student_id))
        permissions = int(str(self.permissions), 8)
        for dirname, _, filenames in os.walk(dest):
            for filename in filenames:
                os.chmod(os.path.join(dirname, filename), permissions)
            # If groupshared, set dir permissions - see comment below.
            st_mode = os.stat(dirname).st_mode
            if self.coursedir.groupshared and st_mode & 0o2770 != 0o2770:
                try:
                    os.chmod(dirname, (st_mode|0o2770) & 0o2777)
                except PermissionError:
                    self.log.warning("Could not update permissions of %s to make it groupshared", dirname)
        # If groupshared, set write permissions on directories.  Directories
        # are created within ipython_genutils.path.ensure_dir_exists via
        # nbconvert.writer, (unless there are supplementary files) with a
        # default mode of 755 and there is no way to pass the mode arguments
        # all the way to there!  So we have to walk and fix.
        if self.coursedir.groupshared:
            # Root may be created in this step, and is not included above.
            rootdir = self.coursedir.format_path(self._output_directory, '.', '.')
            # Add 2770 to existing dir permissions (don't unconditionally override)
            st_mode = os.stat(rootdir).st_mode
            if st_mode & 0o2770 != 0o2770:
                try:
                    os.chmod(rootdir, (st_mode|0o2770) & 0o2777)
                except PermissionError:
                    self.log.warning("Could not update permissions of %s to make it groupshared", rootdir) 
Example #18
Source File: jupyter_widget.py    From qtconsole with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _edit(self, filename, line=None):
        """ Opens a Python script for editing.

        Parameters
        ----------
        filename : str
            A path to a local system file.

        line : int, optional
            A line of interest in the file.
        """
        if self.custom_edit:
            self.custom_edit_requested.emit(filename, line)
        elif not self.editor:
            self._append_plain_text('No default editor available.\n'
            'Specify a GUI text editor in the `JupyterWidget.editor` '
            'configurable to enable the %edit magic')
        else:
            try:
                filename = '"%s"' % filename
                if line and self.editor_line:
                    command = self.editor_line.format(filename=filename,
                                                      line=line)
                else:
                    try:
                        command = self.editor.format()
                    except KeyError:
                        command = self.editor.format(filename=filename)
                    else:
                        command += ' ' + filename
            except KeyError:
                self._append_plain_text('Invalid editor command.\n')
            else:
                try:
                    Popen(command, shell=True)
                except OSError:
                    msg = 'Opening editor with command "%s" failed.\n'
                    self._append_plain_text(msg % command) 
Example #19
Source File: baseapp.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_config_file(self, **kwargs: Any) -> None:
        """Load the config file.
        By default, errors in loading config are handled, and a warning
        printed on screen. For testing, the suppress_errors option is set
        to False, so errors will make tests fail.
        """
        if self.config_file:
            paths = [os.path.abspath("{}.py".format(self.config_file))]
        else:
            paths = [os.path.join(x, "{}.py".format(self.config_file_name)) for x in self.config_file_paths]

        if not any(os.path.exists(x) for x in paths):
            self.log.warning("No nbgrader_config.py file found (rerun with --debug to see where nbgrader is looking)")

        super(NbGrader, self).load_config_file(**kwargs) 
Example #20
Source File: app.py    From repo2docker with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _default_log_level(self):
        """The application's default log level"""
        return logging.INFO 
Example #21
Source File: marathonspawner.py    From marathonspawner with ISC License 5 votes vote down vote up
def _port_default(self):
        return 8888

    # default to listening on all-interfaces in the container 
Example #22
Source File: marathonspawner.py    From marathonspawner with ISC License 5 votes vote down vote up
def _get_default_format_volume_name(self):
        return default_format_volume_name

    # fix default port to 8888, used in the container 
Example #23
Source File: base.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def stop_cluster(self, cluster_name, failed=False):
        """Stop a cluster.

        No-op if the cluster is already stopped.

        Parameters
        ----------
        cluster_name : str
            The cluster name.
        failed : bool, optional
            If True, the cluster should be marked as FAILED after stopping. If
            False (default) it should be marked as STOPPED.
        """
        raise NotImplementedError 
Example #24
Source File: backend.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _default_namespace(self):
        ns_path = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
        if os.path.exists(ns_path):
            with open(ns_path) as f:
                return f.read().strip()
        return "default" 
Example #25
Source File: app.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _default_backend_class(self):
        # Separate the default out to avoid traitlets auto-importing it,
        # even if it's unused :(.
        return "dask_gateway_server.backends.local.UnsafeLocalBackend" 
Example #26
Source File: hdfsio.py    From hdfscontents with Apache License 2.0 5 votes vote down vote up
def _hdfs_move_file(self, src, dst):
        if self._hdfs_exists(dst):
            self.hdfs.delete(dst)
        self.hdfs.move(src, self.hdfs,  dst)
        # The pydoop move changes the permissions back to default!
        for p in self.hdfs.walk(dst):
            self.hdfs.chmod(p['name'], 0o0770) 
Example #27
Source File: widgets.py    From ipyvolume with MIT License 5 votes vote down vote up
def _default_scene(self):
        # could be removed when https://github.com/jovyan/pythreejs/issues/176 is solved
        # the default for pythreejs is white, which leads the volume rendering pass to make everything white
        return pythreejs.Scene(background=None) 
Example #28
Source File: gitlab.py    From oauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _default_gitlab_url(self):
        """get default gitlab url from env"""
        gitlab_url = os.getenv('GITLAB_URL')
        gitlab_host = os.getenv('GITLAB_HOST')

        if not gitlab_url and gitlab_host:
            warnings.warn(
                'Use of GITLAB_HOST might be deprecated in the future. '
                'Rename GITLAB_HOST environment variable to GITLAB_URL.',
                PendingDeprecationWarning,
            )
            if gitlab_host.startswith(('https:', 'http:')):
                gitlab_url = gitlab_host
            else:
                # Hides common mistake of users which set the GITLAB_HOST
                # without a protocol specification.
                gitlab_url = 'https://{0}'.format(gitlab_host)
                warnings.warn(
                    'The https:// prefix has been added to GITLAB_HOST.'
                    'Set GITLAB_URL="{0}" instead.'.format(gitlab_host)
                )

        # default to gitlab.com
        if not gitlab_url:
            gitlab_url = 'https://gitlab.com'

        return gitlab_url 
Example #29
Source File: oauth2.py    From oauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_next_url(self, user=None):
        """Get the redirect target from the state field"""
        state = self.get_state_url()
        if state:
            next_url = _deserialize_state(state).get('next_url')
            if next_url:
                return next_url
        # JupyterHub 0.8 adds default .get_next_url for a fallback
        if hasattr(BaseHandler, 'get_next_url'):
            return super().get_next_url(user)
        return url_path_join(self.hub.server.base_url, 'home') 
Example #30
Source File: github.py    From oauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _github_url_default(self):
        github_url = os.environ.get("GITHUB_URL")
        if not github_url:
            # fallback on older GITHUB_HOST config,
            # treated the same as GITHUB_URL
            host = os.environ.get("GITHUB_HOST")
            if host:
                if os.environ.get("GITHUB_HTTP"):
                    protocol = "http"
                    warnings.warn(
                        'Use of GITHUB_HOST with GITHUB_HTTP might be deprecated in the future. '
                        'Use GITHUB_URL=http://{} to set host and protocol together.'.format(
                            host
                        ),
                        PendingDeprecationWarning,
                    )
                else:
                    protocol = "https"
                github_url = "{}://{}".format(protocol, host)

        if github_url:
            if '://' not in github_url:
                # ensure protocol is included, assume https if missing
                github_url = 'https://' + github_url

            return github_url
        else:
            # nothing specified, this is the true default
            github_url = "https://github.com"

        # ensure no trailing slash
        return github_url.rstrip("/")