Parse a STOMP frame into a Frame object.

    :param bytes frame: the frame received from the server (as a byte string)

    :rtype: Frame
13253
def parse_frame(frame):
    
    f = Frame()
    if frame == b'\x0a':
        f.cmd = 'heartbeat'
        return f

    mat = PREAMBLE_END_RE.search(frame)
    if mat:
        preamble_end = mat.start()
        body_start = mat.end()
    else:
        preamble_end = len(frame)
        body_start = preamble_end
    preamble = decode(frame[0:preamble_end])
    preamble_lines = LINE_END_RE.split(preamble)
    preamble_len = len(preamble_lines)
    f.body = frame[body_start:]

    # Skip any leading newlines
    first_line = 0
    while first_line < preamble_len and len(preamble_lines[first_line]) == 0:
        first_line += 1

    if first_line >= preamble_len:
        return None

    # Extract frame type/command
    f.cmd = preamble_lines[first_line]

    # Put headers into a key/value map
    f.headers = parse_headers(preamble_lines, first_line + 1)

    return f
1274929
def recv(self, full_frame=False):
		
		payloadbuffer = b''
		tries = 3
		while tries:
			tmpbuffer = self.serial_h.read(1)
			if tmpbuffer != b'\xee':
				self.loggerio.error('did not receive \\xee as the first byte of the frame')
				self.loggerio.debug('received \\x' + binascii.b2a_hex(tmpbuffer).decode('utf-8') + ' instead')
				tries -= 1
				continue
			tmpbuffer += self.serial_h.read(5)
			sequence, length = struct.unpack('>xxxBH', tmpbuffer)
			payload = self.serial_h.read(length)
			tmpbuffer += payload
			chksum = self.serial_h.read(2)
			if chksum == packet_checksum(tmpbuffer):
				self.serial_h.write(ACK)
				data = tmpbuffer + chksum
				self.loggerio.debug("received frame, length: {0:<3} data: {1}".format(len(data), binascii.b2a_hex(data).decode('utf-8')))
				payloadbuffer += payload
				if sequence == 0:
					if full_frame:
						payloadbuffer = data
					if sys.version_info[0] == 2:
						payloadbuffer = bytearray(payloadbuffer)
					return payloadbuffer
				else:
					tries = 3
			else:
				self.serial_h.write(NACK)
				self.loggerio.warning('crc does not match on received frame')
				tries -= 1
		self.loggerio.critical('failed 3 times to correctly receive a frame')
		raise C1218IOError('failed 3 times to correctly receive a frame')
1225031
def process_frame(self, frame):
        
        cmd_method = frame.cmd.lower()

        if not cmd_method in VALID_COMMANDS:
            raise ProtocolError("Invalid STOMP command: {}".format(frame.cmd))

        method = getattr(self, cmd_method, None)

        if not self.engine.connected and method not in (self.connect, self.stomp):
            raise ProtocolError("Not connected.")

        try:
            transaction = frame.headers.get('transaction')
            if not transaction or method in (self.begin, self.commit, self.abort):
                method(frame)
            else:
                if not transaction in self.engine.transactions:
                    raise ProtocolError(
                        "Invalid transaction specified: %s" % transaction)
                self.engine.transactions[transaction].append(frame)
        except Exception as e:
            self.engine.log.error("Error processing STOMP frame: %s" % e)
            self.engine.log.exception(e)
            try:
                self.engine.connection.send_frame(ErrorFrame(str(e), str(e)))
            except Exception as e:  # pragma: no cover
                self.engine.log.error("Could not send error frame: %s" % e)
                self.engine.log.exception(e)
        else:
            # The protocol is not especially clear here (not sure why I'm surprised)
            # about the expected behavior WRT receipts and errors.  We will assume that
            # the RECEIPT frame should not be sent if there is an error frame.
            # Also we'll assume that a transaction should not preclude sending the receipt
            # frame.
            # import pdb; pdb.set_trace()
            if frame.headers.get('receipt') and method != self.connect:
                self.engine.connection.send_frame(ReceiptFrame(
                    receipt=frame.headers.get('receipt')))
885740
function createFrame (type, payload) {
  var err = validateArgs(type, payload);
  if (err) { throw err; }

  var payloadBuffer = Buffer.isBuffer(payload) ? payload : new Buffer(payload);
  var headerBuffer  = createHeader(type, payload.length);

  return Buffer.concat([headerBuffer, payloadBuffer]);
}
936254
def from_bytes(cls, bitstream, decode_payload=True):
        '''
        
        '''
        packet = cls()

        # Convert to ConstBitStream (if not already provided)
        if not isinstance(bitstream, ConstBitStream):
            if isinstance(bitstream, Bits):
                bitstream = ConstBitStream(auto=bitstream)
            else:
                bitstream = ConstBitStream(bytes=bitstream)

        # Read the version
        version = bitstream.read('uint:4')
        if version != packet.version:
            raise ValueError('Provided bytes do not contain an IPv6 packet')

        # Read the traffic class
        packet.traffic_class = bitstream.read('uint:8')

        # Read the flow label
        packet.flow_label = bitstream.read('uint:20')

        # Read the payload length
        payload_length = bitstream.read('uint:16')

        # Read the next header type
        packet.next_header = bitstream.read('uint:8')

        # Read the hop limit
        packet.hop_limit = bitstream.read('uint:8')

        # Read the source and destination addresses
        packet.source = IPv6Address(bitstream.read('uint:128'))
        packet.destination = IPv6Address(bitstream.read('uint:128'))

        # And the rest is payload
        packet.payload = bitstream.read('bytes:%d' % payload_length)

        if decode_payload:
            payload_class = protocol_registry.get_type_class(packet.next_header)
            if payload_class:
                packet.payload = payload_class.from_bytes(packet.payload)

        # There should be no remaining bits
        if bitstream.pos != bitstream.len:
            raise ValueError('Bits remaining after processing packet')

        # Verify that the properties make sense
        packet.sanitize()

        return packet
290138
def frame_to_sample(self, frame_index):
        
        start = frame_index * self.hop_size
        end = start + self.frame_size
        return start, end
976214
def _read_frame(cls, reader):
        '''
        
        '''
        frame_type = reader.read_octet()
        channel_id = reader.read_short()
        size = reader.read_long()

        payload = Reader(reader, reader.tell(), size)

        # Seek to end of payload
        reader.seek(size, 1)

        ch = reader.read_octet()  # footer
        if ch != 0xce:
            raise Frame.FormatError(
                'Framing error, unexpected byte: %x.  frame type %x. channel %d, payload size %d',
                ch, frame_type, channel_id, size)

        frame_class = cls._frame_type_map.get(frame_type)
        if not frame_class:
            raise Frame.InvalidFrameType("Unknown frame type %x", frame_type)
        return frame_class.parse(channel_id, payload)
1280091
def receive(frame)
      transition(frame, false)

      case frame[:type]
      when :data
        update_local_window(frame)
        # Emit DATA frame
        emit(:data, frame[:payload]) unless frame[:ignore]
        calculate_window_update(@local_window_max_size)
      when :headers
        emit(:headers, frame[:payload]) unless frame[:ignore]
      when :push_promise
        emit(:promise_headers, frame[:payload]) unless frame[:ignore]
      when :priority
        process_priority(frame)
      when :window_update
        process_window_update(frame)
      when :altsvc
        # 4.  The ALTSVC HTTP/2 Frame
        # An ALTSVC frame on a
        # stream other than stream 0 containing non-empty "Origin" information
        # is invalid and MUST be ignored.
        if !frame[:origin] || frame[:origin].empty?
          emit(frame[:type], frame)
        end
      when :blocked
        emit(frame[:type], frame)
      end

      complete_transition(frame)
    end
1141920
def parse(self):
        
        if len(self.raw_data) < 3:
            ValueError("parse() may only be called on a frame containing at "
                       "least 3 bytes of raw data (see fill())")

        # First two bytes are the length of the data
        raw_len = self.raw_data[1:3]

        # Unpack it
        data_len = struct.unpack("> h", raw_len)[0]

        # Read the data
        data = self.raw_data[3:3 + data_len]
        chksum = self.raw_data[-1]

        # Checksum check
        self.data = data
        if not self.verify(chksum):
            raise ValueError("Invalid checksum")
168585
public void processCompleteFrame() throws Http2Exception {
        Frame currentFrame = getCurrentFrame();

        boolean frameSizeError = false;
        try {
            currentFrame.processPayload(this);
        } catch (Http2Exception e) {
            // If we get an error here, it should be safe to assume that this frame doesn't have the expected byte count,
            // which must be treated as an error of type FRAME_SIZE_ERROR.  If we're processing a DATA or PRIORITY frame, then
            // we can treat the error as a stream error rather than a connection error.
            if (!e.isConnectionError()) {
                frameSizeError = true;
            } else {
                // this is a connection error; we need to send a GOAWAY on the connection
                throw e;
            }
        } catch (Exception e) {
            throw new ProtocolException("Error processing the payload for " + currentFrame.getFrameType()
                                        + " frame on stream " + currentFrame.getStreamId());
        }

        // call the stream processor to process this stream. For now, don't return from here until the
        // frame has been fully processed.
        int streamId = currentFrame.getStreamId();
        H2StreamProcessor stream = muxLink.getStream(streamId);

        if (stream == null) {
            if ((streamId != 0) && (streamId % 2 == 0)) {
                if (currentFrame.getFrameType().equals(FrameTypes.PRIORITY)) {
                    // ignore PRIORITY frames in any state
                    return;
                } else if (currentFrame.getFrameType().equals(FrameTypes.RST_STREAM) && streamId < muxLink.getHighestClientStreamId()) {
                    // tolerate RST_STREAM frames that are sent on closed push streams
                    return;
                } else {
                    throw new ProtocolException("Cannot start a stream from the client with an even numbered ID. stream-id: " + streamId);
                }
            } else {
                stream = startNewInboundSession(streamId);
            }
        }
        if (frameSizeError) {
            currentFrame = new FrameRstStream(streamId, 4, (byte) 0, false, FrameDirection.READ);
            ((FrameRstStream) currentFrame).setErrorCode(Constants.FRAME_SIZE_ERROR);
        }

        stream.processNextFrame(currentFrame, Direction.READ_IN);
    }
221132
def decode_header(cls, stream):
        
        read = stream.read
        data = read(2)
        if len(data) != 2:
            raise WebSocketError("Unexpected EOF while decoding header")
        first_byte, second_byte = struct.unpack('!BB', data)
        header = cls(
            fin=first_byte & cls.FIN_MASK == cls.FIN_MASK,
            opcode=first_byte & cls.OPCODE_MASK,
            flags=first_byte & cls.HEADER_FLAG_MASK,
            length=second_byte & cls.LENGTH_MASK)
        has_mask = second_byte & cls.MASK_MASK == cls.MASK_MASK
        if header.opcode > 0x07:
            if not header.fin:
                raise WebSocketError('Received fragmented control frame: {0!r}'.format(data))
            # Control frames MUST have a payload length of 125 bytes or less
            if header.length > 125:
                raise FrameTooLargeException('Control frame cannot be larger than 125 bytes: {0!r}'.format(data))
        if header.length == 126:
            # 16 bit length
            data = read(2)
            if len(data) != 2:
                raise WebSocketError('Unexpected EOF while decoding header')
            header.length = struct.unpack('!H', data)[0]
        elif header.length == 127:
            # 64 bit length
            data = read(8)
            if len(data) != 8:
                raise WebSocketError('Unexpected EOF while decoding header')
            header.length = struct.unpack('!Q', data)[0]
        if has_mask:
            mask = read(4)
            if len(mask) != 4:
                raise WebSocketError('Unexpected EOF while decoding header')
            header.mask = mask
        return header
1296142
def encode_headers(frame)
      payload = frame[:payload]
      payload = @compressor.encode(payload) unless payload.is_a? Buffer

      frames = []

      while payload.bytesize > 0
        cont = frame.dup
        cont[:type] = :continuation
        cont[:flags] = []
        cont[:payload] = payload.slice!(0, @remote_settings[:settings_max_frame_size])
        frames << cont
      end
      if frames.empty?
        frames = [frame]
      else
        frames.first[:type]  = frame[:type]
        frames.first[:flags] = frame[:flags] - [:end_headers]
        frames.last[:flags] << :end_headers
      end

      frames

    rescue StandardError => e
      connection_error(:compression_error, e: e)
      nil
    end
117690
def get_frame(self, outdata, frames, timedata, status):
		

		if not self.keep_listening:
			raise sd.CallbackStop
		
		try:
			chunk = self.queue.get_nowait()
			# Check if the chunk contains the expected number of frames
			# The callback function raises a ValueError otherwise.
			if chunk.shape[0] == frames:
				outdata[:] = chunk
			else:
				outdata.fill(0)
		except Empty:
			outdata.fill(0)
380029
def _read_bytes_to_framed_body(self, b):
        
        _LOGGER.debug("collecting %d bytes", b)
        _b = b

        if b > 0:
            _frames_to_read = math.ceil(b / float(self.config.frame_length))
            b = int(_frames_to_read * self.config.frame_length)
        _LOGGER.debug("%d bytes requested; reading %d bytes after normalizing to frame length", _b, b)

        plaintext = self.source_stream.read(b)
        plaintext_length = len(plaintext)
        _LOGGER.debug("%d bytes read from source", plaintext_length)

        finalize = False

        if b < 0 or plaintext_length < b:
            _LOGGER.debug("Final plaintext read from source")
            finalize = True

        output = b""
        final_frame_written = False

        while (
            # If not finalizing on this pass, exit when plaintext is exhausted
            (not finalize and plaintext)
            # If finalizing on this pass, wait until final frame is written
            or (finalize and not final_frame_written)
        ):
            current_plaintext_length = len(plaintext)
            is_final_frame = finalize and current_plaintext_length < self.config.frame_length
            bytes_in_frame = min(current_plaintext_length, self.config.frame_length)
            _LOGGER.debug(
                "Writing %d bytes into%s frame %d",
                bytes_in_frame,
                " final" if is_final_frame else "",
                self.sequence_number,
            )
            self._bytes_encrypted += bytes_in_frame
            ciphertext, plaintext = serialize_frame(
                algorithm=self._encryption_materials.algorithm,
                plaintext=plaintext,
                message_id=self._header.message_id,
                data_encryption_key=self._derived_data_key,
                frame_length=self.config.frame_length,
                sequence_number=self.sequence_number,
                is_final_frame=is_final_frame,
                signer=self.signer,
            )
            final_frame_written = is_final_frame
            output += ciphertext
            self.sequence_number += 1

        if finalize:
            _LOGGER.debug("Writing footer")
            if self.signer is not None:
                output += serialize_footer(self.signer)
            self.__message_complete = True
        return output
783527
def from_frame(klass, frame, connection):
        
        event = frame.headers['new']
        data = json.loads(frame.body)
        info = data['info']
        build = Build.fromDict(info)
        build.connection = connection
        return klass(build, event)
1257479
def from_bytes(cls, bt):
        
        log.debug("Parsing email from bytes")
        if six.PY2:
            raise MailParserEnvironmentError(
                "Parsing from bytes is valid only for Python 3.x version")
        message = email.message_from_bytes(bt)
        return cls(message)
1002922
def extract_frames(self, bpf_buffer):
        """"""  # noqa: E501

        # Ensure that the BPF buffer contains at least the header
        len_bb = len(bpf_buffer)
        if len_bb < 20:  # Note: 20 == sizeof(struct bfp_hdr)
            return

        # Extract useful information from the BPF header
        if FREEBSD or NETBSD:
            # struct bpf_xhdr or struct bpf_hdr32
            bh_tstamp_offset = 16
        else:
            # struct bpf_hdr
            bh_tstamp_offset = 8

        # Parse the BPF header
        bh_caplen = struct.unpack('I', bpf_buffer[bh_tstamp_offset:bh_tstamp_offset + 4])[0]  # noqa: E501
        next_offset = bh_tstamp_offset + 4
        bh_datalen = struct.unpack('I', bpf_buffer[next_offset:next_offset + 4])[0]  # noqa: E501
        next_offset += 4
        bh_hdrlen = struct.unpack('H', bpf_buffer[next_offset:next_offset + 2])[0]  # noqa: E501
        if bh_datalen == 0:
            return

        # Get and store the Scapy object
        frame_str = bpf_buffer[bh_hdrlen:bh_hdrlen + bh_caplen]
        try:
            pkt = self.guessed_cls(frame_str)
        except Exception:
            if conf.debug_dissector:
                raise
            pkt = conf.raw_layer(frame_str)
        self.received_frames.append(pkt)

        # Extract the next frame
        end = self.bpf_align(bh_hdrlen, bh_caplen)
        if (len_bb - end) >= 20:
            self.extract_frames(bpf_buffer[end:])