class _NSContext(object):
    """
    A mapping from XML namespaces onto their prefixes in the document.
    """

    def __init__(self, parent=None):
        """
        Pull out the parent's namespaces, if there's no parent then default to
        XML.
        """
        self.parent = parent
        if parent is not None:
            self.nss = OrderedDict(parent.nss)
        else:
            self.nss = {"http://www.w3.org/XML/1998/namespace": "xml"}

    def get(self, k, d=None):
        """
        Get a prefix for a namespace.

        @param d: The default prefix value.
        """
        return self.nss.get(k, d)

    def __setitem__(self, k, v):
        """
        Proxy through to setting the prefix for the namespace.
        """
        self.nss.__setitem__(k, v)

    def __getitem__(self, k):
        """
        Proxy through to getting the prefix for the namespace.
        """
        return self.nss.__getitem__(k)
Example #2
1
class Metadata(MutableMapping):
    def __init__(self, seq=None):
        self.dct = OrderedDict(seq) if seq else OrderedDict()

    def __contains__(self, key):
        return self.dct.__contains__(key)

    def __getitem__(self, key):
        return self.dct.__getitem__(key)

    def __setitem__(self, key, value):
        self.dct.__setitem__(key, value)

    def __delitem__(self, key):
        return self.dct.__delitem__(key)

    def __iter__(self):
        return self.dct.__iter__()

    def __len__(self):
        return self.dct.__len__()

    def __repr__(self):
        return repr(self.dct)

    def __str__(self):
        return str(self.dct)
Example #3
1
    def add(self, item):
        """
        Add an element to an OrderedSet.

        This has no effect if the element is already present.
        """
        OrderedDict.__setitem__(self, item, None)
Example #4
1
    def __setitem__(self, key, value):
        """
				>>> T = pykov.Matrix()
				>>> T[('A','B')] = .3
				>>> T
				{('A', 'B'): 0.3}
				>>> T['A','A'] = .7
				>>> T
				{('A', 'B'): 0.3, ('A', 'A'): 0.7}
				>>> T['B','B'] = 0
				>>> T
				{('A', 'B'): 0.3, ('A', 'A'): 0.7}
				>>> T['A','A'] = 0
				>>> T
				{('A', 'B'): 0.3}

				>>> T = pykov.Matrix({('A','B'): 3, ('A','A'): 7, ('B','A'): .1})
				>>> T.states()
				{'A', 'B'}
				>>> T['A','C']=1
				>>> T.states()
				{'A', 'B', 'C'}
				>>> T['A','C']=0
				>>> T.states()
				{'A', 'B'}
				"""
        if abs(value) > numpy.finfo(numpy.float).eps:
            value = int(value * 1000) * 1.0 / 1000.0
            OrderedDict.__setitem__(self, key, value)
        elif key in self:
            del (self[key])
 def __setitem__(self, key, val):
     kl = key.lower()
     if kl in self.keyMap:
         OrderedDict.__setitem__(self, self.keyMap[kl], val)
     else:
         OrderedDict.__setitem__(self, key, val)
         self.keyMap[kl] = key
Example #6
1
class ProductState(Iterable):
    """
    Represents product state as OrderedDict.
    Used for serialization to json and yaml.
    """

    def __init__(self):
        self._coll = OrderedDict()

    def __iter__(self):
        # iterator
        for k, v in self._coll.items():
            yield k, v

    def __setitem__(self, key, value):
        """
        Special method to implement 'ps[key] = value' syntax.
        """
        self._coll.__setitem__(key, value)

    def get_dict(self) -> OrderedDict:
        """
        Returns result as OrderedDict
        """
        return self._coll
Example #7
1
 def __setitem__(self, key, value, PREV=0, NEXT=1, dict_setitem=dict.__setitem__):
     if self.__disabled:
         raise KeyError("you cannot change instance of request data")
     elif not isinstance(value, (list, rdict, ufile)):
         raise ValueError("value has to be list, rdict or ufile")
     else:  # elif key not in self:
         OrderedDict.__setitem__(self, key, value, PREV, NEXT, dict_setitem)
class InfoRow:
    def __init__(self):
        self.dict = OrderedDict()

    def __getitem__(self, item):
        if isinstance(item, int):
            return self.dict.items()[item][1]
        return self.dict.__getitem__(item.lower())

    def __contains__(self, item):
        return self.dict.__contains__(item.lower())

    def __setitem__(self, key, value):
        if isinstance(key, int):
            self.dict.items()[key][1] = value
        self.dict.__setitem__(key.lower(), value)

    def get(self, k, d=None):
        if isinstance(k, int):
            try:
                return self.dict.items()[k][1]
            except:
                return d
        return self.dict.get(k.lower(), d)

    def __str__(self, rowSeparator="\n", columnSeparator="\t"):
        return getStr(dict2Str(self.dict))

    def __unicode__(self):
        return str(self)

    def __repr__(self):
        return str(self)
Example #9
1
class ATimeCache(object):
    """Cache class (dictionary) with a limited size, where only the
    'max_entries' most recently added or accessed entries are stored."""

    def __init__(self, max_entries):
        self._cache = OrderedDict()
        self._max_entries = max_entries

    def _shrink(self):
        while len(self._cache) > self._max_entries:
            self._cache.popitem(last=False)

    def get_max_entries(self):
        return self._max_entries

    def set_max_entries(self, value):
        self._max_entries = value
        self._shrink()

    max_entries = property(get_max_entries, set_max_entries, None, "Set or get the cache size")

    def has_key(self, key):
        return self._cache.has_key(key)

    def __eq__(self, other):
        try:
            return self._cache.__eq__(other._cache)
        except:
            return False

    def __len__(self):
        return self._cache.__len__()

    def __getitem__(self, key):
        value = self._cache.pop(key)
        self._cache[key] = value
        return value

    def __setitem__(self, key, value):
        if self._cache.has_key(key):
            self._cache.pop(key)
        self._cache.__setitem__(key, value)
        self._shrink()

    def __contains__(self, key):
        return self.has_key(key)

    def __str__(self):
        return self.cache.__str__()

    def __iter__(self):
        # Iterate directly on the underlying dict, rather than on this
        # class, in order to change the order of cached items (as
        # opposed to []/__getitem__, which will reinsert an item on top
        # of the stack whenever it is looked up.
        return iter(self._cache)
    def __setitem__(self, key, value, *args, **kwargs):
        """
		This method sets a key and sibling attribute with given value.

		:param key.: Key. ( Object )
		:param value.: Value. ( Object )
		:param \*args: Arguments. ( \* )
		:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
		"""

        OrderedDict.__setitem__(self, key, value, *args, **kwargs)
        OrderedDict.__setattr__(self, key, value)
    def __setattr__(self, attribute, value):
        """
		This method sets both key and sibling attribute with given value.

		:param attribute.: Attribute. ( Object )
		:param value.: Value. ( Object )
		"""

        if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
            if self._OrderedDict__root:
                OrderedDict.__setitem__(self, attribute, value)
        OrderedDict.__setattr__(self, attribute, value)
Example #12
0
 def __setitem__(self, key, value):
     """ Set d[key] to value. """
     with self.lock:
         if len(self) == self.max_len:
             self.popitem(last=False)
         OrderedDict.__setitem__(self, key, value)
         self.key_time_map[key] = {}
Example #13
0
def databaseSchemaBuilder(connection):
    d = OrderedDict()
    sql = "SELECT SCHEMA_NAME,DEFAULT_CHARACTER_SET_NAME,DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA"
    if connection.database:
        sql += " WHERE SCHEMA_NAME = '{}'"
    else:
        params = None
    cur = None
    try:
        cur = connection.cursor(dictionary=True, buffered=True)
        cur.execute(sql.format(connection.database))
        result = cur.fetchall()
    except Exception as e:
        raise e
    finally:
        if cur:
            cur.close()
    if result:
        for db in result:
            name = db.get("SCHEMA_NAME")
            database = DatabaseSchema(name=name, parent=connection)
            database.options["charset"] = db["DEFAULT_CHARACTER_SET_NAME"]
            database.options["collation"] = db["DEFAULT_COLLATION_NAME"]
            d.__setitem__(name, database)
    return d
Example #14
0
    def __setitem__(self, key, value):
        OrderedDict.__setitem__(self, key, value)

        # force regen on next __str__ call
        self.cdxline = None

        # force regen on next to_json() call
        self._cached_json = None
Example #15
0
 def __setitem__(self, key, par):
     # if key not in self:
     #    if not valid_symbol_name(key):
     #        raise KeyError("'%s' is not a valid Parameters name" % key)
     if par is not None and not isinstance(par, (Parameter, PyRhOparameter)):
         raise ValueError("'%s' is not a Parameter" % par)
     OrderedDict.__setitem__(self, key, par)
     par.name = key
Example #16
0
 def __setitem__(self, key, value):
     if key not in self:
         if not valid_symbol_name(key):
             raise KeyError("'%s' is not a valid Parameters name" % key)
     if value is not None and not isinstance(value, Parameter):
         raise ValueError("'%s' is not a Parameter" % value)
     OrderedDict.__setitem__(self, key, value)
     value.name = key
Example #17
0
 def add(self, name, value):
     """Adds a new value for the given key."""
     norm_name = HTTPHeaders._normalize_name(name)
     if norm_name in self:
         # bypass our override of __setitem__ since it modifies _as_list
         OrderedDict.__setitem__(self, norm_name, self[norm_name] + "," + value)
         self._as_list[norm_name].append(value)
     else:
         self[norm_name] = value
Example #18
0
        def __getitem__(self, key, *args, **kwargs):
            # Get the key and remove it from the cache, or raise KeyError
            value = OrderedDict.__getitem__(self, key)
            del self[key]

            # Insert the (key, value) pair on the front of the cache
            OrderedDict.__setitem__(self, key, value)

            # Return the value from the cache
            return value
Example #19
0
 def __setitem__(self, key, par):
     if key not in self:
         if not valid_symbol_name(key):
             raise KeyError("'%s' is not a valid Parameters name" % key)
     if par is not None and not isinstance(par, Parameter):
         raise ValueError("'%s' is not a Parameter" % par)
     OrderedDict.__setitem__(self, key, par)
     par.name = key
     par._expr_eval = self._asteval
     self._asteval.symtable[key] = par.value
Example #20
0
 def __setitem__(self, key, value):
     comtaimKey = 1 if key in silf else 0
     if (len(self) - containKey) >= self._capacity:
         last = self.popitem(last=False)
         print "remove:", last
     if catainKey:
         del self[key]
         print "set:", (key, value)
     else:
         print "add:", (key, value)
     OrderedDict.__setitem__(self.key, value)
Example #21
0
def instances():
    """
        This will list out all the instances and threads per application.
        An application can see only it's threads and instances. 
    """
    mydict = db.hgetall(application_name)
    ordered = OrderedDict()
    for key in sorted(mydict):
        ordered.__setitem__(key, mydict.get(key))
    mylist = []
    return render_template("robots.html", mydict=ordered)
Example #22
0
        def __setitem__(self, key, value, *args, **kwargs):
            # Key was inserted before, remove it so we put it at front later
            if key in self:
                del self[key]

            # Too much items on the cache, remove the least recent used
            elif len(self) >= self._maxsize:
                self.popitem(False)

            # Insert the (key, value) pair on the front of the cache
            OrderedDict.__setitem__(self, key, value, *args, **kwargs)
def applicationsdetails():
    """
    This is the endpoint for providing all info about the applications 
    This is an internal method for registrator through which index.html loads all info
    """
    appdicts = db.hgetall("applications")
    finaldict = OrderedDict()
    for appname in sorted(appdicts):
        instances = json.loads(appdicts.get(appname))
        finaldict.__setitem__(appname, instances)
    return render_template("robots.html", appdicts=finaldict)
Example #24
0
 def __setitem__(self, key, value):
     if key in self:
         OrderedDict.__setitem__(self, key, value)
     else:
         items = self.items() + [(key, value)] if len(self) > 0 else [(key, value)]
         reordered = sorted(items, key=lambda t: (t[1]._shape and not t[1].isrec, t[0]))
         reordered.reverse()  # keep the original pupynere ordering for comparison
         for key in self.keys():
             del self[key]
         for key, val in reordered:
             OrderedDict.__setitem__(self, key, val)
Example #25
0
 def __setitem__(self, key, value):
     containsKey = 1 if key in self else 0
     if len(self) - containsKey > self._capacity:
         last = self.popitem(last=False)
         print("remove:", last)
     if containsKey:
         del self[key]
         print("set:", (key, value))
     else:
         print("add:", (key, value))
     OrderedDict.__setitem__(self, key, value)
Example #26
0
    def __setitem__(self, item, value, **kwargs):

        if isinstance(value, np.ndarray):
            if value.shape == self.shape:
                OrderedDict.__setitem__(self, item, value, **kwargs)
            else:
                raise ValueError(
                    "flags array shape {0} does not match data " "shape {1}".format(value.shape, self.shape)
                )
        else:
            raise TypeError("flags should be given as a Numpy array")
Example #27
0
    def __setitem__(self, key, str_value):
        if not isinstance(str_value, basestring):
            return _OrderedDict.__setitem__(self, key, str_value)

        for fun_key, fun in self._spec._from_str_funs:
            if fun_key == key:
                value = fun(str_value)
                break
        else:
            value = str_value
        _OrderedDict.__setitem__(self, key, value)
Example #28
0
 def __setitem__(self, key, value):
     with self.lock:
         if key in self:
             if self[key]["action"] in ("delete-cypher", "delete-clear"):
                 ## err on the side of caution. if we get a later FS event saying a file has been created, then just replace this deletion in the queue
                 ## note that this update/insertion moves this key to the "back of the line"
                 del self[key]
                 OrderedDict.__setitem__(self, key, value)
             else:
                 self[key]["collided"] = True
         else:
             OrderedDict.__setitem__(self, key, value)
Example #29
0
    def __setitem__(self, k, v):
        # pylint: disable=W0221
        # we want the behavior of OrderedDict, but don't take the
        # additional parameter

        # our keys should always be strings, as should our values. We
        # also have an upper limit on the length we can permit for
        # keys, per the JAR MANIFEST specification.
        k = str(k)
        if len(k) > 68:
            raise ManifestKeyException("key too long", k)
        else:
            OrderedDict.__setitem__(self, k, str(v))
 def __setitem__(self, key, value):
     contains_key = 1 if key in self else 0
     if len(self) - contains_key >= self._capacity:
         last = self.popitem(last=False)
         print("remove: ", last)
     if contains_key:
         del self[key]  # ???为什么要del,难道不会直接覆盖? 效率问题?
         # 覆盖的等于创建了新的对象,原有的value没有呗回收???
         # 用del确保会被gc回收???
         # Re: 可以直接覆盖
         print("set: ", (key, value))
     else:
         print("add: ", (key, value))
     OrderedDict.__setitem__(self, key, value)