Puts the connection into binary (image) mode, issues the given command,
 and fetches the data returned, passing it to the associated block in
 chunks of +blocksize+ characters. Note that +cmd+ is a server command
 (such as "RETR myfile").
558558
def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
      synchronize do
	with_binary(true) do
          conn = transfercmd(cmd, rest_offset)
          loop do
            data = conn.read(blocksize)
            break if data == nil
            yield(data)
          end
          conn.close
          voidresp
        end
      end
    end
1052614
async def execute_command(
        self, *args: bytes, timeout: NumType = None
    ) -> SMTPResponse:
        
        command = b" ".join(args) + b"\r\n"

        await self.write_and_drain(command, timeout=timeout)
        response = await self.read_response(timeout=timeout)

        return response
316971
def send(command, data):
    
    global _lock
    try:
        _lock.acquire()
        data = data.encode('utf8')
        assert len(data) < 1000000, 'Command too long'
        msg = b'%b%06d%b' % (command.value, len(data), data)
        logging.getLogger(__name__).debug('Sending command, data: [%s]' % msg)
        _out_file.write(msg)
        _out_file.flush()
    finally:
        _lock.release()
1357739
def _call(self, cmd, get_output):
        
        server_err = self.server_logger()

        chan = self.get_client().get_transport().open_session()
        try:
            logger.debug("Invoking %r%s",
                         cmd, " (stdout)" if get_output else "")
            chan.exec_command('/bin/sh -c %s' % shell_escape(cmd))
            output = b''
            while True:
                r, w, e = select.select([chan], [], [])
                if chan not in r:
                    continue  # pragma: no cover
                recvd = False
                while chan.recv_stderr_ready():
                    data = chan.recv_stderr(1024)
                    server_err.append(data)
                    recvd = True
                while chan.recv_ready():
                    data = chan.recv(1024)
                    if get_output:
                        output += data
                    recvd = True
                if not recvd and chan.exit_status_ready():
                    break
            output = output.rstrip(b'\r\n')
            return chan.recv_exit_status(), output
        finally:
            server_err.done()
            chan.close()
4927
def send(self, command):
        

        # uBridge responses are of the form:
        #   1xx yyyyyy\r\n
        #   1xx yyyyyy\r\n
        #   ...
        #   100-yyyy\r\n
        # or
        #   2xx-yyyy\r\n
        #
        # Where 1xx is a code from 100-199 for a success or 200-299 for an error
        # The result might be multiple lines and might be less than the buffer size
        # but still have more data. The only thing we know for sure is the last line
        # will begin with '100-' or a '2xx-' and end with '\r\n'

        if self._writer is None or self._reader is None:
            raise UbridgeError("Not connected")

        try:
            command = command.strip() + '\n'
            log.debug("sending {}".format(command))
            self._writer.write(command.encode())
            yield from self._writer.drain()
        except OSError as e:
            raise UbridgeError("Lost communication with {host}:{port} :{error}, Dynamips process running: {run}"
                               .format(host=self._host, port=self._port, error=e, run=self.is_running()))

        # Now retrieve the result
        data = []
        buf = ''
        retries = 0
        max_retries = 10
        while True:
            try:
                try:
                    chunk = yield from self._reader.read(1024)
                except asyncio.CancelledError:
                    # task has been canceled but continue to read
                    # any remaining data sent by the hypervisor
                    continue
                except ConnectionResetError as e:
                    # Sometimes WinError 64 (ERROR_NETNAME_DELETED) is returned here on Windows.
                    # These happen if connection reset is received before IOCP could complete
                    # a previous operation. Ignore and try again....
                    log.warning("Connection reset received while reading uBridge response: {}".format(e))
                    continue
                if not chunk:
                    if retries > max_retries:
                        raise UbridgeError("No data returned from {host}:{port}, uBridge process running: {run}"
                                            .format(host=self._host, port=self._port, run=self.is_running()))
                    else:
                        retries += 1
                        yield from asyncio.sleep(0.1)
                        continue
                retries = 0
                buf += chunk.decode("utf-8")
            except OSError as e:
                raise UbridgeError("Lost communication with {host}:{port} :{error}, uBridge process running: {run}"
                                   .format(host=self._host, port=self._port, error=e, run=self.is_running()))

            # If the buffer doesn't end in '\n' then we can't be done
            try:
                if buf[-1] != '\n':
                    continue
            except IndexError:
                raise UbridgeError("Could not communicate with {host}:{port}, uBridge process running: {run}"
                                   .format(host=self._host, port=self._port, run=self.is_running()))

            data += buf.split('\r\n')
            if data[-1] == '':
                data.pop()
            buf = ''

            # Does it contain an error code?
            if self.error_re.search(data[-1]):
                raise UbridgeError(data[-1][4:])

            # Or does the last line begin with '100-'? Then we are done!
            if data[-1][:4] == '100-':
                data[-1] = data[-1][4:]
                if data[-1] == 'OK':
                    data.pop()
                break

        # Remove success responses codes
        for index in range(len(data)):
            if self.success_re.search(data[index]):
                data[index] = data[index][4:]

        log.debug("returned result {}".format(data))
        return data
853813
def execute_cmd(cmd, **kwargs):
    
    yield '$ {}\n'.format(' '.join(cmd))
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.STDOUT

    proc = subprocess.Popen(cmd, **kwargs)

    # Capture output for logging.
    # Each line will be yielded as text.
    # This should behave the same as .readline(), but splits on `\r` OR `\n`,
    # not just `\n`.
    buf = []
    def flush():
        line = b''.join(buf).decode('utf8', 'replace')
        buf[:] = []
        return line

    c_last = ''
    try:
        for c in iter(partial(proc.stdout.read, 1), b''):
            if c_last == b'\r' and buf and c != b'\n':
                yield flush()
            buf.append(c)
            if c == b'\n':
                yield flush()
            c_last = c
    finally:
        ret = proc.wait()
        if ret != 0:
            raise subprocess.CalledProcessError(ret, cmd)
42638
def cmd(name, *params)
      @mutex.synchronize do
        connect unless connected?
        @conn.write "#{name} #{params.join(' ').gsub('\\', '\\\\\\')}\n"
        status, length = conn_gets.split # <status> <content_length>\n
        content = conn_read(length.to_i + 1) # +1 = \n
        content.chomp!
        raise CommandFailed, "Command #{name} returned with status #{status}: #{content}" if status.to_i != 200
        content
      end
    end
363657
function sendCommand(bleObj, cmd, callback)
{
	var bleBuffer = new ble.charArray(bufferLength);
	bleObj.writeData(cmd, cmd.length);

	// wait up to 1 second
	if (bleObj.dataAvailable(1000))
    {
		bleObj.readData(bleBuffer, bufferLength);
		var bleData = "";
		// read only the number of characters
		// specified by myGPSSensor.readData
		for (var x = 0; x < bufferLength; x++)
		{
			if (bleBuffer.getitem(x) == '\0')
				break;
			else
				bleData += bleBuffer.getitem(x);
		}
		console.log(bleData);
    }
	else
		console.log("Timed out waiting for response");
	if (callback)
		callback();
}
52145
def _get_command_buffer(self, host_id, command_name):
        """"""
        buf = self._cb_poll.get(host_id)
        if buf is not None:
            return buf

        if self._max_concurrency is not None:
            while len(self._cb_poll) >= self._max_concurrency:
                self.join(timeout=1.0)

        def connect():
            return self.connection_pool.get_connection(
                command_name, shard_hint=host_id)
        buf = CommandBuffer(host_id, connect, self.auto_batch)
        self._cb_poll.register(host_id, buf)
        return buf
1302381
private void handleMasterCommand(Command cmd) throws IOException, ConnectionFailedException {
    if (cmd == null) {
      return;
    }
    switch (cmd.getCommandType()) {
      // Currently unused
      case Delete:
        break;
      // Master requests blocks to be removed from Alluxio managed space.
      case Free:
        mAsyncBlockRemover.addBlocksToDelete(cmd.getDataList());
        break;
      // No action required
      case Nothing:
        break;
      // Master requests re-registration
      case Register:
        mWorkerId.set(mMasterClient.getId(mWorkerAddress));
        registerWithMaster();
        break;
      // Unknown request
      case Unknown:
        LOG.error("Master heartbeat sends unknown command {}", cmd);
        break;
      default:
        throw new RuntimeException("Un-recognized command from master " + cmd);
    }
  }
273563
def send (self, command, *args, **kwargs):
        
        status   = False
        cmdobj   = self._cmddict.create(command, *args, **kwargs)
        messages = []

        if not cmdobj.validate(messages):
            for msg in messages:
                log.error(msg)
        else:
            encoded = cmdobj.encode()

            if self._verbose:
                size = len(cmdobj.name)
                pad  = (size - len(cmdobj.name) + 1) * ' '
                gds.hexdump(encoded, preamble=cmdobj.name + ':' + pad)

            try:
                values = (self._host, self._port, str(cmdobj))
                log.command('Sending to %s:%d: %s' % values)
                self._socket.sendto(encoded, (self._host, self._port))
                status = True

                with pcap.open(self.CMD_HIST_FILE, 'a') as output:
                    output.write(str(cmdobj))
            except socket.error as e:
                log.error(e.message)
            except IOError as e:
                log.error(e.message)

        return status
1000268
def readCmd(cls, cmd):
        
        args = shlex.split(cmd)
        proc = subprocess.Popen(args, stdout=subprocess.PIPE)
        (proc_stdout, proc_stderr) = proc.communicate(input=None)  # proc_stdin
        return proc_stdout.decode()
1007652
def data_from_payload(self, cmd):
        
        multipart = False
        ckey      = "%s /%s" % (self.command, cmd)

        if not isinstance(self._query_params, dict):
            self._query_params = {}

        if ckey in _NCMD:
            self._cmd = _NCMD[ckey]
        else:
            for key in sorted(_RCMD, key=len, reverse=True):
                if not key.startswith("%s " % self.command):
                    continue

                m = _RCMD[key].name.match(cmd)
                if m:
                    self._cmd = _RCMD[key]
                    self._query_params.update(m.groupdict())
                    break

        try:
            if not self._cmd:
                raise self.req_error(404)

            tenc     = self.headers.get('Transfer-Encoding')
            if tenc and tenc.lower() != 'identity':
                raise self.req_error(501, "Not supported; Transfer-Encoding: %s" % tenc)

            ctype    = self.headers.get('Content-Type')
            if ctype:
                ctype = ctype.lower().split(';', 1)[0]
                if ctype == 'multipart/form-data':
                    if not self._ALLOWED_MULTIPART_FORM:
                        raise self.req_error(501, "Not supported; Content-Type: %s", ctype)
                    multipart = True
                elif self._ALLOWED_CONTENT_TYPES:
                    ct_found = False
                    for x in self._ALLOWED_CONTENT_TYPES:
                        if ctype == x:
                            ct_found = True
                            break
                    if not ct_found:
                        raise self.req_error(501, "Not supported; Content-Type: %s" % ctype)

            try:
                clen = long(self.headers.get('Content-Length') or 0)
            except (ValueError, TypeError):
                raise self.req_error(411)

            if clen < 0:
                raise self.req_error(411)
            elif clen > long(_OPTIONS['max_body_size']):
                raise self.req_error(413)

            if self._cmd.to_auth:
                self.authenticate(self._cmd.auth_users)

            if clen > 0:
                payload       = self.rfile.read(clen)
                self._payload = StringIO(payload)

                if multipart:
                    try:
                        self._payload_params = cgi.FieldStorage(environ = {'REQUEST_METHOD': 'POST'},
                                                                fp      = self._payload,
                                                                headers = self.headers)
                    except Exception, e:
                        raise self.req_error(415, text=str(e))
                else:
                    charset = self._cmd.charset or DEFAULT_CHARSET

                    try:
                        if ctype == 'application/x-www-form-urlencoded':
                            self._payload_params = urlparse.parse_qsl(payload)
                        else:
                            self._payload_params = self.parse_payload(payload, charset)
                    except ValueError, e:
                        raise self.req_error(415, text=str(e))

            res = self._cmd.handler(self)

            if not isinstance(res, HttpResponse):
                return self.response_dumps(res)

            return res
        finally:
            payload                 = None
            self._payload           = None
            self._payload_params    = None
            self._query_params      = {}
1292776
def execute(self, cmd, block_size=DEFAULT_EXECUTE_READ_BLOCK_SIZE):
        
    
        with SshChannel(self) as sc:
            self.__log.debug("Executing command: %s" % (cmd))

            sc.open_session()
            sc.request_exec(cmd)

            buffer_ = bytearray()
            while 1:
                bytes = sc.read(block_size)
                yield bytes
                
                if len(bytes) < block_size:
                    break
233574
def fetch(self, command):
        
        logging.debug('SENT: %s: %s' % (self.host, command))
        self.write('%s\n' % command)
        while 1:
            buffer = self.read_until('\n').strip()
            if len(buffer):
                break
        status, length = map(int, buffer.split())
        content = ''
        assert status == 200, 'Bad response code: {status} {text} ({command})'.format(status=status, text=self.read_until('\n').strip(), command=command)
        while len(content) < length:
            content += self.read_until('\n')
        logging.debug('RECV: %s: %dB %s' % (status,length,content[:30]))
        self.read_eager()
        return (status, length), content
81280
def retrlines(cmd) # :yield: line
      synchronize do
	with_binary(false) do
          conn = transfercmd(cmd)
          loop do
            line = conn.gets
            break if line == nil
            yield(line.sub(/\r?\n\z/, ""), !line.match(/\n\z/).nil?)
          end
          conn.close
          voidresp
        end
      end
    end
1234491
def command(self, command, arg=None):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:
            sock.connect((self.host, self.port))
            payload = {"command": command}
            if arg is not None:
                # Parameter must be converted to basestring (no int)
                payload.update({'parameter': unicode(arg)})

            sock.send(json.dumps(payload))
            received = self._receive(sock)
        finally:
            sock.shutdown(socket.SHUT_RDWR)
            sock.close()

        return json.loads(received[:-1])