Export a remote function.

        Args:
            remote_function: the RemoteFunction object.
193888
def export(self, remote_function):
        
        if self._worker.mode is None:
            # If the worker isn't connected, cache the function
            # and export it later.
            self._functions_to_export.append(remote_function)
            return
        if self._worker.mode != ray.worker.SCRIPT_MODE:
            # Don't need to export if the worker is not a driver.
            return
        self._do_export(remote_function)
1172458
def write_to_remote(self, filepath_from, filepath_to, mtime_dt=None):
        """"""

        self.__log.debug("Writing L[%s] -> R[%s]." % (filepath_from, 
                                                      filepath_to))

        with open(filepath_from, 'rb') as file_from:
            with SftpFile(self, filepath_to, 'w') as sf_to:
                while 1:
                    part = file_from.read(MAX_MIRROR_WRITE_CHUNK_SIZE)
                    sf_to.write(part)

                    if len(part) < MAX_MIRROR_WRITE_CHUNK_SIZE:
                        break

        if mtime_dt is None:
            mtime_dt = datetime.now()

        self.utimes_dt(filepath_to, mtime_dt, mtime_dt)
720010
def query_func_module(self, func):
        """"""
        exp = self.session.query(Export).filter_by(
            func=func).first()
        if exp:
            return exp
        logging.debug(_('Function not found: %s'), func)
        alt = func + 'A'
        exp = self.session.query(Export).filter_by(
            func=alt).first()
        if exp:
            logging.warning(_('Using ANSI version: %s'), alt)
            return exp
        logging.warning(_('Not handled: %s or %s'), func, alt)
        return None
304801
function RemoteError(error) {
    /**
     * @member {string} message A message detailing the error.
     * @memberof module:rodosha/messages~RemoteError
     * @instance
     */
    var message = error.message || "Unknown error";
    var name = "RemoteError" + (error.name ? ("[" + error.name + "]") : "");
    Error.call(message);

    /* Inject properties */
    this.message = message;
    this.name = name;
    this.toString = function() {
      return name + ": " + message;
    }

    /**
     * @member {string} stack The stack trace associated with this instance,
     *                        combining both local and remote details.
     * @memberof module:rodosha/messages~RemoteError
     * @instance
     */
    var localStack = this.stack || new Error().stack;
    if (localStack) localStack = localStack.replace(/^(Remote)?Error\n/, '');

    if ((error.stack) || (localStack)) {
      var stack = this.toString();
      if (error.stack) stack += "\n- Remote stack:\n" + error.stack;
      if (localStack)  stack += "\n- Local stack:\n"  + localStack;
      this.stack = stack;
    }

  }
177582
def exec_func_src(func, globals_=None, locals_=None, key_list=None,
                  sentinal=None, update=None, keys=None, verbose=False,
                  start=None, stop=None):
    
    if keys is None:
        keys = key_list
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if update is None:
        update = ut.inIPython()
    if globals_ is None:
        globals_ = ut.get_parent_frame().f_globals
    if locals_ is None:
        locals_ = ut.get_parent_frame().f_locals
    if sentinal is not None:
        sourcecode = ut.replace_between_tags(sourcecode, '', sentinal)
    if start is not None or stop is not None:
        sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)])
    globals_new = globals_.copy()
    if locals_ is not None:
        globals_new.update(locals_)
        # globals_new.update({k: v for k, v in locals_.items()
        #                     if k not in globals_new})
    orig_globals = globals_new.copy()
    #six.exec_(sourcecode, globals_new, locals_)
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    six.exec_(sourcecode, globals_new)
    # Draw intermediate steps
    if keys is None:
        #return locals_
        # Remove keys created in function execution
        ut.delete_keys(globals_new, orig_globals.keys())
        if update:
            # update input globals?
            globals_.update(globals_new)
        # ~~ TODO autodetermine the keys from the function vars
        return globals_new
    else:
        if update:
            # update input globals?
            globals_.update(globals_new)
        #var_list = ut.dict_take(locals_, keys)
        var_list = ut.dict_take(globals_new, keys)
        return var_list
1012140
def rpc_export(rpc_method_name, sync=False):
    """"""
    def dec(f):
        f._nvim_rpc_method_name = rpc_method_name
        f._nvim_rpc_sync = sync
        f._nvim_bind = True
        f._nvim_prefix_plugin_path = False
        return f
    return dec
106643
def call(self, command, *args):
        

        if not command:
            return

        # Look for local methods first
        try:
            res = self.registered[command]['function'](self, *args)
            return Response('local', res, None)

        # Method not found, try remote
        except KeyError:

            # Execute remote command
            res, err = self.client.call(command, *args)
            return Response('remote', res, err, self.client.is_multi())

        # Local exception
        except Exception as e:
            return Response('local', res, str(e))
957486
def export_fun(args):
  """"""
  # Input placeholder for inferencing
  x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS], name="x")

  # Variables of the hidden layer
  hid_w = tf.Variable(tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, hidden_units],
                      stddev=1.0 / IMAGE_PIXELS), name="hid_w")
  hid_b = tf.Variable(tf.zeros([hidden_units]), name="hid_b")
  tf.summary.histogram("hidden_weights", hid_w)

  # Variables of the softmax layer
  sm_w = tf.Variable(tf.truncated_normal([hidden_units, 10],
                     stddev=1.0 / math.sqrt(hidden_units)), name="sm_w")
  sm_b = tf.Variable(tf.zeros([10]), name="sm_b")

  hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)
  hid = tf.nn.relu(hid_lin)
  y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))
  prediction = tf.argmax(y, 1, name="prediction")

  saver = tf.train.Saver()

  with tf.Session() as sess:
    # load graph from a checkpoint
    logging.info("model path: {}".format(args.model_dir))
    ckpt = tf.train.get_checkpoint_state(args.model_dir)
    logging.info("ckpt: {}".format(ckpt))
    assert ckpt and ckpt.model_checkpoint_path, "Invalid model checkpoint path: {}".format(args.model_dir)
    saver.restore(sess, ckpt.model_checkpoint_path)

    logging.info("Exporting saved_model to: {}".format(args.export_dir))
    # exported signatures defined in code
    signatures = {
      tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY: {
        'inputs': {'image': x},
        'outputs': {'prediction': prediction},
        'method_name': tf.saved_model.signature_constants.PREDICT_METHOD_NAME
      },
      'featurize': {
        'inputs': {'image': x},
        'outputs': {'features': hid},
        'method_name': 'featurize'
      }
    }
    TFNode.export_saved_model(sess,
                              args.export_dir,
                              tf.saved_model.tag_constants.SERVING,
                              signatures)
    logging.info("Exported saved_model")
1075667
def run_key(self, key):
        '''
        
        '''
        def func(*args, **kwargs):
            '''
            Run a remote call
            '''
            args = list(args)
            for _key, _val in kwargs:
                args.append('{0}={1}'.format(_key, _val))
            return self.local.cmd(self.minion, key, args)
        return func
741825
def remote_command(function, self, *args, **kwargs):
    '''
    
    '''
    try:
        return function(self, *args, **kwargs)
    except RuntimeError, exception:
        error_message = str(exception)
        match = CRE_REMOTE_ERROR.match(error_message)
        if match:
            # Exception message matches format of remote firmware error.
            command_code = int(match.group('command_int'))
            return_code = int(match.group('return_code_int'))
            raise FirmwareError(command_code, return_code)

        match = CRE_REMOTE_COMMAND_ERROR.match(error_message)
        if match:
            # Exception message matches format of remote firmware error.
            command_code = int(match.group('command_int'))
            command_name = NAMES_BY_COMMAND_CODE[command_code]
            raise RuntimeError(CRE_REMOTE_COMMAND_ERROR.sub(command_name,
                                                            error_message))

        # Not a remote firmware error, so raise original exception.
        raise
673726
def call_remote(method, args)
      # Blank out username and password
      safe_args = args.inject([]) {|memo, v| memo << ((memo.last == :username or memo.last == :password) ? "" : v) }
      key = "#{method}(#{safe_args.join(':')})"
      
      if @recording
        response = super(method, args)
        
        unless @recorded_responses[key]
          # track this { key => request } to avoid duplication in the YAML
          @recorded_responses[key] = true
          
          YAML.dump({ key => response }, @recording_source)
        end
      else
        response = @recorded_responses[key]
        raise ASFRecordingBindingError.new(@logger, "Unable to find matching response for recorded request '#{key}'") unless response
      end
      
      response
    end
310278
def remote(self, func, *args, xfer_func=None, **kwargs):
        """"""
        global HAS_BUFFER
        HAS_BUFFER = self.has_buffer
        if hasattr(func, 'extra_funcs'):
          func_name = func.name
          func_lines = []
          for extra_func in func.extra_funcs:
            func_lines += inspect.getsource(extra_func).split('\n')
            func_lines += ['']
          func_lines += filter(lambda line: line[:1] != '@', func.source.split('\n'))
          func_src = '\n'.join(func_lines)
        else:
          func_name = func.__name__
          func_src = inspect.getsource(func)
        args_arr = [remote_repr(i) for i in args]
        kwargs_arr = ["{}={}".format(k, remote_repr(v)) for k, v in kwargs.items()]
        func_src += 'output = ' + func_name + '('
        func_src += ', '.join(args_arr + kwargs_arr)
        func_src += ')\n'
        func_src += 'if output is None:\n'
        func_src += '    print("None")\n'
        func_src += 'else:\n'
        func_src += '    print(output)\n'
        time_offset = self.time_offset
        if self.adjust_for_timezone:
          time_offset -= time.localtime().tm_gmtoff
        func_src = func_src.replace('TIME_OFFSET', '{}'.format(time_offset))
        func_src = func_src.replace('HAS_BUFFER', '{}'.format(HAS_BUFFER))
        func_src = func_src.replace('BUFFER_SIZE', '{}'.format(BUFFER_SIZE))
        func_src = func_src.replace('IS_UPY', 'True')
        if DEBUG:
            print('----- About to send %d bytes of code to the pyboard -----' % len(func_src))
            print(func_src)
            print('-----')
        self.check_pyb()
        try:
            self.pyb.enter_raw_repl()
            self.check_pyb()
            output = self.pyb.exec_raw_no_follow(func_src)
            if xfer_func:
                xfer_func(self, *args, **kwargs)
            self.check_pyb()
            output, _ = self.pyb.follow(timeout=20)
            self.check_pyb()
            self.pyb.exit_raw_repl()
        except (serial.serialutil.SerialException, TypeError):
            self.close()
            raise DeviceError('serial port %s closed' % self.dev_name_short)
        if DEBUG:
            print('-----Response-----')
            print(output)
            print('-----')
        return output
235345
function prepareRepo(remoteUrl, origin, dir) {
  let promise

  if (remoteUrl) {
    // if a remoteUrl was provided, use it
    promise = wrapPromise.Promise.resolve(remoteUrl)
  } else {
    // else try to extract it from the .git folder of
    // the current directory.
    promise = getRemoteUrl(git(process.cwd()), origin)
  }

  return promise.catch(function (e) { console.error(e) }).then(function (rUrl) {
    remoteUrl = rUrl

    return wrapPromise(function (resolve, reject) {
      function initRepo(repo) {
        repo.branch(function (err, head) {
          if (err) {
            reject(err)
            return
          }

          resolve(new Git(repo, head.name).status())
        })
      }

      function clearAndInitRepo() {
        rimraf(dir, function (rmErr) {
          if (rmErr) {
            reject(rmErr)
            return
          }

          git.clone(rUrl, dir, function (cloneErr, repo) {
            if (cloneErr) {
              reject(cloneErr)
              return
            }

            initRepo(repo)
          })
        })
      }

      // assume that if there is a .git folder get its remoteUrl
      // and check if it mathces the one we want to use.
      getRemoteUrl(git(dir), origin).then(function (cwdRemoteUrl) {
        if (remoteUrl === cwdRemoteUrl) {
          initRepo(git(dir))
          return
        }

        clearAndInitRepo()
      }, function () {

        clearAndInitRepo()
      })
    })
  }).catch(function (err) {
    console.error(err)
  })
}
99617
def exec_func_src2(func, globals_=None, locals_=None, sentinal=None,
                   verbose=False, start=None, stop=None):
    
    import utool as ut
    sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True)
    if globals_ is None:
        globals_ = ut.get_parent_frame().f_globals
    if locals_ is None:
        locals_ = ut.get_parent_frame().f_locals
    if sentinal is not None:
        sourcecode = ut.replace_between_tags(sourcecode, '', sentinal)
    if start is not None or stop is not None:
        sourcecode = '\n'.join(sourcecode.splitlines()[slice(start, stop)])
    if verbose:
        print(ut.color_text(sourcecode, 'python'))
    # TODO: find the name of every variable that was assigned in the function
    # and get it from the context
    locals2_ = locals_.copy()
    globals2_ = globals_.copy()
    six.exec_(sourcecode, globals2_, locals2_)
    return locals2_
1121936
def export(string, template=None, **extra):
    

    def wrapped(f):
        endpoint = (f.__module__ + "." + f.__name__)[16:]
        if template is not None:
            old_f = f

            def f(**kwargs):
                rv = old_f(**kwargs)
                if not isinstance(rv, Response):
                    rv = TemplateResponse(template, **(rv or {}))
                return rv

            f.__name__ = old_f.__name__
            f.__doc__ = old_f.__doc__
        exported_views[endpoint] = (f, string, extra)
        return f

    return wrapped
67982
def remote_eval_last(self, func, *args, **kwargs):
        
        result = self.remote(func, *args, **kwargs).split(b'\r\n')
        messages = result[0:-2]
        messages = b'\n'.join(messages).decode('utf-8')
        return (eval(result[-2]), messages)
323878
def _remote(self,
                args=None,
                kwargs=None,
                num_return_vals=None,
                num_cpus=None,
                num_gpus=None,
                resources=None):
        """"""
        worker = ray.worker.get_global_worker()
        worker.check_connected()

        if self._last_export_session < worker._session_index:
            # If this function was exported in a previous session, we need to
            # export this function again, because current GCS doesn't have it.
            self._last_export_session = worker._session_index
            worker.function_actor_manager.export(self)

        kwargs = {} if kwargs is None else kwargs
        args = [] if args is None else args
        args = ray.signature.extend_args(self._function_signature, args,
                                         kwargs)

        if num_return_vals is None:
            num_return_vals = self._num_return_vals

        resources = ray.utils.resources_from_resource_arguments(
            self._num_cpus, self._num_gpus, self._resources, num_cpus,
            num_gpus, resources)
        if worker.mode == ray.worker.LOCAL_MODE:
            # In LOCAL_MODE, remote calls simply execute the function.
            # We copy the arguments to prevent the function call from
            # mutating them and to match the usual behavior of
            # immutable remote objects.
            result = self._function(*copy.deepcopy(args))
            return result
        object_ids = worker.submit_task(
            self._function_descriptor,
            args,
            num_return_vals=num_return_vals,
            resources=resources)
        if len(object_ids) == 1:
            return object_ids[0]
        elif len(object_ids) > 1:
            return object_ids