Python enum

60 Python code examples are found related to " enum". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: _defines.py    From abseil-py with Apache License 2.0 7 votes vote down vote up
def DEFINE_enum(  # pylint: disable=invalid-name,redefined-builtin
    name, default, enum_values, help, flag_values=_flagvalues.FLAGS,
    module_name=None, **args):
  """Registers a flag whose value can be any string from enum_values.

  Instead of a string enum, prefer `DEFINE_enum_class`, which allows
  defining enums from an `enum.Enum` class.

  Args:
    name: str, the flag name.
    default: str|None, the default value of the flag.
    enum_values: [str], a non-empty list of strings with the possible values for
        the flag.
    help: str, the help message.
    flag_values: FlagValues, the FlagValues instance with which the flag will
        be registered. This should almost never need to be overridden.
    module_name: str, the name of the Python module declaring this flag.
        If not provided, it will be computed using the stack trace of this call.
    **args: dict, the extra keyword args that are passed to Flag __init__.
  """
  DEFINE_flag(_flag.EnumFlag(name, default, help, enum_values, **args),
              flag_values, module_name) 
Example 2
Source File: deobfuscate_api_calls.py    From public_tools with MIT License 6 votes vote down vote up
def get_all_enum_constants():
	'''
	Returns hash of constant numerical representations. Value of each key is an 
	array containing the constant name (array[0]) and the constant ID (array[1]).
	'''
	constants = {}
	all_enums = GetEnumQty()
	for i in range(0, all_enums):
		en = GetnEnum(i)
		first = GetFirstConst(en, -1)
		v1 = GetConstEx(en, first, 0, -1)
		name = GetConstName(v1)
		constants[int(first)] = [name, en]
		while True:
			first = GetNextConst(en, first, -1)
			v1 = GetConstEx(en, first, 0, -1)
			name = GetConstName(v1)
			if first == 0xFFFFFFFF:
				break
			constants[int(first)] = [name, en]
	return constants


# Grabbing all enumerations in the IDB and storing to a variable for later use. 
Example 3
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def get_image_enum_previews(path,key,force_reload=False):
    """ Returns: ImagePreviewCollection
        Par1: path - The path to collect the images from
        Par2: key - The dictionary key the previews will be stored in
    """
    enum_items = []
    if len(key.my_previews) > 0:
        return key.my_previews
    
    if path and os.path.exists(path):
        image_paths = []
        for fn in os.listdir(path):
            if fn.lower().endswith(".png"):
                image_paths.append(fn)

        for i, name in enumerate(image_paths):
            filepath = os.path.join(path, name)
            thumb = key.load(filepath, filepath, 'IMAGE',force_reload)
            filename, ext = os.path.splitext(name)
            enum_items.append((filename, filename, filename, thumb.icon_id, i))
    
    key.my_previews = enum_items
    key.my_previews_dir = path
    return key.my_previews 
Example 4
Source File: encoding_helper.py    From apitools with Apache License 2.0 6 votes vote down vote up
def AddCustomJsonEnumMapping(enum_type, python_name, json_name,
                             package=None):  # pylint: disable=unused-argument
    """Add a custom wire encoding for a given enum value.

    This is primarily used in generated code, to handle enum values
    which happen to be Python keywords.

    Args:
      enum_type: (messages.Enum) An enum type
      python_name: (basestring) Python name for this value.
      json_name: (basestring) JSON name to be used on the wire.
      package: (NoneType, optional) No effect, exists for legacy compatibility.
    """
    if not issubclass(enum_type, messages.Enum):
        raise exceptions.TypecheckError(
            'Cannot set JSON enum mapping for non-enum "%s"' % enum_type)
    if python_name not in enum_type.names():
        raise exceptions.InvalidDataError(
            'Enum value %s not a value for type %s' % (python_name, enum_type))
    field_mappings = _JSON_ENUM_MAPPINGS.setdefault(enum_type, {})
    _CheckForExistingMappings('enum', enum_type, python_name, json_name)
    field_mappings[python_name] = json_name 
Example 5
Source File: message_registry.py    From apitools with Apache License 2.0 6 votes vote down vote up
def AddEnumDescriptor(self, name, description,
                          enum_values, enum_descriptions):
        """Add a new EnumDescriptor named name with the given enum values."""
        message = extended_descriptor.ExtendedEnumDescriptor()
        message.name = self.__names.ClassName(name)
        message.description = util.CleanDescription(description)
        self.__DeclareDescriptor(message.name)
        for index, (enum_name, enum_description) in enumerate(
                zip(enum_values, enum_descriptions)):
            enum_value = extended_descriptor.ExtendedEnumValueDescriptor()
            enum_value.name = self.__names.NormalizeEnumName(enum_name)
            if enum_value.name != enum_name:
                message.enum_mappings.append(
                    extended_descriptor.ExtendedEnumDescriptor.JsonEnumMapping(
                        python_name=enum_value.name, json_name=enum_name))
                self.__AddImport('from %s import encoding' %
                                 self.__base_files_package)
            enum_value.number = index
            enum_value.description = util.CleanDescription(
                enum_description or '<no description>')
            message.values.append(enum_value)
        self.__RegisterDescriptor(message) 
Example 6
Source File: editing.py    From phobos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getSceneEnumProperty(self, context):
        """

        Args:
          context: 

        Returns:

        """
        scenes = bpy.data.scenes.keys()

        # remove current scene from enum
        scenes.remove(context.scene.name)

        # resources scene is not an export configuration
        if 'resources' in scenes:
            scenes.remove('resources')
        return bUtils.compileEnumPropertyList(scenes) 
Example 7
Source File: descriptor.py    From apitools with Apache License 2.0 6 votes vote down vote up
def describe_enum(enum_definition):
    """Build descriptor for Enum class.

    Args:
      enum_definition: Enum class to provide descriptor for.

    Returns:
      Initialized EnumDescriptor instance describing the Enum class.
    """
    enum_descriptor = EnumDescriptor()
    enum_descriptor.name = enum_definition.definition_name().split('.')[-1]

    values = []
    for number in sorted(enum_definition.numbers()):
        value = enum_definition.lookup_by_number(number)
        values.append(describe_enum_value(value))

    if values:
        enum_descriptor.values = values

    return enum_descriptor 
Example 8
Source File: redz-sigint.py    From RedzSIGINT with GNU General Public License v3.0 6 votes vote down vote up
def convert_analyze_to_enum(arg):
        lowerCase = arg.lower()

        if lowerCase == 'capsoi':
            return 1
        elif lowerCase == 'demodsoi':
            return 2
        elif lowerCase == 'basicanalyzesoi':
            return 3
        elif lowerCase == 'downsamplesoi':
            return 5
        elif lowerCase == 'clockrecoverysoi':
            return 6
        elif lowerCase == 'replaysoi':
            return 7
        else:
            return 1000 
Example 9
Source File: models.py    From phobos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def getCategoriesForEnumProperty(self, context):
    """Returns a list of categories for an EnumProperty.
    
    The categories are based on the ``categories`` variable in the current namespace.
    
    If there are no categories return ('-', '-', '-').

    Args:
      context: 

    Returns:
      list: available category in the model library.

    """
    if not categories:
        return [('-',) * 3]
    return sorted([(item,) * 3 for item in categories]) 
Example 10
Source File: script.py    From vim-gdscript3 with MIT License 6 votes vote down vote up
def get_enum_values(line_num):
    lines = [util.strip_line(line_num, util.get_line(line_num))]
    line_count = util.get_line_count()
    while not lines[-1].endswith("}"):
        line_num += 1
        if line_num > line_count:
            return
        lines.append(util.strip_line(line_num, util.get_line(line_num)))
    m = re.match(_ENUM_VALUES_PATTERN, "\n".join(lines), re.DOTALL)
    if m:
        values = [v.strip() for v in m.group(1).replace("\n", ",").split(",")]
        def map_value(v):
            m = re.match("(\w+)(?:\s*=\s*(.*))?", v)
            if m:
                return ConstDecl(-1, m.group(1), m.group(2))
        return list(filter(lambda v: v, map(map_value, values)))


# A token chain is a group of tokens chained via dot accessors.
# "Token" is a loose term referring to anything that produces a value.
# Example:
#     texture.get_data().get_pixel()
# 'texture', 'get_data', and 'get_pixel' all produce values, and are therefore tokens.
#
# A token chain is only considered valid if every token has a discernible type. 
Example 11
Source File: _common.py    From Blender-AnimeHairSupporter with Apache License 2.0 6 votes vote down vote up
def get_bevel_enum_items():
	items = [
		('Sphere', "円", "", 'MESH_CIRCLE'),
		('2', "2本", "", 'OUTLINER_OB_META'),
		('3', "3本", "", 'COLLAPSEMENU'),
		('Triangle', "三角", "", 'EDITMODE_VEC_HLT'),
		('TriangleLoose', "ゆるやか三角", "", 'PLAY_REVERSE'),
		('Square', "四角", "", 'MESH_PLANE'),
		('SquareLoose', "ゆるやか四角", "", 'LATTICE_DATA'),
		('Diamond', "ひし形", "", 'SPACE3'),
		('DiamondLoose', "ゆるやかひし形", "", 'KEYTYPE_EXTREME_VEC'),
		('Sharp', "シャープ", "", 'LINCURVE'),
		('Leaf', "葉っぱ", "", 'MAN_ROT'),
		('V', "切り込み", "", 'FILE_TICK'),
		('Tilde', "波", "", 'IPO_EASE_IN_OUT'),
		('Step', "段差", "", 'IPO_CONSTANT'),
		('Corrugated', "ギザギザ", "", 'RNDCURVE'),
		('Cloud', "雲", "", 'IPO_ELASTIC'),
		]
	for i, item in enumerate(items): items[i] = tuple(list(item) + [i + 1])
	return items 
Example 12
Source File: appliance_image_bundle.py    From intersight-python with Apache License 2.0 6 votes vote down vote up
def upgrade_impact_enum(self, upgrade_impact_enum):
        """
        Sets the upgrade_impact_enum of this ApplianceImageBundle.
        UpgradeImpactEnum is used to indicate the kind of impact the upgrade has on currently running services on the appliance.

        :param upgrade_impact_enum: The upgrade_impact_enum of this ApplianceImageBundle.
        :type: str
        """
        allowed_values = ["None", "Disruptive", "Disruptive-reboot"]
        if upgrade_impact_enum not in allowed_values:
            raise ValueError(
                "Invalid value for `upgrade_impact_enum` ({0}), must be one of {1}"
                .format(upgrade_impact_enum, allowed_values)
            )

        self._upgrade_impact_enum = upgrade_impact_enum 
Example 13
Source File: clang_exporter.py    From pigaios with GNU General Public License v3.0 6 votes vote down vote up
def visit_ENUM_DECL(self, cursor):
    #print("Visiting ENUM DECL")
    value = 0
    for children in cursor.get_children():
      tokens = list(children.get_tokens())
      if len(tokens) == 0:
        # XXX:FIXME: I'm ignoring it too fast, I should take a careful look into
        # it to be sure what should I do here...
        break

      name = tokens[0].spelling
      if len(tokens) == 3:
        value = get_clean_number(tokens[2].spelling)

      # Some error parsing partial source code were an enum member has been
      # initialized to a macro that we know nothing about...
      if type(value) is str:
        return True

      self.enums[name] = value
      if len(tokens) == 1:
        value += 1

    return True 
Example 14
Source File: wmi.py    From PythonForWindows with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_instance_enum(self, clsname, flags=DEFAULT_ENUM_FLAGS, deep=True):
        """Enumerate the instances of ``clsname``. Deep allows to enumerate the instance of subclasses as well

        :returns: :class:`WmiEnumeration`

        Example:
            >>> windows.system.wmi["root\\subscription"].create_instance_enum("__EventConsumer", deep=False).all()
            []
            >>> windows.system.wmi["root\\subscription"].create_instance_enum("__EventConsumer", deep=True).all()
            [<WmiObject instance of "NTEventLogEventConsumer">]

        .. note::

            See https://docs.microsoft.com/en-us/windows/desktop/api/wbemcli/nf-wbemcli-iwbemservices-createinstanceenum
        """
        flags |= gdef.WBEM_FLAG_DEEP if deep else gdef.WBEM_FLAG_SHALLOW
        enumerator = WmiEnumeration()
        self.CreateInstanceEnum(clsname, flags, None, enumerator)
        return enumerator 
Example 15
Source File: CppHeaderParser.py    From FSeam with MIT License 6 votes vote down vote up
def evaluate_enum_stack(self):
        """Create an Enum out of the name stack"""
        debug_print( "evaluating enum" )
        newEnum = CppEnum(self.nameStack)
        if len(list(newEnum.keys())):
            if len(self.curClass):
                newEnum["namespace"] = self.cur_namespace(False)
                klass = self.classes[self.curClass]
                klass["enums"][self.curAccessSpecifier].append(newEnum)
                if self.curAccessSpecifier == 'public' and 'name' in newEnum: klass._public_enums[ newEnum['name'] ] = newEnum
            else:
                newEnum["namespace"] = self.cur_namespace(True)
                self.enums.append(newEnum)
                if 'name' in newEnum and newEnum['name']: self.global_enums[ newEnum['name'] ] = newEnum

            #This enum has instances, turn them into properties
            if "instances" in newEnum:
                instanceType = "enum"
                if "name" in newEnum:
                    instanceType = newEnum["name"]
                for instance in newEnum["instances"]:
                    self.nameStack = [instanceType,  instance]
                    self.evaluate_property_stack()
                del newEnum["instances"] 
Example 16
Source File: output.py    From slither with GNU Affero General Public License v3.0 6 votes vote down vote up
def add_enum(self, enum, additional_fields=None):
        if additional_fields is None:
            additional_fields = {}
        type_specific_fields = {
            'parent': _create_parent_element(enum)
        }
        element = _create_base_element('enum',
                                       enum.name,
                                       enum.source_mapping,
                                       type_specific_fields,
                                       additional_fields)
        self._data['elements'].append(element)

    # endregion
    ###################################################################################
    ###################################################################################
    # region Structures
    ###################################################################################
    ################################################################################### 
Example 17
Source File: avro_builder.py    From data_pipeline_avro_util with Apache License 2.0 6 votes vote down vote up
def begin_enum(self, name, symbols, namespace=None, aliases=None,
                   doc=None, **metadata):
        enum_schema = {
            'type': 'enum',
            'name': name,
            'symbols': symbols
        }
        if namespace:
            self._set_namespace(enum_schema, namespace)
        if aliases:
            self._set_aliases(enum_schema, aliases)
        if doc:
            self._set_doc(enum_schema, doc)
        enum_schema.update(metadata)

        self._save_current_schema()
        self._set_current_schema(enum_schema)
        return self 
Example 18
Source File: reg.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def markEnumRequired(self, enumname, required):
        """Mark an enum as required or not.

        - enumname - name of enum
        - required - boolean (to tag features as required or not)"""
        self.gen.logMsg('diag', 'tagging enum:', enumname, '-> required =', required)
        enum = self.lookupElementInfo(enumname, self.enumdict)
        if enum is not None:
            enum.required = required
            # Tag enum dependencies in 'alias' attribute as required
            depname = enum.elem.get('alias')
            if depname:
                self.gen.logMsg('diag', 'Generating dependent enum',
                                depname, 'for alias', enumname, 'required =', enum.required)
                self.markEnumRequired(depname, required)
        else:
            self.gen.logMsg('warn', 'enum:', enumname, 'IS NOT DEFINED') 
Example 19
Source File: automatic_source_generator.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def getTypeNameEnumTuple(self, param):
        typename = ''
        name = ''
        enum = ''
        for elem in param:
            if elem.tag == 'type':
                typename = noneStr(elem.text)
            elif elem.tag == 'name':
                name = noneStr(elem.text)
            elif elem.tag == 'enum':
                enum = noneStr(elem.text)
        return (typename, name, enum)

    # Retrieve the value of the len tag
    #   self            the AutomaticSourceOutputGenerator object
    #   param           the XML parameter information to access 
Example 20
Source File: xml_consistency.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def check_enum_naming(self, enum_type):
        stripped_enum_type, tag = self.strip_extension_tag(enum_type)
        end = "_{}".format(tag) if tag else ""
        if stripped_enum_type.endswith("FlagBits"):
            end = "_BIT" + end
            stripped_enum_type = stripped_enum_type.replace("FlagBits", "")
        start = self.conventions.generate_structure_type_from_name(stripped_enum_type).replace("XR_TYPE", "XR") + "_"

        value_names = get_enum_value_names(self.db.registry, enum_type)
        for name in value_names:
            if not name.startswith(start):
                self.record_error('Got an enum value whose name does not match the pattern: got', name,
                                  'but expected something that started with', start, 'due to typename being', enum_type)
            if end and not name.endswith(end):
                self.record_error('Got an enum value whose name does not match the pattern: got', name,
                                  'but expected something that ended with', end, 'due to typename being', enum_type) 
Example 21
Source File: entity_db.py    From OpenXR-SDK-Source with Apache License 2.0 6 votes vote down vote up
def handleEnumValue(self, name, info):
        """Add entities, if appropriate, for an item in registry.enumdict.

        Called at construction for every name, info in registry.enumdict.items().
        Calls self.addEntity() accordingly.
        """
        self.addEntity(name, 'ename', elem=info.elem,
                       category='enumvalues', generates=False)

    ###
    # END of methods intended to be implemented, overridden, or extended in child classes!
    ###

    ###
    # Accessors
    ### 
Example 22
Source File: utils_library.py    From BlenderPro with GNU General Public License v3.0 6 votes vote down vote up
def get_folder_enum_previews(path,key):
    """ Returns: ImagePreviewCollection
        Par1: path - The path to collect the folders from
        Par2: key - The dictionary key the previews will be stored in
    """
    enum_items = []
    if len(key.my_previews) > 0:
        return key.my_previews
    
    if path and os.path.exists(path):
        folders = []
        for fn in os.listdir(path):
            if os.path.isdir(os.path.join(path,fn)):
                folders.append(fn)

        for i, name in enumerate(folders):
            filepath = os.path.join(path, name)
            thumb = key.load(filepath, "", 'IMAGE')
            filename, ext = os.path.splitext(name)
            enum_items.append((filename, filename, filename, thumb.icon_id, i))
    
    key.my_previews = enum_items
    key.my_previews_dir = path
    return key.my_previews 
Example 23
Source File: cpp_full.py    From prophy with MIT License 6 votes vote down vote up
def translate_enum(self, node):
        return (
                'template <>\n' +
                'const char* print_traits<{0}>::to_literal({0} x)\n'.format(node.name) +
                '{\n' +
                _indent(
                    'switch (x)\n' +
                    '{\n' +
                    _indent(
                        ''.join('case {0}: return "{0}";\n'.format(m.name) for m in node.members) +
                        'default: return 0;\n'
                    ) +
                    '}\n'
                ) +
                '}'
        ) 
Example 24
Source File: descriptor_pool.py    From coremltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name: The full name of the enum descriptor to load.

    Returns:
      The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 25
Source File: descriptor.py    From protorpc with Apache License 2.0 6 votes vote down vote up
def describe_enum(enum_definition):
  """Build descriptor for Enum class.

  Args:
    enum_definition: Enum class to provide descriptor for.

  Returns:
    Initialized EnumDescriptor instance describing the Enum class.
  """
  enum_descriptor = EnumDescriptor()
  enum_descriptor.name = enum_definition.definition_name().split('.')[-1]

  values = []
  for number in enum_definition.numbers():
    value = enum_definition.lookup_by_number(number)
    values.append(describe_enum_value(value))

  if values:
    enum_descriptor.values = values

  return enum_descriptor 
Example 26
Source File: core.py    From pose-thumbnails with GNU General Public License v2.0 6 votes vote down vote up
def get_enum_items(poselib: bpy.types.Action,
                   pcoll: bpy.utils.previews.ImagePreviewCollection):
    """Return the enum items for the thumbnail previews."""

    enum_items = []
    wm = bpy.context.window_manager
    pose_thumbnail_options = wm.pose_thumbnails.options
    show_all_poses = pose_thumbnail_options.show_all_poses
    for i, pose in enumerate(poselib.pose_markers):
        thumbnail = common.get_thumbnail_from_pose(pose)
        if thumbnail:
            image = _load_image(poselib, pcoll, thumbnail.filepath)
        elif show_all_poses:
            image = get_placeholder_image(pcoll)
        else:
            image = None
        if image is not None:
            enum_items.append((
                str(pose.frame),
                pose.name,
                '',
                image.icon_id,
                i,
            ))
    return enum_items 
Example 27
Source File: traits.py    From ctapipe with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_class_enum_trait(base_class, default_value, help=None):
    """create a configurable CaselessStrEnum traitlet from baseclass

    the enumeration should contain all names of non_abstract_children()
    of said baseclass and the default choice should be given by
    `base_class._default` name.

    default must be specified and must be the name of one child-class
    """
    if help is None:
        help = "{} to use.".format(base_class.__name__)

    choices = [cls.__name__ for cls in non_abstract_children(base_class)]

    if default_value not in choices:
        raise ValueError(f"{default_value} is not in choices: {choices}")

    return CaselessStrEnum(
        choices, default_value=default_value, allow_none=False, help=help,
    ).tag(config=True) 
Example 28
Source File: metadata_template.py    From box-python-sdk with Apache License 2.0 6 votes vote down vote up
def remove_enum_option(self, field_key, option_key):
        """
        Remove an option from an enum field.

        :param field_key:
            The key of the template field in which the option appears
        :type field_key:
            `unicode`
        :param option_key:
            The key of the enum option to remove
        :type option_key:
            `unicode`
        """
        self.add_operation({
            'op': 'removeEnumOption',
            'fieldKey': field_key,
            'enumOptionKey': option_key,
        }) 
Example 29
Source File: metadata_template.py    From box-python-sdk with Apache License 2.0 6 votes vote down vote up
def add_enum_option(self, field_key, option_key):
        """
        Adds a new option to an enum field.

        :param field_key:
            The key of the template field to add the option to
        :type field_key:
            `unicode`
        :param option_key:
            The option to add
        :type option_key:
            `unicode`
        """
        self.add_operation({
            'op': 'addEnumOption',
            'fieldKey': field_key,
            'data': {
                'key': option_key,
            },
        }) 
Example 30
Source File: postgres.py    From rdbms-subsetter with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def fix_postgres_array_of_enum(connection, tbl):
    "Change type of ENUM[] columns to a custom type"

    for col in tbl.c:
        col_str = str(col.type)
        if col_str.endswith('[]'):  # this is an array
            enum_name = col_str[:-2]
            try:  # test if 'enum_name' is an enum
                enum_ranges = connection.execute('''
                        SELECT enum_range(NULL::%s);
                    ''' % enum_name).fetchone()
                enum_values = sql_enum_to_list(enum_ranges[0])
                enum = ENUM(*enum_values, name=enum_name)
                tbl.c[col.name].type = ArrayOfEnum(enum)
            except sa.exc.ProgrammingError as enum_excep:
                if 'does not exist' in str(enum_excep):
                    pass  # Must not have been an enum
                else:
                    raise 
Example 31
Source File: flags.py    From ModelZoo with MIT License 6 votes vote down vote up
def DEFINE_enum_class(name, default, enum_class, help=None, flag_values=_flagvalues.FLAGS, module_name=None, **args):
    """Registers a flag whose value can be the name of enum members.

    Args:
      name: str, the flag name.
      default: Enum|str|None, the default value of the flag.
      enum_class: class, the Enum class with all the possible values for the flag.
      help: str, the help message.
      flag_values: FlagValues, the FlagValues instance with which the flag will
          be registered. This should almost never need to be overridden.
      module_name: str, the name of the Python module declaring this flag.
          If not provided, it will be computed using the stack trace of this call.
      **args: dict, the extra keyword args that are passed to Flag __init__.
    """
    DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
                flag_values, module_name) 
Example 32
Source File: flags.py    From ModelZoo with MIT License 6 votes vote down vote up
def DEFINE_multi_enum(name, default, enum_values, help=None, flag_values=_flagvalues.FLAGS, case_sensitive=True,
                      **args):
    """Registers a flag whose value can be a list strings from enum_values.

    Use the flag on the command line multiple times to place multiple
    enum values into the list.  The 'default' may be a single string
    (which will be converted into a single-element list) or a list of
    strings.

    Args:
      name: str, the flag name.
      default: Union[Iterable[Text], Text, None], the default value of the flag;
          see `DEFINE_multi`.
      enum_values: [str], a non-empty list of strings with the possible values for
          the flag.
      help: str, the help message.
      flag_values: FlagValues, the FlagValues instance with which the flag will
          be registered. This should almost never need to be overridden.
      case_sensitive: Whether or not the enum is to be case-sensitive.
      **args: Dictionary with extra keyword args that are passed to the
          Flag __init__.
    """
    parser = _argument_parser.EnumParser(enum_values, case_sensitive)
    serializer = _argument_parser.ArgumentSerializer()
    DEFINE_multi(parser, serializer, name, default, help, flag_values, **args) 
Example 33
Source File: flags.py    From ModelZoo with MIT License 6 votes vote down vote up
def DEFINE_enum(name, default, enum_values, help=None, flag_values=_flagvalues.FLAGS, module_name=None, **args):
    """Registers a flag whose value can be any string from enum_values.

    Instead of a string enum, prefer `DEFINE_enum_class`, which allows
    defining enums from an `enum.Enum` class.

    Args:
      name: str, the flag name.
      default: str|None, the default value of the flag.
      enum_values: [str], a non-empty list of strings with the possible values for
          the flag.
      help: str, the help message.
      flag_values: FlagValues, the FlagValues instance with which the flag will
          be registered. This should almost never need to be overridden.
      module_name: str, the name of the Python module declaring this flag.
          If not provided, it will be computed using the stack trace of this call.
      **args: dict, the extra keyword args that are passed to Flag __init__.
    """
    DEFINE_flag(_flag.EnumFlag(name, default, help, enum_values, **args),
                flag_values, module_name) 
Example 34
Source File: ccat.py    From ccat with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ask_gcr_enum_repos(self):
        if self.is_configured() is False:
            self.set_configuration()
        
        gcp_registries = ['gcr.io','us.gcr.io','eu.gcr.io','asia.gcr.io']

        questions = [
            {
                'type': 'checkbox',
                'name': 'gcp_registries',
                'message': 'Select GCP registeries to enumerate',
                'choices': self.get_menu_choices_registries(gcp_registries)
            }
        ]

        answers = prompt(questions)
        self.append_configuration(answers)

        return answers 
Example 35
Source File: ccat.py    From ccat with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ask_ecr_enum_repos(self):
        if self.is_configured() is False:
            self.set_configuration()

        aws_regions = self.get_available_regions('ecr')

        questions= [
            {
                'type': 'checkbox',
                'name': 'aws_regions',
                'message': 'Select AWS regions to enumerate',
                'choices': self.get_menu_choices_regions(aws_regions)
            }
        ]

        answers = prompt(questions)
        self.append_configuration(answers)

        return answers 
Example 36
Source File: GXMETA.py    From gxpy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def set_attrib_enum(self, ph_object, ph_attrib, value):
        """
        Set an enum value to an attribute (as an integer)
        
        :param ph_object:  Object
        :param ph_attrib:  Attribute
        :param value:      Value to set
        :type  ph_object:  int
        :type  ph_attrib:  int
        :type  value:      int

        .. versionadded:: 5.1.6

        **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
        """
        self._set_attrib_enum(ph_object, ph_attrib, value) 
Example 37
Source File: GXMETA.py    From gxpy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_attrib_enum(self, ph_object, ph_attrib, value):
        """
        Get an enum value to an attribute (as an integer)
        
        :param ph_object:  Object
        :param ph_attrib:  Attribute
        :param value:      Value to set
        :type  ph_object:  int
        :type  ph_attrib:  int
        :type  value:      int_ref

        .. versionadded:: 5.1.6

        **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
        """
        value.value = self._get_attrib_enum(ph_object, ph_attrib, value.value) 
Example 38
Source File: protocol_generator.py    From pycozmo with MIT License 6 votes vote down vote up
def generate_enum_validation(self, argument: protocol_declaration.EnumArgument):
        if isinstance(argument.data_type, protocol_declaration.UInt8Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 255)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.UInt16Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 65535)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.UInt32Argument):
            self.f.write('validate_integer("{name}", value.value, 0, 4294967295)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int8Argument):
            self.f.write('validate_integer("{name}", value.value, -128, 127)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int16Argument):
            self.f.write('validate_integer("{name}", value.value, -32768, 32767)\n'.format(name=argument.name))
        elif isinstance(argument.data_type, protocol_declaration.Int32Argument):
            self.f.write(
                'validate_integer("{name}", value.value, -2147483648, 2147483647)\n'.format(name=argument.name))
        else:
            raise NotImplementedError("Unexpected enum data type '{}' for '{}'".format(
                argument.data_type.__class__.__name__, argument.name)) 
Example 39
Source File: custom_fields.py    From python-asana with MIT License 6 votes vote down vote up
def create_enum_option(self, custom_field, params={}, **options):
        """Creates an enum option and adds it to this custom field's list of enum options. A custom field can have at most 50 enum options (including disabled options). By default new enum options are inserted at the end of a custom field's list.

        Locked custom fields can only have enum options added by the user who locked the field.

        Returns the full record of the newly created enum option.

        Parameters
        ----------
        custom_field : {Gid} Globally unique identifier for the custom field.
        [data] : {Object} Data for the request
          - name : {String} The name of the enum option.
          - [color] : {String} The color of the enum option. Defaults to 'none'.
          - [insert_before] : {Gid} An existing enum option within this custom field before which the new enum option should be inserted. Cannot be provided together with after_enum_option.
          - [insert_after] : {Gid} An existing enum option within this custom field after which the new enum option should be inserted. Cannot be provided together with before_enum_option.
        """
        path = "/custom_fields/%s/enum_options" % (custom_field)
        return self.client.post(path, params, **options) 
Example 40
Source File: types.py    From BinderFilter with MIT License 6 votes vote down vote up
def make_enum_dict(enum_type):
    """Return a dictionary from a program's enum type.

    Arguments:
        enum_type: The enum to compute the dictionary for.

    Returns:
        The dictionary of the enum.

    Raises:
        TypeError: The type is not an enum.
    """

    if enum_type.code != gdb.TYPE_CODE_ENUM:
        raise TypeError("not an enum type")
    enum_dict = {}
    for field in enum_type.fields():
        # The enum's value is stored in "bitpos".
        enum_dict[field.name] = field.bitpos
    return enum_dict 
Example 41
Source File: _defines.py    From abseil-py with Apache License 2.0 6 votes vote down vote up
def DEFINE_enum_class(  # pylint: disable=invalid-name,redefined-builtin
    name, default, enum_class, help, flag_values=_flagvalues.FLAGS,
    module_name=None, **args):
  """Registers a flag whose value can be the name of enum members.

  Args:
    name: str, the flag name.
    default: Enum|str|None, the default value of the flag.
    enum_class: class, the Enum class with all the possible values for the flag.
    help: str, the help message.
    flag_values: FlagValues, the FlagValues instance with which the flag will
        be registered. This should almost never need to be overridden.
    module_name: str, the name of the Python module declaring this flag.
        If not provided, it will be computed using the stack trace of this call.
    **args: dict, the extra keyword args that are passed to Flag __init__.
  """
  DEFINE_flag(_flag.EnumClassFlag(name, default, help, enum_class, **args),
              flag_values, module_name) 
Example 42
Source File: bleConnection.py    From pyparrot with MIT License 6 votes vote down vote up
def send_enum_command_packet_ack(self, command_tuple, enum_value, usb_id=None):
        """
        Send a command on the ack channel with enum parameters as well (most likely a flip).
        All commandsandsensors except PCMD go on the ack channel per
        http://forum.developer.parrot.com/t/ble-characteristics-of-minidrones/5912/2

        the id of the last command sent (for use in ack) is the send counter (which is incremented before sending)

        :param command_tuple: 3 tuple of the command bytes.  0 padded for 4th byte
        :param enum_value: the enum index
        :return: nothing
        """
        self.characteristic_send_counter['SEND_WITH_ACK'] = (self.characteristic_send_counter['SEND_WITH_ACK'] + 1) % 256
        if (usb_id is None):
            packet = struct.pack("<BBBBBBI", self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                                 command_tuple[0], command_tuple[1], command_tuple[2], 0,
                                 enum_value)
        else:
            color_print((self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                         command_tuple[0], command_tuple[1], command_tuple[2], 0, usb_id, enum_value), 1)
            packet = struct.pack("<BBBBHBI", self.data_types['DATA_WITH_ACK'], self.characteristic_send_counter['SEND_WITH_ACK'],
                                 command_tuple[0], command_tuple[1], command_tuple[2],
                                 usb_id, enum_value)
        return self.send_command_packet_ack(packet) 
Example 43
Source File: custom_fields.py    From python-asana with MIT License 6 votes vote down vote up
def update_enum_option(self, enum_option, params={}, **options):
        """Updates an existing enum option. Enum custom fields require at least one enabled enum option.

        Locked custom fields can only be updated by the user who locked the field.

        Returns the full record of the updated enum option.

        Parameters
        ----------
        enum_option : {Gid} Globally unique identifier for the enum option.
        [data] : {Object} Data for the request
          - name : {String} The name of the enum option.
          - [color] : {String} The color of the enum option. Defaults to 'none'.
          - [enabled] : {Boolean} Whether or not the enum option is a selectable value for the custom field.
        """
        path = "/enum_options/%s" % (enum_option)
        return self.client.put(path, params, **options) 
Example 44
Source File: patches.py    From django-more with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
                db_type=db_type,
                values=values),
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example 45
Source File: core.py    From pyschema with Apache License 2.0 6 votes vote down vote up
def add_enum(self, enum_definition):
        new_values_set = set(enum_definition.values)
        old_values_set = self._enum_map.get(enum_definition.name)

        if old_values_set is not None and new_values_set != old_values_set:
            warnings.warn(
                "Enum {!r} overwritten! Was: {}, Overwritten by: {}".format(
                    enum_definition.name,
                    old_values_set,
                    new_values_set
                )
            )

        if enum_definition.name is not None:
            self._enum_map[enum_definition.name] = enum_definition.values
        # return the definition to allow the method to be used as a decorator
        return enum_definition 
Example 46
Source File: common.py    From surreal with MIT License 6 votes vote down vote up
def get_enum(enum_class, option):
    """
    Args:
        enum_class:
        option: if the value doesn't belong to Enum, throw error.
            Can be either the str name or the actual enum value
    """
    assert issubclass(enum_class, StringEnum)
    if isinstance(option, enum_class):
        return option
    else:
        assert_type(option, str)
        option = option.lower()
        options = enum_class.__members__
        if option not in options:
            raise ValueError('"{}" is not a valid option for {}. '
                             'Available options are {}.'
             .format(option, enum_class.__name__, list(options)))
        return options[option] 
Example 47
Source File: utils.py    From graphene-sqlalchemy with MIT License 6 votes vote down vote up
def sort_enum_for_model(cls, name=None, symbol_name=None):
    """Get a Graphene Enum for sorting the given model class.

    This is deprecated, please use object_type.sort_enum() instead.
    """
    warnings.warn(
        "sort_enum_for_model() is deprecated; use object_type.sort_enum() instead.",
        DeprecationWarning,
        stacklevel=2,
    )

    from .enums import sort_enum_for_object_type

    return sort_enum_for_object_type(
        _deprecated_object_type_for_model(cls, name),
        name,
        get_symbol_name=symbol_name or _deprecated_default_symbol_name,
    ) 
Example 48
Source File: converter.py    From graphene-django with MIT License 6 votes vote down vote up
def generate_enum_name(django_model_meta, field):
    if graphene_settings.DJANGO_CHOICE_FIELD_ENUM_CUSTOM_NAME:
        # Try and import custom function
        custom_func = import_string(
            graphene_settings.DJANGO_CHOICE_FIELD_ENUM_CUSTOM_NAME
        )
        name = custom_func(field)
    elif graphene_settings.DJANGO_CHOICE_FIELD_ENUM_V3_NAMING is True:
        name = "{app_label}{object_name}{field_name}Choices".format(
            app_label=to_camel_case(django_model_meta.app_label.title()),
            object_name=django_model_meta.object_name,
            field_name=to_camel_case(field.name.title()),
        )
    else:
        name = to_camel_case("{}_{}".format(django_model_meta.object_name, field.name))
    return name 
Example 49
Source File: ctypesparser.py    From ctypesgen with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def make_enum_from_specifier(specifier):
    tag = specifier.tag

    enumerators = []
    last_name = None
    for e in specifier.enumerators:
        if e.expression:
            value = e.expression
        else:
            if last_name:
                value = BinaryExpressionNode(
                    "addition",
                    (lambda x, y: x + y),
                    "(%s + %s)",
                    (False, False),
                    IdentifierExpressionNode(last_name),
                    ConstantExpressionNode(1),
                )
            else:
                value = ConstantExpressionNode(0)

        enumerators.append((e.name, value))
        last_name = e.name

    return CtypesEnum(tag, enumerators, src=(specifier.filename, specifier.lineno)) 
Example 50
Source File: folder_view.py    From Email_My_PC with MIT License 6 votes vote down vote up
def make_item_enum(level, flags):
    pidls = []
    nums = """zero one two three four five size seven eight nine ten""".split()
    for i, name in enumerate(nums):
        size = random.randint(0,255)
        sides = 1
        while sides in [1,2]:
            sides = random.randint(0,5)
        is_folder = (i % 2) != 0
        # check the flags say to include it.
        # (This seems strange; if you ask the same folder for, but appear
        skip = False
        if not (flags & shellcon.SHCONTF_STORAGE):
            if is_folder:
                skip = not (flags & shellcon.SHCONTF_FOLDERS)
            else:
                skip = not (flags & shellcon.SHCONTF_NONFOLDERS)
        if not skip:
            data = dict(name=name, size=size, sides=sides, level=level, is_folder=is_folder)
            pidls.append([pickle.dumps(data)])
    return NewEnum(pidls, shell.IID_IEnumIDList)

# start of Utils.cpp port 
Example 51
Source File: RFExplorer.py    From RFExplorer-for-Python with GNU Lesser General Public License v3.0 6 votes vote down vote up
def GetModelEnumFromText(sText):
    """Returns model enumerator based on text provided

    Parameters:
        sText -- One of "433M", "868M", "915M", "WSUB1G", "2.4G", "WSUB3G", "6G", "WSUB1G_PLUS" or "RFE6GEN"
    Returns:
        RFE_Common.eModel Valid model enumerator or will set to MODEL_NONE if not found
	"""
    eReturn = RFE_Common.eModel.MODEL_NONE

    for nInd in range(len(g_arrModels)):
        if (sText.upper() == g_arrModels[nInd]):
            eReturn = RFE_Common.eModel(nInd)
            break

    return eReturn

#--------------------------------------------------------- 
Example 52
Source File: javaobj.py    From MR with MIT License 6 votes vote down vote up
def write_enum(self, obj):
        """
        Writes an Enum value

        :param obj: A JavaEnum object
        """
        # FIXME: the output doesn't have the same references as the real
        # serializable form
        self._writeStruct(">B", 1, (self.TC_ENUM,))

        try:
            idx = self.references.index(obj)
        except ValueError:
            # New reference
            self.references.append(obj)
            logging.debug(
                "*** Adding ref 0x%X for enum: %s",
                len(self.references) - 1 + self.BASE_REFERENCE_IDX, obj)

            self.write_classdesc(obj.get_class())
        else:
            self.write_reference(idx)

        self.write_string(obj.constant) 
Example 53
Source File: io.py    From spavro with Apache License 2.0 6 votes vote down vote up
def read_enum(self, writers_schema, readers_schema, decoder):
        """
        An enum is encoded by a int, representing the zero-based position
        of the symbol in the schema.
        """
        # read data
        index_of_symbol = decoder.read_int()
        if index_of_symbol >= len(writers_schema.symbols):
            fail_msg = "Can't access enum index %d for enum with %d symbols"\
                                 % (index_of_symbol, len(writers_schema.symbols))
            raise SchemaResolutionException(fail_msg, writers_schema, readers_schema)
        read_symbol = writers_schema.symbols[index_of_symbol]

        # schema resolution
        if read_symbol not in readers_schema.symbols:
            fail_msg = "Symbol %s not present in Reader's Schema" % read_symbol
            raise SchemaResolutionException(fail_msg, writers_schema, readers_schema)

        return read_symbol 
Example 54
Source File: descriptor_pool.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def FindEnumTypeByName(self, full_name):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name (str): The full name of the enum descriptor to load.

    Returns:
      EnumDescriptor: The enum descriptor for the named type.

    Raises:
      KeyError: if the enum cannot be found in the pool.
    """

    full_name = _NormalizeFullyQualifiedName(full_name)
    if full_name not in self._enum_descriptors:
      self._FindFileContainingSymbolInDb(full_name)
    return self._enum_descriptors[full_name] 
Example 55
Source File: _GXCommon.py    From Gurux.DLMS.Python with GNU General Public License v2.0 6 votes vote down vote up
def getEnum(cls, buff, info):
        value = None
        #  If there is not enough data available.
        if len(buff) - buff.position < 1:
            info.complete = False
            return None
        value = buff.getUInt8()
        if info.xml:
            info.xml.appendLine(info.xml.getDataType(info.type_), None, info.xml.integerToHex(value, 2))
        return GXEnum(value)

    #
    # Get UInt64 value from DLMS data.
    #
    # buff
    # Received DLMS data.
    # info
    # Data info.
    # parsed UInt64 value.
    # 
Example 56
Source File: schema.py    From tartiflette with MIT License 6 votes vote down vote up
def add_enum_definition(self, enum_definition: "GraphQLEnumType") -> None:
        """
        Adds a GraphQLScalarType to the defined scalar list.
        :param enum_definition: GraphQLEnumType to add
        :type enum_definition: GraphQLEnumType
        """
        if enum_definition.name in self._enum_definitions:
            raise RedefinedImplementation(
                "new GraphQL enum definition `{}` "
                "overrides existing enum definition `{}`.".format(
                    enum_definition.name,
                    repr(self._enum_definitions.get(enum_definition.name)),
                )
            )

        self._enum_definitions[enum_definition.name] = enum_definition
        self._input_types.append(enum_definition.name)
        self.add_type_definition(enum_definition)