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)
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)
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?
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)
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)
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)
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, )
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
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)
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)
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)
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()
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()
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)
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
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
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)
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)
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
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
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 update_event(self, inp=-1): self.set_output_val(0, enum.unique(self.input(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}),
def assert_bijective(cls): enum.unique(cls)
def test_currency(): unique(Currency) assert Currency.EGP.value == 31 assert format(Currency.EUR, 's') == '€'
def test_continent(): unique(Continent) assert Continent.AF.value == 'Africa'
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):
def test_country(): unique(Country) assert Country.PH.value == 'Philippines'
def test_subdivision(): unique(Subdivision) assert Subdivision['ES-CA'].value == 963
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
def __new__(metacls, classname, bases, classdict): cls = super().__new__(metacls, classname, bases, classdict) return enum.unique(cls)
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
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)
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)
def _make_enum(self): pairs = ((t.name, t.type) for t in self._type_records) return unique(Enum(self.name, pairs))
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