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

Consumes an unsigned 64bit integer number.

        Returns:
          The integer parsed.

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


try:<EOL><INDENT>result = ParseFloat(self.token)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes an floating point number.

        Returns:
          The number parsed.

        Raises:
          ParseError: If a floating point number couldn't be consumed.


try:<EOL><INDENT>result = ParseBool(self.token)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consumes a boolean value.

        Returns:
          The bool parsed.

        Raises:
          ParseError: If a boolean value couldn't be consumed.


the_bytes = self.ConsumeByteString()<EOL>try:<EOL><INDENT>return six.text_type(the_bytes, '<STR_LIT:utf-8>')<EOL><DEDENT>except UnicodeDecodeError as e:<EOL><INDENT>raise self._StringParseError(e)<EOL><DEDENT>

Consumes a string value.

        Returns:
          The string parsed.

        Raises:
          ParseError: If a string value couldn't be consumed.


the_list = [self._ConsumeSingleByteString()]<EOL>while self.token and self.token[<NUM_LIT:0>] in _QUOTES:<EOL><INDENT>the_list.append(self._ConsumeSingleByteString())<EOL><DEDENT>return b'<STR_LIT>'.join(the_list)<EOL>

Consumes a byte array value.

        Returns:
          The array parsed (as a string).

        Raises:
          ParseError: If a byte array value couldn't be consumed.


text = self.token<EOL>if len(text) < <NUM_LIT:1> or text[<NUM_LIT:0>] not in _QUOTES:<EOL><INDENT>raise self._ParseError('<STR_LIT>' % (text,))<EOL><DEDENT>if len(text) < <NUM_LIT:2> or text[-<NUM_LIT:1>] != text[<NUM_LIT:0>]:<EOL><INDENT>raise self._ParseError('<STR_LIT>' % (text,))<EOL><DEDENT>try:<EOL><INDENT>result = text_encoding.CUnescape(text[<NUM_LIT:1>:-<NUM_LIT:1>])<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise self._ParseError(str(e))<EOL><DEDENT>self.NextToken()<EOL>return result<EOL>

Consume one token of a string literal.

        String literals (whether bytes or text) can come in multiple adjacent
        tokens which are automatically concatenated, like in C or Python.  This
        method only consumes one token.

        Returns:
          The token parsed.
        Raises:
          ParseError: When the wrong format data is found.


return ParseError('<STR_LIT>' % (<EOL>self._previous_line + <NUM_LIT:1>, self._previous_column + <NUM_LIT:1>, message))<EOL>

Creates and *returns* a ParseError for the previously read token.

        Args:
          message: A message to set for the exception.

        Returns:
          A ParseError instance.


return ParseError('<STR_LIT>' % (<EOL>self._line + <NUM_LIT:1>, self._column + <NUM_LIT:1>, message))<EOL>

Creates and *returns* a ParseError for the current token.


self._previous_line = self._line<EOL>self._previous_column = self._column<EOL>self._column += len(self.token)<EOL>self._SkipWhitespace()<EOL>if not self._more_lines:<EOL><INDENT>self.token = '<STR_LIT>'<EOL>return<EOL><DEDENT>match = self._TOKEN.match(self._current_line, self._column)<EOL>if match:<EOL><INDENT>token = match.group(<NUM_LIT:0>)<EOL>self.token = token<EOL><DEDENT>else:<EOL><INDENT>self.token = self._current_line[self._column]<EOL><DEDENT>


js = _MessageToJsonObject(message, including_default_value_fields)<EOL>return json.dumps(js, indent=<NUM_LIT:2>)<EOL>

Converts protobuf message to JSON format.

    Args:
      message: The protocol buffers message instance to serialize.
      including_default_value_fields: If True, singular primitive fields,
          repeated fields, and map fields will always be serialized.  If
          False, only serialize non-empty fields.  Singular message fields
          and oneof fields are not affected by this option.

    Returns:
      A string containing the JSON formatted protocol buffer message.


message_descriptor = message.DESCRIPTOR<EOL>full_name = message_descriptor.full_name<EOL>if _IsWrapperMessage(message_descriptor):<EOL><INDENT>return _WrapperMessageToJsonObject(message)<EOL><DEDENT>if full_name in _WKTJSONMETHODS:<EOL><INDENT>return _WKTJSONMETHODS[full_name][<NUM_LIT:0>](<EOL>message, including_default_value_fields)<EOL><DEDENT>js = {}<EOL>return _RegularMessageToJsonObject(<EOL>message, js, including_default_value_fields)<EOL>

Converts message to an object according to Proto3 JSON Specification.


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.


def _FieldToJsonObject(<EOL>field, value, including_default_value_fields=False):

if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>return _MessageToJsonObject(value, including_default_value_fields)<EOL><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>enum_value = field.enum_type.values_by_number.get(value, None)<EOL>if enum_value is not None:<EOL><INDENT>return enum_value.name<EOL><DEDENT>else:<EOL><INDENT>raise SerializeToJsonError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:<EOL><INDENT>if field.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>return base64.b64encode(value).decode('<STR_LIT:utf-8>')<EOL><DEDENT>else:<EOL><INDENT>return value<EOL><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:<EOL><INDENT>return bool(value)<EOL><DEDENT>elif field.cpp_type in _INT64_TYPES:<EOL><INDENT>return str(value)<EOL><DEDENT>elif field.cpp_type in _FLOAT_TYPES:<EOL><INDENT>if math.isinf(value):<EOL><INDENT>if value < <NUM_LIT:0.0>:<EOL><INDENT>return _NEG_INFINITY<EOL><DEDENT>else:<EOL><INDENT>return _INFINITY<EOL><DEDENT><DEDENT>if math.isnan(value):<EOL><INDENT>return _NAN<EOL><DEDENT><DEDENT>return value<EOL>

Converts field value 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.


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

Converts message by ToJsonString according to Proto3 JSON Specification.


which = message.WhichOneof('<STR_LIT>')<EOL>if which is None or which == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>if which == '<STR_LIT>':<EOL><INDENT>return _ListValueMessageToJsonObject(message.list_value)<EOL><DEDENT>if which == '<STR_LIT>':<EOL><INDENT>value = message.struct_value<EOL><DEDENT>else:<EOL><INDENT>value = getattr(message, which)<EOL><DEDENT>oneof_descriptor = message.DESCRIPTOR.fields_by_name[which]<EOL>return _FieldToJsonObject(oneof_descriptor, value)<EOL>

Converts Value message according to Proto3 JSON Specification.


return [_ValueMessageToJsonObject(value)<EOL>for value in message.values]<EOL>

Converts ListValue message according to Proto3 JSON Specification.


fields = message.fields<EOL>ret = {}<EOL>for key in fields:<EOL><INDENT>ret[key] = _ValueMessageToJsonObject(fields[key])<EOL><DEDENT>return ret<EOL>

Converts Struct message according to Proto3 JSON Specification.


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.


names = []<EOL>message_descriptor = message.DESCRIPTOR<EOL>for name in js:<EOL><INDENT>try:<EOL><INDENT>field = message_descriptor.fields_by_camelcase_name.get(name, None)<EOL>if not field:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(<EOL>message_descriptor.full_name, name))<EOL><DEDENT>if name in names:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(<EOL>message.DESCRIPTOR.full_name, name))<EOL><DEDENT>names.append(name)<EOL>if field.containing_oneof is not None:<EOL><INDENT>oneof_name = field.containing_oneof.name<EOL>if oneof_name in names:<EOL><INDENT>raise ParseError('<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>message.DESCRIPTOR.full_name, oneof_name))<EOL><DEDENT>names.append(oneof_name)<EOL><DEDENT>value = js[name]<EOL>if value is None:<EOL><INDENT>message.ClearField(field.name)<EOL>continue<EOL><DEDENT>if _IsMapEntry(field):<EOL><INDENT>message.ClearField(field.name)<EOL>_ConvertMapFieldValue(value, message, field)<EOL><DEDENT>elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:<EOL><INDENT>message.ClearField(field.name)<EOL>if not isinstance(value, list):<EOL><INDENT>raise ParseError('<STR_LIT>'<EOL>'<STR_LIT>'.format(name, value))<EOL><DEDENT>if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>for item in value:<EOL><INDENT>sub_message = getattr(message, field.name).add()<EOL>if (item is None and<EOL>sub_message.DESCRIPTOR.full_name != '<STR_LIT>'):<EOL><INDENT>raise ParseError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>_ConvertMessage(item, sub_message)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>for item in value:<EOL><INDENT>if item is None:<EOL><INDENT>raise ParseError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>getattr(message, field.name).append(<EOL>_ConvertScalarFieldValue(item, field))<EOL><DEDENT><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>sub_message = getattr(message, field.name)<EOL>_ConvertMessage(value, sub_message)<EOL><DEDENT>else:<EOL><INDENT>setattr(message, field.name, _ConvertScalarFieldValue(value, field))<EOL><DEDENT><DEDENT>except ParseError as e:<EOL><INDENT>if field and field.containing_oneof is None:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(name, e))<EOL><DEDENT>else:<EOL><INDENT>raise ParseError(str(e))<EOL><DEDENT><DEDENT>except ValueError as e:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(name, e))<EOL><DEDENT>except TypeError as e:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(name, e))<EOL><DEDENT><DEDENT>

Convert field value pairs into regular message.

    Args:
      js: A JSON object to convert the field value pairs.
      message: A regular protocol message to record the data.

    Raises:
      ParseError: In case of problems converting.


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 isinstance(value, dict) and not value:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>type_url = value['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ParseError('<STR_LIT>')<EOL><DEDENT>sub_message = _CreateMessageFromTypeUrl(type_url)<EOL>message_descriptor = sub_message.DESCRIPTOR<EOL>full_name = message_descriptor.full_name<EOL>if _IsWrapperMessage(message_descriptor):<EOL><INDENT>_ConvertWrapperMessage(value['<STR_LIT:value>'], sub_message)<EOL><DEDENT>elif full_name in _WKTJSONMETHODS:<EOL><INDENT>_WKTJSONMETHODS[full_name][<NUM_LIT:1>](value['<STR_LIT:value>'], sub_message)<EOL><DEDENT>else:<EOL><INDENT>del value['<STR_LIT>']<EOL>_ConvertFieldValuePair(value, sub_message)<EOL><DEDENT>message.value = sub_message.SerializeToString()<EOL>message.type_url = type_url<EOL>

Convert a JSON representation into Any message.


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

Convert a JSON representation into message with FromJsonString.


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.


if not isinstance(value, list):<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(value))<EOL><DEDENT>message.ClearField('<STR_LIT>')<EOL>for item in value:<EOL><INDENT>_ConvertValueMessage(item, message.values.add())<EOL><DEDENT>

Convert a JSON representation into ListValue message.


if not isinstance(value, dict):<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(value))<EOL><DEDENT>for key in value:<EOL><INDENT>_ConvertValueMessage(value[key], message.fields[key])<EOL><DEDENT>return<EOL>

Convert a JSON representation into Struct message.


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.


def _ConvertMapFieldValue(value, message, field):

if not isinstance(value, dict):<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'.format(<EOL>field.name, value))<EOL><DEDENT>key_field = field.message_type.fields_by_name['<STR_LIT:key>']<EOL>value_field = field.message_type.fields_by_name['<STR_LIT:value>']<EOL>for key in value:<EOL><INDENT>key_value = _ConvertScalarFieldValue(key, key_field, True)<EOL>if value_field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:<EOL><INDENT>_ConvertMessage(value[key], getattr(message, field.name)[key_value])<EOL><DEDENT>else:<EOL><INDENT>getattr(message, field.name)[key_value] = _ConvertScalarFieldValue(<EOL>value[key], value_field)<EOL><DEDENT><DEDENT>

Convert map field value for a message map field.

    Args:
      value: A JSON object to convert the map field value.
      message: A protocol message to record the converted data.
      field: The descriptor of the map field to be converted.

    Raises:
      ParseError: In case of convert problems.


def _ConvertScalarFieldValue(value, field, require_str=False):

if field.cpp_type in _INT_TYPES:<EOL><INDENT>return _ConvertInteger(value)<EOL><DEDENT>elif field.cpp_type in _FLOAT_TYPES:<EOL><INDENT>return _ConvertFloat(value)<EOL><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:<EOL><INDENT>return _ConvertBool(value, require_str)<EOL><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:<EOL><INDENT>if field.type == descriptor.FieldDescriptor.TYPE_BYTES:<EOL><INDENT>return base64.b64decode(value)<EOL><DEDENT>else:<EOL><INDENT>return value<EOL><DEDENT><DEDENT>elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:<EOL><INDENT>enum_value = field.enum_type.values_by_name.get(value, None)<EOL>if enum_value is None:<EOL><INDENT>raise ParseError(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(<EOL>field.enum_type.full_name, value))<EOL><DEDENT>return enum_value.number<EOL><DEDENT>

Convert a single scalar field value.

    Args:
      value: A scalar value to convert the scalar field value.
      field: The descriptor of the field to convert.
      require_str: If True, the field value must be a str.

    Returns:
      The converted scalar field value

    Raises:
      ParseError: In case of convert problems.


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.


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>


if require_str:<EOL><INDENT>if value == '<STR_LIT:true>':<EOL><INDENT>return True<EOL><DEDENT>elif value == '<STR_LIT:false>':<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>raise ParseError('<STR_LIT>'.format(value))<EOL><DEDENT><DEDENT>if not isinstance(value, bool):<EOL><INDENT>raise ParseError('<STR_LIT>')<EOL><DEDENT>return value<EOL>

Convert a boolean value.

    Args:
      value: A scalar value to convert.
      require_str: If True, value must be a str.

    Returns:
      The bool parsed.

    Raises:
      ParseError: If a boolean value couldn't be consumed.


return _DEFAULT<EOL>


self._symbols = {}<EOL>self._symbols_by_file = {}<EOL>self.pool = pool or descriptor_pool.Default()<EOL>


desc = message.DESCRIPTOR<EOL>self._symbols[desc.full_name] = message<EOL>if desc.file.name not in self._symbols_by_file:<EOL><INDENT>self._symbols_by_file[desc.file.name] = {}<EOL><DEDENT>self._symbols_by_file[desc.file.name][desc.full_name] = message<EOL>self.pool.AddDescriptor(desc)<EOL>return message<EOL>

Registers the given message type in the local database.

        Args:
          message: a message.Message, to be registered.

        Returns:
          The provided message.


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.


self.pool.AddFileDescriptor(file_descriptor)<EOL>

Registers the given file descriptor in the local database.

        Args:
          file_descriptor: a descriptor.FileDescriptor.

        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.


return self.GetSymbol(descriptor.full_name)<EOL>

Builds a proto2 message class based on the passed in descriptor.

        Passing a descriptor with a fully qualified name matching a previous
        invocation will cause the same class to be returned.

        Args:
          descriptor: The descriptor to build from.

        Returns:
          A class describing the passed in descriptor.


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.


proto_descriptor = factory.pool.FindMessageTypeByName(full_name)<EOL>proto_cls = factory.GetPrototype(proto_descriptor)<EOL>return proto_cls<EOL>

Get a proto class from the MessageFactory by name.

    Args:
      factory: a MessageFactory instance.
      full_name: str, the fully qualified name of the proto type.
    Returns:
      A class, for the type identified by full_name.
    Raises:
      KeyError, if the proto is not found in the factory's descriptor pool.


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 _MakeFileDescriptorProto(proto_file_name, full_name, field_items):

package, name = full_name.rsplit('<STR_LIT:.>', <NUM_LIT:1>)<EOL>file_proto = descriptor_pb2.FileDescriptorProto()<EOL>file_proto.name = os.path.join(package.replace('<STR_LIT:.>', '<STR_LIT:/>'), proto_file_name)<EOL>file_proto.package = package<EOL>desc_proto = file_proto.message_type.add()<EOL>desc_proto.name = name<EOL>for f_number, (f_name, f_type) in enumerate(field_items, <NUM_LIT:1>):<EOL><INDENT>field_proto = desc_proto.field.add()<EOL>field_proto.name = f_name<EOL>field_proto.number = f_number<EOL>field_proto.label = descriptor_pb2.FieldDescriptorProto.LABEL_OPTIONAL<EOL>field_proto.type = f_type<EOL><DEDENT>return file_proto<EOL>

Populate FileDescriptorProto for MessageFactory's DescriptorPool.


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.


capitalize_next = False<EOL>result = []<EOL>for c in name:<EOL><INDENT>if c == '<STR_LIT:_>':<EOL><INDENT>if result:<EOL><INDENT>capitalize_next = True<EOL><DEDENT><DEDENT>elif capitalize_next:<EOL><INDENT>result.append(c.upper())<EOL>capitalize_next = False<EOL><DEDENT>else:<EOL><INDENT>result += c<EOL><DEDENT><DEDENT>if result and result[<NUM_LIT:0>].isupper():<EOL><INDENT>result[<NUM_LIT:0>] = result[<NUM_LIT:0>].lower()<EOL><DEDENT>return '<STR_LIT>'.join(result)<EOL>

Converts name to camel-case and returns it.


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.


def __init__(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>

Initialize the descriptor given its options message and the name of the
        class of the options message. The name of the class is required in case
        the options message is None and has to be created.


def _SetOptions(self, options, options_class_name):

Sets the descriptor's options

        This function is used in generated proto2 files to update descriptor
        options. 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, 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.


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.


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.


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.


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

Copies this to a descriptor_pb2.DescriptorProto.

        Args:
          proto: An empty descriptor_pb2.DescriptorProto.


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.


try:<EOL><INDENT>return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise TypeTransformationError('<STR_LIT>' % proto_type)<EOL><DEDENT>

Converts from a Python proto type to a C++ Proto Type.

        The Python ProtocolBuffer classes specify both the 'Python' datatype and the
        'C++' datatype - and they're not the same. This helper method should
        translate from one to another.

        Args:
          proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*)
        Returns:
          descriptor.FieldDescriptor.CPPTYPE_*, the C++ type.
        Raises:
          TypeTransformationError: when the Python proto type isn't known.


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

super(EnumDescriptor, self).__init__(<EOL>options, '<STR_LIT>', name, full_name, file,<EOL>containing_type, serialized_start=serialized_start,<EOL>serialized_end=serialized_end)<EOL>self.values = values<EOL>for value in self.values:<EOL><INDENT>value.type = self<EOL><DEDENT>self.values_by_name = dict((v.name, v) for v in values)<EOL>self.values_by_number = dict((v.number, v) for v in values)<EOL>

Arguments are as described in the attribute description above.

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


<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, index, number, type=None, options=None):

super(EnumValueDescriptor, self).__init__(options, '<STR_LIT>')<EOL>self.name = name<EOL>self.index = index<EOL>self.number = number<EOL>self.type = type<EOL>

Arguments are as described in the attribute description above.


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>


for method in self.methods:<EOL><INDENT>if name == method.name:<EOL><INDENT>return method<EOL><DEDENT><DEDENT>return None<EOL>

Searches for the specified method, and returns its descriptor.


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

Copies this to a descriptor_pb2.ServiceDescriptorProto.

        Args:
          proto: An empty descriptor_pb2.ServiceDescriptorProto.


def __init__(self, name, full_name, index, containing_service,<EOL>input_type, output_type, options=None):

super(MethodDescriptor, self).__init__(options, '<STR_LIT>')<EOL>self.name = name<EOL>self.full_name = full_name<EOL>self.index = index<EOL>self.containing_service = containing_service<EOL>self.input_type = input_type<EOL>self.output_type = output_type<EOL>

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

        Note that containing_service may be None, and may be set later if necessary.


def __init__(self, name, package, options=None, serialized_pb=None,<EOL>dependencies=None, public_dependencies=None,<EOL>syntax=None, pool=None):

super(FileDescriptor, self).__init__(options, '<STR_LIT>')<EOL>if pool is None:<EOL><INDENT>from typy.google.protobuf import descriptor_pool<EOL>pool = descriptor_pool.Default()<EOL><DEDENT>self.pool = pool<EOL>self.message_types_by_name = {}<EOL>self.name = name<EOL>self.package = package<EOL>self.syntax = syntax or "<STR_LIT>"<EOL>self.serialized_pb = serialized_pb<EOL>self.enum_types_by_name = {}<EOL>self.extensions_by_name = {}<EOL>self.dependencies = (dependencies or [])<EOL>self.public_dependencies = (public_dependencies or [])<EOL>if (api_implementation.Type() == '<STR_LIT>' and<EOL>self.serialized_pb is not None):<EOL><INDENT>_message.default_pool.AddSerializedFile(self.serialized_pb)<EOL><DEDENT>


proto.ParseFromString(self.serialized_pb)<EOL>

Copies this to a descriptor_pb2.FileDescriptorProto.

        Args:
          proto: An empty descriptor_pb2.FileDescriptorProto.


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.


self.pool = pool or descriptor_pool.DescriptorPool()<EOL>self._classes = {}<EOL>


if descriptor.full_name not in self._classes:<EOL><INDENT>descriptor_name = descriptor.name<EOL>if str is bytes:  <EOL><INDENT>descriptor_name = descriptor.name.encode('<STR_LIT:ascii>', '<STR_LIT:ignore>')<EOL><DEDENT>result_class = reflection.GeneratedProtocolMessageType(<EOL>descriptor_name,<EOL>(message.Message,),<EOL>{'<STR_LIT>': descriptor, '<STR_LIT>': None})<EOL>self._classes[descriptor.full_name] = result_class<EOL>for field in descriptor.fields:<EOL><INDENT>if field.message_type:<EOL><INDENT>self.GetPrototype(field.message_type)<EOL><DEDENT><DEDENT>for extension in result_class.DESCRIPTOR.extensions:<EOL><INDENT>if extension.containing_type.full_name not in self._classes:<EOL><INDENT>self.GetPrototype(extension.containing_type)<EOL><DEDENT>extended_class = self._classes[extension.containing_type.full_name]<EOL>extended_class.RegisterExtension(extension)<EOL><DEDENT><DEDENT>return self._classes[descriptor.full_name]<EOL>

Builds a proto2 message class based on the passed in descriptor.

        Passing a descriptor with a fully qualified name matching a previous
        invocation will cause the same class to be returned.

        Args:
          descriptor: The descriptor to build from.

        Returns:
          A class describing the passed in descriptor.


result = {}<EOL>for file_name in files:<EOL><INDENT>file_desc = self.pool.FindFileByName(file_name)<EOL>for name, msg in file_desc.message_types_by_name.items():<EOL><INDENT>if file_desc.package:<EOL><INDENT>full_name = '<STR_LIT:.>'.join([file_desc.package, name])<EOL><DEDENT>else:<EOL><INDENT>full_name = msg.name<EOL><DEDENT>result[full_name] = self.GetPrototype(<EOL>self.pool.FindMessageTypeByName(full_name))<EOL><DEDENT>for name, extension in file_desc.extensions_by_name.items():<EOL><INDENT>if extension.containing_type.full_name not in self._classes:<EOL><INDENT>self.GetPrototype(extension.containing_type)<EOL><DEDENT>extended_class = self._classes[extension.containing_type.full_name]<EOL>extended_class.RegisterExtension(extension)<EOL><DEDENT><DEDENT>return result<EOL>

Gets all the messages from a specified file.

        This will find and resolve dependencies, failing if the descriptor
        pool cannot satisfy them.

        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.


raise NotImplementedError<EOL>

Recursively compares two messages by value and structure.


raise NotImplementedError<EOL>

Outputs a human-readable representation of the message.


raise NotImplementedError<EOL>


raise NotImplementedError<EOL>

Merges the contents of the specified message into current message.

        This method merges the contents of the specified message into the current
        message. Singular fields that are set in the specified message overwrite
        the corresponding fields in the current message. Repeated fields are
        appended. Singular sub-messages and groups are recursively merged.

        Args:
          other_msg: Message to merge into the current 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>

Clears all data that was set in the message.


raise NotImplementedError<EOL>

Mark this as present in the parent.

        This normally happens automatically when you assign a field of a
        sub-message, but sometimes you want to make the sub-message
        present while keeping it empty.  If you find yourself using this,
        you may want to reconsider your design.


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).


raise NotImplementedError<EOL>

Merges serialized protocol buffer data into this message.

        When we find a field in |serialized| that is already present
        in this message:
          - If it's a "repeated" field, we append to the end of our list.
          - Else, if it's a scalar, we overwrite our field.
          - Else, (it's a nonrepeated composite), we recursively merge
            into the existing composite.

        TODO(robinson): Document handling of unknown fields.

        Args:
          serialized: Any object that allows us to call buffer(serialized)
            to access a string of bytes using the buffer interface.

        TODO(robinson): When we switch to a helper, this will return None.

        Returns:
          The number of bytes read from |serialized|.
          For non-group messages, this will always be len(serialized),
          but for messages which are actually groups, this will
          generally be less than len(serialized), since we must
          stop when we reach an END_GROUP tag.  Note that if
          we *do* stop because of an END_GROUP tag, the number
          of bytes returned does not include the bytes
          for the END_GROUP tag information.


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>

Serializes the protocol message to a binary string.

        Returns:
          A binary string representation of the message if all of the required
          fields in the message are set (i.e. the message is initialized).

        Raises:
          message.EncodeError if the message isn't initialized.


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.


raise NotImplementedError<EOL>

Returns a list of (FieldDescriptor, value) tuples for all
        fields in the message which are not empty.  A singular field is non-empty
        if HasField() would return true, and a repeated field is non-empty if
        it contains at least one element.  The fields are ordered by field
        number


raise NotImplementedError<EOL>

Checks if a certain field is set for the message, or if any field inside
        a oneof group is set.  Note that if the field_name is not defined in the
        message descriptor, ValueError will be raised.


raise NotImplementedError<EOL>

Clears the contents of a given field, or the field set inside a oneof
        group.  If the name neither refers to a defined field or oneof group,
        ValueError is raised.


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>

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


raise NotImplementedError<EOL>

Internal method used by the protocol message implementation.
        Clients should not call this directly.

        Sets a listener that this message will call on certain state transitions.

        The purpose of this method is to register back-edges from children to
        parents at runtime, for the purpose of setting "has" bits and
        byte-size-dirty bits in the parent and ancestor objects whenever a child or
        descendant object is modified.

        If the client wants to disconnect this Message from the object tree, she
        explicitly sets callback to None.

        If message_listener is None, unregisters any existing listener.  Otherwise,
        message_listener must implement the MessageListener interface in
        internal/message_listener.py, and we discard any listener registered
        via a previous _SetListener() call.


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


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


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.


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.


self._internal_db.Add(file_desc_proto)<EOL>

Adds the FileDescriptorProto and its types to this pool.

        Args:
          file_desc_proto: The FileDescriptorProto to add.


<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.


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.


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

Adds an EnumDescriptor to the pool.

        This method also registers the FileDescriptor associated with the message.

        Args:
          enum_desc: An EnumDescriptor.


if not isinstance(file_desc, descriptor.FileDescriptor):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>self._file_descriptors[file_desc.name] = file_desc<EOL>

Adds a FileDescriptor to the pool, non-recursively.

        If the FileDescriptor contains messages or enums, the caller must explicitly
        register them.

        Args:
          file_desc: A FileDescriptor.


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.


symbol = _NormalizeFullyQualifiedName(symbol)<EOL>try:<EOL><INDENT>return self._descriptors[symbol].file<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return self._enum_descriptors[symbol].file<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>file_proto = self._internal_db.FindFileContainingSymbol(symbol)<EOL><DEDENT>except KeyError as error:<EOL><INDENT>if self._descriptor_db:<EOL><INDENT>file_proto = self._descriptor_db.FindFileContainingSymbol(symbol)<EOL><DEDENT>else:<EOL><INDENT>raise error<EOL><DEDENT><DEDENT>if not file_proto:<EOL><INDENT>raise KeyError('<STR_LIT>' % symbol)<EOL><DEDENT>return self._ConvertFileProtoToFileDescriptor(file_proto)<EOL>

Gets the FileDescriptor for the file containing the specified symbol.

        Args:
          symbol: The name of the symbol to search for.

        Returns:
          A FileDescriptor that contains the specified symbol.

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


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.


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

Loads the named enum descriptor from the pool.

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

        Returns:
          The enum descriptor for the named type.


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.


full_name = _NormalizeFullyQualifiedName(full_name)<EOL>message_name, _, extension_name = full_name.rpartition('<STR_LIT:.>')<EOL>try:<EOL><INDENT>scope = self.FindMessageTypeByName(message_name)<EOL><DEDENT>except KeyError:<EOL><INDENT>scope = self.FindFileContainingSymbol(full_name)<EOL><DEDENT>return scope.extensions_by_name[extension_name]<EOL>

Loads the named extension descriptor from the pool.

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

        Returns:
          A FieldDescriptor, describing the named extension.


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 _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None,<EOL>scope=None, syntax=None):

if package:<EOL><INDENT>desc_name = '<STR_LIT:.>'.join((package, desc_proto.name))<EOL><DEDENT>else:<EOL><INDENT>desc_name = desc_proto.name<EOL><DEDENT>if file_desc is None:<EOL><INDENT>file_name = None<EOL><DEDENT>else:<EOL><INDENT>file_name = file_desc.name<EOL><DEDENT>if scope is None:<EOL><INDENT>scope = {}<EOL><DEDENT>nested = [<EOL>self._ConvertMessageDescriptor(<EOL>nested, desc_name, file_desc, scope, syntax)<EOL>for nested in desc_proto.nested_type]<EOL>enums = [<EOL>self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope)<EOL>for enum in desc_proto.enum_type]<EOL>fields = [self._MakeFieldDescriptor(field, desc_name, index)<EOL>for index, field in enumerate(desc_proto.field)]<EOL>extensions = [<EOL>self._MakeFieldDescriptor(extension, desc_name, index,<EOL>is_extension=True)<EOL>for index, extension in enumerate(desc_proto.extension)]<EOL>oneofs = [<EOL>descriptor.OneofDescriptor(desc.name, '<STR_LIT:.>'.join((desc_name, desc.name)),<EOL>index, None, [])<EOL>for index, desc in enumerate(desc_proto.oneof_decl)]<EOL>extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range]<EOL>if extension_ranges:<EOL><INDENT>is_extendable = True<EOL><DEDENT>else:<EOL><INDENT>is_extendable = False<EOL><DEDENT>desc = descriptor.Descriptor(<EOL>name=desc_proto.name,<EOL>full_name=desc_name,<EOL>filename=file_name,<EOL>containing_type=None,<EOL>fields=fields,<EOL>oneofs=oneofs,<EOL>nested_types=nested,<EOL>enum_types=enums,<EOL>extensions=extensions,<EOL>options=desc_proto.options,<EOL>is_extendable=is_extendable,<EOL>extension_ranges=extension_ranges,<EOL>file=file_desc,<EOL>serialized_start=None,<EOL>serialized_end=None,<EOL>syntax=syntax)<EOL>for nested in desc.nested_types:<EOL><INDENT>nested.containing_type = desc<EOL><DEDENT>for enum in desc.enum_types:<EOL><INDENT>enum.containing_type = desc<EOL><DEDENT>for field_index, field_desc in enumerate(desc_proto.field):<EOL><INDENT>if field_desc.HasField('<STR_LIT>'):<EOL><INDENT>oneof_index = field_desc.oneof_index<EOL>oneofs[oneof_index].fields.append(fields[field_index])<EOL>fields[field_index].containing_oneof = oneofs[oneof_index]<EOL><DEDENT><DEDENT>scope[_PrefixWithDot(desc_name)] = desc<EOL>self._descriptors[desc_name] = desc<EOL>return desc<EOL>

Adds the proto to the pool in the specified package.

        Args:
          desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
          package: The package the proto should be located in.
          file_desc: The file containing this message.
          scope: Dict mapping short and full symbols to message and enum types.

        Returns:
          The added descriptor.


def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,<EOL>containing_type=None, scope=None):

if package:<EOL><INDENT>enum_name = '<STR_LIT:.>'.join((package, enum_proto.name))<EOL><DEDENT>else:<EOL><INDENT>enum_name = enum_proto.name<EOL><DEDENT>if file_desc is None:<EOL><INDENT>file_name = None<EOL><DEDENT>else:<EOL><INDENT>file_name = file_desc.name<EOL><DEDENT>values = [self._MakeEnumValueDescriptor(value, index)<EOL>for index, value in enumerate(enum_proto.value)]<EOL>desc = descriptor.EnumDescriptor(name=enum_proto.name,<EOL>full_name=enum_name,<EOL>filename=file_name,<EOL>file=file_desc,<EOL>values=values,<EOL>containing_type=containing_type,<EOL>options=enum_proto.options)<EOL>scope['<STR_LIT>' % enum_name] = desc<EOL>self._enum_descriptors[enum_name] = desc<EOL>return desc<EOL>

Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.

        Args:
          enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
          package: Optional package name for the new message EnumDescriptor.
          file_desc: The file containing the enum descriptor.
          containing_type: The type containing this enum.
          scope: Scope containing available types.

        Returns:
          The added descriptor


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


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.


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.


def _MakeEnumValueDescriptor(self, value_proto, index):

return descriptor.EnumValueDescriptor(<EOL>name=value_proto.name,<EOL>index=index,<EOL>number=value_proto.number,<EOL>options=value_proto.options,<EOL>type=None)<EOL>

Creates a enum value descriptor object from a enum value proto.

        Args:
          value_proto: The proto describing the enum value.
          index: The index of the enum value.

        Returns:
          An initialized EnumValueDescriptor object.


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.


for dependency in dependencies:<EOL><INDENT>dep_desc = self.FindFileByName(dependency)<EOL>yield dep_desc<EOL>for parent_dep in dep_desc.dependencies:<EOL><INDENT>yield parent_dep<EOL><DEDENT><DEDENT>

Recursively finds dependencies for file protos.

        Args:
          dependencies: The names of the files being depended on.

        Yields:
          Each direct and indirect dependency.


def _GetTypeFromScope(self, package, type_name, scope):

if type_name not in scope:<EOL><INDENT>components = _PrefixWithDot(package).split('<STR_LIT:.>')<EOL>while components:<EOL><INDENT>possible_match = '<STR_LIT:.>'.join(components + [type_name])<EOL>if possible_match in scope:<EOL><INDENT>type_name = possible_match<EOL>break<EOL><DEDENT>else:<EOL><INDENT>components.pop(-<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>return scope[type_name]<EOL>

Finds a given type name in the current scope.

        Args:
          package: The package the proto should be located in.
          type_name: The name of the type to be found in the scope.
          scope: Dict mapping short and full symbols to message and enum types.

        Returns:
          The descriptor for the requested type.


result_class = MakeClass(descriptor)<EOL>new_msg = result_class()<EOL>new_msg.ParseFromString(byte_str)<EOL>return new_msg<EOL>

Generate a new Message instance from this Descriptor and a byte string.

    Args:
      descriptor: Protobuf Descriptor object
      byte_str: Serialized protocol buffer byte string

    Returns:
      Newly created protobuf Message object.


attributes = {}<EOL>for name, nested_type in descriptor.nested_types_by_name.items():<EOL><INDENT>attributes[name] = MakeClass(nested_type)<EOL><DEDENT>attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor<EOL>return GeneratedProtocolMessageType(str(descriptor.name), (message.Message,),<EOL>attributes)<EOL>

Construct a class object for a protobuf described by descriptor.

    Composite descriptors are handled by defining the new class as a member of the
    parent class, recursing as deep as necessary.
    This is the dynamic equivalent to:

    class Parent(message.Message):
      __metaclass__ = GeneratedProtocolMessageType
      DESCRIPTOR = descriptor
      class Child(message.Message):
        __metaclass__ = GeneratedProtocolMessageType
        DESCRIPTOR = descriptor.nested_types[0]

    Sample usage:
      file_descriptor = descriptor_pb2.FileDescriptorProto()
      file_descriptor.ParseFromString(proto2_string)
      msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
      msg_class = reflection.MakeClass(msg_descriptor)
      msg = msg_class()

    Args:
      descriptor: A descriptor.Descriptor object describing the protobuf.
    Returns:
      The Message class object described by the descriptor.


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

<EOL>if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary:<EOL><INDENT>return<EOL><DEDENT>descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY]<EOL>service_builder = _ServiceBuilder(descriptor)<EOL>service_builder.BuildService(cls)<EOL>

Creates a message service class.

        Args:
          name: Name of the class (ignored, but required by the metaclass
            protocol).
          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.


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.


self.descriptor = service_descriptor<EOL>

Initializes an instance of the service class builder.

        Args:
          service_descriptor: ServiceDescriptor to use when constructing the
            service class.


<EOL>def _WrapCallMethod(srvc, method_descriptor,<EOL>rpc_controller, request, callback):<EOL><INDENT>return self._CallMethod(srvc, method_descriptor,<EOL>rpc_controller, request, callback)<EOL><DEDENT>self.cls = cls<EOL>cls.CallMethod = _WrapCallMethod<EOL>cls.GetDescriptor = staticmethod(lambda: self.descriptor)<EOL>cls.GetDescriptor.__doc__ = "<STR_LIT>"<EOL>cls.GetRequestClass = self._GetRequestClass<EOL>cls.GetResponseClass = self._GetResponseClass<EOL>for method in self.descriptor.methods:<EOL><INDENT>setattr(cls, method.name, self._GenerateNonImplementedMethod(method))<EOL><DEDENT>

Constructs the service class.

        Args:
          cls: The class that will be constructed.


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.


if method_descriptor.containing_service != self.descriptor:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>')<EOL><DEDENT>return method_descriptor.input_type._concrete_class<EOL>

Returns the class of the request protocol message.

        Args:
          method_descriptor: Descriptor of the method for which to return the
            request protocol message class.

        Returns:
          A class that represents the input protocol message of the specified
          method.


if method_descriptor.containing_service != self.descriptor:<EOL><INDENT>raise RuntimeError(<EOL>'<STR_LIT>')<EOL><DEDENT>return method_descriptor.output_type._concrete_class<EOL>

Returns the class of the response protocol message.

        Args:
          method_descriptor: Descriptor of the method for which to return the
            response protocol message class.

        Returns:
          A class that represents the output protocol message of the specified
          method.


return lambda inst, rpc_controller, request, callback: (<EOL>self._NonImplementedMethod(method.name, rpc_controller, callback))<EOL>

Generates and returns a method that can be set for a service methods.

        Args:
          method: Descriptor of the service method for which a method is to be
            generated.

        Returns:
          A method that can be added to the service class.


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.


Initializes an instance of the service stub class builder.

        Args:
          service_descriptor: ServiceDescriptor to use when constructing the
            stub class.


def _ServiceStubInit(stub, rpc_channel):<EOL><INDENT>stub.rpc_channel = rpc_channel<EOL><DEDENT>self.cls = cls<EOL>cls.__init__ = _ServiceStubInit<EOL>for method in self.descriptor.methods:<EOL><INDENT>setattr(cls, method.name, self._GenerateStubMethod(method))<EOL><DEDENT>

Constructs the stub class.

        Args:
          cls: The class that will be constructed.


def _StubMethod(self, stub, method_descriptor,<EOL>rpc_controller, request, callback):

return stub.rpc_channel.CallMethod(<EOL>method_descriptor, rpc_controller, request,<EOL>method_descriptor.output_type._concrete_class, callback)<EOL>

The body of all service methods in the generated stub class.

        Args:
          stub: Stub instance.
          method_descriptor: Descriptor of the invoked method.
          rpc_controller: Rpc controller to execute the method.
          request: Request protocol message.
          callback: A callback to execute when the method finishes.
        Returns:
          Response message (in case of blocking call).


message_name = '<STR_LIT:.>'.join((package, desc_proto.name))<EOL>yield message_name<EOL>for nested_type in desc_proto.nested_type:<EOL><INDENT>for symbol in _ExtractSymbols(nested_type, message_name):<EOL><INDENT>yield symbol<EOL><DEDENT><DEDENT>for enum_type in desc_proto.enum_type:<EOL><INDENT>yield '<STR_LIT:.>'.join((message_name, enum_type.name))<EOL><DEDENT>

Pulls out all the symbols from a descriptor proto.

    Args:
      desc_proto: The proto to extract symbols from.
      package: The package containing the descriptor type.

    Yields:
      The fully qualified name found in the descriptor.


proto_name = file_desc_proto.name<EOL>if proto_name not in self._file_desc_protos_by_file:<EOL><INDENT>self._file_desc_protos_by_file[proto_name] = file_desc_proto<EOL><DEDENT>elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:<EOL><INDENT>raise DescriptorDatabaseConflictingDefinitionError(<EOL>'<STR_LIT>' % proto_name)<EOL><DEDENT>package = file_desc_proto.package<EOL>for message in file_desc_proto.message_type:<EOL><INDENT>self._file_desc_protos_by_symbol.update(<EOL>(name, file_desc_proto) for name in _ExtractSymbols(message, package))<EOL><DEDENT>for enum in file_desc_proto.enum_type:<EOL><INDENT>self._file_desc_protos_by_symbol[<EOL>'<STR_LIT:.>'.join((package, enum.name))] = file_desc_proto<EOL><DEDENT>for extension in file_desc_proto.extension:<EOL><INDENT>self._file_desc_protos_by_symbol[<EOL>'<STR_LIT:.>'.join((package, extension.name))] = file_desc_proto<EOL><DEDENT>

Adds the FileDescriptorProto and its types to this database.

        Args:
          file_desc_proto: The FileDescriptorProto to add.
        Raises:
          DescriptorDatabaseException: if an attempt is made to add a proto
            with the same name but different definition than an exisiting
            proto in the database.


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.


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.


<EOL>Ord = ord if isinstance(text, six.string_types) else lambda x: x<EOL>if as_utf8:<EOL><INDENT>return '<STR_LIT>'.join(_cescape_utf8_to_str[Ord(c)] for c in text)<EOL><DEDENT>return '<STR_LIT>'.join(_cescape_byte_to_str[Ord(c)] for c in text)<EOL>

Escape a bytes string for use in an ascii protocol buffer.

    text.encode('string_escape') does not seem to satisfy our needs as it
    encodes unprintable characters using two-digit hex escapes whereas our
    C++ unescaping function allows hex escapes to be any length.  So,
    "\0011".encode('string_escape') ends up being "\\x011", which will be
    decoded in C++ as a single-character string with char code 0x11.

    Args:
      text: A byte string to be escaped
      as_utf8: Specifies if result should be returned in UTF-8 encoding
    Returns:
      Escaped string


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>


def CallMethod(self, method_descriptor, rpc_controller,<EOL>request, done):

raise NotImplementedError<EOL>

Calls a method of the service specified by method_descriptor.

        If "done" is None then the call is blocking and the response
        message will be returned directly.  Otherwise the call is asynchronous
        and "done" will later be called with the response value.

        In the blocking case, RpcException will be raised on error.

        Preconditions:
        * method_descriptor.service == GetDescriptor
        * request is of the exact same classes as returned by
          GetRequestClass(method).
        * After the call has started, the request must not be modified.
        * "rpc_controller" is of the correct type for the RPC implementation being
          used by this Service.  For stubs, the "correct type" depends on the
          RpcChannel which the stub is using.

        Postconditions:
        * "done" will be called when the method is complete.  This may be
          before CallMethod() returns or it may be at some point in the future.
        * If the RPC failed, the response value passed to "done" will be None.
          Further details about the failure can be found by querying the
          RpcController.


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)


raise NotImplementedError<EOL>

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

        This method isn't really needed, as the RpcChannel's CallMethod constructs
        the response protocol message. It's provided anyway in case it is useful
        for the caller to know the response type in advance.


raise NotImplementedError<EOL>

Resets the RpcController to its initial state.

        After the RpcController has been reset, it may be reused in
        a new call. Must not be called while an RPC is in progress.


raise NotImplementedError<EOL>

Returns true if the call failed.

        After a call has finished, returns true if the call failed.  The possible
        reasons for failure depend on the RPC implementation.  Failed() must not
        be called before a call has finished.  If Failed() returns true, the
        contents of the response message are undefined.


raise NotImplementedError<EOL>

If Failed is true, returns a human-readable description of the error.


raise NotImplementedError<EOL>

Initiate cancellation.

        Advises the RPC system that the caller desires that the RPC call be
        canceled.  The RPC system may cancel it immediately, may wait awhile and
        then cancel it, or may not even cancel the call at all.  If the call is
        canceled, the "done" callback will still be called and the RpcController
        will indicate that the call failed at that time.


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>

Checks if the client cancelled the RPC.

        If true, indicates that the client canceled the RPC, so the server may
        as well give up on replying to it.  The server should still call the
        final "done" callback.


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.


def CallMethod(self, method_descriptor, rpc_controller,<EOL>request, response_class, done):

raise NotImplementedError<EOL>

Calls the method identified by the descriptor.

        Call the given method of the remote service.  The signature of this
        procedure looks the same as Service.CallMethod(), but the requirements
        are less strict in one important way:  the request object doesn't have to
        be of any specific class as long as its descriptor is method.input_type.


return DispatchGroup().dispatch(func)<EOL>

Create a new dispatch on func. Bind additional dispatches with
@func.dispatch


self.callees = deque()<EOL>

callees is a list of (bind_args, function) pairs. bind_args is a
function that, when called with the arguments, attempts to bind them
in a way that matches function's type signature, or raises a TypeError
on failure.


@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 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


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.


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


<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.


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

Adds the decorated function to this dispatch.


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.


def lookup_explicit(self, args, kwargs):

for bind_args, callee in self.callees:<EOL><INDENT>try:<EOL><INDENT>bind_args(args, kwargs)<EOL><DEDENT>except TypeError:<EOL><INDENT>continue<EOL><DEDENT>return callee<EOL><DEDENT>else:<EOL><INDENT>raise DispatchError(args, kwargs, self)<EOL><DEDENT>

Lookup the function that will be called with a given set of arguments,
or raise DispatchError. Requires explicit tuple/dict grouping of
arguments (see DispatchGroup.lookup for a function-like interface).


return args[<NUM_LIT:0>].lookup_explicit(args[<NUM_LIT:1>:], kwargs)<EOL>

Get the function that will be called with a given set of arguments, or
raises DispatchError. Can be called with


return self.lookup_explicit(args, kwargs)(*args, **kwargs)<EOL>

Dispatch a call. Call the first function whose type signature matches
the arguemts.


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.


return args[<NUM_LIT:0>].execute(args[<NUM_LIT:1>:], kwargs)<EOL>

Function-like syntax to execute a dispatched call.


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.


access_token_url = OAUTH_ROOT + '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT>': self.client_id,<EOL>'<STR_LIT>': self.client_secret,<EOL>'<STR_LIT>': self.redirect_uri,<EOL>'<STR_LIT:code>': code,<EOL>}<EOL>resp = requests.get(access_token_url, params=params)<EOL>if not resp.ok:<EOL><INDENT>raise MixcloudOauthError("<STR_LIT>")<EOL><DEDENT>return resp.json()['<STR_LIT>']<EOL>

Exchange the authorization code for an access token.


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

Depending on the data available when the instance was created,
it may be necessary to fetch data.


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


label_pattern = re.compile(r"<STR_LIT>")<EOL>if labels is not None:<EOL><INDENT>prefixes = tuple(L + '<STR_LIT::>' for L in labels<EOL>if label_pattern.match(L + '<STR_LIT::>'))<EOL>for record in ltsvfile:<EOL><INDENT>record = record.rstrip('<STR_LIT:\r\n>')<EOL>yield [x.split('<STR_LIT::>', <NUM_LIT:1>) for x in record.split('<STR_LIT:\t>')<EOL>if x.startswith(prefixes)]<EOL><DEDENT>return<EOL><DEDENT>for record in ltsvfile:<EOL><INDENT>record = record.rstrip('<STR_LIT:\r\n>')<EOL>yield [x.split('<STR_LIT::>', <NUM_LIT:1>) for x in record.split('<STR_LIT:\t>')<EOL>if label_pattern.match(x)]<EOL><DEDENT>

Make LTSV Reader for reading selected labels.

    :param  ltsvfile: iterable of lines.
    :param  labels: sequence of labels. (optional)
    :return: generator of record in [[label, value], ...] form.


def DictReader(ltsvfile, labels=None, dict_type=dict):

for rec in reader(ltsvfile, labels):<EOL><INDENT>yield dict_type(rec)<EOL><DEDENT>

Make LTSV Reader for reading selected labels.

    :param  ltsvfile: iterable of lines.
    :param  labels: sequence of labels.
    :return: generator of record in {label: value, ...} form.


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/


for k, v in changes.items():<EOL><INDENT>if isinstance(v, dict):<EOL><INDENT>merge_dicts(base.setdefault(k, {}), v)<EOL><DEDENT>else:<EOL><INDENT>base.setdefault(k, v)<EOL><DEDENT><DEDENT>

Merge b into a recursively, without overwriting values.

    :param base: the dict that will be altered.
    :param changes: changes to update base.


def convert(self, schema_node, definition_handler):

converted = {<EOL>'<STR_LIT:name>': schema_node.name,<EOL>'<STR_LIT>': self._in,<EOL>'<STR_LIT>': schema_node.required<EOL>}<EOL>if schema_node.description:<EOL><INDENT>converted['<STR_LIT:description>'] = schema_node.description<EOL><DEDENT>if schema_node.default:<EOL><INDENT>converted['<STR_LIT:default>'] = schema_node.default<EOL><DEDENT>schema = definition_handler(schema_node)<EOL>schema.pop('<STR_LIT:title>', None)<EOL>converted.update(schema)<EOL>if schema.get('<STR_LIT:type>') == '<STR_LIT>':<EOL><INDENT>converted['<STR_LIT>'] = {'<STR_LIT:type>': schema['<STR_LIT>']['<STR_LIT:type>']}<EOL><DEDENT>return converted<EOL>

Convert node schema into a parameter object.


script_generator = request.registry.settings.get(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>')<EOL>package, callable = script_generator.split('<STR_LIT::>')<EOL>imported_package = importlib.import_module(package)<EOL>script_callable = getattr(imported_package, callable)<EOL>template = pkg_resources.resource_string(<EOL>'<STR_LIT>', '<STR_LIT>').decode('<STR_LIT:utf8>')<EOL>html = Template(template).safe_substitute(<EOL>ui_css_url=ui_css_url,<EOL>ui_js_bundle_url=ui_js_bundle_url,<EOL>ui_js_standalone_url=ui_js_standalone_url,<EOL>swagger_ui_script=script_callable(request),<EOL>)<EOL>return Response(html)<EOL>

Serves Swagger UI page, default Swagger UI config is used but you can
override the callable that generates the `<script>` tag by setting
`cornice_swagger.swagger_ui_script_generator` in pyramid config, it defaults
to 'cornice_swagger.views:swagger_ui_script_template'

:param request:
:return:


doc = cornice_swagger.CorniceSwagger(<EOL>cornice.service.get_services(), pyramid_registry=request.registry)<EOL>kwargs = request.registry.settings['<STR_LIT>']<EOL>my_spec = doc.generate(**kwargs)<EOL>return my_spec<EOL>

:param request:
:return:

Generates JSON representation of Swagger spec


swagger_spec_url = request.route_url('<STR_LIT>')<EOL>template = pkg_resources.resource_string(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>).decode('<STR_LIT:utf8>')<EOL>return Template(template).safe_substitute(<EOL>swagger_spec_url=swagger_spec_url,<EOL>)<EOL>

:param request:
:return:

Generates the <script> code that bootstraps Swagger UI, it will be injected
into index template


def __init__(self, ref=<NUM_LIT:0>, type_converter=TypeConverter()):

self.definition_registry = {}<EOL>self.ref = ref<EOL>self.type_converter = type_converter<EOL>

:param ref:
    The depth that should be used by self.ref when calling self.from_schema.


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.