Executor for `globus endpoint server update`
967497
def server_update(
    endpoint_id,
    server_id,
    subject,
    port,
    scheme,
    hostname,
    incoming_data_ports,
    outgoing_data_ports,
):
    
    client = get_client()

    server_doc = assemble_generic_doc(
        "server", subject=subject, port=port, scheme=scheme, hostname=hostname
    )

    # n.b. must be done after assemble_generic_doc(), as that function filters
    # out `None`s, which we need to be able to set for `'unspecified'`
    if incoming_data_ports:
        server_doc.update(
            incoming_data_port_start=incoming_data_ports[0],
            incoming_data_port_end=incoming_data_ports[1],
        )
    if outgoing_data_ports:
        server_doc.update(
            outgoing_data_port_start=outgoing_data_ports[0],
            outgoing_data_port_end=outgoing_data_ports[1],
        )

    res = client.update_endpoint_server(endpoint_id, server_id, server_doc)
    formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message")
102423
def _executor_internal(self, host):
        '''  '''

        host_variables = self.inventory.get_variables(host)
        if self.transport in [ 'paramiko', 'ssh' ]:
            port = host_variables.get('ansible_ssh_port', self.remote_port)
            if port is None:
                port = C.DEFAULT_REMOTE_PORT
        else:
            # fireball, local, etc
            port = self.remote_port

        inject = {}
        inject.update(host_variables)
        inject.update(self.module_vars)
        inject.update(self.setup_cache[host])
        inject['hostvars'] = HostVars(self.setup_cache, self.inventory)
        inject['group_names'] = host_variables.get('group_names', [])
        inject['groups'] = self.inventory.groups_list()

        # allow with_foo to work in playbooks...
        items = None
        items_plugin = self.module_vars.get('items_lookup_plugin', None)
        if items_plugin is not None and items_plugin in utils.plugins.lookup_loader:
            items_terms = self.module_vars.get('items_lookup_terms', '')
            items_terms = utils.template_ds(self.basedir, items_terms, inject)
            items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=self.basedir).run(items_terms, inject=inject)
            if type(items) != list:
                raise errors.AnsibleError("lookup plugins have to return a list: %r" % items)

            if len(items) and self.module_name in [ 'apt', 'yum' ]:
                # hack for apt and soon yum, with_items maps back into a single module call
                inject['item'] = ",".join(items)
                items = None

        # logic to decide how to run things depends on whether with_items is used

        if items is None:
            return self._executor_internal_inner(host, self.module_name, self.module_args, inject, port)
        elif len(items) > 0:
            # executing using with_items, so make multiple calls
            # TODO: refactor
            aggregrate = {}
            all_comm_ok = True
            all_changed = False
            all_failed = False
            results = []
            for x in items:
                inject['item'] = x
                result = self._executor_internal_inner(host, self.module_name, self.module_args, inject, port)
                results.append(result.result)
                if result.comm_ok == False:
                    all_comm_ok = False
                    all_failed = True
                    break
                for x in results:
                    if x.get('changed') == True:
                        all_changed = True
                    if (x.get('failed') == True) or (('rc' in x) and (x['rc'] != 0)):
                        all_failed = True
                        break
            msg = 'All items completed'
            if all_failed:
                msg = "One or more items failed."
            rd_result = dict(failed=all_failed, changed=all_changed, results=results, msg=msg)
            if not all_failed:
                del rd_result['failed']
            return ReturnData(host=host, comm_ok=all_comm_ok, result=rd_result)
        else:
            self.callbacks.on_skipped(host, None)
            return ReturnData(host=host, comm_ok=True, result=dict(skipped=True))
408365
def update_endpoint(self, endpoint):
        
        self._validate_uuid(endpoint.endpoint_id)
        self._validate_subscriber_id(endpoint.subscriber_id)

        url = "/notification/v1/endpoint/{}".format(endpoint.endpoint_id)
        response = NWS_DAO().putURL(
            url, self._write_headers(), self._json_body(endpoint.json_data()))

        if response.status != 204:
            raise DataFailureException(url, response.status, response.data)
        return response.status
796670
def update_org_smarthost(self, orgid, serverid, data):
        """"""
        return self.api_call(
            ENDPOINTS['orgsmarthosts']['update'],
            dict(orgid=orgid, serverid=serverid),
            body=data)
872865
def update(self,
               stats,
               duration=3,
               cs_status=None,
               return_to_browser=False):
        
        # Flush display
        logger.debug('Servers list: {}'.format(stats))
        self.flush(stats)

        # Wait
        exitkey = False
        countdown = Timer(self.__refresh_time)
        while not countdown.finished() and not exitkey:
            # Getkey
            pressedkey = self.__catch_key(stats)
            # Is it an exit or select server key ?
            exitkey = (
                pressedkey == ord('\x1b') or pressedkey == ord('q') or pressedkey == 10)
            if not exitkey and pressedkey > -1:
                # Redraw display
                self.flush(stats)
            # Wait 100ms...
            self.wait()

        return self.active_server
673874
def execute(self, requests, resp_generator, *args, **kwargs):
        '''
            
        '''
        result_futures = [self.executor_pool.submit(resp_generator, req, *args, **kwargs) for req in requests]
        resp = [res_future.result() for res_future in result_futures]
        return resp
1172011
function ({ throttle = 5000, live }) {
      var stream = PullPushAbort()

      var lastResolvedValues = {}

      var timer = null
      var queued = false
      var sync = false

      var update = () => {
        // clear queue
        clearTimeout(timer)
        queued = false

        // get latest replication state (merge together values)
        var resolvedValues = resolveValues(values, ssb.id)

        // push changes since last update
        stream.push(objectDiff(lastResolvedValues, resolvedValues))

        // update internal de-dupe list
        lastResolvedValues = resolvedValues
      }

      pull(
        view.stream({ live }),
        stream.aborter,
        pull.drain((msg) => {
          if (stream.ended) return

          if (!sync) {
            // we'll store the incoming values (they will be updated as the view updates so
            // do not need to be manually patched)
            sync = true
            update()

            // if not live, we can close stream
            if (!live) stream.end()
          } else if (msg) {
            if (!queued) {
              queued = true
              timer = setTimeout(update, throttle)
            }
          }
        }, (err) => {
          if (err) return stream.end(err)
        })
      )

      return stream
    }
975324
private void scheduleUpdateFactory(final ServerControllerFactory controllerFactory) {
		// change configuration using new (or null when not available) ServerControllerFactory
		Future<?> future = configExecutor.submit(() -> updateController(config, controllerFactory));

		// Make sure we destroy things synchronously
		if (controllerFactory == null) {
			try {
				future.get(20, TimeUnit.SECONDS);
				// CHECKSTYLE:OFF
			} catch (Exception e) {
				LOG.info("Error when updating factory: " + e.getMessage(), e);
			}
			// CHECKSTYLE:ON
		}
	}
1119424
def execute_greenlet_async(func, *args, **kwargs):
  
  global _GREENLET_EXECUTOR
  if _GREENLET_EXECUTOR is None:
    _GREENLET_EXECUTOR = GreenletExecutor(
      num_greenlets=settings.node.greenlet_pool_size)
  return _GREENLET_EXECUTOR.submit(func, *args, **kwargs)
438712
def server_delete(endpoint_id, server):
    
    client = get_client()

    mode = _detect_mode(server)

    # list (even if not necessary) in order to make errors more consistent when
    # mode='id'
    endpoint, server_list = get_endpoint_w_server_list(endpoint_id)

    if server_list == "S3":
        raise click.UsageError("You cannot delete servers from S3 endpoints.")

    # we don't *have to* raise an error in the GCP case, since the API would
    # deny it too, but doing so makes our errors a little bit more consistent
    # with deletes against S3 endpoints and shares
    if endpoint["is_globus_connect"]:
        raise click.UsageError(
            "You cannot delete servers from Globus Connect Personal endpoints"
        )

    if mode != "id":
        matches = _spec_to_matches(server_list, server, mode)
        if not matches:
            raise click.UsageError('No server was found matching "{}"'.format(server))
        elif len(matches) > 1:
            raise click.UsageError(
                dedent(
                    """\
                Multiple servers matched "{}":
                    {}
            """
                ).format(server, [x["id"] for x in matches])
            )
        else:
            server = matches[0]["id"]

    response = client.delete_endpoint_server(endpoint_id, server)

    formatted_print(response, text_format=FORMAT_TEXT_RAW, response_key="message")
420354
def server_show(endpoint_id, server_id):
    
    client = get_client()

    server_doc = client.get_endpoint_server(endpoint_id, server_id)
    if not server_doc["uri"]:  # GCP endpoint server
        fields = (("ID", "id"),)
        text_epilog = dedent(
            """
            This server is for a Globus Connect Personal installation.

            For its connection status, try:
            globus endpoint show {}
        """.format(
                endpoint_id
            )
        )
    else:

        def advertised_port_summary(server):
            def get_range_summary(start, end):
                return (
                    "unspecified"
                    if not start and not end
                    else "unrestricted"
                    if start == 1024 and end == 65535
                    else "{}-{}".format(start, end)
                )

            return "incoming {}, outgoing {}".format(
                get_range_summary(
                    server["incoming_data_port_start"], server["incoming_data_port_end"]
                ),
                get_range_summary(
                    server["outgoing_data_port_start"], server["outgoing_data_port_end"]
                ),
            )

        fields = (
            ("ID", "id"),
            ("URI", "uri"),
            ("Subject", "subject"),
            ("Data Ports", advertised_port_summary),
        )
        text_epilog = None

    formatted_print(
        server_doc,
        text_format=FORMAT_TEXT_RECORD,
        fields=fields,
        text_epilog=text_epilog,
    )
736446
def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
        """"""

        data = {}
        self._copy_if_updated(data, is_public=is_public,
                              is_protected=is_protected)
        return self._patch('/job-executions/%s' % obj_id, data)
134226
def run(endpoint, name=None):
    """"""
    try:
        if os.isatty(0):
            # output mode
            for data in stream_skypipe_output(endpoint, name):
                sys.stdout.write(data)
                sys.stdout.flush()

        else:
            # input mode
            with skypipe_input_stream(endpoint, name) as stream:
                for line in stream_stdin_lines():
                    stream.send(line)

    except KeyboardInterrupt:
        pass
491910
def UpdateSNMPObjs():
	

	global threadingString

	LogMsg("Beginning data update.")
	data = ""

	# Obtain the data by calling an external command. We don't use
	# subprocess.check_output() here for compatibility with Python versions
	# older than 2.7.
	LogMsg("Calling external command \"sleep 5; date\".")
	proc = subprocess.Popen(
		"sleep 5; date", shell=True, env={ "LANG": "C" },
		stdout=subprocess.PIPE, stderr=subprocess.STDOUT
	)
	output = proc.communicate()[0].splitlines()[0]
	rc = proc.poll()
	if rc != 0:
		LogMsg("An error occured executing the command: {0}".format(output))
		return

	msg = "Updating \"threadingString\" object with data \"{0}\"."
	LogMsg(msg.format(output))
	threadingString.update(output)

	LogMsg("Data update done, exiting thread.")
1266162
@Override
  public Map<WorkerInfo, ArrayList<MigrateCommand>> selectExecutors(MigrateConfig config,
      List<WorkerInfo> jobWorkerInfoList, SelectExecutorsContext context) throws Exception {
    AlluxioURI source = new AlluxioURI(config.getSource());
    AlluxioURI destination = new AlluxioURI(config.getDestination());
    if (source.equals(destination)) {
      return new HashMap<>();
    }
    checkMigrateValid(config, context.getFileSystem());
    Preconditions.checkState(!jobWorkerInfoList.isEmpty(), "No workers are available");

    List<URIStatus> allPathStatuses = getPathStatuses(source, context.getFileSystem());
    ConcurrentMap<WorkerInfo, ArrayList<MigrateCommand>> assignments = Maps.newConcurrentMap();
    ConcurrentMap<String, WorkerInfo> hostnameToWorker = Maps.newConcurrentMap();
    for (WorkerInfo workerInfo : jobWorkerInfoList) {
      hostnameToWorker.put(workerInfo.getAddress().getHost(), workerInfo);
    }
    List<BlockWorkerInfo> alluxioWorkerInfoList =
        AlluxioBlockStore.create(context.getFsContext()).getAllWorkers();
    // Assign each file to the worker with the most block locality.
    for (URIStatus status : allPathStatuses) {
      if (status.isFolder()) {
        migrateDirectory(status.getPath(), source.getPath(), destination.getPath(),
            context.getFileSystem());
      } else {
        WorkerInfo bestJobWorker =
            getBestJobWorker(status, alluxioWorkerInfoList, jobWorkerInfoList, hostnameToWorker);
        String destinationPath =
            computeTargetPath(status.getPath(), source.getPath(), destination.getPath());
        assignments.putIfAbsent(bestJobWorker, Lists.newArrayList());
        assignments.get(bestJobWorker).add(new MigrateCommand(status.getPath(), destinationPath));
      }
    }
    return assignments;
  }
264518
private void openCli(SessionContext context, Executor executor) {
		CliClient cli = null;
		try {
			cli = new CliClient(context, executor);
			// interactive CLI mode
			if (options.getUpdateStatement() == null) {
				cli.open();
			}
			// execute single update statement
			else {
				final boolean success = cli.submitUpdate(options.getUpdateStatement());
				if (!success) {
					throw new SqlClientException("Could not submit given SQL update statement to cluster.");
				}
			}
		} finally {
			if (cli != null) {
				cli.close();
			}
		}
	}
625053
def run(config, start, end, accounts, region, debug):
    """"""
    config = validate.callback(config)
    destination = config.get('destination')
    start = start and parse(start) or start
    end = end and parse(end) or datetime.now()
    executor = debug and MainThreadExecutor or ThreadPoolExecutor
    with executor(max_workers=32) as w:
        futures = {}
        for account in config.get('accounts', ()):
            if accounts and account['name'] not in accounts:
                continue
            futures[
                w.submit(process_account, account, start,
                         end, destination, region)] = account
        for f in as_completed(futures):
            account = futures[f]
            if f.exception():
                log.error("Error on account %s err: %s",
                          account['name'], f.exception())
            log.info("Completed %s", account['name'])