Ejemplo n.º 1
0
    def get_fields(self, serialize, obj=None, data=None, nested=False):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        for key, field in self.fields.items():
            ret[key] = field
            # Set up the field
            field.initialize(parent=self)

        # Add in the default fields
        fields = self.default_fields(serialize, obj, data, nested)
        for key, val in fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 2
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            ret[key] = field
            # Set up the field
            field.initialize(parent=self, field_name=key)

        # Add in the default fields
        default_fields = self.get_default_fields()
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 3
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            ret[key] = field
            # Set up the field
            field.initialize(parent=self, field_name=key)

        # Add in the default fields
        default_fields = self.get_default_fields()
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 4
0
def _com_to_dict(com):
    """ convert committee into a suitable dict for output """
    od = SortedDict(_fdict(com.__dict__))
    od.pop('parent_id')
    if '_state' in od:
        od.pop('_state')
    return od
Ejemplo n.º 5
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            ret[key] = field

        # Add in the default fields
        default_fields = self.get_default_fields()
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            assert isinstance(
                self.opts.fields,
                (list, tuple)), '`fields` must be a list or tuple'
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            assert isinstance(
                self.opts.exclude,
                (list, tuple)), '`exclude` must be a list or tuple'
            for key in self.opts.exclude:
                ret.pop(key, None)

        # Mark immutable fields as read-only if there was an object instance provided
        if self.object:
            # Ensure that 'immutable_fields' is an iterable
            assert isinstance(
                self.opts.immutable_fields,
                (list, tuple)), '`immutable_fields` must be a list or tuple'

            # Set the `read_only` flag to any fields that have been specified
            # in the `immutable_fields` option
            for field_name in self.opts.immutable_fields:
                assert field_name in ret, (
                    "Non-existant field '%s' specified in `immutable_fields` "
                    "on serializer '%s'." %
                    (field_name, self.__class__.__name__))
                ret[field_name].read_only = True

        for key, field in ret.items():
            field.initialize(parent=self, field_name=key)

        return ret
Ejemplo n.º 6
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            if isinstance(field, HALLinkField):
                self.add_field_to_links(key, field)
            else:
                ret[key] = field

        # Add in the default fields
        default_fields = self.get_default_fields(ret)
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple'
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            assert isinstance(self.opts.exclude, (list, tuple)), '`exclude` must be a list or tuple'
            for key in self.opts.exclude:
                ret.pop(key, None)
                self.additional_links.pop(key, None)
                self.embedded_fields.pop(key, None)

        # additional embedded fields
        if getattr(self.opts, 'additional_embedded', None):
            assert isinstance(self.opts.additional_embedded, (list, tuple)), '`exclude` must be a list or tuple'
            for key in self.opts.additional_embedded:
                field = ret.pop(key, None)
                if field:
                    self.add_field_to_embedded(key, field)

        for key, field in ret.items():
            field.initialize(parent=self, field_name=key)

        return ret
Ejemplo n.º 7
0
class QualityOfService(object):

    def __init__(self, backend, resource, prefetch_count=None,
            interval=None):
        self.backend = backend
        self.resource = resource
        self.prefetch_count = prefetch_count
        self.interval = interval
        self._delivered = SortedDict()
        self._restored_once = False
        atexit.register(self.restore_unacked_once)

    def can_consume(self):
        return len(self._delivered) > self.prefetch_count

    def append(self, message, queue_name, delivery_tag):
        self._delivered[delivery_tag] = message, queue_name

    def ack(self, delivery_tag):
        self._delivered.pop(delivery_tag, None)

    def restore_unacked(self):
        for delivery_tag, delivered in self._delivered.items():
            message, queue_name = delivered
            send = self.backend.prepare_message(message.body, 2, 10,
                                                message.content_type,
                                                message.content_encoding)
            send["destination"] = queue_name
            self.resource.put(queue_name, serialize(send))
        self._delivered = SortedDict()

    def requeue(self, delivery_tag):
        try:
            message, queue_name = self._delivered.pop(delivery_tag)
        except KeyError:
            pass
        self.resource.put(queue_name, message)

    def restore_unacked_once(self):
        if not self._restored_once:
            if self._delivered:
                sys.stderr.write(
                    "Restoring unacknowledged messages: %s\n" % (
                        self._delivered))
            self.restore_unacked()
            if self._delivered:
                sys.stderr.write("UNRESTORED MESSAGES: %s\n" % (
                    self._delivered))
Ejemplo n.º 8
0
def get_model_order(model_lists):
    
    model_adj = SortedDict()
    for model in model_lists:
        model_adj[ model ]  = get_related_models(model)
    
    order = filter(lambda m: not bool(model_adj[m]), model_adj.keys())
    map(lambda m: model_adj.pop(m), order)
    while model_adj:
        for model in model_adj:
            deps = model_adj[model]
            if model in deps:
                #Es recursivo
                deps.remove(model)
            if all(map(lambda d: d not in model_adj, deps)):
                order.append(model)
                model_adj.pop(model)
    return order
Ejemplo n.º 9
0
def breadcrumbs_add(request, ctx):
    bc = request.session.get('bc', SortedDict())
    title = ctx.get('title', '')
    if not title:  # Não tem title definido, tenta montar baseado na URL
        path_splited = request.path.split('/')
        path_splited.reverse()
        for i in path_splited:
            if i and not i.isdigit():
                title = i.replace('_', ' ').capitalize()
                break
    if request.path == '/':
        bc = SortedDict()
    if title in bc:  # Removendo itens após o ``title`` encontrado
        title_index = bc.keyOrder.index(title)
        for key in bc.keyOrder[title_index + 1:]:
            bc.pop(key)
    bc[title] = request.get_full_path()
    request.session['bc'] = bc
    ctx['breadcrumbs'] = bc
Ejemplo n.º 10
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            ret[key] = field

        # Add in the default fields
        default_fields = self.get_default_fields()
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If "fields" is specified, use those fields, in that order.
        if self.opts.fields:
            assert isinstance(
                self.opts.fields,
                (list, tuple)), "`fields` must be a list or tuple"
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in "exclude"
        if self.opts.exclude:
            assert isinstance(
                self.opts.exclude,
                (list, tuple)), "`exclude` must be a list or tuple"
            for key in self.opts.exclude:
                ret.pop(key, None)

        for key, field in ret.items():
            field.initialize(parent=self, field_name=key)

        return ret
    def get_fields(self, serialize, obj=None, data=None, nested=False):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        for key, field in self.fields.items():
            ret[key] = field
            # Determine if the declared field corrosponds to a model field.
            try:
                if key == 'pk':
                    model_field = obj._meta.pk
                else:
                    model_field = obj._meta.get_field_by_name(key)[0]
            except:
                model_field = None
            # Set up the field
            field.initialize(parent=self, model_field=model_field)

        # Add in the default fields
        fields = self.default_fields(serialize, obj, data, nested)
        for key, val in fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 12
0
    def get_fields(self, serialize, obj=None, data=None, nested=False):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        for key, field in self.fields.items():
            ret[key] = field
            # Determine if the declared field corrosponds to a model field.
            try:
                if key == 'pk':
                    model_field = obj._meta.pk
                else:
                    model_field = obj._meta.get_field_by_name(key)[0]
            except:
                model_field = None
            # Set up the field
            field.initialize(parent=self, model_field=model_field)

        # Add in the default fields
        fields = self.default_fields(serialize, obj, data, nested)
        for key, val in fields.items():
            if key not in ret:
                ret[key] = val

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 13
0
def extract_params(params, prefix='turbion.'):
    """Extracts additional request params and checks signature"""
    params = SortedDict(
        [(name[len(prefix):], value)\
            for name, value in params.iteritems() if name.startswith(prefix)]
    )
    signature = params.pop('signature', '')
    if signature != _sign(params):
        raise ValueError('Parameters signature doesn\'t match')

    return params
Ejemplo n.º 14
0
    def get_fields(self):
        """
        Returns the complete set of fields for the object as a dict.

        This will be the set of any explicitly declared fields,
        plus the set of fields returned by get_default_fields().
        """
        ret = SortedDict()

        # Get the explicitly declared fields
        base_fields = copy.deepcopy(self.base_fields)
        for key, field in base_fields.items():
            ret[key] = field

        # Add in the default fields
        default_fields = self.get_default_fields()
        for key, val in default_fields.items():
            if key not in ret:
                ret[key] = val

        # If "fields" is specified, use those fields, in that order.
        if self.opts.fields:
            assert isinstance(self.opts.fields, (list, tuple)), "`fields` must be a list or tuple"
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in "exclude"
        if self.opts.exclude:
            assert isinstance(self.opts.exclude, (list, tuple)), "`exclude` must be a list or tuple"
            for key in self.opts.exclude:
                ret.pop(key, None)

        for key, field in ret.items():
            field.initialize(parent=self, field_name=key)

        return ret
Ejemplo n.º 15
0
    def from_querydict(cls, image_or_storage_path, querydict, secure=False):
        kwargs = SortedDict()
        for verbose, short in six.iteritems(cls.query_map):
            if short in querydict:
                kwargs[verbose] = querydict[short]

        if 'security' in kwargs:
            if not cls.check_security_hash(kwargs.pop('security'), kwargs):
                raise ValueError("Security check failed.")
        elif secure:
            raise ValueError("Security hash missing.")

        adjustments = cls._deserialize_requested(kwargs['requested'])
        return cls([image_or_storage_path], adjustments)
Ejemplo n.º 16
0
    def get_checking_fields(self, special_exclude=['id']):
        """
        Returns the set of fields on which we perform checkings
        """
        ret = SortedDict()
        for f in self._meta.fields:
            # avoid special_exclude fields
            if f.attname in special_exclude:
                continue
            ret[f.attname] = f

        # Deal with reverse relationships
        reverse_rels = self._meta.get_all_related_objects()
        # reverse_rels += self._meta.get_all_related_many_to_many_objects()
        for relation in reverse_rels:
            accessor_name = relation.get_accessor_name()
            to_many = relation.field.rel.multiple
            if not self.opts.fields or accessor_name not in self.opts.fields:
                continue
            if not to_many:
                raise NotImplementedError
            ret[accessor_name] = PrimaryKeyRelatedField()

        # If 'fields' is specified, use those fields, in that order.
        if self.opts.fields:
            new = SortedDict()
            for key in self.opts.fields:
                new[key] = ret[key]
            ret = new

        # Remove anything in 'exclude'
        if self.opts.exclude:
            for key in self.opts.exclude:
                ret.pop(key, None)

        return ret
Ejemplo n.º 17
0
    def from_querydict(cls, image_or_storage_path, querydict, secure=False):
        kwargs = SortedDict()
        for verbose, short in cls.param_map.iteritems():
            try:
                value = querydict[short]
            except KeyError:
                continue
            if verbose in cls.int_params:
                # Raises ValueError if it can't be converted.
                value = int(value)
            kwargs[verbose] = value

        if 'security' in kwargs:
            if not cls.check_security_hash(kwargs.pop('security'), kwargs):
                raise ValueError("Security check failed.")
        elif secure:
            raise ValueError("Security hash missing.")

        return cls(image_or_storage_path, **kwargs)
Ejemplo n.º 18
0
    def from_querydict(cls,
                       image_or_storage_path,
                       querydict,
                       secure=False,
                       generate=False):
        kwargs = SortedDict()
        for verbose, short in six.iteritems(cls.query_map):
            if short in querydict:
                kwargs[verbose] = querydict[short]

        if 'security' in kwargs:
            if not cls.check_security_hash(kwargs.pop('security'), kwargs):
                raise ValueError("Security check failed.")
        elif secure:
            raise ValueError("Security hash missing.")

        adjustments = cls._deserialize_requested(kwargs['requested'])
        helper = cls([image_or_storage_path], generate=generate)
        for adjustment in adjustments:
            helper.adjust(adjustment)
        return helper
Ejemplo n.º 19
0
    def before(self, api, kwargs=None, **extra):
        """Formats given keyword arguments in MetaTrader format.

        <command>-arg1=val1|arg2=val2|...
        """
        # Thanks to the bug in NEWACCOUNT, we are forced to use
        # SortedDict.

        def ensure_unicode(string):
            if isinstance(string, str):
                return string.decode('cp1251')
            return unicode(string)

        kwargs = SortedDict(kwargs or {})
        kwargs.update(extra)

        key = kwargs.pop("key", None)
        if self.encoded and not key:
            raise MT4Error("Key required to call %r" % self)

        qs = u"%s-%s" % (self.command.upper(),
                         u"|".join(u"{}={}".format(*map(ensure_unicode, pair)) for pair in kwargs.iteritems()))

        return (qs, ), {"key": key, "sensitive_fields_regexp": getattr(self, "sensitive_fields_regexp", None)}
Ejemplo n.º 20
0
class SortedDictTests(SimpleTestCase):
    def setUp(self):
        self.d1 = SortedDict()
        self.d1[7] = 'seven'
        self.d1[1] = 'one'
        self.d1[9] = 'nine'

        self.d2 = SortedDict()
        self.d2[1] = 'one'
        self.d2[9] = 'nine'
        self.d2[0] = 'nil'
        self.d2[7] = 'seven'

    def test_basic_methods(self):
        self.assertEqual(self.d1.keys(), [7, 1, 9])
        self.assertEqual(self.d1.values(), ['seven', 'one', 'nine'])
        self.assertEqual(self.d1.items(), [(7, 'seven'), (1, 'one'), (9, 'nine')])

    def test_overwrite_ordering(self):
        """ Overwriting an item keeps it's place. """
        self.d1[1] = 'ONE'
        self.assertEqual(self.d1.values(), ['seven', 'ONE', 'nine'])

    def test_append_items(self):
        """ New items go to the end. """
        self.d1[0] = 'nil'
        self.assertEqual(self.d1.keys(), [7, 1, 9, 0])

    def test_delete_and_insert(self):
        """
        Deleting an item, then inserting the same key again will place it
        at the end.
        """
        del self.d2[7]
        self.assertEqual(self.d2.keys(), [1, 9, 0])
        self.d2[7] = 'lucky number 7'
        self.assertEqual(self.d2.keys(), [1, 9, 0, 7])

    def test_change_keys(self):
        """
        Changing the keys won't do anything, it's only a copy of the
        keys dict.
        """
        k = self.d2.keys()
        k.remove(9)
        self.assertEqual(self.d2.keys(), [1, 9, 0, 7])

    def test_init_keys(self):
        """
        Initialising a SortedDict with two keys will just take the first one.

        A real dict will actually take the second value so we will too, but
        we'll keep the ordering from the first key found.
        """
        tuples = ((2, 'two'), (1, 'one'), (2, 'second-two'))
        d = SortedDict(tuples)

        self.assertEqual(d.keys(), [2, 1])

        real_dict = dict(tuples)
        self.assertEqual(sorted(real_dict.values()), ['one', 'second-two'])

        # Here the order of SortedDict values *is* what we are testing
        self.assertEqual(d.values(), ['second-two', 'one'])

    def test_overwrite(self):
        self.d1[1] = 'not one'
        self.assertEqual(self.d1[1], 'not one')
        self.assertEqual(self.d1.keys(), self.d1.copy().keys())

    def test_append(self):
        self.d1[13] = 'thirteen'
        self.assertEqual(
            repr(self.d1),
            "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}"
        )

    def test_pop(self):
        self.assertEqual(self.d1.pop(1, 'missing'), 'one')
        self.assertEqual(self.d1.pop(1, 'missing'), 'missing')

        # We don't know which item will be popped in popitem(), so we'll
        # just check that the number of keys has decreased.
        l = len(self.d1)
        self.d1.popitem()
        self.assertEqual(l - len(self.d1), 1)

    def test_dict_equality(self):
        d = SortedDict((i, i) for i in xrange(3))
        self.assertEqual(d, {0: 0, 1: 1, 2: 2})

    def test_tuple_init(self):
        d = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")

    def test_pickle(self):
        self.assertEqual(
            pickle.loads(pickle.dumps(self.d1, 2)),
            {7: 'seven', 1: 'one', 9: 'nine'}
        )

    def test_clear(self):
        self.d1.clear()
        self.assertEqual(self.d1, {})
        self.assertEqual(self.d1.keyOrder, [])
Ejemplo n.º 21
0
class SortedDictTests(SimpleTestCase):
    def setUp(self):
        self.d1 = SortedDict()
        self.d1[7] = 'seven'
        self.d1[1] = 'one'
        self.d1[9] = 'nine'

        self.d2 = SortedDict()
        self.d2[1] = 'one'
        self.d2[9] = 'nine'
        self.d2[0] = 'nil'
        self.d2[7] = 'seven'

    def test_basic_methods(self):
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9])
        self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'one', 'nine'])
        self.assertEqual(list(six.iteritems(self.d1)), [(7, 'seven'), (1, 'one'), (9, 'nine')])

    def test_overwrite_ordering(self):
        """ Overwriting an item keeps its place. """
        self.d1[1] = 'ONE'
        self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'ONE', 'nine'])

    def test_append_items(self):
        """ New items go to the end. """
        self.d1[0] = 'nil'
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0])

    def test_delete_and_insert(self):
        """
        Deleting an item, then inserting the same key again will place it
        at the end.
        """
        del self.d2[7]
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0])
        self.d2[7] = 'lucky number 7'
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7])

    if six.PY2:
        def test_change_keys(self):
            """
            Changing the keys won't do anything, it's only a copy of the
            keys dict.

            This test doesn't make sense under Python 3 because keys is
            an iterator.
            """
            k = self.d2.keys()
            k.remove(9)
            self.assertEqual(self.d2.keys(), [1, 9, 0, 7])

    def test_init_keys(self):
        """
        Initialising a SortedDict with two keys will just take the first one.

        A real dict will actually take the second value so we will too, but
        we'll keep the ordering from the first key found.
        """
        tuples = ((2, 'two'), (1, 'one'), (2, 'second-two'))
        d = SortedDict(tuples)

        self.assertEqual(list(six.iterkeys(d)), [2, 1])

        real_dict = dict(tuples)
        self.assertEqual(sorted(six.itervalues(real_dict)), ['one', 'second-two'])

        # Here the order of SortedDict values *is* what we are testing
        self.assertEqual(list(six.itervalues(d)), ['second-two', 'one'])

    def test_overwrite(self):
        self.d1[1] = 'not one'
        self.assertEqual(self.d1[1], 'not one')
        self.assertEqual(list(six.iterkeys(self.d1)), list(six.iterkeys(self.d1.copy())))

    def test_append(self):
        self.d1[13] = 'thirteen'
        self.assertEqual(
            repr(self.d1),
            "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}"
        )

    def test_pop(self):
        self.assertEqual(self.d1.pop(1, 'missing'), 'one')
        self.assertEqual(self.d1.pop(1, 'missing'), 'missing')

        # We don't know which item will be popped in popitem(), so we'll
        # just check that the number of keys has decreased.
        l = len(self.d1)
        self.d1.popitem()
        self.assertEqual(l - len(self.d1), 1)

    def test_dict_equality(self):
        d = SortedDict((i, i) for i in range(3))
        self.assertEqual(d, {0: 0, 1: 1, 2: 2})

    def test_tuple_init(self):
        d = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")

    def test_pickle(self):
        self.assertEqual(
            pickle.loads(pickle.dumps(self.d1, 2)),
            {7: 'seven', 1: 'one', 9: 'nine'}
        )

    def test_copy(self):
        orig = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        copied = copy.copy(orig)
        self.assertEqual(list(six.iterkeys(orig)), [1, 0, 2])
        self.assertEqual(list(six.iterkeys(copied)), [1, 0, 2])

    def test_clear(self):
        self.d1.clear()
        self.assertEqual(self.d1, {})
        self.assertEqual(self.d1.keyOrder, [])

    def test_reversed(self):
        self.assertEqual(list(self.d1), [7, 1, 9])
        self.assertEqual(list(self.d2), [1, 9, 0, 7])
        self.assertEqual(list(reversed(self.d1)), [9, 1, 7])
        self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1])

    def test_insert(self):
        d = SortedDict()
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            d.insert(0, "hello", "world")
        assert w[0].category is DeprecationWarning

    def test_value_for_index(self):
        d = SortedDict({"a": 3})
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            self.assertEqual(d.value_for_index(0), 3)
        assert w[0].category is DeprecationWarning
Ejemplo n.º 22
0
class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase):
    def setUp(self):
        super(SortedDictTests, self).setUp()
        self.d1 = SortedDict()
        self.d1[7] = 'seven'
        self.d1[1] = 'one'
        self.d1[9] = 'nine'

        self.d2 = SortedDict()
        self.d2[1] = 'one'
        self.d2[9] = 'nine'
        self.d2[0] = 'nil'
        self.d2[7] = 'seven'

    def test_basic_methods(self):
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9])
        self.assertEqual(list(six.itervalues(self.d1)),
                         ['seven', 'one', 'nine'])
        self.assertEqual(list(six.iteritems(self.d1)),
                         [(7, 'seven'), (1, 'one'), (9, 'nine')])

    def test_overwrite_ordering(self):
        """ Overwriting an item keeps its place. """
        self.d1[1] = 'ONE'
        self.assertEqual(list(six.itervalues(self.d1)),
                         ['seven', 'ONE', 'nine'])

    def test_append_items(self):
        """ New items go to the end. """
        self.d1[0] = 'nil'
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0])

    def test_delete_and_insert(self):
        """
        Deleting an item, then inserting the same key again will place it
        at the end.
        """
        del self.d2[7]
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0])
        self.d2[7] = 'lucky number 7'
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7])

    if six.PY2:

        def test_change_keys(self):
            """
            Changing the keys won't do anything, it's only a copy of the
            keys dict.

            This test doesn't make sense under Python 3 because keys is
            an iterator.
            """
            k = self.d2.keys()
            k.remove(9)
            self.assertEqual(self.d2.keys(), [1, 9, 0, 7])

    def test_init_keys(self):
        """
        Initialising a SortedDict with two keys will just take the first one.

        A real dict will actually take the second value so we will too, but
        we'll keep the ordering from the first key found.
        """
        tuples = ((2, 'two'), (1, 'one'), (2, 'second-two'))
        d = SortedDict(tuples)

        self.assertEqual(list(six.iterkeys(d)), [2, 1])

        real_dict = dict(tuples)
        self.assertEqual(sorted(six.itervalues(real_dict)),
                         ['one', 'second-two'])

        # Here the order of SortedDict values *is* what we are testing
        self.assertEqual(list(six.itervalues(d)), ['second-two', 'one'])

    def test_overwrite(self):
        self.d1[1] = 'not one'
        self.assertEqual(self.d1[1], 'not one')
        self.assertEqual(list(six.iterkeys(self.d1)),
                         list(six.iterkeys(self.d1.copy())))

    def test_append(self):
        self.d1[13] = 'thirteen'
        self.assertEqual(repr(self.d1),
                         "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}")

    def test_pop(self):
        self.assertEqual(self.d1.pop(1, 'missing'), 'one')
        self.assertEqual(self.d1.pop(1, 'missing'), 'missing')

        # We don't know which item will be popped in popitem(), so we'll
        # just check that the number of keys has decreased.
        l = len(self.d1)
        self.d1.popitem()
        self.assertEqual(l - len(self.d1), 1)

    def test_dict_equality(self):
        d = SortedDict((i, i) for i in range(3))
        self.assertEqual(d, {0: 0, 1: 1, 2: 2})

    def test_tuple_init(self):
        d = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")

    def test_pickle(self):
        self.assertEqual(pickle.loads(pickle.dumps(self.d1, 2)), {
            7: 'seven',
            1: 'one',
            9: 'nine'
        })

    def test_copy(self):
        orig = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        copied = copy.copy(orig)
        self.assertEqual(list(six.iterkeys(orig)), [1, 0, 2])
        self.assertEqual(list(six.iterkeys(copied)), [1, 0, 2])

    def test_clear(self):
        self.d1.clear()
        self.assertEqual(self.d1, {})
        self.assertEqual(self.d1.keyOrder, [])

    def test_reversed(self):
        self.assertEqual(list(self.d1), [7, 1, 9])
        self.assertEqual(list(self.d2), [1, 9, 0, 7])
        self.assertEqual(list(reversed(self.d1)), [9, 1, 7])
        self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1])
Ejemplo n.º 23
0
class SortedDictTests(SimpleTestCase):
    def setUp(self):
        super(SortedDictTests, self).setUp()
        self.d1 = SortedDict()
        self.d1[7] = "seven"
        self.d1[1] = "one"
        self.d1[9] = "nine"

        self.d2 = SortedDict()
        self.d2[1] = "one"
        self.d2[9] = "nine"
        self.d2[0] = "nil"
        self.d2[7] = "seven"

    def test_basic_methods(self):
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9])
        self.assertEqual(list(six.itervalues(self.d1)), ["seven", "one", "nine"])
        self.assertEqual(list(six.iteritems(self.d1)), [(7, "seven"), (1, "one"), (9, "nine")])

    def test_overwrite_ordering(self):
        """ Overwriting an item keeps its place. """
        self.d1[1] = "ONE"
        self.assertEqual(list(six.itervalues(self.d1)), ["seven", "ONE", "nine"])

    def test_append_items(self):
        """ New items go to the end. """
        self.d1[0] = "nil"
        self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0])

    def test_delete_and_insert(self):
        """
        Deleting an item, then inserting the same key again will place it
        at the end.
        """
        del self.d2[7]
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0])
        self.d2[7] = "lucky number 7"
        self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7])

    if six.PY2:

        def test_change_keys(self):
            """
            Changing the keys won't do anything, it's only a copy of the
            keys dict.

            This test doesn't make sense under Python 3 because keys is
            an iterator.
            """
            k = self.d2.keys()
            k.remove(9)
            self.assertEqual(self.d2.keys(), [1, 9, 0, 7])

    def test_init_keys(self):
        """
        Initialising a SortedDict with two keys will just take the first one.

        A real dict will actually take the second value so we will too, but
        we'll keep the ordering from the first key found.
        """
        tuples = ((2, "two"), (1, "one"), (2, "second-two"))
        d = SortedDict(tuples)

        self.assertEqual(list(six.iterkeys(d)), [2, 1])

        real_dict = dict(tuples)
        self.assertEqual(sorted(six.itervalues(real_dict)), ["one", "second-two"])

        # Here the order of SortedDict values *is* what we are testing
        self.assertEqual(list(six.itervalues(d)), ["second-two", "one"])

    def test_overwrite(self):
        self.d1[1] = "not one"
        self.assertEqual(self.d1[1], "not one")
        self.assertEqual(list(six.iterkeys(self.d1)), list(six.iterkeys(self.d1.copy())))

    def test_append(self):
        self.d1[13] = "thirteen"
        self.assertEqual(repr(self.d1), "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}")

    def test_pop(self):
        self.assertEqual(self.d1.pop(1, "missing"), "one")
        self.assertEqual(self.d1.pop(1, "missing"), "missing")

        # We don't know which item will be popped in popitem(), so we'll
        # just check that the number of keys has decreased.
        l = len(self.d1)
        self.d1.popitem()
        self.assertEqual(l - len(self.d1), 1)

    def test_dict_equality(self):
        d = SortedDict((i, i) for i in range(3))
        self.assertEqual(d, {0: 0, 1: 1, 2: 2})

    def test_tuple_init(self):
        d = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}")

    def test_pickle(self):
        self.assertEqual(pickle.loads(pickle.dumps(self.d1, 2)), {7: "seven", 1: "one", 9: "nine"})

    def test_copy(self):
        orig = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
        copied = copy.copy(orig)
        self.assertEqual(list(six.iterkeys(orig)), [1, 0, 2])
        self.assertEqual(list(six.iterkeys(copied)), [1, 0, 2])

    def test_clear(self):
        self.d1.clear()
        self.assertEqual(self.d1, {})
        self.assertEqual(self.d1.keyOrder, [])

    def test_reversed(self):
        self.assertEqual(list(self.d1), [7, 1, 9])
        self.assertEqual(list(self.d2), [1, 9, 0, 7])
        self.assertEqual(list(reversed(self.d1)), [9, 1, 7])
        self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1])
Ejemplo n.º 24
0
class Chart(object):

    BASE = "http://chart.apis.google.com/chart"
    defaults = {
        "chs": "200x200",
        "cht": "lc"
    }

    def __init__(self):
        # Use a SortedDict for the options so they are added in a
        # deterministic manner; this eases things like dealing with cache keys
        # or writing unit tests.
        self.options = SortedDict()
        self.datasets = []
        self.hidden_datasets = []
        self.axes = []
        self.datarange = None
        self.alt = None

    def clone(self):
        clone = self.__class__()
        clone.options = self.options.copy()
        clone.datasets = self.datasets[:]
        clone.hidden_datasets = self.hidden_datasets[:]
        clone.axes = self.axes[:]
        return clone

    def img(self, color_override = None):
        orig_colors = self.options.get('chco')
        # If color_override is set, replace the chco option with this color
        if color_override is not None:
            final_color = []
            for c in self.options['chco'].split(','):
                if c == color_override:
                    c = orig_colors.split(',')[0]
                else:
                    c = _chart_inactive_color
                final_color.append(c)
            self.options['chco'] = ','.join(final_color)
        url = self.url()
        if orig_colors:
            self.options['chco'] = orig_colors
        width, height = self.options["chs"].split("x")
        if self.alt:
            alt = '%s' % escape(self.alt)
        else:
            alt = ''
        s = mark_safe('<img src="%s" width="%s" height="%s" alt="%s" />' % (escape(url), width, height, alt))

        return s

    def url(self):
        if self.options.get('cht', None) == 't':
            self.datasets.append(self.options.pop("_mapdata"))

        # Figure out the chart's data range
        if not self.datarange:
            maxvalue = max(max(d) for d in chain(self.datasets, self.hidden_datasets) if d)
            minvalue = min(min(d) for d in chain(self.datasets, self.hidden_datasets) if d)
            self.datarange = (minvalue, maxvalue)

        # Encode data
        if "chds" in self.options or self.options.get('cht', None) == 'gom':
            # text encoding if scaling provided, or for google-o-meter type
            data = "|".join(encode_text(d) for d in chain(self.datasets, self.hidden_datasets))
            encoded_data = "t%d:%s" % (len(self.datasets), data)
        else:
            # extended encoding otherwise
            data = extended_separator.join(encode_extended(d, self.datarange) for d in chain(self.datasets, self.hidden_datasets))
            encoded_data = "e%d:%s" % (len(self.datasets), data)

        # Update defaults
        for k in self.defaults:
            if k not in self.options:
                self.options[k] = self.defaults[k]

        # Start to calculate the URL
        url = "%s?%s&chd=%s" % (self.BASE, urlencode(self.options), encoded_data)

        # Calculate axis options
        if self.axes:
            axis_options = SortedDict()
            axis_sides = []
            for i, axis in enumerate(self.axes):
                axis_sides.append(axis.side)
                for opt in axis.options:
                    try:
                        axis_options.setdefault(opt, []).append(axis.options[opt] % i)
                    except TypeError:
                        pass

            # Turn the option lists into strings
            axis_sides = smart_join(",", *axis_sides)
            for opt in axis_options:
                axis_options[opt] = smart_join("|", *axis_options[opt])

            url += "&chxt=%s&%s" % (axis_sides, urlencode(axis_options))

        return url


    def charts(self):
        res = []
        count = 1
        for o in self.options['_final_color_map'].items():
            res.append({  'id': count,
                          'color': o[0],
                          'label': o[1],
                          'img': self.img(color_override=o[0])
                       })
            count += 1
        return res
Ejemplo n.º 25
0
class Chart(object):

	BASE = "http://chart.apis.google.com/chart"
	defaults = {
		"chs": "200x200",
		"cht": "lc"
	}

	def __init__(self):
		# Use a SortedDict for the opeions so they are added in a
		# deterministic manner; this eases things like dealing with cache keys 
		# or writing unit tests.
		self.options = SortedDict()
		self.datasets = []
		self.axes = []
		self.datarange = None
		self.alt = None
		self.grid_lines = False

	def clone(self):
		clone = self.__class__()
		clone.options = self.options.copy()
		clone.datasets = self.datasets[:]
		clone.axes = self.axes[:]
		return clone

	def img(self):
		url = self.url()
		width, height = self.options["chs"].split("x")
		if self.alt:
			alt = 'alt="%s" ' % escape(self.alt)
		else:
			alt = ''
		s = mark_safe('<img src="%s" width="%s" height="%s" %s/>' % (escape(url), width, height, alt))
		return s

	def url(self):
		if self.options.get('cht', None) == 't':
			self.datasets.append(self.options.pop("_mapdata"))

		# Figure out the chart's data range
		if not self.datarange:
			maxvalue = max(max(d) for d in self.datasets if d)
			minvalue = min(min(d) for d in self.datasets if d)
			self.datarange = (minvalue, maxvalue)
		
		# Encode data
		if "chds" in self.options or self.options.get('cht', None) == 'gom':
			# text encoding if scaling provided, or for google-o-meter type
			data = "|".join(encode_text(d) for d in self.datasets)
			if self.grid_lines:
				 encoded_data = "t1:%s" % data
			else:
				 encoded_data = "t:%s" % data
		else: 
			# extended encoding otherwise
			data = extended_separator.join(encode_extended(d, self.datarange) for d in self.datasets)
			encoded_data = "e:%s" % data
		
		# Update defaults
		for k in self.defaults:
			if k not in self.options:
				self.options[k] = self.defaults[k]
		
		# Start to calcuate the URL
		url = "%s?%s&chd=%s" % (self.BASE, urlencode(self.options), encoded_data)
		
		# Calculate axis options
		if self.axes:
			axis_options = SortedDict()
			axis_sides = []
			for i, axis in enumerate(self.axes):
				axis_sides.append(axis.side)
				for opt in axis.options:
					axis_options.setdefault(opt, []).append(axis.options[opt] % i)
		
			# Turn the option lists into strings
			axis_sides = smart_join(",", *axis_sides)
			for opt in axis_options:
				axis_options[opt] = smart_join("|", *axis_options[opt])
			
			url += "&chxt=%s&%s" % (axis_sides, urlencode(axis_options))
			
		return url
Ejemplo n.º 26
0
class Chart(object):

    BASE = "http://chart.apis.google.com/chart"
    defaults = {"chs": "200x200", "cht": "lc"}

    def __init__(self):
        # Use a SortedDict for the options so they are added in a
        # deterministic manner; this eases things like dealing with cache keys
        # or writing unit tests.
        self.options = SortedDict()
        self.datasets = []
        self.hidden_datasets = []
        self.axes = []
        self.datarange = None
        self.alt = None

    def clone(self):
        clone = self.__class__()
        clone.options = self.options.copy()
        clone.datasets = self.datasets[:]
        clone.hidden_datasets = self.hidden_datasets[:]
        clone.axes = self.axes[:]
        return clone

    def img(self, color_override=None):
        orig_colors = self.options.get('chco')
        # If color_override is set, replace the chco option with this color
        if color_override is not None:
            final_color = []
            for c in self.options['chco'].split(','):
                if c == color_override:
                    c = orig_colors.split(',')[0]
                else:
                    c = _chart_inactive_color
                final_color.append(c)
            self.options['chco'] = ','.join(final_color)
        url = self.url()
        if orig_colors:
            self.options['chco'] = orig_colors
        width, height = self.options["chs"].split("x")
        if self.alt:
            alt = '%s' % escape(self.alt)
        else:
            alt = ''
        s = mark_safe('<img src="%s" width="%s" height="%s" alt="%s" />' %
                      (escape(url), width, height, alt))

        return s

    def url(self):
        if self.options.get('cht', None) == 't':
            self.datasets.append(self.options.pop("_mapdata"))

        # Figure out the chart's data range
        if not self.datarange:
            maxvalue = max(
                max(d) for d in chain(self.datasets, self.hidden_datasets)
                if d)
            minvalue = min(
                min(d) for d in chain(self.datasets, self.hidden_datasets)
                if d)
            self.datarange = (minvalue, maxvalue)

        # Encode data
        if "chds" in self.options or self.options.get('cht', None) == 'gom':
            # text encoding if scaling provided, or for google-o-meter type
            data = "|".join(
                encode_text(d)
                for d in chain(self.datasets, self.hidden_datasets))
            encoded_data = "t%d:%s" % (len(self.datasets), data)
        else:
            # extended encoding otherwise
            data = extended_separator.join(
                encode_extended(d, self.datarange)
                for d in chain(self.datasets, self.hidden_datasets))
            encoded_data = "e%d:%s" % (len(self.datasets), data)

        # Update defaults
        for k in self.defaults:
            if k not in self.options:
                self.options[k] = self.defaults[k]

        # Start to calculate the URL
        url = "%s?%s&chd=%s" % (self.BASE, urlencode(
            self.options), encoded_data)

        # Calculate axis options
        if self.axes:
            axis_options = SortedDict()
            axis_sides = []
            for i, axis in enumerate(self.axes):
                axis_sides.append(axis.side)
                for opt in axis.options:
                    try:
                        axis_options.setdefault(opt, []).append(
                            axis.options[opt] % i)
                    except TypeError:
                        pass

            # Turn the option lists into strings
            axis_sides = smart_join(",", *axis_sides)
            for opt in axis_options:
                axis_options[opt] = smart_join("|", *axis_options[opt])

            url += "&chxt=%s&%s" % (axis_sides, urlencode(axis_options))

        return url

    def charts(self):
        res = []
        count = 1
        for o in self.options['_final_color_map'].items():
            res.append({
                'id': count,
                'color': o[0],
                'label': o[1],
                'img': self.img(color_override=o[0])
            })
            count += 1
        return res
Ejemplo n.º 27
0
class Chart(object):

    BASE = "http://chart.apis.google.com/chart"
    defaults = {"chs": "200x200", "cht": "lc"}

    def __init__(self):
        # Use a SortedDict for the opeions so they are added in a
        # deterministic manner; this eases things like dealing with cache keys
        # or writing unit tests.
        self.options = SortedDict()
        self.datasets = []
        self.axes = []
        self.datarange = None
        self.alt = None

    def clone(self):
        clone = self.__class__()
        clone.options = self.options.copy()
        clone.datasets = self.datasets[:]
        clone.axes = self.axes[:]
        return clone

    def img(self):
        url = self.url()
        width, height = self.options["chs"].split("x")
        if self.alt:
            alt = 'alt="%s" ' % escape(self.alt)
        else:
            alt = ''
        s = mark_safe('<img src="%s" width="%s" height="%s" %s/>' %
                      (escape(url), width, height, alt))
        return s

    def url(self):
        if self.options.get('cht', None) == 't':
            self.datasets.append(self.options.pop("_mapdata"))

        # Figure out the chart's data range
        if not self.datarange:
            if self.datasets == [[]]:
                maxvalue = 0
                minvalue = 0
            else:
                maxvalue = max(max(d) for d in self.datasets if d)
                minvalue = min(min(d) for d in self.datasets if d)
            self.datarange = (minvalue, maxvalue)

        # Encode data
        if "chds" in self.options or self.options.get('cht', None) == 'gom':
            # text encoding if scaling provided, or for google-o-meter type
            data = "|".join(encode_text(d) for d in self.datasets)
            encoded_data = "t:%s" % data
        else:
            # extended encoding otherwise
            data = extended_separator.join(
                encode_extended(d, self.datarange) for d in self.datasets)
            encoded_data = "e:%s" % data

        # Update defaults
        for k in self.defaults:
            if k not in self.options:
                self.options[k] = self.defaults[k]

        # Start to calcuate the URL
        url = "%s?%s&chd=%s" % (self.BASE, urlencode(
            self.options), encoded_data)

        # Calculate axis options
        if self.axes:
            axis_options = SortedDict()
            axis_sides = []
            for i, axis in enumerate(self.axes):
                axis_sides.append(axis.side)
                for opt in axis.options:
                    axis_options.setdefault(opt,
                                            []).append(axis.options[opt] % i)

            # Turn the option lists into strings
            axis_sides = smart_join(",", *axis_sides)
            for opt in axis_options:
                axis_options[opt] = smart_join("|", *axis_options[opt])

            url += "&chxt=%s&%s" % (axis_sides, urlencode(axis_options))

        return url