Reads and processes RETURNVALUE stream.

        This stream is used to send OUTPUT parameters from RPC to client.
        Stream format url: http://msdn.microsoft.com/en-us/library/dd303881.aspx
515435
def process_param(self):
        
        self.log_response_message('got RETURNVALUE message')
        r = self._reader
        if tds_base.IS_TDS72_PLUS(self):
            ordinal = r.get_usmallint()
        else:
            r.get_usmallint()  # ignore size
            ordinal = self._out_params_indexes[self.return_value_index]
        name = r.read_ucs2(r.get_byte())
        r.get_byte()  # 1 - OUTPUT of sp, 2 - result of udf
        param = tds_base.Column()
        param.column_name = name
        self.get_type_info(param)
        param.value = param.serializer.read(r)
        self.output_params[ordinal] = param
        self.return_value_index += 1
635599
public void streamResult(OutputStream os,
                          HeadersAmp headers,
                          String address,
                          long qId,
                          int sequence,
                          List<Object> values,
                          Throwable exn,
                          boolean isComplete)
     throws IOException
  {
    init(os);

    OutH3 out = _out;

    if (out == null) {
      return;
    }
    
    if (log.isLoggable(_level)) {
      log.log(_level, "hamp-stream-result-w " + values + "," + isComplete + " (in " + this + ")"
                 + "\n  {id:" + qId + " to:" + address + ", " + headers + "," + os + "}");
    }
    
    try {
      out.writeLong(MessageTypeHamp.STREAM_RESULT.ordinal());
    
      writeHeaders(out, headers);
    
      writeToAddress(out, address);
      out.writeLong(qId);
      
      out.writeLong(sequence);

      out.writeObject(values);
      out.writeObject(exn);
      out.writeBoolean(isComplete);
      
      //out.flushBuffer();
      out.flush();
    } catch (Throwable e) {
      log.log(Level.WARNING, e.toString(), e);
      
      throw e;
    }
  }
1070593
private long processNackWithReturnValue(ControlNack nackMsg)
                    throws SIResourceException
    {
        // This is called by a PubSubOutputHandler when it finds Unknown
        // ticks in it's own stream and need the InputStream to resend them
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "processNackWithReturnValue", nackMsg);

        long returnValue = -1;

        // The upstream cellule for this stream is stored in the originStreamMap
        // unless we were the originator.
        SIBUuid12 stream = nackMsg.getGuaranteedStreamUUID();

        if (_sourceStreamManager.hasStream(stream))
        {
            // 242139: Currently we get back to here for every processNack
            // that the InternalOutputStream handles. This is an error but
            // a harmles one. For now the fix is to avoid throwing an exception 
            // as the InternalOutputstream has in fact satisfied the Nack correctly.  
            // The longer term fix is to writeCombined range into the IOS not just the
            // value

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Ignoring processNack on sourceStream at PubSubInputHandler");

            returnValue = _sourceStreamManager.getStreamSet().getStream(nackMsg.getPriority(), nackMsg.getReliability()).getCompletedPrefix();
        }
        else
        {
            // Else we are an IME
            //  send nacks if necessary
            _internalInputStreamManager.processNack(nackMsg);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "processNackWithReturnValue", new Long(returnValue));

        return returnValue;

    }
226899
void readToData(boolean returnOnYield)
        throws IOException
    {
        InputStream is = getInputStream();

        if (is == null)
            return;

        for (int tag = is.read(); tag >= 0; tag = is.read()) {
            switch (tag) {
                case 'Y':
                    server.freeReadLock();
                    if (returnOnYield)
                        return;
                    server.readChannel(channel);
                    break;

                case 'Q':
                    server.freeReadLock();
                    this.is = null;
                    this.server = null;
                    return;

                case 'U':
                    this.url = readUTF();
                    break;

                case 'D':
                    chunkLength = (is.read() << 8) + is.read();
                    return;

                default:
                    readTag(tag);
                    break;
            }
        }
    }
1345523
private RpcElement readRpc(Location location, String documentation) {
    String name = reader.readName();

    reader.require('(');

    boolean requestStreaming = false;
    String requestType;
    String word = reader.readWord();
    if (word.equals("stream")) {
      requestStreaming = true;
      requestType = reader.readDataType();
    } else {
      requestType = reader.readDataType(word);
    }
    reader.require(')');

    if (!reader.readWord().equals("returns")) throw reader.unexpected("expected 'returns'");

    reader.require('(');

    boolean responseStreaming = false;
    String responseType;
    word = reader.readWord();
    if (word.equals("stream")) {
      responseStreaming = true;
      responseType = reader.readDataType();
    } else {
      responseType = reader.readDataType(word);
    }
    reader.require(')');

    ImmutableList.Builder<OptionElement> options = ImmutableList.builder();
    if (reader.peekChar('{')) {
      while (true) {
        String rpcDocumentation = reader.readDocumentation();
        if (reader.peekChar('}')) {
          break;
        }
        Object declared = readDeclaration(rpcDocumentation, Context.RPC);
        if (declared instanceof OptionElement) {
          options.add((OptionElement) declared);
        }
      }
    } else {
      reader.require(';');
    }

    return new RpcElement(
        location,
        name,
        documentation,
        requestType,
        responseType,
        requestStreaming,
        responseStreaming,
        options.build()
    );
  }
1288066
function read (req, res, next, parse, debug, options) {
  var length
  var opts = options || {}
  var stream

  // flag as parsed
  req._body = true

  // read options
  var encoding = opts.encoding !== null
    ? opts.encoding || 'utf-8'
    : null
  var verify = opts.verify

  try {
    // get the content stream
    stream = contentstream(req, debug, opts.inflate)
    length = stream.length
    stream.length = undefined
  } catch (err) {
    return next(err)
  }

  // set raw-body options
  opts.length = length
  opts.encoding = verify
    ? null
    : encoding

  // assert charset is supported
  if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
    return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
      charset: encoding.toLowerCase()
    }))
  }

  // read body
  debug('read body')
  getBody(stream, opts, function (err, body) {
    if (err) {
      // default to 400
      setErrorStatus(err, 400)

      // echo back charset
      if (err.type === 'encoding.unsupported') {
        err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
          charset: encoding.toLowerCase()
        })
      }

      // read off entire request
      stream.resume()
      onFinished(req, function onfinished () {
        next(err)
      })
      return
    }

    // verify
    if (verify) {
      try {
        debug('verify body')
        verify(req, res, body, encoding)
      } catch (err) {
        // default to 403
        setErrorStatus(err, 403)
        next(err)
        return
      }
    }

    // parse
    var str
    try {
      debug('parse body')
      str = typeof body !== 'string' && encoding !== null
        ? iconv.decode(body, encoding)
        : body
      req.body = parse(str)
    } catch (err) {
      err.body = str === undefined
        ? body
        : str

      // default to 400
      setErrorStatus(err, 400)

      next(err)
      return
    }

    next()
  })
}
1169321
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0):
        '''
        
        '''

        # initiate protocol
        error_count = 0
        char = 0
        cancel = 0
        while True:
            # first try CRC mode, if this fails,
            # fall back to checksum mode
            if error_count >= retry:
                self.abort(timeout=timeout)
                return None
            elif crc_mode and error_count < (retry / 2):
                if not self.putc(CRC):
                    time.sleep(delay)
                    error_count += 1
            else:
                crc_mode = 0
                if not self.putc(NAK):
                    time.sleep(delay)
                    error_count += 1

            char = self.getc(1, timeout)
            if not char:
                error_count += 1
                continue
            elif char == SOH:
                #crc_mode = 0
                break
            elif char == STX:
                break
            elif char == CAN:
                if cancel:
                    return None
                else:
                    cancel = 1
            else:
                error_count += 1

        # read data
        error_count = 0
        income_size = 0
        packet_size = 128
        sequence = 1
        cancel = 0
        while True:
            while True:
                if char == SOH:
                    packet_size = 128
                    break
                elif char == STX:
                    packet_size = 1024
                    break
                elif char == EOT:
                    # We received an EOT, so send an ACK and return the received
                    # data length
                    self.putc(ACK)
                    return income_size
                elif char == CAN:
                    # cancel at two consecutive cancels
                    if cancel:
                        return None
                    else:
                        cancel = 1
                else:
                    if not quiet:
                        print >> sys.stderr, \
                            'recv ERROR expected SOH/EOT, got', ord(char)
                    error_count += 1
                    if error_count >= retry:
                        self.abort()
                        return None
            # read sequence
            error_count = 0
            cancel = 0
            seq1 = ord(self.getc(1))
            seq2 = 0xff - ord(self.getc(1))
            if seq1 == sequence and seq2 == sequence:
                # sequence is ok, read packet
                # packet_size + checksum
                data = self.getc(packet_size + 1 + crc_mode, timeout)
                if crc_mode:
                    csum = (ord(data[-2]) << 8) + ord(data[-1])
                    data = data[:-2]
                    log.debug('CRC (%04x <> %04x)' % \
                        (csum, self.calc_crc(data)))
                    valid = csum == self.calc_crc(data)
                else:
                    csum = data[-1]
                    data = data[:-1]
                    log.debug('checksum (checksum(%02x <> %02x)' % \
                        (ord(csum), self.calc_checksum(data)))
                    valid = ord(csum) == self.calc_checksum(data)

                # valid data, append chunk
                if valid:
                    income_size += len(data)
                    stream.write(data)
                    self.putc(ACK)
                    sequence = (sequence + 1) % 0x100
                    char = self.getc(1, timeout)
                    continue
            else:
                # consume data
                self.getc(packet_size + 1 + crc_mode)
                self.debug('expecting sequence %d, got %d/%d' % \
                    (sequence, seq1, seq2))

            # something went wrong, request retransmission
            self.putc(NAK)
962106
public int readFrom(InputStream stream) throws IOException {
        int bytesRead = stream.read(buffer);
        if (bytesRead < 0) {
            bytesInBuffer = 0;
        } else {
            bytesInBuffer = bytesRead;
        }
        return bytesRead;
    }
815006
def getoutputencoding(stream=None):
    
    if stream is None:
        stream = sys.stdout
    encoding = stream.encoding
    if not encoding:
        encoding = getpreferredencoding()
    return encoding
1122238
private boolean readNextValue() throws IOException, SQLException {
    byte[] buf = reader.getPacketArray(false);

    //is error Packet
    if (buf[0] == ERROR) {
      protocol.removeActiveStreamingResult();
      protocol.removeHasMoreResults();
      protocol.setHasWarnings(false);
      ErrorPacket errorPacket = new ErrorPacket(new Buffer(buf));
      resetVariables();
      throw ExceptionMapper.get(errorPacket.getMessage(), errorPacket.getSqlState(),
          errorPacket.getErrorNumber(), null, false);
    }

    //is end of stream
    if (buf[0] == EOF && ((eofDeprecated && buf.length < 0xffffff)
        || (!eofDeprecated && buf.length < 8))) {
      int serverStatus;
      int warnings;

      if (!eofDeprecated) {
        //EOF_Packet
        warnings = (buf[1] & 0xff) + ((buf[2] & 0xff) << 8);
        serverStatus = ((buf[3] & 0xff) + ((buf[4] & 0xff) << 8));

        //CallableResult has been read from intermediate EOF server_status
        //and is mandatory because :
        //
        // - Call query will have an callable resultSet for OUT parameters
        //   this resultSet must be identified and not listed in JDBC statement.getResultSet()
        //
        // - after a callable resultSet, a OK packet is send,
        //   but mysql before 5.7.4 doesn't send MORE_RESULTS_EXISTS flag
        if (callableResult) {
          serverStatus |= MORE_RESULTS_EXISTS;
        }

      } else {

        //OK_Packet with a 0xFE header
        int pos = skipLengthEncodedValue(buf, 1); //skip update count
        pos = skipLengthEncodedValue(buf, pos); //skip insert id
        serverStatus = ((buf[pos++] & 0xff) + ((buf[pos++] & 0xff) << 8));
        warnings = (buf[pos++] & 0xff) + ((buf[pos] & 0xff) << 8);
        callableResult = (serverStatus & PS_OUT_PARAMETERS) != 0;
      }
      protocol.setServerStatus((short) serverStatus);
      protocol.setHasWarnings(warnings > 0);
      if ((serverStatus & MORE_RESULTS_EXISTS) == 0) {
        protocol.removeActiveStreamingResult();
      }

      resetVariables();
      return false;
    }

    //this is a result-set row, save it
    if (dataSize + 1 >= data.length) {
      growDataArray();
    }
    data[dataSize++] = buf;
    return true;
  }
696715
def GetStream(data=None):
        
        if len(__mstreams_available__) == 0:
            if data:
                mstream = MemoryStream(data)
                mstream.seek(0)
            else:
                mstream = MemoryStream()
            __mstreams__.append(mstream)
            return mstream

        mstream = __mstreams_available__.pop()

        if data is not None and len(data):
            mstream.Cleanup()
            mstream.write(data)

        mstream.seek(0)

        return mstream
583787
function streamToJsonValue (res, cb) {
  streamToValue(res, (err, data) => {
    if (err) {
      return cb(err)
    }

    if (!data || data.length === 0) {
      return cb()
    }

    // TODO: check if needed, afaik JSON.parse can parse Buffers
    if (Buffer.isBuffer(data)) {
      data = data.toString()
    }

    let res
    try {
      res = JSON.parse(data)
    } catch (err) {
      return cb(err)
    }

    cb(null, res)
  })
}
450229
public int getReturnCode() {
        long returnCode = this.stagingByteBuffer.getLong(RETURN_CODE_INDEX * 8);
        if (returnCode > Integer.MAX_VALUE) {
            AsyncException ae = new AsyncException("Return code value invalid");
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Invalid value returned for return code, exception: " + ae.getMessage());
            }
            FFDCFilter.processException(ae, getClass().getName(), "227", this);
            return Integer.MAX_VALUE;
        }
        return (int) returnCode;
    }
688705
def rest_get_stream(self, url, session=None, verify=True, cert=None):
        
        res = session.get(url, stream=True, verify=verify, cert=cert)
        return res.raw, res.status_code
912997
function readValue(str) {
            shared.utils.dassert(shared.utils.isValue(str));
            var rs = new ReadStream(str);
            return rs.readNextValue();
        }
747198
def output(self, stream, disabletransferencoding = None):
        
        if self._sendHeaders:
            raise HttpProtocolException('Cannot modify response, headers already sent')
        self.outputstream = stream
        try:
            content_length = len(stream)
        except Exception:
            pass
        else:
            self.header(b'Content-Length', str(content_length).encode('ascii'))
        if disabletransferencoding is not None:
            self.disabledeflate = disabletransferencoding
        self._startResponse()
1269317
def _handle_return(self, node, scope, ctxt, stream):
        
        self._dlog("handling return")
        if node.expr is None:
            ret_val = None
        else:
            ret_val = self._handle_node(node.expr, scope, ctxt, stream)
        self._dlog("return value = {}".format(ret_val))
        raise errors.InterpReturn(ret_val)