Encode an IPMB message.

    header: IPMB header object
    data: IPMI message data as bytestring

    Returns the message as bytestring.
779045
def encode_ipmb_msg(header, data):
    
    msg = array('B')

    msg.fromstring(header.encode())
    if data is not None:
        a = array('B')
        a.fromstring(data)
        msg.extend(a)
    msg.append(checksum(msg[3:]))
    return msg.tostring()
715378
def encode(self):
        
        buf = bytearray()
        for typ in sorted(self.format.keys()):
            encoded = None
            if typ != 0xFFFF: # end of block
                (name, marshall) = self.format[typ]
                value = getattr(self, name, None)
                if value is not None:
                    try:
                        encoded = marshall.encode(value)
                        self.log.debug("Encoded field [{0}] to value {1!r}".format(name, encoded))
                    except:
                        self.log.exception("Error encoding key/value: key={0}, value={1!r}".format(name, value))
                        raise
            
            # Note, there is an assumption here that encode() func is returning
            # a byte string (so len = num bytes).  That should be a safe assumption.
            size = len(encoded) if encoded is not None else 0
            packed = struct.pack('<H', typ)
            packed += struct.pack('<I', size)
            if encoded is not None:
                if isinstance(encoded, bytearray):
                    encoded = str(encoded)
                elif isinstance(encoded, unicode):
                    encoded = encoded.encode('utf-8')
                packed += struct.pack('<%ds' % size, encoded)
                
            buf += packed
            
        return buf
439363
def encode_request(name, from_, to):
    
    client_message = ClientMessage(payload_size=calculate_size(name, from_, to))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_int(from_)
    client_message.append_int(to)
    client_message.update_frame_length()
    return client_message
125377
public IoBuffer encodeMessage(Header header, IRTMPEvent message) {
        IServiceCall call = null;
        switch (header.getDataType()) {
            case TYPE_CHUNK_SIZE:
                return encodeChunkSize((ChunkSize) message);
            case TYPE_INVOKE:
                log.trace("Invoke {}", message);
                call = ((Invoke) message).getCall();
                if (call != null) {
                    log.debug("{}", call.toString());
                    Object[] args = call.getArguments();
                    if (args != null && args.length > 0) {
                        Object a0 = args[0];
                        if (a0 instanceof Status) {
                            Status status = (Status) a0;
                            //code: NetStream.Seek.Notify
                            if (StatusCodes.NS_SEEK_NOTIFY.equals(status.getCode())) {
                                //desc: Seeking 25000 (stream ID: 1).
                                int seekTime = Integer.valueOf(status.getDescription().split(" ")[1]);
                                log.trace("Seek to time: {}", seekTime);
                                // TODO make sure this works on stream ids > 1
                                //audio and video channels
                                int[] channels = new int[] { 5, 6 };
                                //if its a seek notification, reset the "mapping" for audio (5) and video (6)
                                RTMP rtmp = ((RTMPConnection) Red5.getConnectionLocal()).getState();
                                for (int channelId : channels) {
                                    LiveTimestampMapping mapping = rtmp.getLastTimestampMapping(channelId);
                                    if (mapping != null) {
                                        long timestamp = mapping.getClockStartTime() + (seekTime & 0xFFFFFFFFL);
                                        log.trace("Setting last stream time to: {}", timestamp);
                                        mapping.setLastStreamTime(timestamp);
                                    } else {
                                        log.trace("No ts mapping for channel id: {}", channelId);
                                    }
                                }
                            }
                        }
                    }
                }
                return encodeInvoke((Invoke) message);
            case TYPE_NOTIFY:
                log.trace("Notify {}", message);
                call = ((Notify) message).getCall();
                if (call == null) {
                    return encodeStreamMetadata((Notify) message);
                } else {
                    return encodeNotify((Notify) message);
                }
            case TYPE_PING:
                if (message instanceof SetBuffer) {
                    return encodePing((SetBuffer) message);
                } else if (message instanceof SWFResponse) {
                    return encodePing((SWFResponse) message);
                } else {
                    return encodePing((Ping) message);
                }
            case TYPE_BYTES_READ:
                return encodeBytesRead((BytesRead) message);
            case TYPE_AGGREGATE:
                log.trace("Encode aggregate message");
                return encodeAggregate((Aggregate) message);
            case TYPE_AUDIO_DATA:
                log.trace("Encode audio message");
                return encodeAudioData((AudioData) message);
            case TYPE_VIDEO_DATA:
                log.trace("Encode video message");
                return encodeVideoData((VideoData) message);
            case TYPE_FLEX_SHARED_OBJECT:
                return encodeFlexSharedObject((ISharedObjectMessage) message);
            case TYPE_SHARED_OBJECT:
                return encodeSharedObject((ISharedObjectMessage) message);
            case TYPE_SERVER_BANDWIDTH:
                return encodeServerBW((ServerBW) message);
            case TYPE_CLIENT_BANDWIDTH:
                return encodeClientBW((ClientBW) message);
            case TYPE_FLEX_MESSAGE:
                return encodeFlexMessage((FlexMessage) message);
            case TYPE_FLEX_STREAM_SEND:
                return encodeFlexStreamSend((FlexStreamSend) message);
            default:
                log.warn("Unknown object type: {}", header.getDataType());
        }
        return null;
    }
382010
def encode_bridged_message(routing, header, payload, seq):
    

    # change header requester addresses for bridging
    header.rq_sa = routing[-1].rq_sa
    header.rs_sa = routing[-1].rs_sa
    tx_data = encode_ipmb_msg(header, payload)

    for bridge in reversed(routing[:-1]):
        tx_data = encode_send_message(tx_data,
                                      rq_sa=bridge.rq_sa,
                                      rs_sa=bridge.rs_sa,
                                      channel=bridge.channel,
                                      seq=seq)

    return tx_data
11871
def _encode_to_binary_string(message, on, off):
    
    def to_string(i, s):
        if i == 0 and s == off:
            return off * 4
        return s
    return ''.join(to_string(i, s) for i, s in enumerate(_encode_binary(message, on=on, off=off)))
1306397
def encode_contents(self):
        

        if self.variable_size:
            resp_length = 1
        else:
            resp_length = self.fixed_response_size << 1

        header = struct.pack("<HBB", self.rpc_id, self.address, resp_length)
        return bytearray(header) + self.payload
1204633
def _encode_message_set(cls, messages, offset=None):
        
        message_set = []
        incr = 1
        if offset is None:
            incr = 0
            offset = 0
        for message in messages:
            encoded_message = KafkaCodec._encode_message(message)
            message_set.append(struct.pack('>qi', offset, len(encoded_message)))
            message_set.append(encoded_message)
            offset += incr
        return b''.join(message_set)
1072718
def encode_string(data, encoding='hex'):
    '''
    
    '''
    if six.PY2:
        return data.encode(encoding)
    else:
        if isinstance(data, str):
            data = bytes(data, 'utf-8')
        return codecs.encode(data, encoding).decode('ascii')
357790
def to_bytes(self):
        
        '''
        # Verify that properties make sense
        self.sanitize()

        # Start with the type
        bitstream = BitArray('uint:4=%d' % self.message_type)

        # Add the flags
        bitstream += BitArray('bool=%d, bool=%d' % (self.security,
                                                    self.ddt_originated))

        # Add padding
        bitstream += self._reserved1

        # Determine payload
        payload = self.payload
        if hasattr(payload, 'to_bytes'):
            payload = payload.to_bytes()

        return bitstream.bytes + payload
28805
def data_to_bytes(self, data_element, encoding=None):
        
        if encoding is None:
            encoding = self.encoding
        text = self.data_to_string(data_element)
        return bytes_(text, encoding=encoding)
475210
def encode(self, version, padding, extension, cc, seqnum, marker, pt, ssrc, payload):
		""""""

		timestamp = int(time())
		print("timestamp: " + str(timestamp))
		self.header = bytearray(HEADER_SIZE)
		#--------------
		# TO COMPLETE
		#--------------
		# Fill the header bytearray with RTP header fields

		#RTP-version filed(V), must set to 2
		#padding(P),extension(X),number of contributing sources(CC) and marker(M) fields all set to zero in this lab

		#Because we have no other contributing sources(field CC == 0),the CSRC-field does not exist
		#Thus the length of the packet header is therefore 12 bytes


			#Above all done in ServerWorker.py

		# ...
		#header[] =

		#header[0] = version + padding + extension + cc + seqnum + marker + pt + ssrc
		self.header[0] = version << 6
		self.header[0] = self.header[0] | padding << 5
		self.header[0] = self.header[0] | extension << 4
		self.header[0] = self.header[0] | cc
		self.header[1] = marker << 7
		self.header[1] = self.header[1] | pt

		self.header[2] = seqnum >> 8
		self.header[3] = seqnum

		self.header[4] = (timestamp >> 24) & 0xFF
		self.header[5] = (timestamp >> 16) & 0xFF
		self.header[6] = (timestamp >> 8) & 0xFF
		self.header[7] = timestamp & 0xFF

		self.header[8] = ssrc >> 24
		self.header[9] = ssrc >> 16
		self.header[10] = ssrc >> 8
		self.header[11] = ssrc


		# Get the payload from the argument
		# self.payload = ...
		self.payload = payload
410747
public static String encode(byte[] bytes)
    {
        StringBuilder sb = new StringBuilder(bytes.length << 1);
        for (byte aByte : bytes)
        {
            sb.append(convertDigit(aByte >> 4));
            sb.append(convertDigit(aByte & 0x0f));
        }
        return sb.toString();
    }
15522
def encode_request(name, uuid, callable, address):
    
    client_message = ClientMessage(payload_size=calculate_size(name, uuid, callable, address))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(name)
    client_message.append_str(uuid)
    client_message.append_data(callable)
    AddressCodec.encode(client_message, address)
    client_message.update_frame_length()
    return client_message
1000362
def encode (self):
    """"""
    byte = self.default

    for bit, name, value0, value1, default in SeqCmdAttrs.Table:
      if name in self.attrs:
        value = self.attrs[name]
        byte  = setBit(byte, bit, value == value1)

    return struct.pack('B', byte)
10344
def encode_contents(self):
        

        header = struct.pack("<LL", self.offset, len(self.raw_data))
        return bytearray(header) + self.raw_data
595197
def _encode(msg, head=False, binary=False):
    
    rawstr = str(_MAGICK) + u"{0:s} {1:s} {2:s} {3:s} {4:s}".format(
        msg.subject, msg.type, msg.sender, msg.time.isoformat(), msg.version)

    if not head and msg.data:
        if not binary and isinstance(msg.data, six.string_types):
            return (rawstr + ' ' +
                    'text/ascii' + ' ' + msg.data)
        elif not binary:
            return (rawstr + ' ' +
                    'application/json' + ' ' +
                    json.dumps(msg.data, default=datetime_encoder))
        else:
            return (rawstr + ' ' +
                    'binary/octet-stream' + ' ' + msg.data)
    return rawstr