Parse the body of a close :class:`Frame`.

    Returns a tuple (``code``, ``reason``) if successful otherwise
    raise :class:`.ProtocolError`.
9663
def parse_close(data):
    '''
    '''
    length = len(data)
    if length == 0:
        return 1005, ''
    elif length == 1:
        raise ProtocolError("Close frame too short")
    else:
        code, = unpack('!H', data[:2])
        if not (code in CLOSE_CODES or 3000 <= code < 5000):
            raise ProtocolError("Invalid status code for websocket")
        reason = data[2:].decode('utf-8')
        return code, reason
175645
def Parse(self, how):
        '''
        '''
        if type(how) == types.ClassType: how = how.typecode
        return how.parse(self.body_root, self)
639249
def parse(cls, payload):
        
        try:
            method, args, ref = payload
        except Exception as exception:
            raise RequestParseError(exception)
        else:
            return method, args, ref
845026
def parseRest(self, response):
        
        body = json.loads(response)

        try:
            error = body['error']['description']
            code = body['error']['code']
        except Exception:
            return body['data']
        else:
            raise ClickatellError(error, code);
984987
def parse_response(resp)
      body = JSON.parse(resp.body)
      if body['error']
        raise Apilayer::Error.new(
          body['error']['info'],
          body['error']['code']
        )
      else
        body
      end
    end
661209
private void verifyFrameOpcode(WebSocketFrame frame) throws WebSocketException
    {
        switch (frame.getOpcode())
        {
            case CONTINUATION:
            case TEXT:
            case BINARY:
            case CLOSE:
            case PING:
            case PONG:
                // Known opcode
                return;

            default:
                break;
        }

        // If extended use of web socket frames is allowed.
        if (mWebSocket.isExtended())
        {
            // Allow the unknown opcode.
            return;
        }

        // A frame has an unknown opcode.
        throw new WebSocketException(
            WebSocketError.UNKNOWN_OPCODE,
            "A frame has an unknown opcode: 0x" + Integer.toHexString(frame.getOpcode()));
    }
825714
def check_end_blocks(frame):
    
    try:
        try:
            module_name = frame.f_globals['__name__']
        except KeyError:
            warnings.warn(
                'Can not get the source of an uknown module. '
                'End-of-block syntax check is skipped.',
                EndSyntaxWarning)
            return
        end

        filename = frame.f_globals.get('__file__', '<unknown>')
        try:
            source = inspect.getsource(sys.modules[module_name])
        except Exception:
            warnings.warn(
                'Can not get the source of module "%s". '
                'End-of-block syntax check is skipped.' % (module_name,),
                EndSyntaxWarning)
            return
        end
    finally:
        del frame
    end

    root = ast.parse(source)
    for node in ast.walk(root):
        bodies = get_compound_bodies(node)
        if not bodies:
            continue
        end

        # FIXME: This is an inaccurate hack to handle if-elif-else.
        if (isinstance(node, ast.If) and
                len(node.orelse) == 1 and
                isinstance(node.orelse[0], ast.If)):
            continue
        end

        # FIXME: This is an inaccurate hack to handle try-except-finally
        # statement which is parsed as ast.TryExcept in ast.TryFinally in
        # Python 2.
        if (PY2 and
                isinstance(node, ast.TryFinally) and
                len(node.body) == 1 and
                isinstance(node.body[0], ast.TryExcept)):
            continue
        end

        for body in bodies:
            skip_next = False
            for i, child in enumerate(body):
                if skip_next:
                    skip_next = False
                elif is_end_node(child):
                    raise SyntaxError(
                        '"end" does not close a block.',
                        [filename, child.lineno, child.col_offset,
                         source.splitlines()[child.lineno - 1] + '\n'])
                elif get_compound_bodies(child):
                    try:
                        ok = is_end_node(body[i + 1])
                    except IndexError:
                        ok = False
                    end
                    if not ok:
                        raise SyntaxError(
                            'This block is not closed with "end".',
                            [filename, child.lineno, child.col_offset,
                             source.splitlines()[child.lineno - 1] + '\n'])
                    end
                    skip_next = True
                end
            end
        end
    end
642603
def read_frame(self):
        
        header = Header.decode_header(self.stream)
        if header.flags:
            raise WebSocketError
        if not header.length:
            return header, ''
        try:
            payload = self.stream.read(header.length)
        except socket_error:
            payload = ''
        except Exception:
            logger.debug("{}: {}".format(type(e), six.text_type(e)))
            payload = ''
        if len(payload) != header.length:
            raise WebSocketError('Unexpected EOF reading frame payload')
        if header.mask:
            payload = header.unmask_payload(payload)
        return header, payload
1273893
function parseBody(req, limit, callback) {
  const body = [];

  function handleData(data) {
    body.push(data);

    /**
    Stop collecting data and call the callback with an error if request exceeds limit.
    Calling function should close the connection.
    */
    if (Buffer.concat(body).length > limit) {
      req.removeListener('data', handleData);
      req.removeListener('end', handleEnd);

      const error = new Error();
      error.httpCode = 413;
      error.message = http.STATUS_CODES[413];

      callback(error);
    }
  }

  function handleEnd() {
    const type = req.headers['content-type'];

    if (type === 'application/x-www-form-urlencoded') {
      callback(null, querystring.parse(Buffer.concat(body).toString()));

    } else if (type === 'application/json') {
      callback(null, JSON.parse(Buffer.concat(body).toString()));

    } else {
      callback(null, Buffer.concat(body).toString());
    }
  }

  req.on('data', handleData);
  req.on('end', handleEnd);
}
1346249
def find_importer_frame():
    
    byte = lambda ch: ord(ch) if PY2 else ch
    frame = inspect.currentframe()
    try:
        while frame:
            code = frame.f_code
            lasti = frame.f_lasti
            if byte(code.co_code[lasti]) == dis.opmap['IMPORT_NAME']:
                # FIXME: Support EXTENDED_ARG.
                arg = (
                    byte(code.co_code[lasti + 1])
                    + byte(code.co_code[lasti + 2]) * 256)
                name = code.co_names[arg]
                if name == 'end':
                    break
                end
            end
            frame = frame.f_back
        end
        return frame
    finally:
        del frame
    end
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')))
51551
def handle_close(self, header, payload):
        
        if not payload:
            self.close(1000, None)
            return
        if len(payload) < 2:
            raise WebSocketError('Invalid close frame: {0} {1}'.format(header, payload))
        rv = payload[:2]
        if six.PY2:
            code = struct.unpack('!H', str(rv))[0]
        else:
            code = struct.unpack('!H', bytes(rv))[0]
        payload = payload[2:]
        if payload:
            validator = Utf8Validator()
            val = validator.validate(payload)
            if not val[0]:
                raise UnicodeError
        if not self._is_valid_close_code(code):
            raise WebSocketError('Invalid close code {0}'.format(code))
        self.close(code, payload)
834659
def _parse_action(action):
    
    i_open = action.find('(')
    if i_open is -1:
        # return action name, finished
        return {'name': action, 'args': [], 'event_args': False}
    # we need to parse the arguments
    i_close = action.rfind(')')
    if i_close is -1:
        raise Exception('Bracket in argument opened but not closed.')
    action_name = action[:i_open]
    arglist = action[i_open+1:i_close].strip()
    if not arglist:
        # no arglist, just return method name
        return {'name': action_name, 'args': [], 'event_args': False}
    if '*' in arglist:
        return {'name': action_name, 'args': [], 'event_args': True}
    return {'name': action_name, 'args': _parse_arg_list(arglist), 'event_args': False}
47721
def handle_control_frame(self, frame):
        
        if frame.opcode == OPCODE_CLOSE:
            self.close_frame_received = True
            code, reason = frame.unpack_close()

            if self.close_frame_sent:
                self.onclose(code, reason)
                self.sock.close()
                raise SocketClosed(True)
            else:
                self.close_params = (code, reason)
                self.send_close_frame(code, reason)

        elif frame.opcode == OPCODE_PING:
            # Respond with a pong message with identical payload
            self.send_frame(ControlFrame(OPCODE_PONG, frame.payload))

        elif frame.opcode == OPCODE_PONG:
            # Assert that the PONG payload is identical to that of the PING
            if not self.ping_sent:
                raise PingError('received PONG while no PING was sent')

            self.ping_sent = False

            if frame.payload != self.ping_payload:
                raise PingError('received PONG with invalid payload')

            self.ping_payload = None
            self.onpong(frame.payload)
893
async def read_message(self) -> Optional[Data]:
        
        frame = await self.read_data_frame(max_size=self.max_size)

        # A close frame was received.
        if frame is None:
            return None

        if frame.opcode == OP_TEXT:
            text = True
        elif frame.opcode == OP_BINARY:
            text = False
        else:  # frame.opcode == OP_CONT
            raise WebSocketProtocolError("Unexpected opcode")

        # Shortcut for the common case - no fragmentation
        if frame.fin:
            return frame.data.decode("utf-8") if text else frame.data

        # 5.4. Fragmentation
        chunks: List[Data] = []
        max_size = self.max_size
        if text:
            decoder_factory = codecs.getincrementaldecoder("utf-8")
            # https://github.com/python/typeshed/pull/2752
            decoder = decoder_factory(errors="strict")  # type: ignore
            if max_size is None:

                def append(frame: Frame) -> None:
                    nonlocal chunks
                    chunks.append(decoder.decode(frame.data, frame.fin))

            else:

                def append(frame: Frame) -> None:
                    nonlocal chunks, max_size
                    chunks.append(decoder.decode(frame.data, frame.fin))
                    max_size -= len(frame.data)

        else:
            if max_size is None:

                def append(frame: Frame) -> None:
                    nonlocal chunks
                    chunks.append(frame.data)

            else:

                def append(frame: Frame) -> None:
                    nonlocal chunks, max_size
                    chunks.append(frame.data)
                    max_size -= len(frame.data)

        append(frame)

        while not frame.fin:
            frame = await self.read_data_frame(max_size=max_size)
            if frame is None:
                raise WebSocketProtocolError("Incomplete fragmented message")
            if frame.opcode != OP_CONT:
                raise WebSocketProtocolError("Unexpected opcode")
            append(frame)

        # mypy cannot figure out that chunks have the proper type.
        return ("" if text else b"").join(chunks)
1186399
def parse(self):
        ""
        if self._parsed: return
        root = self._root = to_ele(self._raw) # The <rpc-reply> element
        # Per RFC 4741 an <ok/> tag is sent when there are no errors or warnings
        ok = root.find(qualify("ok"))
        if ok is None:
            # Create RPCError objects from <rpc-error> elements
            error = root.find('.//'+qualify('rpc-error'))
            if error is not None:
                for err in root.getiterator(error.tag):
                    # Process a particular <rpc-error>
                    self._errors.append(self.ERROR_CLS(err))
        self._parsing_hook(root)
        self._parsed = True
883128
def parse_frame(buf):
    """"""
    # read header
    while buf.available < 2:
        yield

    data = buf.read(2)
    first_byte, second_byte = struct.unpack('!BB', data)

    fin = (first_byte >> 7) & 1
    rsv1 = (first_byte >> 6) & 1
    rsv2 = (first_byte >> 5) & 1
    rsv3 = (first_byte >> 4) & 1
    opcode = first_byte & 0xf

    # frame-fin = %x0 ; more frames of this message follow
    #           / %x1 ; final frame of this message
    # frame-rsv1 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    # frame-rsv2 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    # frame-rsv3 = %x0 ; 1 bit, MUST be 0 unless negotiated otherwise
    if rsv1 or rsv2 or rsv3:
        raise WebSocketError('Received frame with non-zero reserved bits')

    if opcode > 0x7 and fin == 0:
        raise WebSocketError('Received fragmented control frame')

    if fin == 0 and opcode == OPCODE_CONTINUATION:
        raise WebSocketError(
            'Received new fragment frame with non-zero opcode')

    has_mask = (second_byte >> 7) & 1
    length = (second_byte) & 0x7f

    # Control frames MUST have a payload length of 125 bytes or less
    if opcode > 0x7 and length > 125:
        raise WebSocketError(
            "Control frame payload cannot be larger than 125 bytes")

    # read payload
    if length == 126:
        while buf.available < 2:
            yield

        length = struct.unpack_from('!H', buf.read(2))[0]
    elif length > 126:
        while buf.available < 4:
            yield

        length = struct.unpack_from('!Q', buf.read(4))[0]

    if has_mask:
        while buf.available < 4:
            yield

        mask = buf.read(4)

    if length:
        while buf.available < length:
            yield

        payload = buf.read(length)
    else:
        payload = b''

    if has_mask:
        mask = [ord(i) for i in mask]
        payload = [chr(ord(b) ^ mask[i % 4]) for i, b in enumerate(payload)]

    yield fin, opcode, payload