Exemplo n.º 1
0
    def test_unique_dirty(self):
        try:
            class Dirty(Enum):
                __order__ = 'one two tres'
                one = 1
                two = 'dos'
                tres = 1
            unique(Dirty)
        except ValueError:
            exc = sys.exc_info()[1]
            message = exc.args[0]
        self.assertTrue('tres -> one' in message)

        try:
            class Dirtier(IntEnum):
                __order__ = 'single double triple turkey'
                single = 1
                double = 1
                triple = 3
                turkey = 3
            unique(Dirtier)
        except ValueError:
            exc = sys.exc_info()[1]
            message = exc.args[0]
        self.assertTrue('double -> single' in message)
        self.assertTrue('turkey -> triple' in message)
Exemplo n.º 2
0
def member_of(obj, arg):
    if isinstance(arg, enum.Enum):
        enum.unique(obj)  # check that enum has unique values
        arg = arg.name

    if not hasattr(obj, arg):
        raise com.IbisTypeError(
            'Value with type {} is not a member of {}'.format(type(arg), obj))
    return getattr(obj, arg)
Exemplo n.º 3
0
def unique3(S, start, stop):
    """Return True if there are no duplicate elements in slice S[start:stop]."""
    if stop - start <= 1: return True
    elif not unique(S, start, stop - 1): return False
    elif not unique(S, start + 1, stop): return False
    else: return S[start] != S[stop - 1]


# first part has duplicate
# second part has duplicate # do first and last differ?
Exemplo n.º 4
0
def member_of(obj, arg):
    if isinstance(arg, enum.Enum):
        enum.unique(obj)  # check that enum has unique values
        arg = arg.name

    if not hasattr(obj, arg):
        raise com.IbisTypeError(
            'Value with type {} is not a member of {}'.format(type(arg), obj)
        )
    return getattr(obj, arg)
Exemplo n.º 5
0
 def test_unique_clean(self):
     class Clean(Enum):
         one = 1
         two = 'dos'
         tres = 4.0
     unique(Clean)
     class Cleaner(IntEnum):
         single = 1
         double = 2
         triple = 3
     unique(Cleaner)
Exemplo n.º 6
0
def member_of(obj, arg, **kwargs):
    if isinstance(arg, ir.EnumValue):
        arg = arg.op().value
    if isinstance(arg, enum.Enum):
        enum.unique(obj)  # check that enum has unique values
        arg = arg.name

    if not hasattr(obj, arg):
        raise com.IbisTypeError(
            f'Value with type {type(arg)} is not a member of {obj}')
    return getattr(obj, arg)
Exemplo n.º 7
0
    def __init__(
        self,
        *,
        coerce: Optional[Callable[[Any], Optional[_GT]]] = None,
        empty_value: Optional[str] = "",
        enum: Optional[Type[_GT]] = None,
        choices: Optional[EnumChoiceIterator[_GT]] = None,
        required: bool = True,
        widget: Optional[Union[Widget, Type[Widget]]] = None,
        label: Optional[str] = None,
        initial: Optional[_GT] = None,
        help_text: str = "",
        error_messages: Optional[Any] = None,
        show_hidden_initial: bool = False,
        validators: Sequence[Any] = (),
        localize: bool = False,
        disabled: bool = False,
        label_suffix: Optional[Any] = None,
    ) -> None:
        """When instantiated by a model form, choices will be populated and
        enum will not, as Django strips all but a defined set of kwargs.

        And coerce will be populated by the model as well.

        When using this field directly in a form, enum will be populated and
        choices and coerce should be None."""

        if enum is not None and choices is None:
            self.enum = enum
            choices = EnumChoiceIterator(enum=enum, include_blank=required)
            coerce = lambda value: coerce_to_enum(self.enum, value)
        elif enum is None and choices is not None:
            self.enum = choices.enum
        else:
            assert False, "Pass enum or choices. Not both"

        unique(self.enum)

        return super().__init__(
            coerce=coerce,
            empty_value=empty_value,
            choices=choices,
            required=required,
            widget=widget,
            label=label,
            initial=initial,
            help_text=help_text,
            error_messages=error_messages,
            show_hidden_initial=show_hidden_initial,
            validators=validators,
            localize=localize,
            disabled=disabled,
            label_suffix=label_suffix,
        )
Exemplo n.º 8
0
def named_equally(enumeration: t.Type[ENUM]) -> t.Type[ENUM]:
    """Make sure all the values in the given enum are unique and equal to their
    key.
    """
    enum.unique(enumeration)

    for name, member in enumeration.__members__.items():
        if name != member.value:
            raise ValueError('Member {} has a wrong value: {}'.format(
                name, member.value))

    return enumeration
Exemplo n.º 9
0
    def test_unique_clean(self):
        class Clean(Enum):
            one = 1
            two = 'dos'
            tres = 4.0

        unique(Clean)

        class Cleaner(IntEnum):
            single = 1
            double = 2
            triple = 3

        unique(Cleaner)
Exemplo n.º 10
0
 def __new__(metacls, classname, bases, classdict):
     labels = []
     value_as_label = classdict.pop('__value_as_label__', False)
     for key in classdict._member_names:
         args = classdict[key]
         if (isinstance(args, (list, tuple)) and len(args) > 1
                 and isinstance(args[-1], (Promise, str))):
             if len(args) == 2 and isinstance(args[0], enum.auto):
                 value = key
                 label = args[1]
             else:
                 *value, label = args
                 value = tuple(value)
         else:
             value = args
             if value_as_label:
                 label = value
             else:
                 label = key.replace('_', ' ').title()
         labels.append(label)
         # Use dict.__setitem__() to suppress defenses against double
         # assignment in enum's classdict.
         dict.__setitem__(classdict, key, value)
     cls = super().__new__(metacls, classname, bases, classdict)
     cls._value2label_map_ = dict(zip(cls._value2member_map_, labels))
     # Add a label property to instances of enum which uses the enum member
     # that is passed in as "self" as the value to use when looking up the
     # label in the choices.
     cls.label = property(
         lambda self: cls._value2label_map_.get(self.value))
     return enum.unique(cls)
Exemplo n.º 11
0
 def __new__(metacls, classname, bases, classdict):
     labels = []
     for key in classdict._member_names:
         value = classdict[key]
         if (
             isinstance(value, (list, tuple)) and
             len(value) > 1 and
             isinstance(value[-1], (Promise, str))
         ):
             *value, label = value
             value = tuple(value)
         else:
             label = key.replace('_', ' ').title()
         labels.append(label)
         # Use dict.__setitem__() to suppress defenses against double
         # assignment in enum's classdict.
         dict.__setitem__(classdict, key, value)
     cls = super().__new__(metacls, classname, bases, classdict)
     cls._value2label_map_ = dict(zip(cls._value2member_map_, labels))
     # Add a label property to instances of enum which uses the enum member
     # that is passed in as "self" as the value to use when looking up the
     # label in the choices.
     cls.label = property(lambda self: cls._value2label_map_.get(self.value))
     cls.do_not_call_in_templates = True
     return enum.unique(cls)
Exemplo n.º 12
0
    def __new__(metacls, classname, bases, classdict, **kwds):
        extra_keys = {'next', 'initial'}
        extra_data = []

        # Always is expected that start will be 1
        auto_start = 1
        auto_last_values = []
        auto_count = 0

        for key in classdict._member_names:
            value = classdict[key]
            member_extra_data = {
                'next': None,
                'initial': True,
                'label': key.replace('_', ' ').title()
            }
            if isinstance(value, Choice):
                choice = value
                value = choice.value
                label = choice.label
                member_extra_data.update({
                    'next': choice.next,
                    'initial': choice.initial,
                    **choice.extra
                })

            elif (isinstance(value, (list, tuple)) and len(value) > 1
                  and isinstance(value[-1], (Promise, str))):
                *value, label = value
                value = tuple(value)
                if len(value) == 1:
                    value = value[0]
            else:
                label = None

            if label is None:
                label = key.replace('_', ' ').title()

            member_extra_data['label'] = label

            extra_keys.update(member_extra_data.keys())
            extra_data.append(member_extra_data)
            if isinstance(value, enum.auto):
                value = classdict['_generate_next_value_'](key, auto_start,
                                                           auto_count,
                                                           auto_last_values)

            auto_count += 1
            auto_last_values.append(value)

            # Use dict.__setitem__() to suppress defenses against double
            # assignment in enum's classdict.
            dict.__setitem__(classdict, key, value)
        cls = super().__new__(metacls, classname, bases, classdict, **kwds)
        cls._value2data_map_ = dict(zip(cls._value2member_map_, extra_data))
        for key in extra_keys:
            set_enum_attribute(cls, key, cls._value2data_map_)
        return enum.unique(cls)
Exemplo n.º 13
0
    def __init__(self, base_enum):
        """Init.

        :param enum base_enum: Enum, to which elements values are translated.

        """
        base_enum = unique(base_enum)
        self.base_enum = base_enum
        self._generate_values_tree()
Exemplo n.º 14
0
    def __init__(self, base_enum):
        """Init.

        :param enum base_enum: Enum, to which elements values are translated.

        """
        base_enum = unique(base_enum)
        self.base_enum = base_enum
        self.generate_search_table()
Exemplo n.º 15
0
    def computeDirectMethod(self):
        self.clearResults()

        point_size = len(self._input_points)

        if point_size < 3:
            return

        for i in range(point_size - 1):
            p = self._input_points[i]
            for j in range(i + 1, point_size):
                q = self._input_points[j]
                rel = q - p

                valid = True
                last_value = 0.0

                for k in range(point_size):
                    if k == i or k == j:
                        continue

                    r = self._input_points[k]
                    outer_prod = rel.outerProduct(r - p)

                    if math.fabs(outer_prod) < EPSILON:
                        # point is on the line
                        if (r - p).r2() < rel.r2():
                            # point is on the segment
                            valid = False
                            break

                    if (outer_prod > 0.0
                            and last_value < 0.0) or (outer_prod < 0.0
                                                      and last_value > 0.0):
                        # point exists in the opposite side
                        valid = False
                        break

                    last_value = outer_prod

                if valid:
                    self._vertices.append(p)
                    self._vertices.append(q)

                    if last_value < 0.0:
                        self._edges.append(Segment2D(p, q))

                    else:
                        self._edges.append(Segment2D(q, p))

        # sort vertices by counter clockwise order

        if len(self._vertices):
            BASE_ = self._vertices[len(self._vertices) - 1]
            self._vertices.sort(key=functools.cmp_to_key(AngleSortPredicate))
            self._vertices = unique(self._vertices)
Exemplo n.º 16
0
    def get_enum(cls) -> Type[models.TextChoices]:
        """Возвращает перечисление источников для модели."""

        enum = unique(
            models.TextChoices(
                'Source',
                [(alias, (alias, source_cls.title))
                 for alias, source_cls in cls.get_sources().items()]))

        return enum
Exemplo n.º 17
0
    def wrapper(cl):
        res = unique(cl)
        res.__fb_module__ = modules[fb_cl.__module__]
        res.__fb_class__ = fb_cl

        if cl.__name__ != fb_cl.__name__:
            raise ValueError(
                f"Names don't match: {cl.__name__}/{fb_cl.__name__}.")

        for member in cl:
            if not hasattr(fb_cl, member.name):
                raise ValueError(f"{cl}/{member.name} doesn't match {fb_cl}.")

        return res
Exemplo n.º 18
0
def enum(name, items, start=1, is_int=False):
    """Factory for simple enumerations.

    Args:
        name: Name of the enum
        items: Iterable of items to be sequentially enumerated.
        start: The number to use for the first value.
               We use 1 as default so enum members are always True.
        is_init: True if the enum should be a Python IntEnum
    """
    enums = [(v, i) for (i, v) in enumerate(items, start)]
    base = pyenum.IntEnum if is_int else pyenum.Enum
    base = pyenum.unique(base)
    return base(name, enums)
Exemplo n.º 19
0
 def __new__(metacls, classname, bases, classdict, **kwds):
     labels = []
     for key in classdict._member_names:
         value = classdict[key]
         if (isinstance(value, (list, tuple)) and len(value) > 1
                 and isinstance(value[-1], (Promise, str))):
             *value, label = value
             value = tuple(value)
         else:
             label = key.replace('_', ' ').title()
         labels.append(label)
         # Use dict.__setitem__() to suppress defenses against double
         # assignment in enum's classdict.
         dict.__setitem__(classdict, key, value)
     cls = super().__new__(metacls, classname, bases, classdict, **kwds)
     for member, label in zip(cls.__members__.values(), labels):
         member._label_ = label
     return enum.unique(cls)
Exemplo n.º 20
0
    def __new__(mcs, cls, bases, classdict):
        # check if the __new__ was invoked for StateMachine itself
        try:
            is_base_cls = StateMachine not in bases
        except NameError:
            is_base_cls = True

        if not is_base_cls:
            event_listeners = collections.defaultdict(list)
            change_listeners = collections.defaultdict(list)
            remove = set()
            for name, value in classdict.items():
                if hasattr(value, '_on_state'):
                    states = value._on_state
                    for state in states:
                        if isinstance(state, enum.Enum):
                            state = state.value
                        event_listeners[state].append(value)
                    remove.add(name)
                if hasattr(value, '_on_transition'):
                    transitions = value._on_transition
                    for transition in transitions:
                        current, next = transition
                        if isinstance(current, enum.Enum):
                            current = current.value
                        if isinstance(next, enum.Enum):
                            next = next.value
                        change_listeners[(current, next)].append(value)
                    remove.add(name)
            for name in remove:
                del classdict[name]
            classdict['__event_listeners__'] = dict(event_listeners)
            classdict['__change_listeners__'] = dict(change_listeners)
            obj = enum.unique(super().__new__(mcs, cls, bases, classdict))
            if 0 not in obj._value2member_map_:
                raise ValueError(f'No start state found in {obj!r}')
        else:
            obj = super().__new__(mcs, cls, bases, classdict)
        return obj
Exemplo n.º 21
0
    def __new__(mcs, cls, bases, classdict):  # pylint: disable=too-many-branches
        # check if the __new__ was invoked for StateMachine itself
        try:
            is_base_cls = StateMachine not in bases
        except NameError:
            is_base_cls = True

        if not is_base_cls:
            event_listeners = collections.defaultdict(list)
            change_listeners = collections.defaultdict(list)
            remove = set()
            for name, value in classdict.items():
                if hasattr(value, "_on_state"):
                    states = value._on_state  # pylint: disable=protected-access
                    for state in states:
                        if isinstance(state, enum.Enum):
                            state = state.value
                        event_listeners[state].append(value)
                    remove.add(name)
                if hasattr(value, "_on_transition"):
                    transitions = (value._on_transition)  # pylint: disable=protected-access
                    for (current, next_state) in transitions:
                        if isinstance(current, enum.Enum):
                            current = current.value
                        if isinstance(next_state, enum.Enum):
                            next_state = next_state.value
                        change_listeners[(current, next_state)].append(value)
                    remove.add(name)
            for name in remove:
                del classdict[name]
            classdict["__event_listeners__"] = dict(event_listeners)
            classdict["__change_listeners__"] = dict(change_listeners)
            obj = enum.unique(super().__new__(mcs, cls, bases, classdict))
            if 0 not in obj._value2member_map_:
                raise ValueError(f"No start state found in {obj!r}")
        else:
            obj = super().__new__(mcs, cls, bases, classdict)
        return obj
Exemplo n.º 22
0
from ieml.dictionary.dictionary import Dictionary
from ieml.dictionary.tools import term

logger = logging.getLogger(__name__)

RelationType = unique(
    IntEnum(
        'RelationType', {
            'Null': 0,
            'Equal': 1,
            'Crossed': 2,
            'Associated': 3,
            'Twin': 4,
            'Opposed': 5,
            **{'Rank_%d' % i: 6 + i
               for i in range(6)},
            **{
                'Child_%s' % ''.join(s): int(11 + (3**i - 1) / 2 + j)
                for i in range(1, 4) for j, s in enumerate(
                    product('sam', repeat=i))
            },
            **{
                'Father_%s' % ''.join(s): int(50 + (3**i - 1) / 2 + j)
                for i in range(1, 4) for j, s in enumerate(
                    product('sam', repeat=i))
            }
        }))


def default_metric(dictionary_version):
    mat = get_matrix('distance', dictionary_version)
    return lambda t0, t1: mat[t0.index, t1.index]
Exemplo n.º 23
0
 def update_event(self, inp=-1):
     self.set_output_val(0, enum.unique(self.input(0)))
Exemplo n.º 24
0
    'CLUSTER_COLOR_B',
    'CLUSTER_COLOR_SAMPLE',
    'CLUSTER_COLOR_APPLY',
    'CLUSTER_COLOR_RESET',
    'SAVED_PROFILES',
    'LOAD_PROFILE',
    'NEW_PROFILE_NAME',
    'SAVE_PROFILE',
    'MENU_TABS',
    'COLOR_MANIPULATION_TAB',
    'EXCLUSION_TAB',
    'PERSISTENCE_TAB',
]

# noinspection PyArgumentList
Fields = unique(
    Enum('Fields', [(name, _as_id(name)) for name in _FIELDS], type=str))


def make_title():
    return html.H4(id=Fields.TITLE,
                   children=divik_result_path(),
                   style={'text-align': 'center'})


def make_plot():
    result_depth = depth(divik_result())
    return html.Div(id=Fields.CLUSTERS_CONTAINER,
                    children=[
                        dcc.Graph(id=Fields.CLUSTERS_GRAPH,
                                  figure=default_clusters_figure(),
                                  style={'min-height': 600}),
Exemplo n.º 25
0
 def assert_bijective(cls):
     enum.unique(cls)
Exemplo n.º 26
0
def test_currency():
    unique(Currency)
    assert Currency.EGP.value == 31
    assert format(Currency.EUR, 's') == '€'
Exemplo n.º 27
0
def test_continent():
    unique(Continent)
    assert Continent.AF.value == 'Africa'
Exemplo n.º 28
0
import numpy as np
from scipy.sparse.csr import csr_matrix

from ieml.dictionary.dictionary import Dictionary
from ieml.dictionary.tools import term

logger = logging.getLogger(__name__)

RelationType = unique(IntEnum('RelationType', {
    'Null': 0,
    'Equal': 1,
    'Crossed': 2,
    'Associated': 3,
    'Twin': 4,
    'Opposed': 5,
    **{'Rank_%d'%i: 6 + i  for i in range(6)},

    **{'Child_%s'%''.join(s): int(11 + (3 ** i - 1) / 2 + j) for i in range(1, 4) for j, s in
       enumerate(product('sam', repeat=i))},

    **{'Father_%s' % ''.join(s): int(50 + (3 ** i - 1) / 2 + j) for i in range(1, 4) for j, s in
       enumerate(product('sam', repeat=i))}
}))


def default_metric(dictionary_version):
    mat = get_matrix('distance', dictionary_version)
    return lambda t0, t1: mat[t0.index, t1.index]


def term_ranking(t):
Exemplo n.º 29
0
def test_country():
    unique(Country)
    assert Country.PH.value == 'Philippines'
Exemplo n.º 30
0
def test_subdivision():
    unique(Subdivision)
    assert Subdivision['ES-CA'].value == 963
Exemplo n.º 31
0
def unique_enum(cls):
    """Make the enum class unique and provide a reverse mapping"""
    cls = enum.unique(cls)
    cls.__values__ = OrderedDict(
        (v.value, v) for v in cls.__members__.values())
    return cls
Exemplo n.º 32
0
 def __new__(metacls, classname, bases, classdict):
     cls = super().__new__(metacls, classname, bases, classdict)
     return enum.unique(cls)
Exemplo n.º 33
0
        Args:
            stream (object): a writable binary file-like object
        '''
        assert (not stream.closed) and stream.writable

        pstr = pickle.dumps(self)
        pstrlen = str(len(pstr)).encode()
        stream.write(pstrlen + b'\n' + pstr)
        stream.flush()


# Enumerated type for TrafficRequest; module-level for pickling purposes
TrafficRequestType = enum.unique(
    enum.Enum(
        'TrafficRequestType',
        'EXIT SHUTDOWN START TEST',
    ), )


class TrafficRequest(TrafficMessage):
    ''' Request object sent from client to server '''
    def __init__(self, message, identifier=None, payload=None):
        ''' Create a TrafficRequest of the given type with the specified
        payload

        Args:
            message (TrafficRequestType): the message type
            identifier (int): a unique identifier used to refer to a single
                test driver
            payload (object): the payload to incorporate; defaults to None
Exemplo n.º 34
0
def unique_mask(enumeration):
    for name, value in enumeration.__members__.items():
        if value ^ (value & (-value)) > 0:
            raise ValueError(f"Non-binary mask found in {enumeration}: "
                             f"{name} -> {value}")
    unique(enumeration)
Exemplo n.º 35
0
 def __init__(self, enum_class, *args, **kwargs):
   if not issubclass(enum_class, enum.Enum):
     raise ValueError("enum_class argument must be a Python 3 enum.")
   self.enum_class = enum.unique(enum_class) # ensure unique members to prevent accidental database corruption
   kwargs['choices'] = [(item, item.name) for item in self.enum_class]
   super(EnumField, self).__init__(*args, **kwargs)
Exemplo n.º 36
0
 def _make_enum(self):
     pairs = ((t.name, t.type) for t in self._type_records)
     return unique(Enum(self.name, pairs))
Exemplo n.º 37
0
Feb ==> Month.Feb , 2
Mar ==> Month.Mar , 3
Apr ==> Month.Apr , 4
May ==> Month.May , 5
Jun ==> Month.Jun , 6
Jul ==> Month.Jul , 7
Aug ==> Month.Aug , 8
Sep ==> Month.Sep , 9
Oct ==> Month.Oct , 10
Nov ==> Month.Nov , 11
Dec ==> Month.Dec , 12

1)定义枚举时,成员名称不允许重复;
2)默认情况下,不同的成员值允许相同,但是两个相同值的成员,第二个的名称会被视作为第一个成员的别名;
3)如果枚举中存在相同值的成员,在通过值获取枚举成员时,只能获取到第一个成员
4)如果要限制定义枚举时,不能定义相同值的成员,可以使用装饰器@unique (需要导入unique模块)
eg:
 from enum import Enum, unique

@unique
class Weekday(Enum):       #枚举定义用class关键字,继承Enum类

    Sun = 0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6