fields = message.ListFields()<EOL>if self.use_index_order:<EOL><INDENT>fields.sort(key=lambda x: x[<NUM_LIT:0>].index)<EOL><DEDENT>for field, value in fields:<EOL><INDENT>if _IsMapEntry(field):<EOL><INDENT>for key in sorted(value):<EOL><INDENT>entry_submsg = field.message_type._concrete_class(<EOL>key=key, value=value[key])<EOL>self.PrintField(field, entry_submsg)<EOL><DEDENT><DEDENT>elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>for element in value:<EOL><INDENT>self.PrintField(field, element)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.PrintField(field, value)<EOL><DEDENT><DEDENT>

Convert protobuf message to text format.

        Args:
          message: The protocol buffers message.


try:<EOL><INDENT>result = ParseInteger(self.token, is_signed=False, is_long=False)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes an unsigned 32bit integer number.

        Returns:
          The integer parsed.

        Raises:
          ParseError: If an unsigned 32bit integer couldn't be consumed.


if isinstance(value, dict):<EOL><INDENT>_ConvertStructMessage(value, message.struct_value)<EOL><DEDENT>elif isinstance(value, list):<EOL><INDENT>_ConvertListValueMessage(value, message.list_value)<EOL><DEDENT>elif value is None:<EOL><INDENT>message.null_value = <NUM_LIT:0><EOL><DEDENT>elif isinstance(value, bool):<EOL><INDENT>message.bool_value = value<EOL><DEDENT>elif isinstance(value, six.string_types):<EOL><INDENT>message.string_value = value<EOL><DEDENT>elif isinstance(value, _INT_OR_FLOAT):<EOL><INDENT>message.number_value = value<EOL><DEDENT>else:<EOL><INDENT>raise ParseError('<STR_LIT>')<EOL><DEDENT>

Convert a JSON representation into Value message.


<EOL>return message.ToJsonString()<EOL>

Converts message by ToJsonString according to Proto3 JSON Specification.


<EOL>message.FromJsonString(value)<EOL>

Convert a JSON representation into message with FromJsonString.


if isinstance(value, float):<EOL><INDENT>raise ParseError('<STR_LIT>'.format(value))<EOL><DEDENT>if isinstance(value, six.text_type) and value.find('<STR_LIT:U+0020>') != -<NUM_LIT:1>:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(value))<EOL><DEDENT>return int(value)<EOL>

Convert an integer.

    Args:
      value: A scalar value to convert.

    Returns:
      The integer value.

    Raises:
      ParseError: If an integer couldn't be consumed.


field = message.DESCRIPTOR.fields_by_name['<STR_LIT:value>']<EOL>setattr(message, '<STR_LIT:value>', _ConvertScalarFieldValue(value, field))<EOL>

Convert a JSON representation into Wrapper message.


if not isinstance(text, six.text_type): text = text.decode('<STR_LIT:utf-8>')<EOL>try:<EOL><INDENT>if sys.version_info < (<NUM_LIT:2>, <NUM_LIT:7>):<EOL><INDENT>js = json.loads(text)<EOL><DEDENT>else:<EOL><INDENT>js = json.loads(text, object_pairs_hook=_DuplicateChecker)<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(str(e)))<EOL><DEDENT>_ConvertMessage(js, message)<EOL>return message<EOL>

Parses a JSON representation of a protocol message into a message.

    Args:
      text: Message JSON representation.
      message: A protocol beffer message to merge into.

    Returns:
      The same message passed as argument.

    Raises::
      ParseError: On JSON parsing problems.


def _RegularMessageToJsonObject(message, js, including_default_value_fields):

fields = message.ListFields()<EOL>include_default = including_default_value_fields<EOL>try:<EOL><INDENT>for field, value in fields:<EOL><INDENT>name = field.camelcase_name<EOL>if _IsMapEntry(field):<EOL><INDENT>v_field = field.message_type.fields_by_name['<STR_LIT:value>']<EOL>js_map = {}<EOL>for key in value:<EOL><INDENT>if isinstance(key, bool):<EOL><INDENT>if key:<EOL><INDENT>recorded_key = '<STR_LIT:true>'<EOL><DEDENT>else:<EOL><INDENT>recorded_key = '<STR_LIT:false>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>recorded_key = key<EOL><DEDENT>js_map[recorded_key] = _FieldToJsonObject(<EOL>v_field, value[key], including_default_value_fields)<EOL><DEDENT>js[name] = js_map<EOL><DEDENT>elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>js[name] = [_FieldToJsonObject(field, k, include_default)<EOL>for k in value]<EOL><DEDENT>else:<EOL><INDENT>js[name] = _FieldToJsonObject(field, value, include_default)<EOL><DEDENT><DEDENT>if including_default_value_fields:<EOL><INDENT>message_descriptor = message.DESCRIPTOR<EOL>for field in message_descriptor.fields:<EOL><INDENT>if ((field.label != descriptor.FieldDescriptor.LABEL_REPEATED and<EOL>field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE) or<EOL>field.containing_oneof):<EOL><INDENT>continue<EOL><DEDENT>name = field.camelcase_name<EOL>if name in js:<EOL><INDENT>continue<EOL><DEDENT>if _IsMapEntry(field):<EOL><INDENT>js[name] = {}<EOL><DEDENT>elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>js[name] = []<EOL><DEDENT>else:<EOL><INDENT>js[name] = _FieldToJsonObject(field, field.default_value)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise SerializeToJsonError(<EOL>'<STR_LIT>'.format(field.name, e))<EOL><DEDENT>return js<EOL>

Converts normal message according to Proto3 JSON Specification.


if not message.ListFields():<EOL><INDENT>return {}<EOL><DEDENT>js = {}<EOL>type_url = message.type_url<EOL>js['<STR_LIT>'] = type_url<EOL>sub_message = _CreateMessageFromTypeUrl(type_url)<EOL>sub_message.ParseFromString(message.value)<EOL>message_descriptor = sub_message.DESCRIPTOR<EOL>full_name = message_descriptor.full_name<EOL>if _IsWrapperMessage(message_descriptor):<EOL><INDENT>js['<STR_LIT:value>'] = _WrapperMessageToJsonObject(sub_message)<EOL>return js<EOL><DEDENT>if full_name in _WKTJSONMETHODS:<EOL><INDENT>js['<STR_LIT:value>'] = _WKTJSONMETHODS[full_name][<NUM_LIT:0>](sub_message, including_default)<EOL>return js<EOL><DEDENT>return _RegularMessageToJsonObject(sub_message, js, including_default)<EOL>

Converts Any message according to Proto3 JSON Specification.


message_descriptor = message.DESCRIPTOR<EOL>full_name = message_descriptor.full_name<EOL>if _IsWrapperMessage(message_descriptor):<EOL><INDENT>_ConvertWrapperMessage(value, message)<EOL><DEDENT>elif full_name in _WKTJSONMETHODS:<EOL><INDENT>_WKTJSONMETHODS[full_name][<NUM_LIT:1>](value, message)<EOL><DEDENT>else:<EOL><INDENT>_ConvertFieldValuePair(value, message)<EOL><DEDENT>

Convert a JSON object into a message.

    Args:
      value: A JSON object.
      message: A WKT or regular protocol message to record the data.

    Raises:
      ParseError: In case of convert problems.


if value == '<STR_LIT>':<EOL><INDENT>raise ParseError('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>return float(value)<EOL><DEDENT>except ValueError:<EOL><INDENT>if value == _NEG_INFINITY:<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>elif value == _INFINITY:<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>elif value == _NAN:<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(value))<EOL><DEDENT><DEDENT>


result = {}<EOL>for f in files:<EOL><INDENT>result.update(self._symbols_by_file[f])<EOL><DEDENT>return result<EOL>

Gets all the messages from a specified file.

        This will find and resolve dependencies, failing if they are not registered
        in the symbol database.

        Args:
          files: The file names to extract messages from.

        Returns:
          A dictionary mapping proto names to the message classes. This will include
          any dependent messages as well as any messages defined in the same file as
          a specified message.

        Raises:
          KeyError: if a file could not be found.


self.pool.AddEnumDescriptor(enum_descriptor)<EOL>return enum_descriptor<EOL>

Registers the given enum descriptor in the local database.

        Args:
          enum_descriptor: a descriptor.EnumDescriptor.

        Returns:
          The provided descriptor.


return self._symbols[symbol]<EOL>

Tries to find a symbol in the local database.

        Currently, this method only returns message.Message instances, however, if
        may be extended in future to support other symbol types.

        Args:
          symbol: A str, a protocol buffer symbol.

        Returns:
          A Python class corresponding to the symbol.

        Raises:
          KeyError: if the symbol could not be found.


def MakeSimpleProtoClass(fields, full_name=None, pool=None):

factory = message_factory.MessageFactory(pool=pool)<EOL>if full_name is not None:<EOL><INDENT>try:<EOL><INDENT>proto_cls = _GetMessageFromFactory(factory, full_name)<EOL>return proto_cls<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>field_items = fields.items()<EOL>if not isinstance(fields, OrderedDict):<EOL><INDENT>field_items = sorted(field_items)<EOL><DEDENT>fields_hash = hashlib.sha1()<EOL>for f_name, f_type in field_items:<EOL><INDENT>fields_hash.update(f_name.encode('<STR_LIT:utf-8>'))<EOL>fields_hash.update(str(f_type).encode('<STR_LIT:utf-8>'))<EOL><DEDENT>proto_file_name = fields_hash.hexdigest() + '<STR_LIT>'<EOL>if full_name is None:<EOL><INDENT>full_name = ('<STR_LIT>' +<EOL>fields_hash.hexdigest())<EOL>try:<EOL><INDENT>proto_cls = _GetMessageFromFactory(factory, full_name)<EOL>return proto_cls<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>factory.pool.Add(<EOL>_MakeFileDescriptorProto(proto_file_name, full_name, field_items))<EOL>return _GetMessageFromFactory(factory, full_name)<EOL>

Create a Protobuf class whose fields are basic types.

    Note: this doesn't validate field names!

    Args:
      fields: dict of {name: field_type} mappings for each field in the proto. If
          this is an OrderedDict the order will be maintained, otherwise the
          fields will be sorted by name.
      full_name: optional str, the fully-qualified name of the proto type.
      pool: optional DescriptorPool instance.
    Returns:
      a class, the new protobuf class with a FileDescriptor.


def __init__(self, name, full_name, index, containing_type, fields):

self.name = name<EOL>self.full_name = full_name<EOL>self.index = index<EOL>self.containing_type = containing_type<EOL>self.fields = fields<EOL>

Arguments are as described in the attribute description above.


def __init__(self, options, options_class_name, name, full_name,<EOL>file, containing_type, serialized_start=None,<EOL>serialized_end=None):

super(_NestedDescriptorBase, self).__init__(<EOL>options, options_class_name)<EOL>self.name = name<EOL>self.full_name = full_name<EOL>self.file = file<EOL>self.containing_type = containing_type<EOL>self._serialized_start = serialized_start<EOL>self._serialized_end = serialized_end<EOL>

Constructor.

        Args:
          options: Protocol message options or None
            to use default message options.
          options_class_name: (str) The class name of the above options.

          name: (str) Name of this protocol message type.
          full_name: (str) Fully-qualified name of this protocol message type,
            which will include protocol "package" name and the name of any
            enclosing types.
          file: (FileDescriptor) Reference to file info.
          containing_type: if provided, this is a nested descriptor, with this
            descriptor as parent, otherwise None.
          serialized_start: The start index (inclusive) in block in the
            file.serialized_pb that describes this descriptor.
          serialized_end: The end index (exclusive) in block in the
            file.serialized_pb that describes this descriptor.


desc = self<EOL>while desc.containing_type is not None:<EOL><INDENT>desc = desc.containing_type<EOL><DEDENT>return desc<EOL>

Returns the root if this is a nested type, or itself if its the root.


def _SetOptions(self, options, options_class_name):

self._options = options<EOL>self._options_class_name = options_class_name<EOL>self.has_options = options is not None<EOL>

Sets the descriptor's options

        This function is used in generated proto2 files to update descriptor
        options. It must not be used outside proto2.


return self.enum_types_by_name[enum].values_by_number[value].name<EOL>

Returns the string name of an enum value.

        This is just a small helper method to simplify a common operation.

        Args:
          enum: string name of the Enum.
          value: int, value of the enum.

        Returns:
          string name of the enum value.

        Raises:
          KeyError if either the Enum doesn't exist or the value is not a valid
            value for the enum.


if (self.file is not None and<EOL>self._serialized_start is not None and<EOL>self._serialized_end is not None):<EOL><INDENT>proto.ParseFromString(self.file.serialized_pb[<EOL>self._serialized_start:self._serialized_end])<EOL><DEDENT>else:<EOL><INDENT>raise Error('<STR_LIT>')<EOL><DEDENT>

Copies this to the matching proto in descriptor_pb2.

        Args:
          proto: An empty proto instance from descriptor_pb2.

        Raises:
          Error: If self couldnt be serialized, due to to few constructor arguments.


<EOL>super(EnumDescriptor, self).CopyToProto(proto)<EOL>

Copies this to a descriptor_pb2.EnumDescriptorProto.

        Args:
          proto: An empty descriptor_pb2.EnumDescriptorProto.


def __init__(self, name, full_name, filename, containing_type, fields,<EOL>nested_types, enum_types, extensions, options=None,<EOL>is_extendable=True, extension_ranges=None, oneofs=None,<EOL>file=None, serialized_start=None, serialized_end=None,<EOL>syntax=None):

super(Descriptor, self).__init__(<EOL>options, '<STR_LIT>', name, full_name, file,<EOL>containing_type, serialized_start=serialized_start,<EOL>serialized_end=serialized_end)<EOL>self.fields = fields<EOL>for field in self.fields:<EOL><INDENT>field.containing_type = self<EOL><DEDENT>self.fields_by_number = dict((f.number, f) for f in fields)<EOL>self.fields_by_name = dict((f.name, f) for f in fields)<EOL>self._fields_by_camelcase_name = None<EOL>self.nested_types = nested_types<EOL>for nested_type in nested_types:<EOL><INDENT>nested_type.containing_type = self<EOL><DEDENT>self.nested_types_by_name = dict((t.name, t) for t in nested_types)<EOL>self.enum_types = enum_types<EOL>for enum_type in self.enum_types:<EOL><INDENT>enum_type.containing_type = self<EOL><DEDENT>self.enum_types_by_name = dict((t.name, t) for t in enum_types)<EOL>self.enum_values_by_name = dict(<EOL>(v.name, v) for t in enum_types for v in t.values)<EOL>self.extensions = extensions<EOL>for extension in self.extensions:<EOL><INDENT>extension.extension_scope = self<EOL><DEDENT>self.extensions_by_name = dict((f.name, f) for f in extensions)<EOL>self.is_extendable = is_extendable<EOL>self.extension_ranges = extension_ranges<EOL>self.oneofs = oneofs if oneofs is not None else []<EOL>self.oneofs_by_name = dict((o.name, o) for o in self.oneofs)<EOL>for oneof in self.oneofs:<EOL><INDENT>oneof.containing_type = self<EOL><DEDENT>self.syntax = syntax or "<STR_LIT>"<EOL>

Arguments to __init__() are as described in the description
        of Descriptor fields above.

        Note that filename is an obsolete argument, that is not used anymore.
        Please use file.name to access this as an attribute.


message.ParseFromString(string)<EOL>return message<EOL>

Parses serialized options.

    This helper function is used to parse serialized options in generated
    proto2 files. It must not be used outside proto2.


if self._options:<EOL><INDENT>return self._options<EOL><DEDENT>from typy.google.protobuf import descriptor_pb2<EOL>try:<EOL><INDENT>options_class = getattr(descriptor_pb2, self._options_class_name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise RuntimeError('<STR_LIT>' %<EOL>(self._options_class_name))<EOL><DEDENT>self._options = options_class()<EOL>return self._options<EOL>

Retrieves descriptor options.

        This method returns the options set or creates the default options for the
        descriptor.


def __init__(self, name, full_name, index, number, type, cpp_type, label,<EOL>default_value, message_type, enum_type, containing_type,<EOL>is_extension, extension_scope, options=None,<EOL>has_default_value=True, containing_oneof=None):

super(FieldDescriptor, self).__init__(options, '<STR_LIT>')<EOL>self.name = name<EOL>self.full_name = full_name<EOL>self._camelcase_name = None<EOL>self.index = index<EOL>self.number = number<EOL>self.type = type<EOL>self.cpp_type = cpp_type<EOL>self.label = label<EOL>self.has_default_value = has_default_value<EOL>self.default_value = default_value<EOL>self.containing_type = containing_type<EOL>self.message_type = message_type<EOL>self.enum_type = enum_type<EOL>self.is_extension = is_extension<EOL>self.extension_scope = extension_scope<EOL>self.containing_oneof = containing_oneof<EOL>if api_implementation.Type() == '<STR_LIT>':<EOL><INDENT>if is_extension:<EOL><INDENT>self._cdescriptor = _message.default_pool.FindExtensionByName(full_name)<EOL><DEDENT>else:<EOL><INDENT>self._cdescriptor = _message.default_pool.FindFieldByName(full_name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._cdescriptor = None<EOL><DEDENT>

The arguments are as described in the description of FieldDescriptor
        attributes above.

        Note that containing_type may be None, and may be set later if necessary
        (to deal with circular references between message types, for example).
        Likewise for extension_scope.


def MakeDescriptor(desc_proto, package='<STR_LIT>', build_file_if_cpp=True,<EOL>syntax=None):

if api_implementation.Type() == '<STR_LIT>' and build_file_if_cpp:<EOL><INDENT>from typy.google.protobuf import descriptor_pb2<EOL>file_descriptor_proto = descriptor_pb2.FileDescriptorProto()<EOL>file_descriptor_proto.message_type.add().MergeFrom(desc_proto)<EOL>proto_name = str(uuid.uuid4())<EOL>if package:<EOL><INDENT>file_descriptor_proto.name = os.path.join(package.replace('<STR_LIT:.>', '<STR_LIT:/>'),<EOL>proto_name + '<STR_LIT>')<EOL>file_descriptor_proto.package = package<EOL><DEDENT>else:<EOL><INDENT>file_descriptor_proto.name = proto_name + '<STR_LIT>'<EOL><DEDENT>_message.default_pool.Add(file_descriptor_proto)<EOL>result = _message.default_pool.FindFileByName(file_descriptor_proto.name)<EOL>if _USE_C_DESCRIPTORS:<EOL><INDENT>return result.message_types_by_name[desc_proto.name]<EOL><DEDENT><DEDENT>full_message_name = [desc_proto.name]<EOL>if package: full_message_name.insert(<NUM_LIT:0>, package)<EOL>enum_types = {}<EOL>for enum_proto in desc_proto.enum_type:<EOL><INDENT>full_name = '<STR_LIT:.>'.join(full_message_name + [enum_proto.name])<EOL>enum_desc = EnumDescriptor(<EOL>enum_proto.name, full_name, None, [<EOL>EnumValueDescriptor(enum_val.name, ii, enum_val.number)<EOL>for ii, enum_val in enumerate(enum_proto.value)])<EOL>enum_types[full_name] = enum_desc<EOL><DEDENT>nested_types = {}<EOL>for nested_proto in desc_proto.nested_type:<EOL><INDENT>full_name = '<STR_LIT:.>'.join(full_message_name + [nested_proto.name])<EOL>nested_desc = MakeDescriptor(nested_proto,<EOL>package='<STR_LIT:.>'.join(full_message_name),<EOL>build_file_if_cpp=False,<EOL>syntax=syntax)<EOL>nested_types[full_name] = nested_desc<EOL><DEDENT>fields = []<EOL>for field_proto in desc_proto.field:<EOL><INDENT>full_name = '<STR_LIT:.>'.join(full_message_name + [field_proto.name])<EOL>enum_desc = None<EOL>nested_desc = None<EOL>if field_proto.HasField('<STR_LIT>'):<EOL><INDENT>type_name = field_proto.type_name<EOL>full_type_name = '<STR_LIT:.>'.join(full_message_name +<EOL>[type_name[type_name.rfind('<STR_LIT:.>')+<NUM_LIT:1>:]])<EOL>if full_type_name in nested_types:<EOL><INDENT>nested_desc = nested_types[full_type_name]<EOL><DEDENT>elif full_type_name in enum_types:<EOL><INDENT>enum_desc = enum_types[full_type_name]<EOL><DEDENT><DEDENT>field = FieldDescriptor(<EOL>field_proto.name, full_name, field_proto.number - <NUM_LIT:1>,<EOL>field_proto.number, field_proto.type,<EOL>FieldDescriptor.ProtoTypeToCppProtoType(field_proto.type),<EOL>field_proto.label, None, nested_desc, enum_desc, None, False, None,<EOL>options=field_proto.options, has_default_value=False)<EOL>fields.append(field)<EOL><DEDENT>desc_name = '<STR_LIT:.>'.join(full_message_name)<EOL>return Descriptor(desc_proto.name, desc_name, None, None, fields,<EOL>list(nested_types.values()), list(enum_types.values()), [],<EOL>options=desc_proto.options)<EOL>

Make a protobuf Descriptor given a DescriptorProto protobuf.

    Handles nested descriptors. Note that this is limited to the scope of defining
    a message inside of another message. Composite fields can currently only be
    resolved if the message is defined in the same scope as the field.

    Args:
      desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
      package: Optional package name for the new message Descriptor (string).
      build_file_if_cpp: Update the C++ descriptor pool if api matches.
                         Set to False on recursion, so no duplicates are created.
      syntax: The syntax/semantics that should be used.  Set to "proto3" to get
              proto3 field presence semantics.
    Returns:
      A Descriptor for protobuf messages.


for file_proto in file_protos:<EOL><INDENT>_FACTORY.pool.Add(file_proto)<EOL><DEDENT>return _FACTORY.GetMessages([file_proto.name for file_proto in file_protos])<EOL>

Builds a dictionary of all the messages available in a set of files.

    Args:
      file_protos: A sequence of file protos to build messages out of.

    Returns:
      A dictionary mapping proto names to the message classes. This will include
      any dependent messages as well as any messages defined in the same file as
      a specified message.


raise NotImplementedError<EOL>

Outputs a human-readable representation of the message.


if self is other_msg:<EOL><INDENT>return<EOL><DEDENT>self.Clear()<EOL>self.MergeFrom(other_msg)<EOL>

Copies the content of the specified message into the current message.

        The method clears the current message and then merges the specified
        message using MergeFrom.

        Args:
          other_msg: Message to copy into the current one.


raise NotImplementedError<EOL>

Returns the serialized size of this message.
        Recursively calls ByteSize() on all contained messages.


return dict(serialized=self.SerializePartialToString())<EOL>


raise NotImplementedError<EOL>

Checks if the message is initialized.

        Returns:
          The method returns True if the message is initialized (i.e. all of its
          required fields are set).


self.Clear()<EOL>self.MergeFromString(serialized)<EOL>

Parse serialized protocol buffer data into this message.

        Like MergeFromString(), except we clear the object first and
        do not return the value that MergeFromString returns.


raise NotImplementedError<EOL>

Returns the name of the field that is set inside a oneof group, or
        None if no field is set.  If no group with the given name exists, ValueError
        will be raised.


raise NotImplementedError<EOL>

Serializes the protocol message to a binary string.

        This method is similar to SerializeToString but doesn't check if the
        message is initialized.

        Returns:
          A string representation of the partial message.


self.__init__()<EOL>self.ParseFromString(state['<STR_LIT>'])<EOL>


<EOL>from typy.google.protobuf import descriptor_pb2<EOL>file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString(<EOL>serialized_file_desc_proto)<EOL>self.Add(file_desc_proto)<EOL>

Adds the FileDescriptorProto and its types to this pool.

        Args:
          serialized_file_desc_proto: A bytes string, serialization of the
            FileDescriptorProto to add.


for desc in descriptors:<EOL><INDENT>yield (_PrefixWithDot(desc.full_name), desc)<EOL>for symbol in self._ExtractSymbols(desc.nested_types):<EOL><INDENT>yield symbol<EOL><DEDENT>for enum in desc.enum_types:<EOL><INDENT>yield (_PrefixWithDot(enum.full_name), enum)<EOL><DEDENT><DEDENT>

Pulls out all the symbols from descriptor protos.

        Args:
          descriptors: The messages to extract descriptors from.
        Yields:
          A two element tuple of the type name and descriptor object.


if not isinstance(desc, descriptor.Descriptor):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>self._descriptors[desc.full_name] = desc<EOL>self.AddFileDescriptor(desc.file)<EOL>

Adds a Descriptor to the pool, non-recursively.

        If the Descriptor contains nested messages or enums, the caller must
        explicitly register them. This method also registers the FileDescriptor
        associated with the message.

        Args:
          desc: A Descriptor.


self._internal_db = descriptor_database.DescriptorDatabase()<EOL>self._descriptor_db = descriptor_db<EOL>self._descriptors = {}<EOL>self._enum_descriptors = {}<EOL>self._file_descriptors = {}<EOL>

Initializes a Pool of proto buffs.

        The descriptor_db argument to the constructor is provided to allow
        specialized file descriptor proto lookup code to be triggered on demand. An
        example would be an implementation which will read and compile a file
        specified in a call to FindFileByName() and not require the call to Add()
        at all. Results from this database will be cached internally here as well.

        Args:
          descriptor_db: A secondary source of file descriptors.


def _SetAllFieldTypes(self, package, desc_proto, scope):

package = _PrefixWithDot(package)<EOL>main_desc = self._GetTypeFromScope(package, desc_proto.name, scope)<EOL>if package == '<STR_LIT:.>':<EOL><INDENT>nested_package = _PrefixWithDot(desc_proto.name)<EOL><DEDENT>else:<EOL><INDENT>nested_package = '<STR_LIT:.>'.join([package, desc_proto.name])<EOL><DEDENT>for field_proto, field_desc in zip(desc_proto.field, main_desc.fields):<EOL><INDENT>self._SetFieldType(field_proto, field_desc, nested_package, scope)<EOL><DEDENT>for extension_proto, extension_desc in (<EOL>zip(desc_proto.extension, main_desc.extensions)):<EOL><INDENT>extension_desc.containing_type = self._GetTypeFromScope(<EOL>nested_package, extension_proto.extendee, scope)<EOL>self._SetFieldType(extension_proto, extension_desc, nested_package, scope)<EOL><DEDENT>for nested_type in desc_proto.nested_type:<EOL><INDENT>self._SetAllFieldTypes(nested_package, nested_type, scope)<EOL><DEDENT>

Sets all the descriptor's fields's types.

        This method also sets the containing types on any extensions.

        Args:
          package: The current package of desc_proto.
          desc_proto: The message descriptor to update.
          scope: Enclosing scope of available types.


try:<EOL><INDENT>return self._file_descriptors[file_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>file_proto = self._internal_db.FindFileByName(file_name)<EOL><DEDENT>except KeyError as error:<EOL><INDENT>if self._descriptor_db:<EOL><INDENT>file_proto = self._descriptor_db.FindFileByName(file_name)<EOL><DEDENT>else:<EOL><INDENT>raise error<EOL><DEDENT><DEDENT>if not file_proto:<EOL><INDENT>raise KeyError('<STR_LIT>' % file_name)<EOL><DEDENT>return self._ConvertFileProtoToFileDescriptor(file_proto)<EOL>

Gets a FileDescriptor by file name.

        Args:
          file_name: The path to the file to get a descriptor for.

        Returns:
          A FileDescriptor for the named file.

        Raises:
          KeyError: if the file can not be found in the pool.


def _SetFieldType(self, field_proto, field_desc, package, scope):

if field_proto.type_name:<EOL><INDENT>desc = self._GetTypeFromScope(package, field_proto.type_name, scope)<EOL><DEDENT>else:<EOL><INDENT>desc = None<EOL><DEDENT>if not field_proto.HasField('<STR_LIT:type>'):<EOL><INDENT>if isinstance(desc, descriptor.Descriptor):<EOL><INDENT>field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE<EOL><DEDENT>else:<EOL><INDENT>field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM<EOL><DEDENT><DEDENT>field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType(<EOL>field_proto.type)<EOL>if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE<EOL>or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP):<EOL><INDENT>field_desc.message_type = desc<EOL><DEDENT>if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:<EOL><INDENT>field_desc.enum_type = desc<EOL><DEDENT>if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>field_desc.has_default_value = False<EOL>field_desc.default_value = []<EOL><DEDENT>elif field_proto.HasField('<STR_LIT>'):<EOL><INDENT>field_desc.has_default_value = True<EOL>if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or<EOL>field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):<EOL><INDENT>field_desc.default_value = float(field_proto.default_value)<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:<EOL><INDENT>field_desc.default_value = field_proto.default_value<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:<EOL><INDENT>field_desc.default_value = field_proto.default_value.lower() == '<STR_LIT:true>'<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:<EOL><INDENT>field_desc.default_value = field_desc.enum_type.values_by_name[<EOL>field_proto.default_value].number<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>field_desc.default_value = text_encoding.CUnescape(<EOL>field_proto.default_value)<EOL><DEDENT>else:<EOL><INDENT>field_desc.default_value = int(field_proto.default_value)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>field_desc.has_default_value = False<EOL>if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or<EOL>field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT):<EOL><INDENT>field_desc.default_value = <NUM_LIT:0.0><EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING:<EOL><INDENT>field_desc.default_value = u'<STR_LIT>'<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL:<EOL><INDENT>field_desc.default_value = False<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM:<EOL><INDENT>field_desc.default_value = field_desc.enum_type.values[<NUM_LIT:0>].number<EOL><DEDENT>elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>field_desc.default_value = b'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>field_desc.default_value = <NUM_LIT:0><EOL><DEDENT><DEDENT>field_desc.type = field_proto.type<EOL>

Sets the field's type, cpp_type, message_type and enum_type.

        Args:
          field_proto: Data about the field in proto format.
          field_desc: The descriptor to modiy.
          package: The package the field's container is in.
          scope: Enclosing scope of available types.


full_name = _NormalizeFullyQualifiedName(full_name)<EOL>if full_name not in self._descriptors:<EOL><INDENT>self.FindFileContainingSymbol(full_name)<EOL><DEDENT>return self._descriptors[full_name]<EOL>

Loads the named descriptor from the pool.

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

        Returns:
          The descriptor for the named type.


return name.lstrip('<STR_LIT:.>')<EOL>

Remove leading period from fully-qualified type name.

    Due to b/13860351 in descriptor_database.py, types in the root namespace are
    generated with a leading period. This function removes that prefix.

    Args:
      name: A str, the fully-qualified symbol name.

    Returns:
      A str, the normalized fully-qualified symbol name.


def _MakeFieldDescriptor(self, field_proto, message_name, index,<EOL>is_extension=False):

Creates a field descriptor from a FieldDescriptorProto.

        For message and enum type fields, this method will do a look up
        in the pool for the appropriate descriptor for that type. If it
        is unavailable, it will fall back to the _source function to
        create it. If this type is still unavailable, construction will
        fail.

        Args:
          field_proto: The proto describing the field.
          message_name: The name of the containing message.
          index: Index of the field
          is_extension: Indication that this field is for an extension.

        Returns:
          An initialized FieldDescriptor object


full_name = _NormalizeFullyQualifiedName(full_name)<EOL>message_name, _, field_name = full_name.rpartition('<STR_LIT:.>')<EOL>message_descriptor = self.FindMessageTypeByName(message_name)<EOL>return message_descriptor.fields_by_name[field_name]<EOL>

Loads the named field descriptor from the pool.

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

        Returns:
          The field descriptor for the named field.


if file_proto.name not in self._file_descriptors:<EOL><INDENT>built_deps = list(self._GetDeps(file_proto.dependency))<EOL>direct_deps = [self.FindFileByName(n) for n in file_proto.dependency]<EOL>public_deps = [direct_deps[i] for i in file_proto.public_dependency]<EOL>file_descriptor = descriptor.FileDescriptor(<EOL>pool=self,<EOL>name=file_proto.name,<EOL>package=file_proto.package,<EOL>syntax=file_proto.syntax,<EOL>options=file_proto.options,<EOL>serialized_pb=file_proto.SerializeToString(),<EOL>dependencies=direct_deps,<EOL>public_dependencies=public_deps)<EOL>if _USE_C_DESCRIPTORS:<EOL><INDENT>def _AddMessageDescriptor(message_desc):<EOL><INDENT>self._descriptors[message_desc.full_name] = message_desc<EOL>for nested in message_desc.nested_types:<EOL><INDENT>_AddMessageDescriptor(nested)<EOL><DEDENT>for enum_type in message_desc.enum_types:<EOL><INDENT>_AddEnumDescriptor(enum_type)<EOL><DEDENT><DEDENT>def _AddEnumDescriptor(enum_desc):<EOL><INDENT>self._enum_descriptors[enum_desc.full_name] = enum_desc<EOL><DEDENT>for message_type in file_descriptor.message_types_by_name.values():<EOL><INDENT>_AddMessageDescriptor(message_type)<EOL><DEDENT>for enum_type in file_descriptor.enum_types_by_name.values():<EOL><INDENT>_AddEnumDescriptor(enum_type)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>scope = {}<EOL>for dependency in built_deps:<EOL><INDENT>scope.update(self._ExtractSymbols(<EOL>dependency.message_types_by_name.values()))<EOL>scope.update((_PrefixWithDot(enum.full_name), enum)<EOL>for enum in dependency.enum_types_by_name.values())<EOL><DEDENT>for message_type in file_proto.message_type:<EOL><INDENT>message_desc = self._ConvertMessageDescriptor(<EOL>message_type, file_proto.package, file_descriptor, scope,<EOL>file_proto.syntax)<EOL>file_descriptor.message_types_by_name[message_desc.name] = (<EOL>message_desc)<EOL><DEDENT>for enum_type in file_proto.enum_type:<EOL><INDENT>file_descriptor.enum_types_by_name[enum_type.name] = (<EOL>self._ConvertEnumDescriptor(enum_type, file_proto.package,<EOL>file_descriptor, None, scope))<EOL><DEDENT>for index, extension_proto in enumerate(file_proto.extension):<EOL><INDENT>extension_desc = self._MakeFieldDescriptor(<EOL>extension_proto, file_proto.package, index, is_extension=True)<EOL>extension_desc.containing_type = self._GetTypeFromScope(<EOL>file_descriptor.package, extension_proto.extendee, scope)<EOL>self._SetFieldType(extension_proto, extension_desc,<EOL>file_descriptor.package, scope)<EOL>file_descriptor.extensions_by_name[extension_desc.name] = (<EOL>extension_desc)<EOL><DEDENT>for desc_proto in file_proto.message_type:<EOL><INDENT>self._SetAllFieldTypes(file_proto.package, desc_proto, scope)<EOL><DEDENT>if file_proto.package:<EOL><INDENT>desc_proto_prefix = _PrefixWithDot(file_proto.package)<EOL><DEDENT>else:<EOL><INDENT>desc_proto_prefix = '<STR_LIT>'<EOL><DEDENT>for desc_proto in file_proto.message_type:<EOL><INDENT>desc = self._GetTypeFromScope(<EOL>desc_proto_prefix, desc_proto.name, scope)<EOL>file_descriptor.message_types_by_name[desc_proto.name] = desc<EOL><DEDENT><DEDENT>self.Add(file_proto)<EOL>self._file_descriptors[file_proto.name] = file_descriptor<EOL><DEDENT>return self._file_descriptors[file_proto.name]<EOL>

Creates a FileDescriptor from a proto or returns a cached copy.

        This method also has the side effect of loading all the symbols found in
        the file into the appropriate dictionaries in the pool.

        Args:
          file_proto: The proto to convert.

        Returns:
          A FileDescriptor matching the passed in proto.


def _NonImplementedMethod(self, method_name, rpc_controller, callback):

rpc_controller.SetFailed('<STR_LIT>' % method_name)<EOL>callback(None)<EOL>

The body of all methods in the generated service class.

        Args:
          method_name: Name of the method being executed.
          rpc_controller: RPC controller used to execute this method.
          callback: A callback which will be invoked when the method finishes.


def __init__(cls, name, bases, dictionary):

super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary)<EOL>if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary:<EOL><INDENT>return<EOL><DEDENT>descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY]<EOL>service_stub_builder = _ServiceStubBuilder(descriptor)<EOL>service_stub_builder.BuildServiceStub(cls)<EOL>

Creates a message service stub class.

        Args:
          name: Name of the class (ignored, here).
          bases: Base classes of the class being constructed.
          dictionary: The class dictionary of the class being constructed.
            dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object
            describing this protocol service type.


def _CallMethod(self, srvc, method_descriptor,<EOL>rpc_controller, request, callback):

if method_descriptor.containing_service != self.descriptor:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>')<EOL><DEDENT>method = getattr(srvc, method_descriptor.name)<EOL>return method(rpc_controller, request, callback)<EOL>

Calls the method described by a given method descriptor.

        Args:
          srvc: Instance of the service for which this method is called.
          method_descriptor: Descriptor that represent the method to call.
          rpc_controller: RPC controller to use for this method's execution.
          request: Request protocol message.
          callback: A callback to invoke after the method has completed.


return self._file_desc_protos_by_symbol[symbol]<EOL>

Finds the file descriptor proto containing the specified symbol.

        The symbol should be a fully qualified name including the file descriptor's
        package and any containing messages. Some examples:

        'some.package.name.Message'
        'some.package.name.Message.NestedEnum'

        The file descriptor proto containing the specified symbol must be added to
        this database using the Add method or else an error will be raised.

        Args:
          symbol: The fully qualified symbol name.

        Returns:
          The file descriptor proto containing the symbol.

        Raises:
          KeyError if no file contains the specified symbol.


return self._file_desc_protos_by_file[name]<EOL>

Finds the file descriptor proto by file name.

        Typically the file name is a relative path ending to a .proto file. The
        proto with the given name will have to have been added to this database
        using the Add method or else an error will be raised.

        Args:
          name: The file name to find.

        Returns:
          The file descriptor proto matching the name.

        Raises:
          KeyError if no file by the given name was added.


def ReplaceHex(m):<EOL><INDENT>if len(m.group(<NUM_LIT:1>)) & <NUM_LIT:1>:<EOL><INDENT>return m.group(<NUM_LIT:1>) + '<STR_LIT>' + m.group(<NUM_LIT:2>)<EOL><DEDENT>return m.group(<NUM_LIT:0>)<EOL><DEDENT>result = _CUNESCAPE_HEX.sub(ReplaceHex, text)<EOL>if str is bytes:  <EOL><INDENT>return result.decode('<STR_LIT>')<EOL><DEDENT>result = '<STR_LIT>'.join(_cescape_highbit_to_str[ord(c)] for c in result)<EOL>return (result.encode('<STR_LIT:ascii>')  <EOL>.decode('<STR_LIT>')<EOL>.encode('<STR_LIT>'))<EOL>

Unescape a text string with C-style escape sequences to UTF-8 bytes.


raise NotImplementedError<EOL>

Sets a failure reason.

        Causes Failed() to return true on the client side.  "reason" will be
        incorporated into the message returned by ErrorText().  If you find
        you need to return machine-readable information about failures, you
        should incorporate it into your response protocol buffer and should
        NOT call SetFailed().


raise NotImplementedError<EOL>

Sets a callback to invoke on cancel.

        Asks that the given callback be called when the RPC is canceled.  The
        callback will always be called exactly once.  If the RPC completes without
        being canceled, the callback will be called after completion.  If the RPC
        has already been canceled when NotifyOnCancel() is called, the callback
        will be called immediately.

        NotifyOnCancel() must be called no more than once per request.


raise NotImplementedError<EOL>

Returns the class of the request message for the specified method.

        CallMethod() requires that the request is of a particular subclass of
        Message. GetRequestClass() gets the default instance of this required
        type.

        Example:
          method = service.GetDescriptor().FindMethodByName("Foo")
          request = stub.GetRequestClass(method)()
          request.ParseFromString(input)
          service.CallMethod(method, request, callback)


self.callees.appendleft(self._make_dispatch(func))<EOL>return self._make_wrapper(func)<EOL>

Adds the decorated function to this dispatch, at the FRONT of the order.
Useful for allowing third parties to add overloaded functionality
to be executed before default functionality.


if isinstance(annotation, type) or (<EOL>isinstance(annotation, tuple) and<EOL>all(isinstance(a, type) for a in annotation)):<EOL><INDENT>if kind is Parameter.VAR_POSITIONAL:<EOL><INDENT>return (lambda args: all(isinstance(x, annotation) for x in args))<EOL><DEDENT>else:<EOL><INDENT>return (lambda x: isinstance(x, annotation))<EOL><DEDENT><DEDENT>elif callable(annotation):<EOL><INDENT>return annotation<EOL><DEDENT>else:<EOL><INDENT>return (lambda x: x == annotation)<EOL><DEDENT>

For a given annotation, return a function which, when called on a
function argument, returns true if that argument matches the annotation.
If the annotation is a type, it calls isinstance; if it's a callable,
it calls it on the object; otherwise, it performs a value comparison.
If the parameter is variadic (*args) and the annotation is a type, the
matcher will attempt to match each of the arguments in args


sig = signature(func)<EOL>matchers = tuple(cls._make_all_matchers(sig.parameters.items()))<EOL>return (partial(cls._bind_args, sig, matchers), func)<EOL>

Create a dispatch pair for func- a tuple of (bind_args, func), where
bind_args is a function that, when called with (args, kwargs), attempts
to bind those args to the type signature of func, or else raise a
TypeError


return [callee[<NUM_LIT:1>] for callee in self.callees]<EOL>

Get a list of registered functions, in the order that they will be
checked.


for name, param in parameters:<EOL><INDENT>annotation = param.annotation<EOL>if annotation is not Parameter.empty:<EOL><INDENT>yield name, cls._make_param_matcher(annotation, param.kind)<EOL><DEDENT><DEDENT>

For every parameter, create a matcher if the parameter has an
annotation.


<EOL>@wraps(func)<EOL>def executor(*args, **kwargs):<EOL><INDENT>return self.execute(args, kwargs)<EOL><DEDENT>executor.dispatch = self.dispatch<EOL>executor.dispatch_first = self.dispatch_first<EOL>executor.func = func<EOL>executor.lookup = self.lookup<EOL>return executor<EOL>

Makes a wrapper function that executes a dispatch call for func. The
wrapper has the dispatch and dispatch_first attributes, so that
additional overloads can be added to the group.


@staticmethod<EOL><INDENT>def _bind_args(sig, param_matchers, args, kwargs):<DEDENT>

<EOL>bound = sig.bind(*args, **kwargs)<EOL>if not all(param_matcher(bound.arguments[param_name])<EOL>for param_name, param_matcher in param_matchers):<EOL><INDENT>raise TypeError<EOL><DEDENT>return bound<EOL>

Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.


if self._description is None:<EOL><INDENT>self._load()<EOL><DEDENT>return self._description<EOL>


auth_url = OAUTH_ROOT + '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT>': self.client_id,<EOL>'<STR_LIT>': self.redirect_uri,<EOL>}<EOL>return "<STR_LIT>".format(auth_url, urlencode(params))<EOL>

Return a URL to redirect the user to for OAuth authentication.


if not docstring:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>lines = six.u(docstring).expandtabs().splitlines()<EOL>lines = [line.strip() for line in lines]<EOL>res = six.u('<STR_LIT:\n>').join(lines)<EOL>return res<EOL>

Remove the tabs to spaces, and remove the extra spaces / tabs that are in
front of the text in docstrings.

Implementation taken from http://www.python.org/dev/peps/pep-0257/


self.parameter_registry = {}<EOL>self.type_converter = type_converter<EOL>self.parameter_converter = parameter_converter<EOL>self.definitions = definition_handler<EOL>self.ref = ref<EOL>

:param definition_handler:
    Callable that handles swagger definition schemas.
:param ref:
    Specifies the ref value when calling from_xxx methods.


name = base_name or resp.get('<STR_LIT:title>', '<STR_LIT>') or resp.get('<STR_LIT:name>', '<STR_LIT>')<EOL>pointer = self.json_pointer + name<EOL>self.response_registry[name] = resp<EOL>return {'<STR_LIT>': pointer}<EOL>

Store a response schema and return a reference to it.

:param schema:
    Swagger response definition.
:param base_name:
    Name that should be used for the reference.

:rtype: dict
:returns: JSON pointer to the original response definition.


self.__dict__.update(**kwargs)<EOL>message = ("<STR_LIT>")<EOL>warnings.warn(message, DeprecationWarning)<EOL>return self.generate(*args, **kwargs)<EOL>


def _extract_operation_from_view(self, view, args):

op = {<EOL>'<STR_LIT>': {<EOL>'<STR_LIT:default>': {<EOL>'<STR_LIT:description>': '<STR_LIT>'<EOL>}<EOL>},<EOL>}<EOL>renderer = args.get('<STR_LIT>', '<STR_LIT>')<EOL>if "<STR_LIT>" in renderer:  <EOL><INDENT>produces = ['<STR_LIT:application/json>']<EOL><DEDENT>elif renderer == '<STR_LIT>':<EOL><INDENT>produces = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>produces = None<EOL><DEDENT>if produces:<EOL><INDENT>op.setdefault('<STR_LIT:produces>', produces)<EOL><DEDENT>consumes = args.get('<STR_LIT>')<EOL>if consumes is not None:<EOL><INDENT>consumes = to_list(consumes)<EOL>consumes = [x for x in consumes if not callable(x)]<EOL>op['<STR_LIT>'] = consumes<EOL><DEDENT>is_colander = self._is_colander_schema(args)<EOL>if is_colander:<EOL><INDENT>schema = self._extract_transform_colander_schema(args)<EOL>parameters = self.parameters.from_schema(schema)<EOL><DEDENT>else:<EOL><INDENT>parameters = None<EOL><DEDENT>if parameters:<EOL><INDENT>op['<STR_LIT>'] = parameters<EOL><DEDENT>if isinstance(view, six.string_types):<EOL><INDENT>if '<STR_LIT>' in args:<EOL><INDENT>ob = args['<STR_LIT>']<EOL>view_ = getattr(ob, view.lower())<EOL>docstring = trim(view_.__doc__)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>docstring = str(trim(view.__doc__))<EOL><DEDENT>if docstring and self.summary_docstrings:<EOL><INDENT>op['<STR_LIT>'] = docstring<EOL><DEDENT>if '<STR_LIT>' in args:<EOL><INDENT>op['<STR_LIT>'] = self.responses.from_schema_mapping(args['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT>' in args:<EOL><INDENT>op['<STR_LIT>'] = args['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in args:<EOL><INDENT>op['<STR_LIT>'] = args['<STR_LIT>']<EOL><DEDENT>if '<STR_LIT>' in args:<EOL><INDENT>op['<STR_LIT>'] = args['<STR_LIT>']<EOL><DEDENT>return op<EOL>

Extract swagger operation details from colander view definitions.

:param view:
    View to extract information from.
:param args:
    Arguments from the view decorator.

:rtype: dict
:returns: Operation definition.


params = []<EOL>for param_schema in schema_node.children:<EOL><INDENT>location = param_schema.name<EOL>if location is '<STR_LIT:body>':<EOL><INDENT>name = param_schema.__class__.__name__<EOL>if name == '<STR_LIT:body>':<EOL><INDENT>name = schema_node.__class__.__name__ + '<STR_LIT>'<EOL><DEDENT>param = self.parameter_converter(location,<EOL>param_schema)<EOL>param['<STR_LIT:name>'] = name<EOL>if self.ref:<EOL><INDENT>param = self._ref(param)<EOL><DEDENT>params.append(param)<EOL><DEDENT>elif location in (('<STR_LIT:path>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT:GET>')):<EOL><INDENT>for node_schema in param_schema.children:<EOL><INDENT>param = self.parameter_converter(location, node_schema)<EOL>if self.ref:<EOL><INDENT>param = self._ref(param)<EOL><DEDENT>params.append(param)<EOL><DEDENT><DEDENT><DEDENT>return params<EOL>

Creates a list of Swagger params from a colander request schema.

:param schema_node:
    Request schema to be transformed into Swagger.
:param validators:
    Validators used in colander with the schema.

:rtype: list
:returns: List of Swagger parameters.


def from_schema(self, schema_node, base_name=None):

return self._ref_recursive(self.type_converter(schema_node), self.ref, base_name)<EOL>

Creates a Swagger definition from a colander schema.

:param schema_node:
    Colander schema to be transformed into a Swagger definition.
:param base_name:
    Schema alternative title.

:rtype: dict
:returns: Swagger schema.


def generate(self, title=None, version=None, base_path=None,<EOL>info=None, swagger=None, **kwargs):

title = title or self.api_title<EOL>version = version or self.api_version<EOL>info = info or self.swagger.get('<STR_LIT:info>', {})<EOL>swagger = swagger or self.swagger<EOL>base_path = base_path or self.base_path<EOL>swagger = swagger.copy()<EOL>info.update(title=title, version=version)<EOL>swagger.update(swagger='<STR_LIT>', info=info, basePath=base_path)<EOL>paths, tags = self._build_paths()<EOL>if tags:<EOL><INDENT>swagger.setdefault('<STR_LIT>', [])<EOL>tag_names = {t['<STR_LIT:name>'] for t in swagger['<STR_LIT>']}<EOL>for tag in tags:<EOL><INDENT>if tag['<STR_LIT:name>'] not in tag_names:<EOL><INDENT>swagger['<STR_LIT>'].append(tag)<EOL><DEDENT><DEDENT><DEDENT>if paths:<EOL><INDENT>swagger.setdefault('<STR_LIT>', {})<EOL>merge_dicts(swagger['<STR_LIT>'], paths)<EOL><DEDENT>definitions = self.definitions.definition_registry<EOL>if definitions:<EOL><INDENT>swagger.setdefault('<STR_LIT>', {})<EOL>merge_dicts(swagger['<STR_LIT>'], definitions)<EOL><DEDENT>parameters = self.parameters.parameter_registry<EOL>if parameters:<EOL><INDENT>swagger.setdefault('<STR_LIT>', {})<EOL>merge_dicts(swagger['<STR_LIT>'], parameters)<EOL><DEDENT>responses = self.responses.response_registry<EOL>if responses:<EOL><INDENT>swagger.setdefault('<STR_LIT>', {})<EOL>merge_dicts(swagger['<STR_LIT>'], responses)<EOL><DEDENT>return swagger<EOL>

Generate a Swagger 2.0 documentation. Keyword arguments may be used
        to provide additional information to build methods as such ignores.

        :param title:
            The name presented on the swagger document.
        :param version:
            The version of the API presented on the swagger document.
        :param base_path:
            The path that all requests to the API must refer to.
        :param info:
            Swagger info field.
        :param swagger:
            Extra fields that should be provided on the swagger documentation.

        :rtype: dict
        :returns: Full OpenAPI/Swagger compliant specification for the application.


name = base_name or param.get('<STR_LIT:title>', '<STR_LIT>') or param.get('<STR_LIT:name>', '<STR_LIT>')<EOL>pointer = self.json_pointer + name<EOL>self.parameter_registry[name] = param<EOL>return {'<STR_LIT>': pointer}<EOL>

Store a parameter schema and return a reference to it.

:param schema:
    Swagger parameter definition.
:param base_name:
    Name that should be used for the reference.

:rtype: dict
:returns: JSON pointer to the original parameter definition.


config.add_route('<STR_LIT>', api_explorer_path,<EOL>factory=route_factory)<EOL>config.add_view('<STR_LIT>',<EOL>permission=permission,<EOL>route_name='<STR_LIT>')<EOL>

:param config:
    Pyramid configurator object
:param api_explorer_path:
    where to expose Swagger UI interface view
:param permission:
    pyramid permission for those views
:param route_factory:
    factory for context object for those routes

This registers and configures the view that serves api explorer


key = request.matchdict['<STR_LIT:key>']<EOL>return _VALUES.get(key)<EOL>


key = request.matchdict['<STR_LIT:key>']<EOL>_VALUES[key] = request.json_body<EOL>return _VALUES.get(key)<EOL>

Set the value and returns *True* or *False*.


def teardown_databases(self, old_config, **kwargs):

pass<EOL>

Override the database teardown defined in parent class


pass<EOL>

Override the database creation defined in parent class


for line in open(os.path.join(os.path.dirname(__file__), relpath), encoding='<STR_LIT>'):<EOL><INDENT>if keyword in line:<EOL><INDENT>if '<STR_LIT:">' in line:<EOL><INDENT>return line.split('<STR_LIT:">')[<NUM_LIT:1>]<EOL><DEDENT>elif "<STR_LIT:'>" in line:<EOL><INDENT>return line.split("<STR_LIT:'>")[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>

Read __version__ or other properties from a python file without importing it

    from gist.github.com/technonik/406623 but with added keyward kwarg


if skipset is None: skipset = set()<EOL>for item in iterable:<EOL><INDENT>if item not in skipset:<EOL><INDENT>skipset.add(item)<EOL>yield item<EOL><DEDENT><DEDENT>

Redundant items are repeated items or items in the original skipset.


def get_noconflict_metaclass(bases, left_metas, right_metas):

<EOL>metas = left_metas + tuple(map(type, bases)) + right_metas<EOL>needed_metas = remove_redundant(metas)<EOL>if needed_metas in memoized_metaclasses_map:<EOL><INDENT>return memoized_metaclasses_map[needed_metas]<EOL><DEDENT>elif not needed_metas:         <EOL><INDENT>meta = type<EOL><DEDENT>elif len(needed_metas) == <NUM_LIT:1>: <EOL><INDENT>meta = needed_metas[<NUM_LIT:0>]<EOL><DEDENT>elif needed_metas == bases: <EOL><INDENT>raise TypeError("<STR_LIT>", needed_metas)<EOL><DEDENT>else: <EOL><INDENT>metaname = '<STR_LIT:_>' + '<STR_LIT>'.join([m.__name__ for m in needed_metas])<EOL>meta = classmaker()(metaname, needed_metas, {})<EOL><DEDENT>memoized_metaclasses_map[needed_metas] = meta<EOL>return meta<EOL>

Not intended to be used outside of this module, unless you know
    what you are doing.


def bug_info(exc_type, exc_value, exc_trace):

if hasattr(sys, '<STR_LIT>') or not sys.stderr.isatty():<EOL><INDENT>sys.__excepthook__(exc_type, exc_value, exc_trace)<EOL><DEDENT>else:<EOL><INDENT>import ipdb<EOL>traceback.print_exception(exc_type, exc_value, exc_trace)<EOL>print<EOL>ipdb.post_mortem(exc_trace)<EOL><DEDENT>

Prints the traceback and invokes the ipython debugger on any exception

    Only invokes ipydb if you are outside ipython or python interactive session.
    So scripts must be called from OS shell in order for exceptions to ipy-shell-out.

    Dependencies:
      Needs `pip install ipdb`

    Arguments:
      exc_type (type): The exception type/class (e.g. RuntimeError)
      exc_value (Exception): The exception instance (e.g. the error message passed to the Exception constructor)
      exc_trace (Traceback): The traceback instance

    References:
      http://stackoverflow.com/a/242531/623735

    Example Usage:
      $  python -c 'from pug import debug;x=[];x[0]'
      Traceback (most recent call last):
        File "<string>", line 1, in <module>
      IndexError: list index out of range

      > <string>(1)<module>()

      ipdb> x
      []
      ipdb> locals()
      {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'x': [], 'debug': <module 'pug.debug' from 'pug/debug.py'>, '__name__': '__main__', '__doc__': None}
      ipdb>


<EOL>return tuple(force_hashable(obj))<EOL>

Force frozenset() command to freeze the order and contents of multables and iterables like lists, dicts, generators

    Useful for memoization and constructing dicts or hashtables where keys must be immutable


def _denormalize(obj, fields=None, save=False, overwrite=False):

if not fields:<EOL><INDENT>meta = obj._meta<EOL>fields = [f.name for f in meta.fields if not hasattr(f, '<STR_LIT>') and not f.primary_key and hasattr(meta, '<STR_LIT>' + f.name) and hasattr(meta, '<STR_LIT:_>' + f.name)]<EOL><DEDENT>for field in fields:<EOL><INDENT>if not overwrite and not isinstance(getattr(obj, field, None), NoneType):<EOL><INDENT>continue<EOL><DEDENT>if hasattr(obj, field):<EOL><INDENT>setattr(obj, field, getattr(obj, '<STR_LIT:_>' + field, None))<EOL><DEDENT><DEDENT>if save:<EOL><INDENT>obj.save()<EOL><DEDENT>return obj<EOL>

Update/populate any database fields that are not related fields (FKs) but have `_get`ters to populate them with


<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>

Extract version information from the given file.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>

TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE


<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>

Create, populate and return the VersioneerConfig() object.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>

TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)


@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>]  <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out)  <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT:date>"] = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL>return pieces<EOL>

Get version from 'git describe' in the root of the source tree.

    This only gets called if the git-archive 'subst' keywords were *not*
    expanded, and _version.py hasn't already been rewritten with a short
    version string, meaning we're inside a checked out source tree.


def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>

Decorator to mark a method as the handler for a particular VCS.


if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>

Build up version string, with post-release "local version identifier".

    Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
    get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty

    Exceptions:
    1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]


<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>

Get the keywords needed to look up the version information.


if data_format in component_8bit_formats:<EOL><INDENT>return <NUM_LIT:8><EOL><DEDENT>elif data_format in component_10bit_formats:<EOL><INDENT>return <NUM_LIT:10><EOL><DEDENT>elif data_format in component_12bit_formats:<EOL><INDENT>return <NUM_LIT:12><EOL><DEDENT>elif data_format in component_14bit_formats:<EOL><INDENT>return <NUM_LIT><EOL><DEDENT>elif data_format in component_16bit_formats:<EOL><INDENT>return <NUM_LIT:16><EOL><DEDENT>return None<EOL>

Returns the number of (used) bits per pixel.
So without padding.
Returns None if format is not known.


Releases all external resources including the controlling device.


return self._payload<EOL>

:return: A containing object which derives from :class:`PayloadBase` class.


def __init__(self, thread: ThreadBase=None):

<EOL>assert thread<EOL>super().__init__()<EOL>self._thread = thread<EOL>self._locked_mutex = None<EOL>


timestamp = <NUM_LIT:0><EOL>try:<EOL><INDENT>timestamp = self._buffer.timestamp_ns<EOL><DEDENT>except (InvalidParameterException, NotImplementedException,<EOL>NotAvailableException):<EOL><INDENT>try:<EOL><INDENT>_ = self.timestamp_frequency<EOL><DEDENT>except InvalidParameterException:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>timestamp = self._buffer.timestamp<EOL><DEDENT>except (InvalidParameterException, NotAvailableException):<EOL><INDENT>timestamp = <NUM_LIT:0><EOL><DEDENT><DEDENT><DEDENT>return timestamp<EOL>

:return: The timestamp in the TL specific unit.


return self._interface<EOL>

:return: The parent :class:`Interface` module object of the connecting remote device.


def __init__(self, *, buffer=None, node_map=None, logger=None):

<EOL>assert buffer<EOL>assert node_map<EOL>self._logger = logger or get_logger(name=__name__)<EOL>super().__init__()<EOL>self._buffer = buffer<EOL>self._node_map = node_map<EOL>self._payload = self._build_payload(<EOL>buffer=buffer,<EOL>node_map=node_map,<EOL>logger=self._logger<EOL>)<EOL>

:param buffer:
:param node_map:
:param logger:


raise NotImplementedError<EOL>

This method is abstract and should be reimplemented in any sub-class.

:return: None.


try:<EOL><INDENT>if self._part:<EOL><INDENT>value = self._part.width<EOL><DEDENT>else:<EOL><INDENT>value = self._buffer.width<EOL><DEDENT><DEDENT>except InvalidParameterException:<EOL><INDENT>value = self._node_map.Width.value<EOL><DEDENT>return value<EOL>

:return: The width of the data component in the buffer in number of pixels.


try:<EOL><INDENT>if self._part:<EOL><INDENT>value = self._part.height<EOL><DEDENT>else:<EOL><INDENT>value = self._buffer.height<EOL><DEDENT><DEDENT>except InvalidParameterException:<EOL><INDENT>value = self._node_map.Height.value<EOL><DEDENT>return value<EOL>

:return: The height of the data component in the buffer in number of pixels.


if not os.path.exists(file_path):<EOL><INDENT>self._logger.warning(<EOL>'<STR_LIT>'.format(file_path)<EOL>)<EOL><DEDENT>if file_path not in self._cti_files:<EOL><INDENT>self._cti_files.append(file_path)<EOL>self._logger.info(<EOL>'<STR_LIT>'.format(file_path)<EOL>)<EOL><DEDENT>

Adds a CTI file to work with to the CTI file list.

:param file_path: Set a file path to the target CTI file.

:return: None.


def __init__(self, *, mutex=None, worker=None, logger=None,<EOL>sleep_duration=_sleep_duration_default):

<EOL>super().__init__(mutex=mutex, logger=logger)<EOL>self._thread = None<EOL>self._worker = worker<EOL>self._sleep_duration = sleep_duration<EOL>

:param mutex:
:param worker:
:param logger:
:param sleep_duration:


<EOL>assert buffer<EOL>assert node_map<EOL>self._logger = logger or get_logger(name=__name__)<EOL>super().__init__(buffer=buffer, logger=self._logger)<EOL>


self._is_running = True<EOL>self._start()<EOL>self._logger.debug(<EOL>'<STR_LIT>'.format(self.id_)<EOL>)<EOL>


Initializes the :class:`Harvester` object. Once you reset the
:class:`Harvester` object, all allocated resources, including buffers
and remote device, will be released.

:return: None.


return self._components<EOL>

:return: A :class:`list` containing objects that derive from :const:`ComponentBase` class.


return self._cti_files<EOL>

:return: A :class:`list` object containing :class:`str` objects.


if self.data is None:<EOL><INDENT>return None<EOL><DEDENT>return self._data.reshape(<EOL>self.height + self.y_padding,<EOL>int(self.width * self._num_components_per_pixel + self.x_padding)<EOL>)<EOL>

Returns a NumPy array that represents the 2D pixel location,
which is defined by PFNC, of the original image data.

You may use the returned NumPy array for a calculation to map the
original image to another format.

:return: A NumPy array that represents the 2D pixel location.


return self._device_info_list<EOL>

:return: A :class:`list` object containing :class:`DeviceInfo` objects


return self._system<EOL>

:return: The parent :class:`System` module object of the connecting remote device.


return self._buffer.data_format<EOL>

:return: The data type of the data component.


def __init__(self, *, mutex=None, logger=None):

<EOL>self._logger = logger or get_logger(name=__name__)<EOL>super().__init__()<EOL>self._is_running = False<EOL>self._mutex = mutex<EOL>


return self._buffer.payload_type<EOL>


try:<EOL><INDENT>if self._part:<EOL><INDENT>value = self._part.y_padding<EOL><DEDENT>else:<EOL><INDENT>value = self._buffer.padding_y<EOL><DEDENT><DEDENT>except (InvalidParameterException, NotImplementedException):<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>return value<EOL>

:return: The Y padding of the data component in the buffer in number of pixels.


<EOL>assert buffer<EOL>assert node_map<EOL>self._logger = logger or get_logger(name=__name__)<EOL>super().__init__(buffer=buffer, logger=self._logger)<EOL>self._components.append(<EOL>self._build_component(<EOL>buffer=buffer, node_map=node_map<EOL>)<EOL>)<EOL>


raise NotImplementedError<EOL>

This method is abstract and should be reimplemented in any sub-class.

Starts its worker running.

:return: None.


def __init__(self, *, profile=False, logger=None):

<EOL>self._logger = logger or get_logger(name=__name__)<EOL>super().__init__()<EOL>self._cti_files = []<EOL>self._producers = []<EOL>self._systems = []<EOL>self._interfaces = []<EOL>self._device_info_list = []<EOL>self._ias = []<EOL>self._has_revised_device_list = False<EOL>self._timeout_for_update = <NUM_LIT:1000>  <EOL>if profile:<EOL><INDENT>from harvesters._private.core.helper.profiler import Profiler<EOL>self._profiler = Profiler()<EOL><DEDENT>else:<EOL><INDENT>self._profiler = None<EOL><DEDENT>if self._profiler:<EOL><INDENT>self._profiler.print_diff()<EOL><DEDENT>self._finalizer = weakref.finalize(self, self._reset)<EOL>


if not self._create_ds_at_connection:<EOL><INDENT>self._setup_data_streams()<EOL><DEDENT>num_required_buffers = self._num_buffers<EOL>for data_stream in self._data_streams:<EOL><INDENT>try:<EOL><INDENT>num_buffers = data_stream.buffer_announce_min<EOL>if num_buffers < num_required_buffers:<EOL><INDENT>num_buffers = num_required_buffers<EOL><DEDENT><DEDENT>except InvalidParameterException as e:<EOL><INDENT>num_buffers = num_required_buffers<EOL>self._logger.debug(e, exc_info=True)<EOL><DEDENT>if data_stream.defines_payload_size():<EOL><INDENT>buffer_size = data_stream.payload_size<EOL><DEDENT>else:<EOL><INDENT>buffer_size = self.device.node_map.PayloadSize.value<EOL><DEDENT>raw_buffers = self._create_raw_buffers(<EOL>num_buffers, buffer_size<EOL>)<EOL>buffer_tokens = self._create_buffer_tokens(<EOL>raw_buffers<EOL>)<EOL>self._announced_buffers = self._announce_buffers(<EOL>data_stream=data_stream, _buffer_tokens=buffer_tokens<EOL>)<EOL>self._queue_announced_buffers(<EOL>data_stream=data_stream, buffers=self._announced_buffers<EOL>)<EOL><DEDENT>try:<EOL><INDENT>acq_mode = self.device.node_map.AcquisitionMode.value<EOL>if acq_mode == '<STR_LIT>':<EOL><INDENT>num_images_to_acquire = -<NUM_LIT:1><EOL><DEDENT>elif acq_mode == '<STR_LIT>':<EOL><INDENT>num_images_to_acquire = <NUM_LIT:1><EOL><DEDENT>elif acq_mode == '<STR_LIT>':<EOL><INDENT>num_images_to_acquire = self.device.node_map.AcquisitionFrameCount.value<EOL><DEDENT>else:<EOL><INDENT>num_images_to_acquire = -<NUM_LIT:1><EOL><DEDENT><DEDENT>except LogicalErrorException as e:<EOL><INDENT>num_images_to_acquire = -<NUM_LIT:1><EOL>self._logger.debug(e, exc_info=True)<EOL><DEDENT>self._num_images_to_acquire = num_images_to_acquire<EOL>try:<EOL><INDENT>self.device.node_map.TLParamsLocked.value = <NUM_LIT:1><EOL><DEDENT>except LogicalErrorException:<EOL><INDENT>pass<EOL><DEDENT>self._is_acquiring_images = True<EOL>for data_stream in self._data_streams:<EOL><INDENT>data_stream.start_acquisition(<EOL>ACQ_START_FLAGS_LIST.ACQ_START_FLAGS_DEFAULT,<EOL>self._num_images_to_acquire<EOL>)<EOL><DEDENT>if self.thread_image_acquisition:<EOL><INDENT>self.thread_image_acquisition.start()<EOL><DEDENT>self.device.node_map.AcquisitionStart.execute()<EOL>self._logger.info(<EOL>'<STR_LIT>'.format(self._device.id_)<EOL>)<EOL>if self._profiler:<EOL><INDENT>self._profiler.print_diff()<EOL><DEDENT>

Starts image acquisition.

:return: None.


try:<EOL><INDENT>if self._part:<EOL><INDENT>value = self._part.x_padding<EOL><DEDENT>else:<EOL><INDENT>value = self._buffer.padding_x<EOL><DEDENT><DEDENT>except InvalidParameterException:<EOL><INDENT>value = <NUM_LIT:0><EOL><DEDENT>return value<EOL>

Returns
:return: The X padding of the data component in the buffer in number of pixels.


raise NotImplementedError<EOL>

This method is abstract and should be reimplemented in any sub-class.

Acquires a mutex.

:return: None.


return symbolics[self.data_format_value]<EOL>

:return: The data type of the data component as string.


raise NotImplementedError<EOL>

This method is abstract and should be reimplemented in any sub-class.

Releases the acquired mutex.

:return: None.


def __init__(self, *, buffer=None, part=None, node_map=None, logger=None):

<EOL>assert buffer<EOL>assert node_map<EOL>super().__init__(buffer=buffer)<EOL>self._logger = logger or get_logger(name=__name__)<EOL>self._part = part<EOL>self._node_map = node_map<EOL>self._data = None<EOL>self._num_components_per_pixel = <NUM_LIT:0><EOL>symbolic = self.data_format<EOL>if self.x_padding > <NUM_LIT:0>:<EOL><INDENT>dtype = '<STR_LIT>'<EOL>bytes_per_pixel_data_component = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>if symbolic in uint16_formats:<EOL><INDENT>dtype = '<STR_LIT>'<EOL>bytes_per_pixel_data_component = <NUM_LIT:2><EOL><DEDENT>elif symbolic in uint32_formats:<EOL><INDENT>dtype = '<STR_LIT>'<EOL>bytes_per_pixel_data_component = <NUM_LIT:4><EOL><DEDENT>elif symbolic in float32_formats:<EOL><INDENT>dtype = '<STR_LIT>'<EOL>bytes_per_pixel_data_component = <NUM_LIT:4><EOL><DEDENT>elif symbolic in uint8_formats:<EOL><INDENT>dtype = '<STR_LIT>'<EOL>bytes_per_pixel_data_component = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self._data = None<EOL>return<EOL><DEDENT><DEDENT>if symbolic in lmn_444_location_formats:<EOL><INDENT>num_components_per_pixel = <NUM_LIT><EOL><DEDENT>elif symbolic in lmn_422_location_formats:<EOL><INDENT>num_components_per_pixel = <NUM_LIT><EOL><DEDENT>elif symbolic in lmn_411_location_formats:<EOL><INDENT>num_components_per_pixel = <NUM_LIT><EOL><DEDENT>elif symbolic in lmno_4444_location_formats:<EOL><INDENT>num_components_per_pixel = <NUM_LIT><EOL><DEDENT>elif symbolic in mono_location_formats orsymbolic in bayer_location_formats:<EOL><INDENT>num_components_per_pixel = <NUM_LIT:1.><EOL><DEDENT>else:<EOL><INDENT>self._data = None<EOL>return<EOL><DEDENT>self._num_components_per_pixel = num_components_per_pixel<EOL>self._symbolic = symbolic<EOL>width = self.width<EOL>height = self.height<EOL>if self._part:<EOL><INDENT>count = self._part.data_size<EOL>count //= bytes_per_pixel_data_component<EOL>data_offset = self._part.data_offset<EOL><DEDENT>else:<EOL><INDENT>count = width * height<EOL>count *= num_components_per_pixel<EOL>count += self.y_padding<EOL>data_offset = <NUM_LIT:0><EOL><DEDENT>if _is_logging_buffer_manipulation:<EOL><INDENT>self._logger.debug(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT:)>'.format(<EOL>len(self._buffer.raw_buffer),<EOL>int(count),<EOL>dtype,<EOL>data_offset,<EOL>symbolic,<EOL>self.x_padding,<EOL>self.y_padding,<EOL>)<EOL>)<EOL><DEDENT>self._data = np.frombuffer(<EOL>self._buffer.raw_buffer,<EOL>count=int(count),<EOL>dtype=dtype,<EOL>offset=data_offset<EOL>)<EOL>

:param buffer:
:param part:
:param node_map:


def __init__(self, base=None, worker=None,<EOL>sleep_duration=_sleep_duration_default):

<EOL>assert base<EOL>super().__init__(daemon=self._is_interactive())<EOL>self._worker = worker<EOL>self._base = base<EOL>self._sleep_duration = sleep_duration<EOL>

:param base:
:param worker:
:param sleep_duration:


return self._buffer.payload_type<EOL>

:return: The payload type that the :class:`Buffer` object contains.


def fetch_buffer(self, *, timeout=<NUM_LIT:0>, is_raw=False):

if not self.is_acquiring_images:<EOL><INDENT>raise TimeoutException<EOL><DEDENT>watch_timeout = True if timeout > <NUM_LIT:0> else False<EOL>buffer = None<EOL>base = time.time()<EOL>while buffer is None:<EOL><INDENT>if watch_timeout and (time.time() - base) > timeout:<EOL><INDENT>raise TimeoutException<EOL><DEDENT>else:<EOL><INDENT>with MutexLocker(self.thread_image_acquisition):<EOL><INDENT>if len(self._holding_filled_buffers) > <NUM_LIT:0>:<EOL><INDENT>if is_raw:<EOL><INDENT>buffer = self._holding_filled_buffers.pop(<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>_buffer = self._holding_filled_buffers.pop(<NUM_LIT:0>)<EOL>self._update_chunk_data(buffer=_buffer)<EOL>buffer = Buffer(<EOL>buffer=_buffer,<EOL>node_map=self.device.node_map,<EOL>logger=self._logger<EOL>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>if _is_logging_buffer_manipulation:<EOL><INDENT>self._logger.debug(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT:.>'.format(<EOL>buffer._buffer.context,<EOL>buffer._buffer.frame_id,<EOL>buffer._buffer.parent.id_,<EOL>buffer._buffer.parent.parent.id_<EOL>)<EOL>)<EOL><DEDENT>return buffer<EOL>

Fetches the latest :class:`Buffer` object and returns it.

:param timeout: Set timeout value in second.
:param is_raw: Set :const:`True` if you need a raw GenTL Buffer module.

:return: A :class:`Buffer` object.


def compare_group(_from, _to, group):<EOL><INDENT>"""<STR_LIT>"""<EOL>source = DATA[_from][group]<EOL>actual = '<STR_LIT:U+0020>'.join(sanscript.transliterate(source, _from, _to).split())<EOL>expected = '<STR_LIT:U+0020>'.join(DATA[_to][group].split())<EOL>assert expected == actual, "<STR_LIT>" % (_from, _to, expected, actual)<EOL><DEDENT>for group in DATA[_from]:<EOL><INDENT>if _to in DATA and group in DATA[_to]:<EOL><INDENT>compare_group(_from, _to, group)<EOL><DEDENT><DEDENT>


if encoding_scheme == sanscript.DEVANAGARI:<EOL><INDENT>key = text<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>key = regex.sub("<STR_LIT>", "<STR_LIT>", key)<EOL>return key<EOL><DEDENT>else:<EOL><INDENT>logging.warning("<STR_LIT>".format(encoding_scheme, text))<EOL>return regex.sub("<STR_LIT>", "<STR_LIT>", text)<EOL><DEDENT>

Given some devanAgarI sanskrit text, this function produces a "key" so
that

1] The key should be the same for different observed orthographical
forms of the same text. For example:

::

    - "dharmma" vs "dharma"
    - "rAmaM gacChati" vs "rAma~N gacChati" vs "rAma~N gacChati"
    - "kurvan eva" vs "kurvanneva"

2] The key should be different for different for different texts.

-  "stamba" vs "stambha"

This function attempts to succeed at [1] and [2] almostall the time.
Longer the text, probability of failing at [2] decreases, while
probability of failing at [1] increases (albeit very slightly).

Sources of orthographically divergent forms:

-  Phonetically sensible grammar rules
-  Neglect of sandhi while writing
-  Punctuation, spaces, avagraha-s.
-  Regional-language-influenced mistakes (La instead of la.)

Some example applications of this function:

-  Create a database of quotes or words with minimal duplication.
-  Search a database of quotes or words while being robust to optional
   forms.

Also see equivalent function in the scala indic-transliteration package.


s = str.split<EOL>if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>s = unicode.split<EOL><DEDENT>def pop_all(some_dict, some_list):<EOL><INDENT>for scheme in some_list:<EOL><INDENT>some_dict.pop(scheme)<EOL><DEDENT><DEDENT>global SCHEMES<EOL>SCHEMES = copy.deepcopy(sanscript.SCHEMES)<EOL>pop_all(SCHEMES, [sanscript.ORIYA, sanscript.BENGALI, sanscript.GUJARATI])<EOL>SCHEMES[HK].update({<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': sanscript.SCHEMES[HK]['<STR_LIT>'] + s("""<STR_LIT>""")<EOL>})<EOL>SCHEMES[ITRANS].update({<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': sanscript.SCHEMES[ITRANS]['<STR_LIT>'] + s("""<STR_LIT>""")<EOL>})<EOL>pop_all(SCHEMES[ITRANS].synonym_map, s("""<STR_LIT>"""))<EOL>SCHEMES[OPTITRANS].update({<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': s("""<STR_LIT>""") + s("""<STR_LIT>"""),<EOL>'<STR_LIT>': sanscript.SCHEMES[OPTITRANS]['<STR_LIT>'] + s("""<STR_LIT>""")<EOL>})<EOL>pop_all(SCHEMES[OPTITRANS].synonym_map, s("""<STR_LIT>"""))<EOL>


if sys.version_info < (<NUM_LIT:3>, <NUM_LIT:0>):<EOL><INDENT>try:<EOL><INDENT>text = text.decode('<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>for L in text:<EOL><INDENT>code = ord(L)<EOL>if code >= BRAHMIC_FIRST_CODE_POINT:<EOL><INDENT>for name, start_code in BLOCKS:<EOL><INDENT>if start_code <= code <= BRAHMIC_LAST_CODE_POINT:<EOL><INDENT>return name<EOL><DEDENT><DEDENT><DEDENT><DEDENT>if Regex.IAST_OR_KOLKATA_ONLY.search(text):<EOL><INDENT>if Regex.KOLKATA_ONLY.search(text):<EOL><INDENT>return Scheme.Kolkata<EOL><DEDENT>else:<EOL><INDENT>return Scheme.IAST<EOL><DEDENT><DEDENT>if Regex.ITRANS_ONLY.search(text):<EOL><INDENT>return Scheme.ITRANS<EOL><DEDENT>if Regex.SLP1_ONLY.search(text):<EOL><INDENT>return Scheme.SLP1<EOL><DEDENT>if Regex.VELTHUIS_ONLY.search(text):<EOL><INDENT>return Scheme.Velthuis<EOL><DEDENT>if Regex.ITRANS_OR_VELTHUIS_ONLY.search(text):<EOL><INDENT>return Scheme.ITRANS<EOL><DEDENT>return Scheme.HK<EOL>

Detect the input's transliteration scheme.

      :param text: some text data, either a `unicode` or a `str` encoded
                   in UTF-8.


def transliterate(data, _from=None, _to=None, scheme_map=None, **kw):

if scheme_map is None:<EOL><INDENT>scheme_map = _get_scheme_map(_from, _to)<EOL><DEDENT>options = {<EOL>'<STR_LIT>': {'<STR_LIT>'},<EOL>'<STR_LIT>': set('<STR_LIT:<>'),<EOL>'<STR_LIT>': set('<STR_LIT:>>')<EOL>}<EOL>options.update(kw)<EOL>from indic_transliteration.sanscript.brahmic_mapper import _brahmic<EOL>from indic_transliteration.sanscript.roman_mapper import _roman<EOL>func = _roman if scheme_map.from_scheme.is_roman else _brahmic<EOL>return func(data, scheme_map, **options)<EOL>

Transliterate `data` with the given parameters::

        output = transliterate('idam adbhutam', HK, DEVANAGARI)

    Each time the function is called, a new :class:`SchemeMap` is created
    to map the input scheme to the output scheme. This operation is fast
    enough for most use cases. But for higher performance, you can pass a
    pre-computed :class:`SchemeMap` instead::

        scheme_map = SchemeMap(SCHEMES[HK], SCHEMES[DEVANAGARI])
        output = transliterate('idam adbhutam', scheme_map=scheme_map)

    :param data: the data to transliterate
    :param scheme_map: the :class:`SchemeMap` to use. If specified, ignore
                       `_from` and `_to`. If unspecified, create a
                       :class:`SchemeMap` from `_from` to `_to`.


return SchemeMap(SCHEMES[input_encoding], SCHEMES[output_encoding])<EOL>

Provides a caching layer on top of `SchemeMap` objects to allow faster
    access to scheme maps we've instantiated once.

    :param input_encoding: Input encoding. Must be defined in `SCHEMES`.
    :param output_encoding: Input encoding. Must be defined in `SCHEMES`.


out = []<EOL>for x in y:<EOL><INDENT>if x < <NUM_LIT>:<EOL><INDENT>out.append(x)<EOL><DEDENT>elif x < <NUM_LIT>:<EOL><INDENT>out.append((x >> <NUM_LIT:6>) | <NUM_LIT>)<EOL>out.append((x & <NUM_LIT>) | <NUM_LIT>)<EOL><DEDENT>elif x < <NUM_LIT>:<EOL><INDENT>out.append((x >> <NUM_LIT:12>) | <NUM_LIT>)<EOL>out.append(((x >> <NUM_LIT:6>) & <NUM_LIT>) | <NUM_LIT>)<EOL>out.append((x & <NUM_LIT>) | <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>out.append((x >> <NUM_LIT>) | <NUM_LIT>)<EOL>out.append((x >> <NUM_LIT:12>) & <NUM_LIT>)<EOL>out.append(((x >> <NUM_LIT:6>) & <NUM_LIT>) | <NUM_LIT>)<EOL>out.append((x & <NUM_LIT>) | <NUM_LIT>)<EOL><DEDENT><DEDENT>return '<STR_LIT>'.join(map(chr, out))<EOL>

converts an array of integers to utf8 string


if i in range(<NUM_LIT:1>, <NUM_LIT:10>):<EOL><INDENT>n = i - <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>raise IllegalInput("<STR_LIT>" % (hex(i)))<EOL><DEDENT>if n > -<NUM_LIT:1>: <EOL><INDENT>self.curr_script = n<EOL>self.delta = n * DELTA<EOL><DEDENT>return<EOL>

set the value of delta to reflect the current codepage


def __init__(self, name, charRange, charClass=TLCharacter):

"""<STR_LIT>"""<EOL>charRange.sort()<EOL>for c in charRange:<EOL><INDENT>try:<EOL><INDENT>tlchar = charClass(c, self)<EOL>self[tlchar.chr] = tlchar<EOL><DEDENT>except ValueError: <EOL><INDENT>pass<EOL><DEDENT><DEDENT>self._longestEntry = <NUM_LIT:1><EOL>self.name = name<EOL>self.transliterationSchemes = {}<EOL>self._register()<EOL>

Set up a character block corresponding to a range of code points.

        Keyword arguments:
        name -- a string containing the name of the character block.
                (should normally use a standard Unicode character block name)
        range -- a list of code points. Reserved code points are ignored.
        charClass -- the class to be used to create the characters.
                     Should be a subclass of TLCharacter.


def _transliterate(self, text, outFormat):

return _Devanagari._transliterate(self, text, outFormat)<EOL>

Need to specify which superclass _transliterate() to call.


def __init__(self, blockName, schemeName, data, swapTable=None):

self.block = characterBlocks[blockName]<EOL>self.name = schemeName<EOL>for equiv, unicodeHexValue in data.items():<EOL><INDENT>self[equiv] = self.block[chr(unicodeHexValue)]<EOL>self[equiv].addEquivalent(self.name, equiv)<EOL><DEDENT>self._longestEntry = max([len(e) for e in data.keys()])<EOL>if self._longestEntry > <NUM_LIT:1>:<EOL><INDENT>self._parseTree = {}<EOL>self._parsedata = list(data.keys())<EOL>self._parsedata.sort()<EOL>self._setupParseTree(<NUM_LIT:0>, len(data) - <NUM_LIT:1>, <NUM_LIT:0>, self._parseTree)<EOL><DEDENT>if swapTable is not None:<EOL><INDENT>if not isinstance(swapTable, dict): raise (TypeError)<EOL><DEDENT>self.swapTable = swapTable<EOL>self._register()<EOL>

Set up a transliteration scheme.

        Keyword arguments:
        blockName -- a string containg the name of the character block this
                     transliteration scheme is used for,
                     e.g. 'CYRILLIC', 'DEVANAGARI'.
        schemeName -- the name of the transliteration scheme.
                      Must be unique.
        data -- a dict containing the data for the transliteration scheme.
                Keys are transliterated Unicode characters or strings.
                Values are integers corresponding to Unicode code points.
                For examples, see the data for the built-in transliteration
                schemes.
        swapTable -- a dict (default None) containing any non-standard
                     letter combinations used in the transliteration scheme
                     that we want to pre-process away before transliterating.
                     See the ITRANS data for examples.

        Raises:
        KeyError: unknown block name.
        TypeError: swapTable is not a dict


TransliterationScheme.__init__(self, blockName, schemeName, data, swapTable)<EOL>self._implicitA = False<EOL>

Set up a Devanagari transliteration scheme.

        Extends TransliterationScheme.__init__


def _transliterate (self, text, outFormat):

result = []<EOL>for c in text:<EOL><INDENT>if c.isspace(): result.append(c)<EOL>try: <EOL><INDENT>result.append(self[c].equivalents[outFormat.name])<EOL><DEDENT>except KeyError:<EOL><INDENT>result.append(_unrecognised(c))<EOL><DEDENT><DEDENT>return result<EOL>

Transliterate the text to the target transliteration scheme.


global options<EOL>defaultOptions = {<EOL>'<STR_LIT>' : '<STR_LIT:utf-8>',  <EOL>'<STR_LIT>' : '<STR_LIT:utf-8>', <EOL>'<STR_LIT>' : '<STR_LIT:?>', <EOL>'<STR_LIT>' : UNRECOGNISED_ECHO,   <EOL>'<STR_LIT>' : False,   <EOL>}<EOL>options = defaultOptions.copy()<EOL>


def getResult(): <EOL><INDENT>if curMatch.isspace():<EOL><INDENT>result.append(curMatch)<EOL>return<EOL><DEDENT>if prevMatch in self:<EOL><INDENT>prev = self[prevMatch]<EOL><DEDENT>else:<EOL><INDENT>prev = None<EOL><DEDENT>if nextMatch in self:<EOL><INDENT>next = self[nextMatch]<EOL><DEDENT>else:<EOL><INDENT>next = None<EOL><DEDENT>try:<EOL><INDENT>equiv = outFormat._equivalent(self[curMatch], <EOL>prev, <EOL>next, <EOL>self._implicitA)<EOL><DEDENT>except KeyError:<EOL><INDENT>equiv = _unrecognised(curMatch)<EOL><DEDENT>for e in equiv:<EOL><INDENT>result.append(e)<EOL><DEDENT><DEDENT>def incr(c):<EOL><INDENT>if self._longestEntry == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>return len(c)<EOL><DEDENT>result = []<EOL>text = self._preprocess(text)<EOL>i = <NUM_LIT:0><EOL>prevMatch = None<EOL>nextMatch = None<EOL>curMatch = self._getNextChar(text, i)<EOL>i = i + len(curMatch)<EOL>while i < len(text):<EOL><INDENT>nextMatch = self._getNextChar(text, i)<EOL>getResult()<EOL>i = i + len(nextMatch)<EOL>prevMatch = curMatch<EOL>curMatch = nextMatch<EOL>nextMatch = None<EOL><DEDENT>getResult() <EOL>return result<EOL>

Transliterate a devanagari text into the target format.

        Transliterating a character to or from Devanagari is not a simple
        lookup: it depends on the preceding and following characters.


def transliterate(text, inFormat, outFormat, requestOptions={}):

def asciiEncode(chr):<EOL><INDENT>value = ord(chr)<EOL>if value > <NUM_LIT:255>:<EOL><INDENT>return '<STR_LIT>' % (value)<EOL><DEDENT>return chr<EOL><DEDENT>try:<EOL><INDENT>options.update(requestOptions)<EOL>"""<STR_LIT>"""<EOL>basestring = (str, bytes)<EOL>"""<STR_LIT>"""<EOL>def findFormat(fmt):<EOL><INDENT>if isinstance(fmt, basestring):<EOL><INDENT>try:<EOL><INDENT>fmt = _names[fmt.upper()]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise (ValueError, '<STR_LIT>' + fmt)<EOL><DEDENT><DEDENT>return fmt<EOL><DEDENT>inFormat = findFormat(inFormat)<EOL>outFormat = findFormat(outFormat)<EOL>"""<STR_LIT>"""<EOL>if not isinstance(text, basestring): <EOL><INDENT>raise (TypeError, "<STR_LIT>")<EOL><DEDENT>def getBlock(format):<EOL><INDENT>if isinstance(format, CharacterBlock):<EOL><INDENT>return format<EOL><DEDENT>else:<EOL><INDENT>return format.block<EOL><DEDENT><DEDENT>inBlock = getBlock(inFormat)<EOL>outBlock = getBlock(outFormat)<EOL>if not inBlock is outBlock:<EOL><INDENT>raise (ValueError, "<STR_LIT>")<EOL><DEDENT>if inFormat is outFormat:<EOL><INDENT>if inFormat._longestEntry == <NUM_LIT:1>:<EOL><INDENT>[inFormat[c] for c in set(text) if not c.isspace()] <EOL>return text<EOL><DEDENT><DEDENT>"""<STR_LIT>"""<EOL>result = inFormat._transliterate(text, outFormat)<EOL>if options['<STR_LIT>']:<EOL><INDENT>result = [asciiEncode(c) for c in result]<EOL><DEDENT>return u'<STR_LIT>'.join(result).encode(options['<STR_LIT>'])<EOL><DEDENT>finally:<EOL><INDENT>resetOptions()<EOL><DEDENT>

Transliterate a text.

    Keyword arguments:
    text -- a unicode string containing the text to be transliterated
    inFormat -- the "from" CharacterBlock or TransliterationScheme, or its name
    outFormat -- the target CharacterBlock or TransliterationScheme, or its name
    requestOptions -- optional dict containing option settings that override the
                      defaults for this request.

    Returns a unicode object containing the text transliterated into the
    target character set.

    Raises:
    ValueError -- unrecognised input or output format.
    KeyError -- a character in text is not a member of inFormat, or has no
    corresponding character defined in outFormat.


return text<EOL>

Make our signature compatible with TransliterationScheme.


def _setupParseTree(self, rowFrom, rowTo, colIndex, tree):

if colIndex == self._longestEntry:<EOL><INDENT>return<EOL><DEDENT>prevchar = None<EOL>rowIndex = rowFrom<EOL>while rowIndex <= rowTo:<EOL><INDENT>if colIndex < len(self._parsedata[rowIndex]):<EOL><INDENT>c = self._parsedata[rowIndex][colIndex]<EOL>if c != prevchar:<EOL><INDENT>tree[c] = {}<EOL>if  prevchar is not None:<EOL><INDENT>self._setupParseTree(rowFrom, rowIndex - <NUM_LIT:1>, colIndex + <NUM_LIT:1>, tree[prevchar])<EOL><DEDENT>rowFrom = rowIndex<EOL>prevchar = c<EOL><DEDENT>if rowIndex == rowTo:<EOL><INDENT>self._setupParseTree(rowFrom, rowIndex, colIndex + <NUM_LIT:1>, tree[prevchar])<EOL><DEDENT><DEDENT>rowIndex = rowIndex + <NUM_LIT:1><EOL><DEDENT>

Build the search tree for multi-character encodings.


def __init__(self, unicodeHexValue, block):

self.isVowel = False<EOL>if unicodeHexValue in DevanagariCharacter._vowelRange:<EOL><INDENT>self.isVowel = True<EOL><DEDENT>self._dependentVowel = None<EOL>if unicodeHexValue in DevanagariCharacter._depVowelRange:<EOL><INDENT>vowel = block[chr(unicodeHexValue - DevanagariCharacter._vowelOffset)]<EOL>vowel._setDependentVowel(unicodeHexValue)<EOL>raise (ValueError) <EOL><DEDENT>TLCharacter.__init__(self, unicodeHexValue, block)<EOL>self.isConsonant = False<EOL>if self.isVowel == Falseand self.chr.isalpha()and self.unicodeHexValue not in (DevanagariCharacter._AVAGRAHA,<EOL>DevanagariCharacter._OM):<EOL><INDENT>self.isConsonant = True<EOL><DEDENT>

Create an object representing a Devanagari character.

        Extends TLCharacter.__init__ to distinguish Devanagari standalone
        vowels, dependent vowels and consonants.

        Raises
        ValueError -- for characters in the Devanagari dependent vowel range.
                      We want these as variants of the corresponding standalone
                      vowels, not as separate characters.


print (transliterate('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'))<EOL>if argv is None:<EOL><INDENT>argv = sys.argv<EOL><DEDENT>try:    <EOL><INDENT>text, inFormat, outFormat = argv[<NUM_LIT:1>:<NUM_LIT:4>]<EOL><DEDENT>except ValueError:<EOL><INDENT>print (main.__doc__)<EOL>return <NUM_LIT:2><EOL><DEDENT>inFormat = inFormat.upper()<EOL>outFormat = outFormat.upper()<EOL>try:<EOL><INDENT>f = open(text)<EOL><DEDENT>except IOError:<EOL><INDENT>print (transliterate(text, inFormat, outFormat))<EOL>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>i = <NUM_LIT:1><EOL>for text in f.readlines():<EOL><INDENT>if len(text) > <NUM_LIT:0> and not text.startswith('<STR_LIT:#>'):<EOL><INDENT>print (transliterate(text, inFormat, outFormat).strip('<STR_LIT:\n>'))<EOL><DEDENT>i = i + <NUM_LIT:1><EOL><DEDENT>f.close()<EOL>return <NUM_LIT:0><EOL><DEDENT>

Call transliterator from a command line.

    python transliterator.py text inputFormat outputFormat

    ... writes the transliterated text to stdout

    text -- the text to be transliterated OR the name of a file containing the text
    inputFormat -- the name of the character block or transliteration scheme that
                   the text is to be transliterated FROM, e.g. 'CYRILLIC', 'IAST'.
                   Not case-sensitive
    outputFormat -- the name of the character block or transliteration scheme that
                   the text is to be transliterated TO, e.g. 'CYRILLIC', 'IAST'.
                   Not case-sensitive


self._git.push('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL>


self._git.tag('<STR_LIT>', value)<EOL>


self._git.commit('<STR_LIT>', message, *args)<EOL>


self._git.branch('<STR_LIT>', '<STR_LIT>')<EOL>


self._git.branch('<STR_LIT>', name)<EOL>


self._git.remote('<STR_LIT>', '<STR_LIT>', url)<EOL>


self._git.rm('<STR_LIT>', path)<EOL>


pass<EOL>

Test set up

This is where you can setup things that you use throughout the tests. This method is called before every test.


handler = logging.StreamHandler()<EOL>handler.setLevel(args.log_level)<EOL>formatter = logging.Formatter(('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'))<EOL>handler.setFormatter(formatter)<EOL>LOGGER.addHandler(handler)<EOL>

This sets up the logging.

Needs the args to get the log level supplied
:param args: The command line arguments


args = get_arguments()<EOL>setup_logging(args)<EOL>version_path = os.path.abspath(os.path.join(<EOL>os.path.dirname(__file__),<EOL>'<STR_LIT:..>',<EOL>'<STR_LIT:..>',<EOL>'<STR_LIT>'<EOL>))<EOL>try:<EOL><INDENT>version_text = open(version_path).read().strip()<EOL><DEDENT>except Exception:<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>try:<EOL><INDENT>semver.parse(version_text)<EOL><DEDENT>except ValueError:<EOL><INDENT>print(('<STR_LIT>'<EOL>'<STR_LIT>').format(version_text))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>new_version = version_text<EOL>if args.version:<EOL><INDENT>try:<EOL><INDENT>if semver.parse(args.version):<EOL><INDENT>new_version = args.version<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>print('<STR_LIT>'.format(args.version))<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>elif args.bump_major:<EOL><INDENT>new_version = semver.bump_major(version_text)<EOL><DEDENT>elif args.bump_minor:<EOL><INDENT>new_version = semver.bump_minor(version_text)<EOL><DEDENT>elif args.bump_patch:<EOL><INDENT>new_version = semver.bump_patch(version_text)<EOL><DEDENT>try:<EOL><INDENT>with open(version_path, '<STR_LIT:w>') as version_file:<EOL><INDENT>version_file.write(new_version)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>print('<STR_LIT>')<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>print(new_version)<EOL>

Main method.

This method holds what you want to execute when
the script is run on command line.


match = _REGEX.match(version)<EOL>if match is None:<EOL><INDENT>raise ValueError('<STR_LIT>' % version)<EOL><DEDENT>verinfo = match.groupdict()<EOL>verinfo['<STR_LIT>'] = int(verinfo['<STR_LIT>'])<EOL>verinfo['<STR_LIT>'] = int(verinfo['<STR_LIT>'])<EOL>verinfo['<STR_LIT>'] = int(verinfo['<STR_LIT>'])<EOL>return verinfo<EOL>

Parse version to major, minor, patch, pre-release, build parts.


async def websocket_accept(self, message, stream_name):

is_first = not self.applications_accepting_frames<EOL>self.applications_accepting_frames.add(stream_name)<EOL>if is_first:<EOL><INDENT>await self.accept()<EOL><DEDENT>

Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket
frames.


async def websocket_close(self, message, stream_name):

if stream_name in self.applications_accepting_frames:<EOL><INDENT>self.applications_accepting_frames.remove(stream_name)<EOL><DEDENT>if self.closing:<EOL><INDENT>return<EOL><DEDENT>if not self.applications_accepting_frames:<EOL><INDENT>await self.close(message.get("<STR_LIT:code>"))<EOL><DEDENT>

Handle downstream `websocket.close` message.

Will disconnect this upstream application from receiving any new frames.

If there are not more upstream applications accepting messages it will then call `close`.