Example #1
1
class RingCache(object):
    def __init__(self, maxEntries=100, isAutoAdd=False):
        self.max = maxEntries
        self.d = OrderedDict()
        self.isAutoAdd = isAutoAdd

    def add(self, k, v=None):
        if self.max <= len(self.d):
            self.d.popitem(last=False)
        if k in self.d:
            del (self.d[k])
        self.d[k] = v

    def get(self, k):
        return self.d[k]

    def remove(self, k):
        del (self.d[k])

    def __contains__(self, k):
        if k in self.d:
            v = self.d[k]
            del (self.d[k])
            self.d[k] = v
            return True
        else:
            if self.isAutoAdd:
                self.add(k)
            return False

    def __len__(self):
        return len(self.d)

    def __repr__(self):
        return self.d.__repr__()
Example #2
1
 def __repr__(self, _repr_running={}):
     temp = self.__class__.__name__
     try:
         # The OrderedDict.__repr__ function takes an
         # extra argument. It also prints the name of
         # the main object's class. This logic temporarily
         # resets the class name so this appears to be
         # what it (fundamentally) is: an OrderedDict
         # object. (For this reason, there is also extra
         # logic to make the XMLDictNode __repr__ function
         # work correctly.)
         self.__class__.__name__ = _OrderedDict.__name__
         rv = _OrderedDict.__repr__(self, _repr_running)
     except:
         rv = _OrderedDict.__repr__(self)
     finally:
         self.__class__.__name__ = temp
     return rv
Example #3
1
 def __repr__(self, _repr_running=None):
     if _repr_running is None:
         _repr_running = {}
     temp = self.__class__.__name__
     try:
         # The OrderedDict.__repr__ function takes an
         # extra argument. It also prints the name of
         # the main object's class. This logic temporarily
         # resets the class name so this appears to be
         # what it (fundamentally) is: an OrderedDict
         # object. (For this reason, there is also extra
         # logic to make the XMLDictNode __repr__ function
         # work correctly.)
         self.__class__.__name__ = _OrderedDict.__name__
         rv = _OrderedDict.__repr__(self, _repr_running)
     except TypeError:
         # Looks like the class didn't understand the second
         # argument. Retry with just one argument.
         rv = _OrderedDict.__repr__(self)
     finally:
         self.__class__.__name__ = temp
     return rv
Example #4
1
class OrderedDefaultDict(object):
    """
    Implements (most of) a default dict with ordering.
    """

    def __init__(self, factory):
        self._factory = factory
        self._dict = OrderedDict()

    def __setitem__(self, key, item):
        self._dict.__setitem__(key, item)

    def __getitem__(self, key):
        if key not in self._dict:
            self._dict[key] = self._factory()
        return self._dict.__getitem__(key)

    def __repr__(self):
        return self._dict.__repr__()

    def __iter__(self):
        return self._dict.__iter__()
Example #5
1
 def __repr__(self):
     return "DefaultOrderedDict(%s, %s)" % (self.default_factory, OrderedDict.__repr__(self))
 def __repr__(self):
     # Make the repr pretty. not functional
     # (i.e. calling eval(repr(config_object)) won't work)
     string = OrderedDict.__repr__(self).strip("Config([])")
     string = string.replace("', ", ":").translate(None, "()")
     return "Config({" + string + "})"
Example #7
1
class ListofEntities(list):
    def __init__(self, typ):
        super(ListofEntities, self).__init__()
        from collections import OrderedDict

        self._dict_entities = OrderedDict()
        self._dict_entities_hash = {}
        self.typeItems = typ
        self.type_instance = typ()
        self.changed = []

    def _update_hashes(self):
        self._dict_entities_hash = {hash(v): v for k, v in self._dict_entities.items()}

    def __hash__(self):
        return hash(frozenset(self._dict_entities))

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

    def __repr__(self):
        return self._dict_entities.__repr__()

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

    def __getitem__(self, item):
        return self._dict_entities.values().__getitem__(item)

    def update_from_changed_entities(self, changed_entities):
        if changed_entities is None:
            return
        for entity in changed_entities:
            if hasattr(entity, "is_tombstone") and entity.is_tombstone:
                continue
            try:
                self._dict_entities[entity.id].update_from_changed_entities(entity)
            except KeyError:
                self._dict_entities[entity.id] = entity
        self._update_hashes()

    def get(self, entity_id):
        return self._dict_entities.get(entity_id)

    def extend(self, objects, track=True):
        if not all(isinstance(x, self.typeItems) for x in objects):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        for o in objects:
            self._dict_entities[o.id] = o
            self._dict_entities_hash[hash(o)] = o
        if track:
            self.changed.extend(objects)

    def append(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        self._dict_entities[o.id] = o
        self._dict_entities_hash[hash(o)] = o
        if track:
            self.changed.append(o)

    def delete(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        if o.id in self._dict_entities:
            del self._dict_entities[o.id]
        if hash(o) in self._dict_entities_hash:
            del self._dict_entities_hash[hash(o)]
        if track:
            o.is_tombstone = True
            self.changed.append(o)

    def modify(self, o, track=True):
        if not isinstance(o, self.typeItems):
            raise ValueError("this ListofEntities can only contain %s" % self.typeItems.__name__)
        if o.id in self._dict_entities:
            h = hash(self._dict_entities[o.id])
            if h in self._dict_entities_hash:
                del self._dict_entities_hash[h]
            self._dict_entities[o.id] = o
            self._dict_entities_hash[hash(o)] = o
            if track:
                self.changed.append(o)

    def __iter__(self):
        return self._dict_entities.values().__iter__()

    def __len__(self):
        return len(self._dict_entities)

    def containsduplicate(self, item):
        if not isinstance(item, self.typeItems):
            return False
        else:
            return item._hash() in self._dict_entities_hash

    def __contains__(self, item):
        if not isinstance(item, self.typeItems):
            return False
        else:
            return item.id in self._dict_entities

    def get_changed_entities(self):
        return self.changed
Example #8
0
 def __repr__(self):
     return "{" + OrderedDict.__repr__(self)[8:-2] + "}"
Example #9
0
 def __repr__(self):
     return "OrderedDefaultDict({}, {})".format(self.default_factory, OrderedDict.__repr__(self))
 def __repr__(self, *args, **kwargs):
     return "OrderedDefaultDict(%s, %s)" % (self.default_factory, OrderedDict.__repr__(self))
Example #11
0
class Headers:
    """Utility for managing HTTP headers for both clients and servers.

    It has a dictionary like interface with few extra functions to facilitate
    the insertion of multiple header values. Header fields are
    **case insensitive**, therefore doing::

        >>> h = Headers()
        >>> h['Content-Length'] = '1050'

    is equivalent to

        >>> h['content-length'] = '1050'

    :param headers: optional iterable over header field/value pairs.
    :param kind: optional headers type, one of ``server``, ``client`` or
        ``both``.
    :param strict: if ``True`` only valid headers field will be included.

    This :class:`Headers` container maintains an ordering as suggested by
    http://www.w3.org/Protocols/rfc2616/rfc2616.html:

    .. epigraph::

        The order in which header fields with differing field names are
        received is not significant. However, it is "good practice" to send
        general-header fields first, followed by request-header or
        response-header fields, and ending with the entity-header fields.

        -- rfc2616 section 4.2

    The strict parameter is rarely used and it forces the omission on
    non-standard header fields.
    """

    @classmethod
    def make(cls, headers):
        if not isinstance(headers, cls):
            headers = cls(headers)
        return headers

    def __init__(self, *args, **kwargs):
        self._headers = OrderedDict()
        if args or kwargs:
            self.update(*args, **kwargs)

    def __repr__(self):
        return self._headers.__repr__()

    def __str__(self):
        return "\r\n".join(self._ordered())

    def __bytes__(self):
        return str(self).encode(DEFAULT_CHARSET)

    def __len__(self):
        return len(self._headers)

    def update(self, *args, **kwargs):
        """Extend the headers with an ``iterable``.

        :param iterable: a dictionary or an iterable over keys, values tuples.
        """
        if len(args) == 1:
            for key, value in mapping_iterator(args[0]):
                self.add_header(key, value)
        elif args:
            raise TypeError("update expected at most 1 arguments, got %d" % len(args))
        for key, value in kwargs.items():
            self.add_header(key, value)

    def override(self, iterable):
        """Extend headers by overriding fields form iterable.

        :param iterable: a dictionary or an iterable over keys, values tuples.
        """
        seen = set()
        for key, value in mapping_iterator(iterable):
            key = key.lower()
            if key in seen:
                self.add_header(key, value)
            else:
                seen.add(key)
                self[key] = value

    def copy(self):
        return self.__class__(self)

    def __contains__(self, key):
        return header_field(key) in self._headers

    def __getitem__(self, key):
        key = header_field(key)
        values = self._headers[key]
        joiner = HEADER_FIELDS_JOINER.get(key, ", ")
        if joiner is None:
            joiner = "; "
        return joiner.join(values)

    def __delitem__(self, key):
        self._headers.__delitem__(header_field(key))

    def __setitem__(self, key, value):
        key = header_field(key)
        if key and value:
            if not isinstance(value, list):
                value = header_values(key, value)
            self._headers[key] = value

    def get(self, key, default=None):
        """Get the field value at ``key`` as comma separated values.

        For example::

            >>> from pulsar.utils.httpurl import Headers
            >>> h = Headers(kind='client')
            >>> h.add_header('accept-encoding', 'gzip')
            >>> h.add_header('accept-encoding', 'deflate')
            >>> h.get('accept-encoding')

        results in::

            'gzip, deflate'
        """
        if key in self:
            return self.__getitem__(key)
        else:
            return default

    def get_all(self, key, default=None):
        """Get the values at header ``key`` as a list rather than a
        string separated by comma (which is returned by the
        :meth:`get` method).

        For example::

            >>> from pulsar.utils.httpurl import Headers
            >>> h = Headers(kind='client')
            >>> h.add_header('accept-encoding', 'gzip')
            >>> h.add_header('accept-encoding', 'deflate')
            >>> h.get_all('accept-encoding')

        results in::

            ['gzip', 'deflate']
        """
        return self._headers.get(header_field(key), default)

    def has(self, field, value):
        """Check if ``value`` is available in header ``field``."""
        value = value.lower()
        for c in self.get_all(field, ()):
            if c.lower() == value:
                return True
        return False

    def pop(self, key, *args):
        return self._headers.pop(header_field(key), *args)

    def clear(self):
        """Same as :meth:`dict.clear`, it removes all headers.
        """
        self._headers.clear()

    def getheaders(self, key):  # pragma    nocover
        """Required by cookielib in python 2.

        If the key is not available, it returns an empty list.
        """
        return self._headers.get(header_field(key), [])

    def add_header(self, key, values):
        """Add ``values`` to ``key`` header.

        If the header is already available, append the value to the list.

        :param key: header name
        :param values: a string value or a list/tuple of strings values
            for header ``key``
        """
        key = header_field(key)
        if key and values:
            if not isinstance(values, (tuple, list)):
                values = header_values(key, values)
            current = self._headers.get(key, [])
            for value in values:
                if value and value not in current:
                    current.append(value)
            self._headers[key] = current

    def remove_header(self, key, value=None):
        """Remove the header at ``key``.

        If ``value`` is provided, it removes only that value if found.
        """
        key = header_field(key)
        if key:
            if value:
                value = value.lower()
                values = self._headers.get(key, [])
                removed = None
                for v in values:
                    if v.lower() == value:
                        removed = v
                        values.remove(v)
                self._headers[key] = values
                return removed
            else:
                return self._headers.pop(key, None)

    def flat(self, version, status):
        """Full headers bytes representation"""
        vs = version + (status, self)
        return ("HTTP/%s.%s %s\r\n%s" % vs).encode(DEFAULT_CHARSET)

    def __iter__(self):
        dj = ", "
        for k, values in self._headers.items():
            joiner = HEADER_FIELDS_JOINER.get(k, dj)
            if joiner:
                yield k, joiner.join(values)
            else:
                for value in values:
                    yield k, value

    def _ordered(self):
        for key, header in self:
            yield "%s: %s" % (key, header)
        yield ""
        yield ""
    def __repr__(self, _repr_running=None):
        if _repr_running is None:
            _repr_running = {}

        return "OrderedDefaultDict(%s, %s)" % (self.default_factory, OrderedDict.__repr__(self, _repr_running))
Example #13
0
 def __repr__(self):
     return "OrderedDefaultDict(%s, %s)" % (self.default_callable, OrderedDict.__repr__(self))
Example #14
0
class Enviroment:
    __global_env = None

    def __init__(self, superEnv=None):
        self.map = OrderedDict()
        self.map_index = []
        self.superEnv = superEnv

        if superEnv == None:
            Enviroment.__global_env = self

            self.put(new(LispSymbol, "+"), Plus())
            self.put(new(LispSymbol, "-"), Minus())
            self.put(new(LispSymbol, "define"), Define())
            self.put(new(LispSymbol, "if"), If())
            self.put(new(LispSymbol, "eq?"), Eq())
            self.put(new(LispSymbol, ">?"), Grt())
            self.put(new(LispSymbol, "<?"), Lwt())
            self.put(new(LispSymbol, "lambda"), Lambda())
            self.put(new(LispSymbol, "begin"), Begin())
            self.put(new(LispSymbol, "set!"), Set())
            self.put(new(LispSymbol, "quote"), Quote())
            self.put(new(LispSymbol, "write"), Write())
            self.put(new(LispSymbol, "print"), BuildInFunctions.Print())
            self.put(new(LispSymbol, "getParam"), GetParam())
            self.put(new(LispSymbol, "getLocal"), GetLocal())
            self.put(new(LispSymbol, "getSuperParam"), GetSuperParam())
            self.put(new(LispSymbol, "getSuperLocal"), GetSuperLocal())
            self.put(new(LispSymbol, "getGlobal"), GetGlobal())
            self.put(new(LispSymbol, "label$"), LispTKLabel())
            self.put(new(LispSymbol, "tk$"), LispTK())
            self.put(new(LispSymbol, "text$"), LispTKText())
            self.put(new(LispSymbol, "button$"), LispTKButton())
            self.put(new(LispSymbol, "frame$"), LispTKFrame())
            self.put(new(LispSymbol, "toplevel$"), LispTKToplevel())
            self.put(new(LispSymbol, "scrollbar$"), LispTKScrollbar())
            self.put(new(LispSymbol, "eval"), Eval())
            self.put(new(LispSymbol, "str_concat"), Str_Concat())
            self.put(new(LispSymbol, "load"), Load())
            self.put(new(LispSymbol, "save"), Save())
            self.put(new(LispSymbol, "type"), Type())
            self.put(new(LispSymbol, "call"), Call())

    def set(self, key, value):
        if key in self.map:
            self.map[key] = value
            self.map_index = self.map.values()
        else:
            raise SymbolNotFound("Key '%s' is not defined, yet" % key.value)

    def put(self, key, value):
        self.map[key] = value
        self.map_index = self.map.values()

    def get(self, key):
        env = self
        while env != None:
            try:
                return env.map[key]
            except KeyError:
                env = env.superEnv
        print "UNDEFINED SYMBOL"
        raise SymbolNotFound('Symbol Not Found: "%s"' % key.value)

    def get_local_by_index(self, index):
        return self.map_index[index]

    def get_global_by_index(self, index):
        return Enviroment.__global_env.map_index[index]

    def get_local_index(self, element):
        i = 0
        for key in self.map:
            if key == element:
                return i
            i += 1
        return -1

    def get_super_local_by_index(self, index, env_number):
        _env = None
        for x in range(env_number):
            _env = self.superEnv
        return _env.get_local_by_index(index)

    def get_super_parameter_by_index(self, index, env_number):
        _env = None
        for x in range(env_number):
            _env = self.superEnv
        return _env.get_parameter_by_index(index)

    def get_global_index(self, element):
        i = 0
        for key in Enviroment.__global_env.map:
            if key == element:
                return i
            i += 1
        return -1

    def setParameterSymbols(self, symbols):
        self.parameter_symbols = symbols

    def getParameterSymbols(self):
        return self.parameter_symbols

    def setParameterList(self, param):
        self.parameter = param

    def get_parameter_by_index(self, index):
        if hasattr(self, "parameter"):
            return self.parameter[index]
        return None

    def __repr__(self):
        return self.map.__repr__()
Example #15
0
 def __repr__(self):
     """
             BodyData.__repr__
     """
     return "(BodyData) " + OrderedDict.__repr__(self)