Build descriptor for Message class.

    Args:
      message_definition: Message class to provide descriptor for.

    Returns:
      Initialized MessageDescriptor instance describing the Message class.
487345
def describe_message(message_definition):
    
    message_descriptor = MessageDescriptor()
    message_descriptor.name = message_definition.definition_name().split(
        '.')[-1]

    fields = sorted(message_definition.all_fields(),
                    key=lambda v: v.number)
    if fields:
        message_descriptor.fields = [describe_field(field) for field in fields]

    try:
        nested_messages = message_definition.__messages__
    except AttributeError:
        pass
    else:
        message_descriptors = []
        for name in nested_messages:
            value = getattr(message_definition, name)
            message_descriptors.append(describe_message(value))

        message_descriptor.message_types = message_descriptors

    try:
        nested_enums = message_definition.__enums__
    except AttributeError:
        pass
    else:
        enum_descriptors = []
        for name in nested_enums:
            value = getattr(message_definition, name)
            enum_descriptors.append(describe_enum(value))

        message_descriptor.enum_types = enum_descriptors

    return message_descriptor
430955
def _message_to_entity(msg, modelclass):
  
  ent = modelclass()
  for prop_name, prop in modelclass._properties.iteritems():
    if prop._code_name == 'blob_':  # TODO: Devise a cleaner test.
      continue  # That's taken care of later.
    value = getattr(msg, prop_name)
    if value is not None and isinstance(prop, model.StructuredProperty):
      if prop._repeated:
        value = [_message_to_entity(v, prop._modelclass) for v in value]
      else:
        value = _message_to_entity(value, prop._modelclass)
    setattr(ent, prop_name, value)
  return ent
89332
public static <ContainingType extends Message, Type>
      GeneratedExtension<ContainingType, Type>
      newMessageScopedGeneratedExtension(final Message scope,
                                         final int descriptorIndex,
                                         final Class singularType,
                                         final Message defaultInstance) {
    // For extensions scoped within a Message, we use the Message to resolve
    // the outer class's descriptor, from which the extension descriptor is
    // obtained.
    return new GeneratedExtension<ContainingType, Type>(
        new ExtensionDescriptorRetriever() {
          //@Override (Java 1.6 override semantics, but we must support 1.5)
          public FieldDescriptor getDescriptor() {
            return scope.getDescriptorForType().getExtensions()
                .get(descriptorIndex);
          }
        },
        singularType,
        defaultInstance);
  }
1354193
def message(self):
        
        message = self.description.format(**self.parameters)
        return '{code} {message}'.format(code=self.code, message=message)
425643
def defines(self, id, domain='messages'):
        
        assert isinstance(id, (str, unicode))
        assert isinstance(domain, (str, unicode))

        return id in self.messages.get(domain, {})
1324707
def getProtocolClasses(superclass=message.Message):
    
    # We keep a manual list of the superclasses that we define here
    # so we can filter them out when we're getting the protocol
    # classes.
    superclasses = set([message.Message])
    thisModule = sys.modules[__name__]
    subclasses = []
    for name, class_ in inspect.getmembers(thisModule):
        if ((inspect.isclass(class_) and
                issubclass(class_, superclass) and
                class_ not in superclasses)):
            subclasses.append(class_)
    return subclasses
127439
def write(self, message):
        
        message.id = message.id or self.writer.next_message_id()

        if message.message_type in self.CALL_REQ_TYPES:
            message_factory = self.request_message_factory
        else:
            message_factory = self.response_message_factory

        fragments = message_factory.fragment(message)
        return self._write_fragments(fragments)
1205594
def _process_messages(self, messages, ignore_unknown_message_types=False):
        
        with self.before_after_send_handling():
            for message_id, message_data in messages.items():
                message_model, dispatch_models = message_data
                try:
                    message_cls = get_registered_message_type(message_model.cls)
                except UnknownMessageTypeError:
                    if ignore_unknown_message_types:
                        continue
                    raise

                message_type_cache = None
                for dispatch in dispatch_models:
                    if not dispatch.message_cache:  # Create actual message text for further usage.
                        try:
                            if message_type_cache is None and not message_cls.has_dynamic_context:
                                # If a message class doesn't depend upon a dispatch data for message compilation,
                                # we'd compile a message just once.
                                message_type_cache = message_cls.compile(message_model, self, dispatch=dispatch)

                            dispatch.message_cache = message_type_cache or message_cls.compile(
                                message_model, self, dispatch=dispatch)

                        except Exception as e:
                            self.mark_error(dispatch, e, message_cls)

                self.send(message_cls, message_model, dispatch_models)
634590
def _fields_to_object(descriptor, fields):
    ''
    # pylint: disable=protected-access
    obj = descriptor._concrete_class()

    for name, value in fields:
        if isinstance(value, tuple):
            subtype = descriptor.fields_by_name[name].message_type
            value = _fields_to_object(subtype, value)
        _assign_to_field(obj, name, value)

    return obj
391854
def _AddMessageMethods(message_descriptor, cls):
  """"""
  _AddListFieldsMethod(message_descriptor, cls)
  _AddHasFieldMethod(message_descriptor, cls)
  _AddClearFieldMethod(message_descriptor, cls)
  if message_descriptor.is_extendable:
    _AddClearExtensionMethod(cls)
    _AddHasExtensionMethod(cls)
  _AddEqualsMethod(message_descriptor, cls)
  _AddStrMethod(message_descriptor, cls)
  _AddReprMethod(message_descriptor, cls)
  _AddUnicodeMethod(message_descriptor, cls)
  _AddByteSizeMethod(message_descriptor, cls)
  _AddSerializeToStringMethod(message_descriptor, cls)
  _AddSerializePartialToStringMethod(message_descriptor, cls)
  _AddMergeFromStringMethod(message_descriptor, cls)
  _AddIsInitializedMethod(message_descriptor, cls)
  _AddMergeFromMethod(cls)
  _AddWhichOneofMethod(message_descriptor, cls)
  _AddReduceMethod(cls)
  # Adds methods which do not depend on cls.
  cls.Clear = _Clear
  cls.DiscardUnknownFields = _DiscardUnknownFields
  cls._SetListener = _SetListener
71816
def create(cls, description="", message=""):
        
        instance = cls()
        instance.revision_id = make_hash_id()
        instance.release_date = datetime.datetime.now()

        if len(description) > 0:
            instance.description = description

        if len(message) > 0:
            instance.message = message

        return instance
537623
def message_to_objects(
        message: Dict, sender: str, sender_key_fetcher: Callable[[str], str] = None, user: UserType = None,
) -> List:
    
    # We only really expect one element here for ActivityPub.
    return element_to_objects(message)
1313005
def toDict(self, msg: Dict) -> Dict:
        

        if isinstance(msg, Request):
            tmsg = msg.as_dict
        elif hasattr(msg, "_asdict"):
            tmsg = dict(msg._asdict())
        elif hasattr(msg, "__dict__"):
            tmsg = dict(msg.__dict__)
        elif self.allowDictOnly:
            raise ValueError("Message cannot be converted to an appropriate "
                             "format for transmission")
        else:
            tmsg = msg
        return tmsg
981877
function Message () {

  if (!(this instanceof Message)) {
    if (typeof arguments[0] === 'object' && arguments[0] instanceof Message) {
      debug('message is a message so return it');
      return arguments[0];
    }
    else {
      debug('creating new message and initializing with arguments');
      var m = new Message();
      Message.prototype.initialize.apply(m, slice.call(arguments));
      return m;
    }
  }
  else {
    this.isMessage = true;
    if (arguments.length) {
      debug('initializing with arguments');
      Message.prototype.initialize.apply(this, slice.call(arguments));
    }
  }

}
269006
def get_message_type(message):
        
        for msg_type in MessageType.FIELDS:
            if Message.is_type(msg_type, message):
                return msg_type

        return MessageType.UNKNOWN
1089776
private static MethodRef getBuilderMethod(Descriptor descriptor) {
    TypeInfo message = messageRuntimeType(descriptor);
    TypeInfo builder = builderRuntimeType(descriptor);
    return MethodRef.createStaticMethod(
            message, new Method("newBuilder", builder.type(), NO_METHOD_ARGS))
        .asNonNullable();
  }
308908
def FindFieldByName(self, full_name):
    
    full_name = _NormalizeFullyQualifiedName(full_name)
    message_name, _, field_name = full_name.rpartition('.')
    message_descriptor = self.FindMessageTypeByName(message_name)
    return message_descriptor.fields_by_name[field_name]