How to use the traitlets.HasTraits function in traitlets

To help you get started, we’ve selected a few traitlets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Irrational-Encoding-Wizardry / yuuno / yuuno / ipython / formatter.py View on Github external
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see .


from traitlets import observe
from traitlets import HasTraits, Instance, Any

from IPython.display import Image as IPyImage

from yuuno.clip import Frame, Clip
from yuuno.ipython.feature import Feature
from yuuno.ipython.environment import Environment


class InlineFormat(HasTraits):
    """
    Represents an inline formatted object.
    """

    clip: Clip = Any()
    first_frame: Frame = Any(read_only=True, allow_none=True)
    environment: Environment = Instance(Environment)

    @observe("clip")
    def _update_initial_frame(self, value):
        value = value['new']
        self.set_trait('first_frame', value[0].to_pil())

    def ipy_image(self) -> IPyImage:
        """
        Converts a clip to an image.
github creare-com / podpac / podpac / core / node.py View on Github external
)
        attr = getattr(attr, n)

    # copy in debug mode
    if settings["DEBUG"]:
        attr = deepcopy(attr)

    return attr


# --------------------------------------------------------#
#  Mixins
# --------------------------------------------------------#


class NoCacheMixin(tl.HasTraits):
    """ Mixin to use no cache by default. """

    cache_ctrl = tl.Instance(CacheCtrl, allow_none=True)

    @tl.default("cache_ctrl")
    def _cache_ctrl_default(self):
        return CacheCtrl([])


class DiskCacheMixin(tl.HasTraits):
    """ Mixin to add disk caching to the Node by default. """

    cache_ctrl = tl.Instance(CacheCtrl, allow_none=True)

    @tl.default("cache_ctrl")
    def _cache_ctrl_default(self):
github timkpaine / paperboy / paperboy / config / output.py View on Github external
import os
import os.path
from traitlets import HasTraits, Unicode
from ..output import LocalOutput
from ..utils import class_to_name, name_to_class


class OutputConfig(HasTraits):
    '''Base class for configuring output'''
    type = Unicode()
    pass


class LocalOutputConfig(OutputConfig):
    '''Output report to local filesystem'''
    type = 'local'
    dir = Unicode(default_value=os.path.expanduser('~/Downloads'))
    clazz = LocalOutput

    def to_json(self):
        ret = {}
        ret['type'] = self.type
        ret['dir'] = self.dir
        ret['clazz'] = class_to_name(self.clazz)
github Irrational-Encoding-Wizardry / yuuno / yuuno / core / registry.py View on Github external
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see .


from traitlets import Type as Class, Dict, List, HasTraits
from traitlets import This
from traitlets import default

from typing import Dict as Dictionary
from typing import List as Listing
from typing import Type, Optional, Callable, Iterator

from yuuno.clip import Clip, T


class Registry(HasTraits):
    """
    Stores which Clip-Type is responsible for wrapping
    specific applications.
    """

    clip_types: Dictionary = Dict(value_trait=Class(klass=Clip), key_trait=Class())
    sub_registries: Listing['Registry'] = List(This())

    @default("clip_types")
    def _init_cliptypes(self) -> Dictionary[Type[Clip], Type[T]]:
        return {}

    @default("sub_registries")
    def _init_subregistries(self) -> Listing['Registry']:
        return []
github quantopian / serializable-traitlets / straitlets / serializable.py View on Github external
if len(errors) == 1:
            # If only one error is passed, pass it through unmodified.
            return list(errors.items())[0][1]
        return super(MultipleTraitErrors, cls).__new__(cls, errors)

    def __init__(self, errors):
        self.errors = errors

    def __str__(self):
        return '\n' + ('\n%s\n' % ('-' * 20)).join(
            ': '.join((name, str(e)))
            for name, e in sorted(self.errors.items(), key=itemgetter(0))
        )


class Serializable(with_metaclass(SerializableMeta, HasTraits)):
    """
    Base class for HasTraits instances that can be serialized into Python
    primitives.

    The traitlets set on Serializables must be instances of
    straitlets.traits.SerializableTrait.
    """

    def __init__(self, **metadata):
        unexpected = viewkeys(metadata) - self.trait_names()
        if unexpected:
            raise TypeError(self._unexpected_kwarg_msg(unexpected))
        super(Serializable, self).__init__(**metadata)

    def validate_all_attributes(self):
        """
github creare-com / podpac / podpac / core / pipeline / output.py View on Github external
from collections import OrderedDict
from io import BytesIO

try:
    import cPickle  # Python 2.7
except:
    import _pickle as cPickle

import traitlets as tl
import numpy as np
import traitlets as tl

from podpac.core.node import Node


class Output(tl.HasTraits):
    """
    Base class for Pipeline Outputs.

    Attributes
    ----------
    node : Node
        output node
    name : string
        output name
    """

    node = tl.Instance(Node)
    name = tl.Unicode()

    def write(self, output, coordinates):
        """Write the node output
github creare-com / podpac / podpac / core / authentication.py View on Github external
# see whats stored in settings already
    u_settings = settings.get("username@{}".format(hostname))
    p_settings = settings.get("password@{}".format(hostname))

    # get username from 1. function input 2. settings 3. python input()
    u = username or u_settings or input("Username: ")
    p = password or p_settings or getpass.getpass()

    # set values in settings
    settings["username@{}".format(hostname)] = u
    settings["password@{}".format(hostname)] = p

    _log.debug("Set credentials for hostname {}".format(hostname))


class RequestsSessionMixin(tl.HasTraits):
    hostname = tl.Unicode(allow_none=False)
    auth_required = tl.Bool(default_value=False)

    @property
    def username(self):
        """Returns username stored in settings for accessing `self.hostname`.
        The username is stored under key `username@`
        
        Returns
        -------
        str
            username stored in settings for accessing `self.hostname`
        
        Raises
        ------
        ValueError
github cyanogen / uchroma / uchroma / server / anim.py View on Github external
self._logger.debug("Loop paused: %s", paused)

        if paused:
            self._pause_event.clear()
        else:
            self._pause_event.set()


RendererInfo = NamedTuple('RendererInfo', [('module', ModuleType),
                                           ('clazz', type),
                                           ('key', str),
                                           ('meta', RendererMeta),
                                           ('traits', dict)])

class AnimationManager(HasTraits):
    """
    Configures and manages animations of one or more renderers
    """

    _renderer_info = FrozenDict()
    paused = Bool(False)

    def __init__(self, driver):
        super(AnimationManager, self).__init__()

        self._driver = driver
        self._loop = None
        self._logger = driver.logger
        self._error = False

        self.layers_changed = Signal()
github cyanogen / uchroma / uchroma / traits.py View on Github external
Create a dict which represents all traits of the given object.
    This dict itself can be inspected in a generic API, or it
    may be converted back to a (stub) instance of HasTraits. This
    facilitates the sending of configurable object properties over
    an interface such as D-Bus.

    :param obj: an instance of HasTraits
    :param value: optional dict of trait values (pulled from obj by default)
    :return: dict representing all traits in obj
    """
    cls_dt = {}
    if isinstance(obj, type) and hasattr(obj, 'class_traits'):
        traits = obj.class_traits()
    elif isinstance(obj, dict):
        traits = obj
    elif isinstance(obj, HasTraits):
        traits = obj.traits()
        values = obj._trait_values
    else:
        raise TypeError("Object does not support traits")

    for k, v in traits.items():
        dt = trait_as_dict(v)
        if dt is None:
            continue
        if values is not None and k in values:
            dt['__value__'] = values[k]
        cls_dt[k] = dt
    return cls_dt
github pbugnion / gmaps / gmaps / drawing.py View on Github external
stroke_color=DEFAULT_STROKE_COLOR,
            stroke_weight=2.0,
            stroke_opacity=geotraitlets.StrokeOpacity.default_value
    ):
        kwargs = dict(
            start=start,
            end=end,
            stroke_color=stroke_color,
            stroke_weight=stroke_weight,
            stroke_opacity=stroke_opacity
        )
        super(Line, self).__init__(**kwargs)


@doc_subst(_doc_snippets)
class PolygonOptions(HasTraits):
    """
    Style options for a polygon.

    Pass an instance of this class to :func:`gmaps.drawing_layer` to
    control the style of new user-drawn polygons on the map.

    :Examples:

    >>> fig = gmaps.figure()
    >>> drawing = gmaps.drawing_layer(
            polygon_options=gmaps.PolygonOptions(
                stroke_color='red', fill_color=(255, 0, 132))
        )
    >>> fig.add_layer(drawing)
    >>> fig # display the figure