Python traitlets.List() Examples

The following are 16 code examples of traitlets.List(). 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: db_base.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_check_clusters(self, clusters):
        """Check the status of multiple clusters.

        This is periodically called to check the status of pending clusters.
        Once a cluster is running this will no longer be called.

        Parameters
        ----------
        clusters : List[Cluster]
            The clusters to be checked.

        Returns
        -------
        statuses : List[bool]
            The status for each cluster. Return False if the cluster has
            stopped or failed, True if the cluster is pending start or running.
        """
        raise NotImplementedError 
Example #2
Source File: db_base.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_check_workers(self, workers):
        """Check the status of multiple workers.

        This is periodically called to check the status of pending workers.
        Once a worker is running this will no longer be called.

        Parameters
        ----------
        workers : List[Worker]
            The workers to be checked.

        Returns
        -------
        statuses : List[bool]
            The status for each worker. Return False if the worker has
            stopped or failed, True if the worker is pending start or running.
        """
        raise NotImplementedError 
Example #3
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def _update_atom_colors(colors, atoms, styles):
        """ Updates list of atoms with the given colors. Colors will be translated to hex.

        Args:
            color (List[str]): list of colors for each atom
            atoms (List[moldesign.Atom]): list of atoms to apply the colors to
            styles (dict): old style dictionary
        """
        styles = dict(styles)

        if len(colors) != len(atoms):
            raise ValueError("Number of colors provided does not match number of atoms provided")

        for atom, color in zip(atoms, colors):
            if str(atom.index) in styles:
                styles[str(atom.index)] = dict(styles[str(atom.index)])
            else:
                styles[str(atom.index)] = {}
            styles[str(atom.index)]['color'] = translate_color(color, prefix='#')

        return styles

    # some convenience synonyms 
Example #4
Source File: validator.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_changed_cells(self, nb: NotebookNode) -> typing.List:
        changed = []
        for cell in nb.cells:
            if not (utils.is_grade(cell) or utils.is_locked(cell)):
                continue

            # if we're ignoring checksums, then remove the checksum from the
            # cell metadata
            if self.ignore_checksums and 'checksum' in cell.metadata.nbgrader:
                del cell.metadata.nbgrader['checksum']

            # verify checksums of cells
            if utils.is_locked(cell) and 'checksum' in cell.metadata.nbgrader:
                old_checksum = cell.metadata.nbgrader['checksum']
                new_checksum = utils.compute_checksum(cell)
                if old_checksum != new_checksum:
                    changed.append(cell)

        return changed 
Example #5
Source File: validator.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_failed_cells(self, nb: NotebookNode) -> typing.List[NotebookNode]:
        failed = []
        for cell in nb.cells:
            if not (self.validate_all or utils.is_grade(cell) or utils.is_locked(cell)):
                continue

            # if it's a grade cell, the check the grade
            if utils.is_grade(cell):
                score, max_score = utils.determine_grade(cell, self.log)

                # it's a markdown cell, so we can't do anything
                if score is None:
                    pass
                elif score < max_score:
                    failed.append(cell)
            elif self.validate_all and cell.cell_type == 'code':
                for output in cell.outputs:
                    if output.output_type == 'error':
                        failed.append(cell)
                        break

        return failed 
Example #6
Source File: validator.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_passed_cells(self, nb: NotebookNode) -> typing.List[NotebookNode]:
        passed = []
        for cell in nb.cells:
            if not (utils.is_grade(cell) or utils.is_locked(cell)):
                continue

            # if it's a grade cell, the check the grade
            if utils.is_grade(cell):
                score, max_score = utils.determine_grade(cell, self.log)

                # it's a markdown cell, so we can't do anything
                if score is None:
                    pass
                elif score == max_score:
                    passed.append(cell)

        return passed 
Example #7
Source File: test_tool.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tool_command_line_precedence():
    """
    ensure command-line has higher priority than config file
    """
    from ctapipe.core.tool import run_tool

    class SubComponent(Component):
        component_param = Float(10.0, help="some parameter").tag(config=True)

    class MyTool(Tool):
        description = "test"
        userparam = Float(5.0, help="parameter").tag(config=True)

        classes = List([SubComponent,])
        aliases = Dict({"component_param": "SubComponent.component_param"})

        def setup(self):
            self.sub = self.add_component(SubComponent(parent=self))

    config = Config(
        {"MyTool": {"userparam": 12.0}, "SubComponent": {"component_param": 15.0}}
    )

    tool = MyTool(config=config)  # sets component_param to 15.0

    run_tool(tool, ["--component_param", "20.0"])
    assert tool.sub.component_param == 20.0
    assert tool.userparam == 12.0 
Example #8
Source File: graph_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def set_colors(self, colormap):
        """
        Args:
         colormap(Mapping[str,List[Atoms]]): mapping of colors to atoms
        """
        for color, atoms in colormap.items():
            self.set_color(atoms=atoms, color=color) 
Example #9
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def selected_atoms(self):
        """ List[moldesign.Atom]: list of selected atoms
        """
        return [self.mol.atoms[i] for i in self.selected_atom_indices] 
Example #10
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def set_color(self, colors, atoms=None, save=True):
        """ Set atom colors

        May be called in several different ways:
          - ``set_color(color, atoms=list_of_atoms_or_None)``
                  where all passed atoms are to be colored a single color
          - ``set_color(list_of_colors, atoms=list_of_atoms_or_None)``
                  with a list of colors for each atom
          -  ``set_color(dict_from_atoms_to_colors)``
                  a dictionary that maps atoms to colors
          - ``set_color(f, atoms=list_of_atoms_or_None)``
                 where f is a function that maps atoms to colors

        Args:
            colors (see note for allowable types): list of colors for each atom, or map
               from atoms to colors, or a single color for all atoms
            atoms (List[moldesign.Atom]): list of atoms (if None, assumed to be mol.atoms; ignored
               if a dict is passed for "color")
            save (bool): always color these atoms this way (until self.unset_color is called)

        See Also:
            :method:`GeometryViewer.color_by`` - to automatically color atoms using numerical
               and categorical data
        """
        if hasattr(colors, 'items'):
            atoms, colors = zip(*colors.items())
        elif atoms is None:
            atoms = self.mol.atoms

        if callable(colors):
            colors = map(colors, atoms)
        elif isinstance(colors, basestring) or not hasattr(colors, '__iter__'):
            colors = [colors for atom in atoms]

        for atom,color in zip(atoms, colors):
            c = translate_color(color, '#')
            if save:
                self.atom_colors[atom] = c
            self.styles[str(atom.index)]['color'] = c
        self.send_state('styles') 
Example #11
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def unset_color(self, atoms=None):
        """ Resets atoms to their default colors

        Args:
            atoms (List[moldesign.Atom]): list of atoms to color (if None, this is applied to
               all atoms)
        """
        if atoms is None:
            atoms = self.mol.atoms

        for atom in atoms:
            self.atom_colors.pop(atom, None)
            self.styles[str(atom.index)].pop('color', None)
        self.send_state('styles') 
Example #12
Source File: geometry_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def hide(self, atoms=None):
        """ Make these atoms invisible

        Args:
            atoms (List[moldesign.Atom]): atoms to apply this style to
               (if not passed, uses all atoms)
        """
        return self.set_style(None,atoms=atoms) 
Example #13
Source File: validator.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_type_changed_cells(self, nb: NotebookNode) -> typing.List[NotebookNode]:
        changed = []

        for cell in nb.cells:
            if not (utils.is_grade(cell) or utils.is_solution(cell) or utils.is_locked(cell)):
                continue
            if 'cell_type' not in cell.metadata.nbgrader:
                continue

            new_type = cell.metadata.nbgrader.cell_type
            old_type = cell.cell_type
            if new_type and (old_type != new_type):
                changed.append(cell)

        return changed 
Example #14
Source File: dbapp.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self):
        # check: is there a subapp given?
        if self.subapp is None:
            print("No assignment command given. List of subcommands:\n")
            for key, (app, desc) in self.subcommands.items():
                print("    {}\n{}\n".format(key, desc))

        # This starts subapps
        super(DbAssignmentApp, self).start() 
Example #15
Source File: dbapp.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def start(self):
        # check: is there a subapp given?
        if self.subapp is None:
            print("No db command given (run with --help for options). List of subcommands:\n")
            self.print_subcommands()

        # This starts subapps
        super(DbApp, self).start() 
Example #16
Source File: validator.py    From nbgrader with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def validate(self, filename: str) -> typing.Dict[str, typing.List[typing.Dict[str, str]]]:
        self.log.info("Validating '{}'".format(os.path.abspath(filename)))
        basename = os.path.basename(filename)
        dirname = os.path.dirname(filename)
        with utils.chdir(dirname):
            nb = read_nb(basename, as_version=current_nbformat)

        type_changed = self._get_type_changed_cells(nb)
        if len(type_changed) > 0:
            results = {}
            results['type_changed'] = [{
                "source": cell.source.strip(),
                "old_type": cell.cell_type,
                "new_type": cell.metadata.nbgrader.cell_type
            } for cell in type_changed]
            return results

        with utils.chdir(dirname):
            nb = self._preprocess(nb)
        changed = self._get_changed_cells(nb)
        passed = self._get_passed_cells(nb)
        failed = self._get_failed_cells(nb)

        results = {}

        if not self.ignore_checksums and len(changed) > 0:
            results['changed'] = [{
                "source": cell.source.strip()
            } for cell in changed]

        elif self.invert:
            if len(passed) > 0:
                results['passed'] = [{
                    "source": cell.source.strip()
                } for cell in passed]

        else:
            if len(failed) > 0:
                results['failed'] = [{
                    "source": cell.source.strip(),
                    "error": ansi2html(self._extract_error(cell)),
                    "raw_error": self._extract_error(cell)
                } for cell in failed]

        return results