def __init__(self, transition: Transition, enum: Type[CustomEnum]) -> None: self.__doc__ = transition.__doc__ self.name = transition.name self.to_state = enum(transition.to_state) self.from_states = [ None if state is None else enum(state) for state in transition.from_states ]
def value_to_enum(enum: enum.Enum, x: Union[int, str, enum.Enum]) -> enum.Enum: """Tries to convert given value to Enum object. Example: .. code-block:: python3 from gd.utils import value_to_enum enum = gd.IconType value_to_enum(enum, 0) -> gd.IconType.CUBE value_to_enum(enum, 'cube') -> gd.IconType.CUBE value_to_enum(enum, gd.IconType.CUBE) -> gd.IconType.CUBE Parameters ---------- enum: :class:`enum.Enum` Instance of *Enum* to convert ``x`` to. x: Union[:class:`int`, :class:`str`, :class:`enum.Enum`] Object to convert to ``enum``. Returns ------- :class:`enum.Enum` Result of converting ``x`` to ``enum``. Raises ------ :exc:`.FailedConversion` Failed to convert ``x`` to ``enum``. """ try: # if int -> enum of value x if isinstance(x, (float, int)): return enum(x) # if str -> enum of name x (converted) elif isinstance(x, str): try: return enum[_name_to_enum(x)] except KeyError: try: return enum[x] except KeyError: return enum(x) # if enum -> enum of value x.value elif isinstance(x, Enum): return enum(x.value) # let's raise it here, so if it is raised, we can tell that invalid type was given. raise ValueError except (KeyError, ValueError): raise FailedConversion(enum=enum, value=x) from None
def main(): enum() #test_l_c() #test_zip() #test_tools() dec_test() for i in primenumber(30): # print(i) pass pass
def _parse(body, enum=VAR_ENUM, re=VAR_RE, template=VAR_TEMPLATE): 'Low-level parsing function for outputs and variables.' item = context = None for m in re.finditer(body): token = enum(m.lastindex) data = m.group(m.lastindex) if token == enum.OPEN: match = m.group(0) leading_lines = len(match) - len(match.lstrip("\n")) start = m.span()[0] line = body[:start].count('\n') + leading_lines + 1 item = {'name': data, 'tags': {}, 'line': line} item.update({k: [] for k in template}) context = None elif token == enum.CLOSE: if item: yield item item = context = None elif token == enum.ATTR_DATA: if not item: continue context = m.group(m.lastindex - 1) item[context].append(data) elif token == enum.SKIP: context = token elif token == enum.COMMENT: if item and data.startswith('tfdoc:'): k, v = data.split(' ', 1) item['tags'][k[6:]] = v elif token == enum.TXT: if context and context != enum.SKIP: item[context].append(data)
def _encode(self, obj, context, path): if obj == enum: return obj.value try: return enum[obj] if isinstance(obj, str) else enum(obj) except ValueError: raise ValidationError("object failed validation: %s" % (obj, ))
class BuiltIn(Entity): builtin_types = enum('Number', 'Text', 'Date', 'Boolean') py_types = [[int, long, float], [str, unicode], [datetime.datetime, datetime.date], [bool]] type_defaults = [0, '', datetime.datetime.now(), False] def __init__(self, name, world=None): self.builtin_type = self.builtin_types(name) super(BuiltIn, self).__init__(name, world) def is_instance(self, inst): return isinstance(inst, self.py_types[self.builtin_type]) def coerce_value(self, value): """ coerce the given value to be storable in the current type """ if self.builtin_type == self.builtin_types.Date and type(value) == str: dt = parse_date.parse_date(value) return dt for target in self.py_types[self.builtin_type]: convert = None try: convert = target(value) except: pass if convert is not None: return convert return None @staticmethod def init_all(): for bi in BuiltIn.builtin_types: BuiltIn(bi) def add_prop(self, name): raise Exception("Can't add properties to builtin types")
def convert_choice_field_to_enum(field): """ Add support to convert ordering choices to Graphql enum. Label is used as enum name. """ registry = get_global_registry() # field label of enum needs to be unique so stored it likewise converted = registry.get_converted_field(field.label) if converted: return converted def get_choices(choices): for value, help_text in choices: if value: name = convert_choice_name(value) description = help_text yield name, value, description name = to_camel_case(field.label) choices = list(get_choices(field.choices)) named_choices = [(c[0], c[1]) for c in choices] named_choices_descriptions = {c[0]: c[2] for c in choices} class EnumWithDescriptionsType(object): @property def description(self): return named_choices_descriptions[self.name] enum = Enum(name, list(named_choices), type=EnumWithDescriptionsType) converted = enum(description=field.help_text, required=field.required) registry.register_converted_field(field.label, converted) return converted
""" from Queue import PriorityQueue from enum import * from chain import * from main import version,help,VERSION from manual import * import logger import alerts import netio import configuration import scheduler import worker SERVER_STATUSES = enum(INIT=1, RUNNING=2, QUIT=3) TRUE = 1 class Application(object): """ Main class of the application """ def __init__(self): super(Application, self).__init__() self.__private_value = 0 self.logger = [] # Logger self.alerts = list() # Customizable alerts for events self.alerts_count = 0 # Count of created alerts self.start_time = 0 # Start time of the server
def _decode(self, obj, context, path): if obj not in enum._value2member_map_: raise ValidationError("object failed validation: %s" % (obj, )) return enum(obj)
# -*- coding: utf-8 -*- import numpy as np import sys from enum import * OrderedListErrors = enum('OBJECT_NOT_FOUND') class OrderedListException(Exception): def __init__(self, code=0, message=""): self.args = (code, message) class OrderedList(): def __init__(self): self._new() def _new(self): self._list = np.array([]) self._order = np.array([], dtype=int) def _append(self, item, order): self._list = np.append(self._list, item) self._order = np.append(self._order, order) def _move(self, order, down):
# ---------- removeTrumpActor() ----- def removeTrumpActor(): global trumpActor global trump if trumpActor != None: trumpActor.removeSelf() trumpActor = None trump = None # ------------------------ main -------------------------------------------- isDebug = False Suit = enum("KREUZ", "HERZ", "KARO", "PIK") if isDebug: Rank = enum("ASS", "KOENIG", "DAME", "BAUER", "ZEHN") else: Rank = enum("ASS", "KOENIG", "DAME", "BAUER", "ZEHN", "NEUN", "ACHT", "SIEBEN", "SECHS") deck = Deck(Suit.values(), Rank.values(), "cover") # ------------ Locations ------------------ handLocations = [ Location(300, 525), Location(75, 300), Location(300, 75), Location(525, 300) ] talonLocation = Location(250, 300)
def internal(obj, data): s = struct.calcsize(fmt) value = struct.unpack(fmt, data[:s])[0] return s, enum(value)
def stream(obj, stream): s = struct.calcsize(fmt) value = struct.unpack(fmt, stream.read(s))[0] return enum(value)
from ch.aplu.jgamegrid import Location, GGMouseListener, GGMouse from ch.aplu.jcardgame import Deck, CardGame, RowLayout, Hand from ch.aplu.jcardgame.Hand import SortType from ch.aplu.util import Monitor from enum import * # ------------------ class MyMouseListener --------------------------------- class MyMouseListener(GGMouseListener): def mouseEvent(self, mouse): Monitor.wakeUp() return True # ------------------------ main -------------------------------------------- Suit = enum("SPADES", "HEARTS", "DIAMONDS", "CLUBS") Rank = enum("ACE", "KING", "QUEEN", "JACK", "TEN", "NINE", "EIGHT", "SEVEN", "SIX") deck = Deck(Suit.values(), Rank.values(), "cover") cg = CardGame(900, 615, 30) cg.addMouseListener(MyMouseListener(), GGMouse.lPress) while True: hand = deck.dealingOut(1, 25)[0] hand.setView(cg, RowLayout(Location(450, 80), 890)) hand.sort(SortType.RANKPRIORITY, True) sequence3 = hand.extractSequences(Suit.HEARTS, 3) for i in range(len(sequence3)): sequence3[i].setView(cg, RowLayout(Location(70 + 150 * i, 230), 120))
\ ]) ## auto add function: 'pure', 'static', 'scope', 'type', 'name', 'params', 'args', 'comment' const.constructor_comment = 'constructor().' const.member_default =['False', 'False', 'public', '', '', '', '','',''] const.member_init =['False', 'False', 'public', 'void', 'init', '', '', \ const.constructor_comment, ''] const.member_destructor =['False', 'False', 'private', 'void', '_destructor', '', '', \ 'called by free(): put resources, forward to super.', ''] const.member_free =['False', 'False', 'public', 'void', 'free', '', '', \ 'free memory after call destructor().', ''] ## Flags const.config_destructor = 'enable_destructor' # add free() to self and all derived-class, auto enable-super const.config_super = 'enable_super' # add member 'super' to vtable const.control_super = '_have_super_ref' const.control_vtable = '_have_vtable_new' const.control_static_var = '_have_static_var' # '' <OR> store first static var's name for init ## cat-category const.func = enum('pure', 'static', 'scope', 'type', 'name', 'params', 'args', 'comment', 'pseudocode') const.func_mode = enum('_None', '_cat', 'cat_name', 'cat_name_type', 'cat_name_type_args', \ 'cat_name_type_args_scope', 'cat_name_type_args_scope_comment', \ 'cat_name_type_args_scope_comment_pseudocode', \ ) # grahic: node&edge const.graphic = 'graphic' const.templ_graphic = '_graphic' const.graphic_node = odict([('type','node'), ('id','name'), ('attrs',''), ('meths',''), ('x',1), ('y',1), ('width',1), ('height',1)]) const.graphic_edge = odict([('type','edge'), ('id','name'), ('source','src'), ('target','dst'), ('uml_edge_type','generalisation')])
def try_enum(enum, val): try: return enum(val) except ValueError: warn('unknown %s: %s' % (enum.__name__, val)) return val
local_cache = "kahnsept.bin" TRACE = True __all__ = [ 'Card', 'World', 'Entity', 'BuiltIn', 'Property', 'Relation', 'Instance' ] """ The allowed cardinalities of a property or relation """ Card = enum( 'one', 'many', 'one_one', # 1:1 - matched (e.g. spouse) 'one_many', # 1:* - partition (e.g., children) 'many_one', # *:1 - reference (e.g., father) 'many_many', # *:* - multi-set (e.g., siblings) many_one=0, # synonym for 'one' many_many=1 # synonym for 'many' ) card_inverse = (Card.one_many, Card.many_many, Card.one_one, Card.many_one) def key_summary(map, limit=7): sum = map.keys()[0:limit] if len(map) > limit: sum.append("and %d others." % (len(map) - limit)) return ", ".join(sum)
APPLICATION_NAME = "login_cli" DATA_DIR = 'data/' USERS_FILE = DATA_DIR + "users.users" PARAMETERS_FILE = DATA_DIR + "login.txt" global options def enum(*args): #enums = dict(zip(args, range(len(args)))) enums = dict(zip(args, args)) return type('Enum', (), enums) FAIL_REASONS = enum('NO_MATCHING_USER', 'INCORRECT_PASSWORD', 'INCORRECT_OTP', 'REPEAT_PASSWORD') OTP_VALID_WINDOW = 1 #----------------------Main Method ---------------------------------- if __name__ == "__main__": try: import sys from simple_parameters import simple_parameters parser = simple_parameters.SimpleParser(PARAMETERS_FILE) (options, args) = parser.resolve_parameters(sys.argv) logger.debug("Input parameters:{}".format(options))
import socket import logging import enum import datetime from Helpers import * now = datetime.datetime.now() logging.basicConfig( filename=''.join(["Logs/", str(datetime.datetime.now()), ".log"]), level=logging.INFO ) ErrorCodes = enum( 'ErrorCodes', 'UNKNOWN_HOST UNKNOWN_FAILURE UNKNOWN_CHANNEL UNKOWN_USER ' 'MESSAGE_SENT PONG_SUCCESS SERVER_CONNECTED HOSTNAME_NOT_RESOLVED ' 'SERVER_DISCONNECTED CHANNEL_JOINED CHANNEL_NAME_MALFORMED CHANNEL_LEFT ' ) class Client(object): DEFAULT_PORT = 6667 def __init__(self, username, host, port, password=None): self.user_name = username self.password = password self.host = host self.port = port self.connection = self.get_connection()
# -*- coding: utf-8 -*- from tables import * import numpy as np import sys from orderedlist import * from mainanimationnew import * from enum import * AnimationListErrors = enum('FILE_EMPTY', 'FILE_NOT_FOUND', 'INVALID_EXTENSION', 'INVALID_FORMAT', 'INVALID_PARAMETER', 'NOT_LOADED', 'ANIMATION_NOT_FOUND') class AnimationListException(Exception): def __init__(self, code=0, message=""): self.args = (code, message) class AnimationItem(IsDescription): path = StringCol(255) order = Int32Col() class AnimationList(OrderedList): def __init__(self): OrderedList.__init__(self) self.__folder_path = os.path.dirname(os.path.realpath(__file__)) + "/data/lists/" self.__animations_path = os.path.dirname(os.path.realpath(__file__)) + "/data/animations/" self.playlist = np.array([])
def convert_to_enums(obj, **enum_mapping: Type[enum.Enum]): for attr, enum in enum_mapping.items(): val = getattr(obj, attr) if val is not None: setattr(obj, attr, enum(val))
import argparse import cv2 import enum import imutils import numpy as np import os import picamera import RPi.GPIO as GPIO import sys def enum(**enums): return type("Enum", (), enums) LightPosition = enum(none=0, left=1, right=2, center=3) def detect_bright_spots(image, sensitivity, min_thresh): output = [] gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(gray, (11, 11), 0) threshold = cv2.threshold(blurred, min_thresh, 255, cv2.THRESH_BINARY)[1] threshold = cv2.erode(threshold, None, iterations=2) threshold = cv2.dilate(threshold, None, iterations=4) labels = measure.label(threshold, neighbors=8, background=0) mask = np.zeros(threshold.shape, dtype="uint8")
""" Logger class Logger controls the application logging capabilites Author: Patryk Zabkiewicz Date: 2016.03.21 License info: This software comes with NO WARRANTY. You use it at your own risk. Full license text is avaible at http://www.gnu.org/licenses/lgpl-3.0.html """ from enum import * LOG_LEVEL = enum(INFO=1, WARRNING=2, ERROR=3) class LogLine(object): """ One line of logs """ def __init__(self, msg, log_level=LOG_LEVEL.INFO): super(LogLine, self).__init__() self.level = log_level self.messange = msg class Logger(object): """ Logger controls the application logging capabilites """ def __init__(self): super(Logger, self).__init__() self.log_store = "~/.imt/server.log" # Standard log path self.log_buffer_size = 10 # Default log buffer size to disk store self.log_buffer_count = 0 # Count of the messanges in the buffer self.log_buffer = list() # Log buffer
import enum THINGS = enum(A="apple", B="banana") def getthings(): return THINGS
import dyn_dict local_cache = "kahnsept.bin" TRACE = True __all__ = ['Card', 'World', 'Entity', 'BuiltIn', 'Property', 'Relation', 'Instance'] """ The allowed cardinalities of a property or relation """ Card = enum('one', 'many', 'one_one', # 1:1 - matched (e.g. spouse) 'one_many', # 1:* - partition (e.g., children) 'many_one', # *:1 - reference (e.g., father) 'many_many', # *:* - multi-set (e.g., siblings) many_one=0, # synonym for 'one' many_many=1 # synonym for 'many' ) card_inverse = (Card.one_many, Card.many_many, Card.one_one, Card.many_one) def key_summary(map, limit=7): sum = map.keys()[0:limit] if len(map) > limit: sum.append("and %d others." % (len(map) - limit)) return ", ".join(sum) class World(object): """
from signals import * from wavsignal import * from hdfsignal import * from lpf import * from orderedlist import * from enum import * ANIMATION_TYPE_NONE = 0 ANIMATION_TYPE_WAV_FILE = 1 ANIMATION_TYPE_HDF_FILE = 2 DEFAULT_FILTER_FREQUENCY_HZ = 20 MainAnimationErrors = enum('FILE_EMPTY', 'FILE_NOT_FOUND', 'INVALID_EXTENSION', 'INVALID_FORMAT', 'INVALID_PARAMETER', 'NOT_LOADED', 'INVALID_TYPE') class MainAnimationException(Exception): def __init__(self, code=0, message=""): self.args = (code, message) class MainAnimationItem(IsDescription): id = Int32Col() path = StringCol(255) order = Int32Col() class VariablesItem(IsDescription): name = StringCol(255) value = Float32Col() parameter = Int32Col()