Example #1
1
    def __sliceToIndex(self, item):
        start = stop = None

        if isinstance(item.start, datetime.datetime):
            start = self._pos_of_time[item.start]
        else:
            if item.start is None:
                start = 0
            else:
                if item.start < 0:
                    start = OrderedDict.__len__(self) + item.start
                else:
                    start = item.start

        if isinstance(item.stop, datetime.datetime):
            stop = self._pos_of_time[item.stop]
        else:
            if item.stop is None:
                stop = OrderedDict.__len__(self)
            else:
                if item.stop < 0:
                    stop = OrderedDict.__len__(self) + item.stop
                else:
                    stop = item.stop

        return start, stop
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
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)
Example #4
1
    def __getitem__(self, item):
        if isinstance(item, slice):
            data = []

            start, stop = self.__sliceToIndex(item)
            for point in xrange(start, stop):
                data += [self.__getitem__(point)]

            return data
        if isinstance(item, int):
            if item < 0:
                return OrderedDict.__getitem__(self, self._time_of_pos[(OrderedDict.__len__(self)) + item])
            else:
                return OrderedDict.__getitem__(self, self._time_of_pos[item])
        else:
            return OrderedDict.__getitem__(self, item)
Example #5
1
class IndexedDict(Mapping):
    """Wrapper around OrderedDict that allows access via item position or key"""

    def __init__(self, *args, **kwargs):
        self._od = OrderedDict(*args, **kwargs)

    def __getitem__(self, k):
        try:
            return list(self._od.values())[k]
        except TypeError:
            return self._od[k]

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

    def __iter__(self):
        return self._od.__iter__()
Example #6
1
class TargetVars(Mapping):
    """Immutable ordered mapping from target variables to their values."""

    EMPTY = EmptyTargetVar()

    def __init__(self, target_vars=tuple(), is_empty=True):
        if is_empty:
            target_vars = [(v, self.EMPTY) for v in target_vars]

        self._od = OrderedDict(target_vars)

    # getitem, len, iter wrap OrderedDict behavior
    def __getitem__(self, k):
        return self._od.__getitem__(k)

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

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

    def update(self, *args, **kwargs):
        cpy = self.copy()
        cpy._od.update(*args, **kwargs)
        return cpy

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

    def __str__(self):
        """Format target vars for printing"""
        if len(self) > 1:
            return "({})".format(", ".join(self._od.keys()))
        else:
            return "".join(self._od.keys())

    def defined_items(self):
        """Return copy of instance, omitting entries that are EMPTY"""
        return self.__class__([(k, v) for k, v in self.items() if v is not self.EMPTY], is_empty=False)
class ChainSet(object):
    """
    Base class for various methods to rename chains

    Contains _chains, which maps from the renamed chain to a tuple with the
    original (object,state,chain). All dict-like accessors work on ChainSets,
    e.g.
        chain_set["A"] -> ("obj",1,"A")

    """

    def __init__(self):
        # Use an OrderedDict in Python >= 1.7 for better printing
        if _orderedDict:
            self._chains = OrderedDict()
        else:
            self._chains = dict()

    def map_chain(self, obj, state, origChain):
        """
        map_chain(string obj,int state, string chain]]) -> string

        Maps a chain letter to a unique chainID. Results are unique within each
        instance, and can be used as keys on this chain set.
        """
        raise NotImplementedError("Base class")

    # delegate most methods to _chains
    def __getattr__(self, at):
        if at in "pop popitem update setdefault".split():
            raise AttributeError("type object '%s' has no attribute '%s'" % (type(self), at))
        return getattr(self._chains, at)

    def __cmp__(self, other):
        return self._chains.__cmp__(other)

    def __eq__(self, other):
        return self._chains.__eq__(other)

    def __ge__(self, other):
        return self._chains.__ge__(other)

    def __gt__(self, other):
        return self._chains.__gt__(other)

    def __le__(self, other):
        return self._chains.__le__(other)

    def __lt__(self, other):
        return self._chains.__lt__(other)

    def __ne__(self, other):
        return self._chains.__ne__(other)

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

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

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

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

    def __str__(self):
        return str(self._chains)

    @staticmethod
    def _int_to_chain(i, base=_default_base):
        """
        _int_to_chain(int,int) -> str

        Converts a positive integer to a chain ID. Chain IDs include uppercase
        characters, numbers, and optionally lowercase letters.

        i = a positive integer to convert
        base = the alphabet size to include. Typically 36 or 62.
        """
        if i < 0:
            raise ValueError("positive integers only")
        if base < 0 or 62 < base:
            raise ValueError("Invalid base")

        quot = int(i) / base
        rem = i % base
        if rem < 26:
            letter = chr(ord("A") + rem)
        elif rem < 36:
            letter = str(rem - 26)
        else:
            letter = chr(ord("a") + rem - 36)
        if quot == 0:
            return letter
        else:
            return ChainSet._int_to_chain(quot - 1, base) + letter
Example #8
1
class DotMap(OrderedDict):
    def __init__(self, *args, **kwargs):
        self._map = OrderedDict()
        if args:
            d = args[0]
            if type(d) is dict:
                for k, v in self.__call_items(d):
                    if type(v) is dict:
                        v = DotMap(v)
                    self._map[k] = v
        if kwargs:
            for k, v in self.__call_items(kwargs):
                self._map[k] = v

    def __call_items(self, obj):
        if hasattr(obj, "iteritems") and ismethod(getattr(obj, "iteritems")):
            return obj.iteritems()
        else:
            return obj.items()

    def items(self):
        return self.iteritems()

    def iteritems(self):
        return self.__call_items(self._map)

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

    def next(self):
        return self._map.next()

    def __setitem__(self, k, v):
        self._map[k] = v

    def __getitem__(self, k):
        if k not in self._map:
            # automatically extend to new DotMap
            self[k] = DotMap()
        return self._map[k]

    def __setattr__(self, k, v):
        if k == "_map":
            super(DotMap, self).__setattr__(k, v)
        else:
            self[k] = v

    def __getattr__(self, k):
        if k == "_map":
            super(DotMap, self).__getattr__(k)
        else:
            return self[k]

    def __delattr__(self, key):
        return self._map.__delitem__(key)

    def __contains__(self, k):
        return self._map.__contains__(k)

    def __str__(self):
        items = []
        for k, v in self.__call_items(self._map):
            items.append("{0}={1}".format(k, repr(v)))
        out = "DotMap({0})".format(", ".join(items))
        return out

    def __repr__(self):
        return str(self)

    def toDict(self):
        d = {}
        for k, v in self.items():
            if type(v) is DotMap:
                v = v.toDict()
            d[k] = v
        return d

    def pprint(self):
        pprint(self.toDict())

        # proper dict subclassing

    def values(self):
        return self._map.values()

    @classmethod
    def parseOther(self, other):
        if type(other) is DotMap:
            return other._map
        else:
            return other

    def __cmp__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__cmp__(other)

    def __eq__(self, other):
        other = DotMap.parseOther(other)
        if not isinstance(other, dict):
            return False
        return self._map.__eq__(other)

    def __ge__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ge__(other)

    def __gt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__gt__(other)

    def __le__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__le__(other)

    def __lt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__lt__(other)

    def __ne__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ne__(other)

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

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

    def clear(self):
        self._map.clear()

    def copy(self):
        return self

    def get(self, key, default=None):
        return self._map.get(key, default)

    def has_key(self, key):
        return key in self._map

    def iterkeys(self):
        return self._map.iterkeys()

    def itervalues(self):
        return self._map.itervalues()

    def keys(self):
        return self._map.keys()

    def pop(self, key, default=None):
        return self._map.pop(key, default)

    def popitem(self):
        return self._map.popitem()

    def setdefault(self, key, default=None):
        self._map.setdefault(key, default)

    def update(self, *args, **kwargs):
        if len(args) != 0:
            self._map.update(*args)
        self._map.update(kwargs)

    def viewitems(self):
        return self._map.viewitems()

    def viewkeys(self):
        return self._map.viewkeys()

    def viewvalues(self):
        return self._map.viewvalues()

    @classmethod
    def fromkeys(cls, seq, value=None):
        d = DotMap()
        d._map = OrderedDict.fromkeys(seq, value)
        return d
Example #9
1
class DotMap(MutableMapping, OrderedDict):
    def __init__(self, *args, **kwargs):
        self._map = OrderedDict()
        self._dynamic = True
        if kwargs:
            if "_dynamic" in kwargs:
                self._dynamic = kwargs["_dynamic"]
        if args:
            d = args[0]
            if isinstance(d, dict):
                for k, v in self.__call_items(d):
                    if type(v) is dict:
                        v = DotMap(v, _dynamic=self._dynamic)
                    if type(v) is list:
                        l = []
                        for i in v:
                            n = i
                            if type(i) is dict:
                                n = DotMap(i, _dynamic=self._dynamic)
                            l.append(n)
                        v = l
                    self._map[k] = v
        if kwargs:
            for k, v in self.__call_items(kwargs):
                if k is not "_dynamic":
                    self._map[k] = v

    def __call_items(self, obj):
        if hasattr(obj, "iteritems") and ismethod(getattr(obj, "iteritems")):
            return obj.iteritems()
        else:
            return obj.items()

    def items(self):
        return self.iteritems()

    def iteritems(self):
        return self.__call_items(self._map)

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

    def next(self):
        return self._map.next()

    def __setitem__(self, k, v):
        self._map[k] = v

    def __getitem__(self, k):
        if k not in self._map and self._dynamic and k != "_ipython_canary_method_should_not_exist_":
            # automatically extend to new DotMap
            self[k] = DotMap()
        return self._map[k]

    def __setattr__(self, k, v):
        if k in {"_map", "_dynamic", "_ipython_canary_method_should_not_exist_"}:
            super(DotMap, self).__setattr__(k, v)
        else:
            self[k] = v

    def __getattr__(self, k):
        if k == {"_map", "_dynamic", "_ipython_canary_method_should_not_exist_"}:
            super(DotMap, self).__getattr__(k)
        else:
            return self[k]

    def __delattr__(self, key):
        return self._map.__delitem__(key)

    def __contains__(self, k):
        return self._map.__contains__(k)

    def __str__(self):
        items = []
        for k, v in self.__call_items(self._map):
            # bizarre recursive assignment situation (why someone would do this is beyond me)
            if id(v) == id(self):
                items.append("{0}=DotMap(...)".format(k))
            else:
                items.append("{0}={1}".format(k, repr(v)))
        out = "DotMap({0})".format(", ".join(items))
        return out

    def __repr__(self):
        return str(self)

    def toDict(self):
        d = {}
        for k, v in self.items():
            if type(v) is DotMap:
                # bizarre recursive assignment support
                if id(v) == id(self):
                    v = d
                else:
                    v = v.toDict()
            elif type(v) is list:
                l = []
                for i in v:
                    n = i
                    if type(i) is DotMap:
                        n = i.toDict()
                    l.append(n)
                v = l
            d[k] = v
        return d

    def pprint(self):
        pprint(self.toDict())

    def empty(self):
        return not any(self)

        # proper dict subclassing

    def values(self):
        return self._map.values()

        # ipython support

    def __dir__(self):
        return self.keys()

    @classmethod
    def parseOther(self, other):
        if type(other) is DotMap:
            return other._map
        else:
            return other

    def __cmp__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__cmp__(other)

    def __eq__(self, other):
        other = DotMap.parseOther(other)
        if not isinstance(other, dict):
            return False
        return self._map.__eq__(other)

    def __ge__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ge__(other)

    def __gt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__gt__(other)

    def __le__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__le__(other)

    def __lt__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__lt__(other)

    def __ne__(self, other):
        other = DotMap.parseOther(other)
        return self._map.__ne__(other)

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

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

    def clear(self):
        self._map.clear()

    def copy(self):
        return DotMap(self.toDict())

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

    def __deepcopy__(self, memo=None):
        return self.copy()

    def get(self, key, default=None):
        return self._map.get(key, default)

    def has_key(self, key):
        return key in self._map

    def iterkeys(self):
        return self._map.iterkeys()

    def itervalues(self):
        return self._map.itervalues()

    def keys(self):
        return self._map.keys()

    def pop(self, key, default=None):
        return self._map.pop(key, default)

    def popitem(self):
        return self._map.popitem()

    def setdefault(self, key, default=None):
        self._map.setdefault(key, default)

    def update(self, *args, **kwargs):
        if len(args) != 0:
            self._map.update(*args)
        self._map.update(kwargs)

    def viewitems(self):
        return self._map.viewitems()

    def viewkeys(self):
        return self._map.viewkeys()

    def viewvalues(self):
        return self._map.viewvalues()

    @classmethod
    def fromkeys(cls, seq, value=None):
        d = DotMap()
        d._map = OrderedDict.fromkeys(seq, value)
        return d

    def __getstate__(self):
        return self.__dict__

    def __setstate__(self, d):
        self.__dict__.update(d)
Example #10
0
class TestNodeSet(ExitStack):
    def __init__(
        self,
        names: Iterable[str] = None,
        count: int = None,
        nodeReg=None,
        tmpdir=None,
        keyshare=True,
        primaryDecider=None,
    ):

        self.tmpdir = tmpdir

        super().__init__()

        self.primaryDecider = primaryDecider

        self.nodes = OrderedDict()  # type: Dict[str, TestNode]
        # Can use just self.nodes rather than maintaining a separate dictionary
        # but then have to pluck attributes from the `self.nodes` so keeping
        # it simple a the cost of extra memory and its test code so not a big
        # deal

        if nodeReg:
            self.nodeReg = nodeReg
        else:
            nodeNames = (
                names
                if names is not None and count is None
                else genNodeNames(count)
                if count is not None
                else error("only one of either names or count is required")
            )
            self.nodeReg = genNodeReg(names=nodeNames)  # type: Dict[str, NodeDetail]
        for name in self.nodeReg.keys():
            node = self.addNode(name)

        # The following lets us access the nodes by name as attributes of the
        # NodeSet. It's not a problem unless a node name shadows a member.
        self.__dict__.update(self.nodes)

    def addNode(self, name: str) -> TestNode:

        if name in self.nodes:
            error("{} already added".format(name))

        assert name in self.nodeReg
        ha, cliname, cliha = self.nodeReg[name]

        # nstack = dict(name=name,
        #               ha=ha,
        #               main=True,
        #               auto=auto if auto is not None else AutoMode.always)
        #
        # # TODO Should the `auto` for client stack always be `AutoMode.always`
        # cstack = dict(name=cliname,
        #               ha=cliha,
        #               main=True,
        #               auto=AutoMode.always)  # client stack is promiscuous, for now

        node = self.enter_context(
            TestNode(
                name=name,
                ha=ha,
                clientAuthNr=SimpleAuthNr(),
                cliname=cliname,
                cliha=cliha,
                nodeRegistry=copy(self.nodeReg),
                basedirpath=self.tmpdir,
                primaryDecider=self.primaryDecider,
            )
        )
        self.nodes[name] = node
        self.__dict__[name] = node
        return node

    def removeNode(self, name, shouldClean):
        self.nodes[name].stop()
        if shouldClean:
            self.nodes[name].nodestack.keep.clearAllDir()
            self.nodes[name].clientstack.keep.clearAllDir()
        del self.nodes[name]
        del self.__dict__[name]
        # del self.nodeRegistry[name]
        # for node in self:
        #     node.removeNodeFromRegistry(name)

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

    def __getitem__(self, key):
        return self.nodes.get(key)

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

    @property
    def nodeNames(self):
        return sorted(self.nodes.keys())

    def getNode(self, node: NodeRef) -> TestNode:
        return (
            node
            if isinstance(node, Node)
            else self.nodes.get(node)
            if isinstance(node, str)
            else error("Expected a node or node name")
        )

    @staticmethod
    def getNodeName(node: NodeRef) -> str:
        return (
            node
            if isinstance(node, str)
            else node.name
            if isinstance(node, Node)
            else error("Expected a node or node name")
        )

    def connect(self, fromNode: NodeRef, toNode: NodeRef):
        fr = self.getNode(fromNode)
        to = self.getNode(toNode)
        fr.connect(to.nodestack.ha)

    def connectAll(self):
        for c in combinations(self.nodes.keys(), 2):
            print("connecting {} to {}".format(*c))
            self.connect(*c)

    def getLastMsgReceived(self, node: NodeRef, method: str = None) -> Tuple:
        return getLastMsgReceivedForNode(self.getNode(node), method)

    def getAllMsgReceived(self, node: NodeRef, method: str = None) -> Tuple:
        return getAllMsgReceivedForNode(self.getNode(node), method)
Example #11
0
class MatchmakerQueue:
    def __init__(self, queue_name: str, player_service: "PlayerService", game_service: "GameService"):
        self.player_service = player_service
        self.game_service = game_service
        self.queue_name = queue_name
        self.rating_prop = "ladder_rating"
        self.queue = OrderedDict()
        self._logger.info("MatchmakerQueue initialized for {}".format(queue_name))

    def notify_potential_opponents(self, search: Search, potential=True):
        """
        Notify opponents who might potentially match the given search object
        :param search: search object to notify for
        :param potential: Whether or not we've started or stopped searching
        :return:
        """
        self._logger.info("Notifying potential opponents")
        for opponent in self.player_service.players.values():
            if opponent == search.player:
                continue
            quality = search.quality_with(opponent)
            if quality >= search.match_threshold:
                opponent.notify_potential_match(search.player, potential)

    def push(self, search: Search):
        """
        Push the given search object onto the queue

        :param search:
        :return:
        """
        self.queue[search.player] = search

    def match(self, s1: Search, s2: Search):
        """
        Mark the given two searches as matched
        :param s1:
        :param s2:
        :return:
        """
        if (s1.is_matched or s2.is_matched) or (s1.is_cancelled or s2.is_cancelled):
            return False
        s1.match(s2)
        s2.match(s1)
        if s1.player in self.queue:
            del self.queue[s1.player]
        if s2.player in self.queue:
            del self.queue[s2.player]
        asyncio.ensure_future(self.game_service.ladder_service.start_game(s1.player, s2.player))
        return True

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

    async def search(self, player, start_time=None, search=None):
        """
        Search for a match.

        If a suitable match is found, immediately calls on_matched_with on both players.

        Otherwise, puts a search object into the Queue and awaits completion

        :param player: Player to search for a matchup for
        """
        search = search or Search(player, start_time)
        with server.stats.timer("matchmaker.search"):
            try:
                self._logger.debug("Searching for matchup for {}".format(player))
                for opponent, opponent_search in self.queue.copy().items():
                    if opponent == player:
                        continue

                    quality = search.quality_with(opponent)
                    threshold = search.match_threshold
                    self._logger.debug(
                        "Game quality between {} and {}: {} (threshold: {})".format(
                            player, opponent, quality, threshold
                        )
                    )
                    if quality >= threshold:
                        if self.match(search, opponent_search):
                            return

                self.notify_potential_opponents(search, True)

                self._logger.debug("Found nobody searching, pushing to queue: {}".format(search))
                self.queue[player] = search
                await search.await_match()
                self._logger.debug("Search complete: {}".format(search))
                self.notify_potential_opponents(search, False)
            except CancelledError:
                pass
Example #12
0
class Stack(object):
    """ Base class to store pandas objects, with special operations to
    return as 3d data (eg panel) and to apply functions itemwise.  Items are
    stored in an ordered dict."""

    itemlabel = "Item"

    _magic = ["__len__", "__iter__", "__reversed__", "__contains__"]

    def __init__(self, data, keys=None, name="", sort_items=False):
        self.name = name

        # Dictionary input
        if isinstance(data, dict):
            logger.debug('Initializing "%s" from dictionary.' % self.full_name)
            if sort_items:
                logger.debug("Sorting keys")
                self._data = OrderedDict(sorted(data.keys(), key=lambda t: t[0]))

            else:
                self._data = OrderedDict(data)

        else:

            if not isinstance(data, Iterable):
                logger.info("%s constructed from non-iterable... converting " "data to an iterable" % self.full_name)
                data = [data]

            if keys:
                if not isinstance(keys, Iterable):
                    logger.info(
                        "%s constructed from non-iterable... converting " "keys to an iterable" % self.full_name
                    )
                    keys = [keys]

                if len(keys) != len(data):
                    raise ValueError("Length mistmatch: keys and data (%s,%s)" % (len(keys), len(data)))

            # If keys not passed, generate them
            else:
                # Zipped data ((key, df), (key, df))
                try:
                    keys, data = zip(*data)
                except Exception:
                    keys = self._gen_keys(len(data))
                    if len(keys) > 1:
                        logger.warn("Generating keys %s-%s" % (keys[0], keys[-1]))
                    else:
                        logger.warn("Generating key %s" % keys[0])

            self._data = OrderedDict([(key, data[i]) for (i, key) in enumerate(keys)])

    @property
    def _address(self):
        """ Property to make easily accesible by multicanvas """
        return mem_address(super(Stack, self).__repr__())

    def _gen_keys(self, length):
        """ Return a list of itemlables (item0, item1 etc...) using
            self.itemlabel and a length"""

        logger.debug("Items not found on %s: generating item list" % self.full_name)
        return [self.itemlabel + str(i) for i in range(length)]

    # --------------------
    # Dictionary Interface
    def __getitem__(self, keyslice):
        """ If single name, used dict interface.  If slice or integer, uses 
        list interface.  All results parameterized to key, data pairs, passed
        directly into a new Stack.
        """
        # Slice as list of strings or int [0, 'foo', 2, 'bar']
        if hasattr(keyslice, "__iter__"):

            tuples_out = []
            for item in keyslice:
                if isinstance(item, str):
                    item = self._data.keys().index(item)
                tuples_out.append(self._data.items()[item])

        else:
            if isinstance(keyslice, int) or isinstance(keyslice, slice):
                tuples_out = self._data.items()[keyslice]
            else:
                tuples_out = [(keyslice, self._data[keyslice])]  # keyslice is name

        # If single item, return TimeSpectra, else, return new Stack
        # Canonical slicing implementaiton; don't change unless good reason
        # Because len() wonky with nested tuples (eg (x,y) and [(x1,y1),(x2,y2)]
        # are both length two, this will work:

        if sum(1 for x in tuples_out) == 2:
            return tuples_out[1]  # Return timespectra
        else:
            return self.__class__(tuples_out)

    def __delitem__(self, keyslice):
        """ Delete a single name, or a keyslice from names/canvas """

        if isinstance(keyslice, str):
            idx = self.names.index(keyslice)
            self.pop(idx)
        else:
            raise NotImplementedError("Deletion only supports single entry")

    def __setitem__(self, name, canvas):
        """ """
        if name in self.names:
            idx = self.names.index(name)
            self.pop(idx)
            self.insert(idx, name, canvas)

        else:
            self.names.append(name)

    def __getattr__(self, attr):
        """ If attribute not found, try attribute lookup in dictionary.  If
        that is not found, try finding attribute on self._data.
        
        For example, self.keys() will first look for self['keys'].  Since
        this isn't found, it calls self._data.keys().  But if I do 
        self.Item1, then it returns self['Item1'].  The very rare conflict
        case that a user has named the items a method that may already exist
        in the dictionary (eg items=['a','b','keys'] is addressed.
        """

        if attr in self._data.keys():
            if hasattr(self._data, attr):
                raise AttributeError(
                    '"%s attribute" found in both the items\
                and as a method of the underlying dictionary object.'
                    % (attr)
                )
            else:
                return self[attr]
        return getattr(self._data, attr)

    # Attributes deferred to self.data /dictionary
    def __len__(self):
        return self._data.__len__()

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

    def __reversed__(self):
        return self._data.__reversed__()

    def __contains__(self):
        return self._data.__contains__()

    def as_3d(self):
        """ Return 3d structure of data.  Default is panel."""
        raise Panel(data=self._data)

        ### Data types without labels

    # Is this realy necessary?  See pyparty.ParticleManger for possibly more consistent implementation
    def get_all(self, attr, astype=tuple):
        """Generator/tuple etc.. of (item, attribute) pairs. """

        return put._parse_generator(((item[0], getattr(item[1], attr)) for item in self.items()), astype)

    def _get_unique(self, attr):
        """ Inspects Stack itemwise for an attribute for unique values.
        If non-unique value for the attributes are found, returns
        "mixed". 
        """
        unique = set(self.get_all(attr, astype=dict).values())
        if len(unique) > 1:
            return "mixed"
        else:
            return tuple(unique)[0]  # set doesn't support indexing

    def set_all(self, attr, val, inplace=False):
        """ Set attributes itemwise.  
            If not inplace, returns new instance of self"""
        if inplace:
            for (key, item) in self.items():
                try:
                    setattr(item, attr, val)
                except Exception as E:
                    raise Exception(
                        'Could not set %s in "%s".  Received the following \
                     exception:\n "%s"'
                        % (attr, key, E)
                    )
        else:
            out = deepcopy(self._data)  # DEEPCOPY
            for item in out:
                setattr(out[item], attr, val)
            return self.__class__(out)

    def apply(self, func, *args, **kwargs):
        """ Applies a user-passed function, or calls an instance method itemwise.
        
        
        Parameters:
        -----------
        func: str or function
            If string, must correspond to a method on the object stored 
            itemwise in the stack.  If a function, appliked itemwise to
            objects stored.  
              
        inplace: False 
            Special kwarg.  If true, self._data modified inplace, 
            otherwise new specstack is returned.
                         
        *args, **kwargs: 
            func arguments.
          
        Returns:
        --------
        If not inplace, returns SpecStack after itemwise application.
            
        """

        inplace = kwargs.pop("inplace", False)

        if isinstance(func, basestring):
            if inplace:
                for item in self:
                    self[item] = getattr(self[item], func)(*args, **kwargs)

            else:
                return self.__class__(OrderedDict([(k, getattr(v, func)(*args, **kwargs)) for k, v in self.items()]))

        # function, numpyfunction etc...
        else:
            if inplace:
                for item in self:
                    self[item] = self[item].apply(func)(*args, **kwargs)

            else:
                return self.__class__(OrderedDict([(k, v.apply(func, *args, **kwargs)) for k, v in self.items()]))

    @property
    def full_name(self):
        """ Timespectra:name or Timespectra:unnamed.  Useful for scripts mostly """
        outname = getattr(self, "name", "unnamed")
        return "%s:%s" % (self.__class__.__name__, self.name)
Example #13
0
 def getTimeFromPos(self, index):
     """ Returns the date associated with an integer index. """
     if index < 0:
         return self._time_of_pos[(OrderedDict.__len__(self)) + index]
     else:
         return self._time_of_pos[index]
Example #14
0
# Enter your code here. Read input from STDIN. Print output to STDOUT
# https://www.hackerrank.com/challenges/word-order
from collections import OrderedDict

wordList = OrderedDict()
for _ in range(int(raw_input())):
    word = raw_input()
    wordList[word] = wordList.get(word, 0) + 1
print wordList.__len__()
for i in wordList.values():
    print i,
class BestPracticeWarning(collections.MutableMapping, base.ValidationError):
    """Represents a best practice warning. These are built within best
    practice rule checking methods and attached to
    :class:`BestPracticeWarningCollection` instances.

    Note:
        This class acts like a dictionary and contains the following keys
        at a minimum:

        * ``'id'``: The id of a node associated with the warning.
        * ``'idref'``: The idref of a node associated with the warning.
        * ``'line'``: The line number of the offending node.
        * ``'message'``: A message associated with the warning.
        * ``'tag'``: The lxml tag for the offending node.

        These keys can be retrieved via the :attr:`core_keys` property.

        Instances of this class may attach additional keys. These `other keys`
        can be obtained via the :attr:`other_keys` property.

    Args:
        node: The ``lxml._Element`` node associated with this warning.
        message: A message for this warning.

    """

    def __init__(self, node, message=None):
        base.ValidationError.__init__(self)

        self._inner = OrderedDict()
        self._node = node

        self["line"] = node.sourceline
        self["message"] = message
        self["id"] = node.attrib.get("id")
        self["idref"] = node.attrib.get("idref")
        self["tag"] = node.tag

    def __unicode__(self):
        return unicode(self.message)

    def __str__(self):
        return unicode(self).encode("utf-8")

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

    def __delitem__(self, key):
        self._inner.__delitem__(key)

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

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

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

    @property
    def line(self):
        """Returns the line number of the warning node in the input document.

        """
        return self["line"]

    @property
    def message(self):
        """Returns a message associated with the warning. This may return
        ``None`` if there is no warning message.

        """
        return self["message"]

    @property
    def core_keys(self):
        """Returns a ``tuple`` of  the keys that can always be found on
        instance of this class.

        Returns:
            A tuple including the following keys.

            * ``'id'``: The id of the warning node. The associated value
              may be ``None``.
            * ``'idref'``: The idref of the warning node. The associated value
              may be ``None``.
            * ``'line'``: The line number of the warning node in the input
              document. The associated value may be ``None``.
            * ``'tag'``: The ``{namespace}localname`` value of the warning
              node.
            * ``'message'``: An optional message that can be attached to the
              warning. The associated value may be ``None``.
        """
        return ("id", "idref", "line", "tag", "message")

    @property
    def other_keys(self):
        """Returns a ``tuple`` of keys attached to instances of this class that
        are not found in the :attr:`core_keys`.

        """
        return tuple(x for x in self.iterkeys() if x not in self.core_keys)

    def as_dict(self):
        """Returns a dictionary representation of this class instance. This
        is implemented for consistency across other validation error types.

        The :class:`.BestPracticeWarning` class extends
        :class:`collections.MutableMapping`, so this method isn't really
        necessary.

        """
        return dict(self.iteritems())