Ejemplo n.º 1
0
    def __init__(self, flagdir=None, environ=None, lock=None, debug=None):
        ''' Initialise the `Flags` instance.

        Parameters:
        * `flagdir`: the directory holding flag state files;
          if omitted use the value from `cs.env.FLAGDIR(environ)`
        * `environ`: the environment mapping to use,
          default `os.environ`
        * `lock`: a `Lock`like mutex to control multithreaded access;
          if omitted no locking is down
        * `debug`: debug mode, default `False`
    '''
        MutableMapping.__init__(self)

        @contextmanager
        def mutex():
            ''' Mutex context manager.
      '''
            if lock:
                lock.acquire()
            try:
                yield
            finally:
                if lock:
                    lock.release()

        self._mutex = mutex
        if debug is None:
            debug = False
        self.debug = debug
        FlaggedMixin.__init__(self, flags=self)
        if flagdir is None:
            flagdir = FLAGDIR(environ=environ)
        self.dirpath = flagdir
        self._old_flags = {}
Ejemplo n.º 2
0
    def update(self, *args, **kwargs):

        if len(args) > 1:
            raise TypeError("update() takes at most 1 positional "
                            "arguments ({} given)".format(len(args)))
        if len(args) >= 1:
            other = args[0]
            if isinstance(other, KeyedList):
                # Merge
                for key, value in other.all_items():
                    self[key] = value
            else:
                MutableMapping.update(self, other)

        for key, value in kwargs.items():
            if isinstance(value, KeyedList):
                try:
                    nestedlist = self[key]
                except KeyError:
                    nestedlist = KeyedList()
                    self[key] = nestedlist
                else:
                    if not isinstance(nestedlist, KeyedList):
                        raise KeyError(
                            'target key "%s" is a value, cannot '
                            'update value against another keyed list' %
                            (key, ))
                nestedlist.update(value)
            else:
                self[key] = value
Ejemplo n.º 3
0
 def __delattr__(self, name):
     # Names starting with an underscore are not preferences but normal
     # instance attributes
     if name.startswith('_'):
         MutableMapping.__delattr__(self, name)
     else:
         del self._all_prefs[self._basename + '.' + name]
Ejemplo n.º 4
0
    def __init__(self, db_instance = None):
        """
Constructor __init__(Instance)

:param db_instance: Encapsulated SQLAlchemy database instance

:since: v1.0.0
        """

        MutableMapping.__init__(self)

        self._db_context_sort_definition = { }
        """
Context specific sort definition instances
        """
        self._db_sort_definition = None
        """
Sort definition instance
        """
        self.local = local()
        """
thread-local instance
        """
        self._lock = ThreadLock()
        """
Thread safety lock
        """
        self._log_handler = NamedLoader.get_singleton("dNG.data.logging.LogHandler", False)
        """
The LogHandler is called whenever debug messages should be logged or errors
happened.
        """

        self.local.db_instance = db_instance
Ejemplo n.º 5
0
    def __init__(self, init_registry=None):
        if init_registry:
            if isinstance(init_registry, dict):
                self._registry = copy.deepcopy(init_registry)
            else:
                raise InvalidJWSERegOperation('Unknown input type')
        else:
            self._registry = {}

        MutableMapping.__init__(self)
Ejemplo n.º 6
0
    def update(self, *args, **kw):
        if args:
            lst = args[0]

            if len(lst) != len(dict(lst)):
                # this does not catch the cases where we overwrite existing
                # keys, but those would produce too many warning
                msg = (
                    "Behavior of MultiDict.update() has changed "
                    "and overwrites duplicate keys. Consider using .extend()"
                )
                warnings.warn(msg, UserWarning, stacklevel=2)
        MutableMapping.update(self, *args, **kw)
Ejemplo n.º 7
0
    def __init__(self, *args, **kwargs):
        """
Constructor __init__(StackedDict)

:since: v1.0.1
        """

        MutableMapping.__init__(self)

        self._dict = dict(*args, **kwargs)
        """
Base of the stacked dict instance.
        """
        self.stacked_dicts = []
        """
Ejemplo n.º 8
0
    def __setattr__(self, key, value):
        if key.startswith('_'):
            return MutableMapping.__setattr__(self, key, value)

        self._check_keyvalue(key, value)

        if self._locked:
            raise KeyError('Handler is locked.')

        if not self._allow_overwrite and hasattr(self, key):
            if key in self._loaded:
                MutableMapping.__setattr__(self, key, value)
                loaded = self._loaded[key]
                self.__dict__[key].load_state_dict(loaded.state_dict())
            else:
                raise KeyError('Overwriting keys not allowed.')
        else:
            MutableMapping.__setattr__(self, key, value)
Ejemplo n.º 9
0
    def encode(self, module: abc.MutableMapping) -> str:
        """Extends the parent function, by adding a restriction.
        For PDS, if there are any GROUP elements, there must be at
        least one OBJECT element in the label.  Behavior here
        depends on the value of this encoder's convert_group_to_object
        property.
        """
        (obj_count, grp_count) = self.count_aggs(module)

        if grp_count > 0 and obj_count < 1:
            if self.convert_group_to_object:
                for k, v in module.items():
                    # First try to convert any GROUPs that would not
                    # be valid PDS GROUPs.
                    if isinstance(v, self.grpcls) and not self.is_PDSgroup(v):
                        module[k] = self.objcls(v)
                        break
                else:
                    # Then just convert the first GROUP
                    for k, v in module.items():
                        if isinstance(v, self.grpcls):
                            module[k] = self.objcls(v)
                            break
                    else:
                        raise ValueError("Couldn't convert any of the GROUPs "
                                         "to OBJECTs.")
            else:
                raise ValueError("This module has a GROUP element, but no "
                                 "OBJECT elements, which is not allowed by "
                                 "the PDS.  You could set "
                                 "*convert_group_to_object* to *True* on the "
                                 "encoder to try and convert a GROUP "
                                 "to an OBJECT.")

        s = super().encode(module)
        if self.tab_replace > 0:
            return s.replace("\t", (" " * self.tab_replace))
        else:
            return s
Ejemplo n.º 10
0
def merge_patch(target: cabc.MutableMapping, patch):
    """Apply JSON merge patch to target

    This function is implementation of the JSON Merget Patch algorithm
    described in RFC 7396. ``target`` is patched in place.

    Parameters:
        target: The target object
        patch: The patch to apply

    Return:
        The result of applying the patch. The returned object may or
        may not be the ``target`` parameter.
    """
    if isinstance(patch, cabc.Mapping):
        if not isinstance(target, cabc.Mapping):
            target = {}
        for key in list(patch.keys()):
            if (value := patch[key]) is None:
                target.pop(key, None)
            else:
                target[key] = merge_patch(target.get(key, {}), value)
        return target
Ejemplo n.º 11
0
 def __getattr__(self, name):
     if name in self.__dict__ or name.startswith('__'):
         return MutableMapping.__getattr__(self, name)
     
     # This function might get called from BrianGlobalPreferencesView with
     # a prefixed name -- therefore the name can contain dots!
     if name in self.pref_register:
         # This asks for a category, not a single preference
         return BrianGlobalPreferencesView(name, self)
     
     basename, _ = parse_preference_name(name)
     if len(basename) and basename not in self.pref_register:
         raise AssertionError(f"__getattr__ received basename '{basename}' which is "
                              f"unregistered. This should never happen!")
     
     return self[name]
Ejemplo n.º 12
0
    else:

        def keys(self):
            # type: () -> List[Any]
            return list(self)

        def items(self):
            # type: () -> List[Tuple[Any, Any]]
            return list(self._iterate_items())

        def values(self):
            # type: () -> List[Any]
            return list(self._iterate_values())


MutableMapping.register(DictAttribute)  # noqa: E305


class ChainMap(MutableMapping):
    """Key lookup on a sequence of maps."""

    key_t = None
    changes = None
    defaults = None
    maps = None

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
            key_t=kwargs.get('key_t'),
Ejemplo n.º 13
0
 def __init__(self, table, txn):
     MutableMapping.__init__(self)
     self._table = table
     self._txn = txn
Ejemplo n.º 14
0
    iteritems = _iterate_items

    def _iterate_values(self):
        # type: () -> Iterable
        for key in self._iterate_keys():
            yield getattr(self.obj, key)

    itervalues = _iterate_values

    items = _iterate_items
    keys = _iterate_keys
    values = _iterate_values


MutableMapping.register(DictAttribute)


class ChainMap(MutableMapping):
    """Key lookup on a sequence of maps."""

    key_t = None
    changes = None
    defaults = None
    maps = None
    _observers = []

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
Ejemplo n.º 15
0
limitations under the License.
"""

__version__ = "0.2.0"

from ctools import _ctools

build_with_debug = _ctools.build_with_debug
strhash = _ctools.strhash
int8_to_datetime = _ctools.int8_to_datetime
jump_consistent_hash = _ctools.jump_consistent_hash

try:
    from collections.abc import MutableMapping  # noqa
except ImportError:
    from collections import MutableMapping  # noqa

CacheMap = _ctools.CacheMap
TTLCache = _ctools.TTLCache
Channel = _ctools.Channel
SortedMap = _ctools.SortedMap

try:
    MutableMapping.register(CacheMap)
    MutableMapping.register(TTLCache)
    MutableMapping.register(SortedMap)
except Exception:  # noqa
    pass

del _ctools, MutableMapping
Ejemplo n.º 16
0
    __iter__ = iterkeys

    def __reversed__(self):
        """Iterate over the values in the cache dict, oldest items
        coming first.
        """
        return iter(tuple(self._queue))

    __copy__ = copy


# register the LRU cache as mutable mapping if possible
try:
    from collections.abc import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::
Ejemplo n.º 17
0
    __iter__ = iterkeys

    def __reversed__(self):
        """Iterate over the values in the cache dict, oldest items
        coming first.
        """
        return iter(tuple(self._queue))

    __copy__ = copy


# register the LRU cache as mutable mapping if possible
try:
    from collections.abc import MutableMapping
    MutableMapping.register(LRUCache)
except ImportError:
    pass


def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::
Ejemplo n.º 18
0
 def __init__(self, parent, deft_config, user_config):
     MutableMapping.__init__(self)
     self._parent = parent
     self._deft_config = deft_config
     self._user_config = user_config
Ejemplo n.º 19
0
 def keys(self):
     """Explicit use of MutableMapping attributes."""
     return MutableMapping.keys(self)
Ejemplo n.º 20
0
 def items(self):
     """Explicit use of MutableMapping attributes."""
     return MutableMapping.items(self)
Ejemplo n.º 21
0
        for key, value in self.items():
            try:
                if (value != other[key]):
                    return False
            except KeyError:
                return False
        return True

    # Easier than making GenericMap actually inherit from Mapping
    keys = Mapping.keys
    values = Mapping.values
    items = Mapping.items


MutableMapping.register(MutableGenericMapS)

@continueClass  # noqa F811
class MutableGenericMapS:
    # Easier than making MutableGenericMap actually inherit from MutableMapping
    setdefault = MutableMapping.setdefault
    update = MutableMapping.update

    # MutableMapping.pop relies on implementation details of MutableMapping
    def pop(self, key, default=None):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not None:
Ejemplo n.º 22
0
    # MutableMapping.pop relies on implementation details of MutableMapping
    def pop(self, key, default=None):
        try:
            value = self[key]
            del self[key]
            return value
        except KeyError:
            if default is not None:
                return default
            else:
                raise


MutableGenericMap.register(str, MutableGenericMapS)
MutableMapping.register(MutableGenericMapS)


class AutoKeyMeta(TemplateMeta):
    """A metaclass for abstract mappings whose key type is implied by their
    constructor arguments.

    This metaclass requires that the mapping have a `dict`-like constructor,
    i.e., it takes a mapping or an iterable of key-value pairs as its first
    positional parameter.

    This class differs from `~lsst.utils.TemplateMeta` only in that the dtype
    (or equivalent) constructor keyword is optional. If it is omitted, the
    class will attempt to infer it from the first argument.
    """
    def __call__(cls, *args, **kwargs):  # noqa N805, non-self first param
Ejemplo n.º 23
0
    else:

        def keys(self):
            # type: () -> List[Any]
            return list(self)

        def items(self):
            # type: () -> List[Tuple[Any, Any]]
            return list(self._iterate_items())

        def values(self):
            # type: () -> List[Any]
            return list(self._iterate_values())


MutableMapping.register(DictAttribute)  # noqa: E305


class ChainMap(MutableMapping):
    """Key lookup on a sequence of maps."""

    key_t = None
    changes = None
    defaults = None
    maps = None
    _observers = []

    def __init__(self, *maps, **kwargs):
        # type: (*Mapping, **Any) -> None
        maps = list(maps or [{}])
        self.__dict__.update(
Ejemplo n.º 24
0
        Makes the *default* argument of the original :meth:`dict.setdefault` non-optional.

        Args:
            element: The element which is added if not already present.
            default: The default multiplicity to add the element with if not in the multiset.

        Returns:
            The multiplicity for *element* if it is in the multiset, else *default*.
        """
        return self._elements.setdefault(element, default)

    def clear(self):
        """Empty the multiset."""
        self._elements.clear()
        self._total = 0


class FrozenMultiset(BaseMultiset):
    """The frozen multiset variant that is immutable and hashable."""
    __slots__ = ()

    def __hash__(self):
        return hash(frozenset(self._elements.items()))

Mapping.register(BaseMultiset)  # type: ignore
MutableMapping.register(Multiset)  # type: ignore

if __name__ == '__main__':
    import doctest
    doctest.testmod()
Ejemplo n.º 25
0
 def __setattr__(self, name, value):  
     # Do not allow to set a category name to something else
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError("Cannot set a preference category.")
     else:
         MutableMapping.__setattr__(self, name, value)      
Ejemplo n.º 26
0
        """
        Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the
        name-value relations as results names. If an optional ``name`` argument is
        given, a nested ``ParseResults`` will be returned.
        """
        def is_iterable(obj):
            try:
                iter(obj)
            except Exception:
                return False
            else:
                return not isinstance(obj, str_type)

        ret = cls([])
        for k, v in other.items():
            if isinstance(v, Mapping):
                ret += cls.from_dict(v, name=k)
            else:
                ret += cls([v], name=k, asList=is_iterable(v))
        if name is not None:
            ret = cls([ret], name=name)
        return ret

    asList = as_list
    asDict = as_dict
    getName = get_name


MutableMapping.register(ParseResults)
MutableSequence.register(ParseResults)
Ejemplo n.º 27
0
 def __delattr__(self, name):
     if 'pref_register' in self.__dict__ and name in self.pref_register:
         raise PreferenceError("Cannot delete a preference category.")
     else:
         MutableMapping.__delattr__(self, name, value)
Ejemplo n.º 28
0
 def values(self):
     """Explicit use of MutableMapping attributes."""
     return MutableMapping.values(self)
Ejemplo n.º 29
0
    def __init__(self, default):
        MutableMapping.__init__(self)
        self._back = {}

        for rtype in RatingType:
            self[rtype] = default