Exemplo n.º 1
0
 def __eq__(self, other):
     """od.__eq__(y) <==> od==y.  Comparison to another OD is
     order-sensitive while comparison to a regular mapping
     is order-insensitive."""
     if isinstance(other, OrderedDict):
         return len(self) == len(other) and \
                all(_imap(_eq, self.iteritems(), other.iteritems()))
     return dict.__eq__(self, other)
Exemplo n.º 2
0
 def __eq__(self, other):
     """od.__eq__(y) <==> od==y.  Comparison to another OD is
     order-sensitive while comparison to a regular mapping
     is order-insensitive."""
     if isinstance(other, OrderedDict):
         return len(self) == len(other) and \
                all(_imap(_eq, self.iteritems(), other.iteritems()))
     return dict.__eq__(self, other)
Exemplo n.º 3
0
    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other)
Exemplo n.º 4
0
    def __eq__(self, other):
        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
        while comparison to a regular mapping is order-insensitive.

        '''
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(_imap(_eq, self, other))
        return dict.__eq__(self, other)
Exemplo n.º 5
0
def tally(predicate, iterable):
    """
    Count how many times the predicate is true.

    Taken from the Python documentation. Under the PSF license.

    :param predicate:
        Predicate function.
    :param iterable:
        Iterable sequence.
    :returns:
        The number of times a predicate is true.
    """
    return sum(_imap(predicate, iterable))
Exemplo n.º 6
0
 def __new__(cls, *args, **kwargs):
     if not len(args) + len(kwargs) == cls._field_len:
         raise TypeError("Invalid number of arguments!")
     arguments = list(args)
     if kwargs:
         def name_to_position(pair):
             return cls._field_names[pair[0]]
         try:
             sorted_args = sorted(kwargs.iteritems(), key=name_to_position)
             # sorted by key, but we only need the value
             arguments.extend(_imap(_itemgetter(1), sorted_args))
         except KeyError:
             raise TypeError("Invalid arguments!")
     return tuple.__new__(cls, arguments)
Exemplo n.º 7
0
    def resolve(self, arg_types, disable_caching=False):
        '''
        Метод разрешающий перегрузку по заданным типам параметров

        возвращаемое значение - функция или None если невозможно разрешить
        перегрузку, если результат неоднозначен бросается
        исключение AmbiguousFunctions
        '''
        result = None
        candidates = []

        try:
            for candidate in self._functions[len(arg_types)]:
                for arg, argtype in _izip(arg_types, candidate[1]):
                    if not issubclass(arg, argtype):
                        break
                else:
                    candidates.append(candidate)

        except KeyError:
            pass

        if len(candidates) == 1:
            result = candidates[0][0]

        elif len(candidates) > 1:
            best_match = (sys.maxint, None)

            for (function, signature) in candidates:
                ancestor_count_sum = sum(
                    _imap(_calculate_number_of_ancestors, arg_types, signature))

                if best_match[0] > ancestor_count_sum:
                    best_match = (ancestor_count_sum, function)

                elif best_match[0] == ancestor_count_sum:
                    raise AmbiguousFunctions

            result = best_match[1]

        if (result is not None) and (not disable_caching):
            self.__cache[arg_types] = result

        return result
Exemplo n.º 8
0
def ipluck(dicts, key, *args, **kwargs):
    """
    Plucks values for a given key from a series of dictionaries as an iterator.

    :param dicts:
        Iterable sequence of dictionaries.
    :param key:
        The key to fetch.
    :param default:
        The default value to use when a key is not found. If this value is
        not specified, a KeyError will be raised when a key is not found.
    :yields:
        Iterator of values for the key.
    """
    if args or kwargs:
        default = kwargs['default'] if kwargs else args[0]

        def _get_value_from_dict(d):
            return d.get(key, default)
    else:
        _get_value_from_dict = lambda w: w[key]
    return _imap(_get_value_from_dict, dicts)
Exemplo n.º 9
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return dict.__eq__(self, other) and all(_imap(_eq, self, other))
     return dict.__eq__(self, other)
Exemplo n.º 10
0
 def __reversed__(self):
     "L.__reversed__() -- return a reverse iterator over the list"
     return _imap(_attrgetter('value'), reversed(self._reflist))
Exemplo n.º 11
0
 def imap(self, f, *args, **kwds):
    #AbstractWorkerPool._AbstractWorkerPool__imap(self, f, *args, **kwds)
     return _imap(f, *args)#, **kwds)
Exemplo n.º 12
0
 def imap(self, f, *args, **kwds):
    #AbstractWorkerPool._AbstractWorkerPool__imap(self, f, *args, **kwds)
     return _imap(f, *args)#, **kwds)
Exemplo n.º 13
0
def _some1(predicate, iterable):
    """Alternative implementation of :func:`some`."""
    return any(_imap(predicate, iterable))
Exemplo n.º 14
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return dict.__eq__(self, other) and all(_imap(_eq, self, other))
     return dict.__eq__(self, other)
Exemplo n.º 15
0
 def imap(self, f, *args, **kwds):
    #AbstractWorkerPool._AbstractWorkerPool__imap(self, f, *args, **kwds)
     if self._exiting: self._is_alive()
     return _imap(f, *args)#, **kwds)
Exemplo n.º 16
0
 def imap(self, f, *args, **kwds):
     #AbstractWorkerPool._AbstractWorkerPool__imap(self, f, *args, **kwds)
     if self._exiting: self._is_alive()
     return _imap(f, *args)  #, **kwds)
Exemplo n.º 17
0
 def __iter__(self):
     "x.__iter__() <==> iter(x)"
     return _imap(_attrgetter('value'), self._reflist)
Exemplo n.º 18
0
 def __eq__(self, other):
     if isinstance(other, self.__class__):
         return dict.__eq__(self, other) and all(_imap(_eq, self, other))
     return dict.__eq__(self, other)
Exemplo n.º 19
0
.. _logutils: https://pypi.python.org/pypi/logutils/
.. _here: http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements

.. moduleauthor:: Patrick Wong <*****@*****.**>
"""

from __future__ import absolute_import
from logging import StreamHandler as _StreamHandler
from itertools import imap as _imap
from functools import partial as _partial
import zachlog as _logging

# Ye olde constants
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = xrange(8)
BOLD, FAINT, ITALIC, UNDERLINE, BLINK = _imap(str, xrange(1, 6))
_CSI, _RESET = '\x1b[', '\x1b[0m'
_LOGGER = _logging.getLogger(__name__)


def _color(fg=None, bg=None, style=""):
    params = []
    if bg:
        params.append(str(bg + 40))
    if fg:
        params.append(str(fg + 30))
    params.extend(style)
    return "%sm" % ";".join(params)


def colorize(msg, foreground, background=None, style=""):
Exemplo n.º 20
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return len(self) == len(other) and all(
             _imap(_eq, self.iteritems(), other.iteritems()))
     return dict.__eq__(self, other)
Exemplo n.º 21
0
 def __eq__(self, other):
     if isinstance(other, OrderedDict):
         return len(self) == len(other) and all(_imap(_eq, self.iteritems(), other.iteritems()))
     return dict.__eq__(self, other)
Exemplo n.º 22
0
 def __contains__(self, value):
     "seq.__contains__(value) <==> value in seq"
     return value in _imap(_attrgetter('value'), self._reflist)