Executor for `globus task-event-list`
192418
def task_event_list(task_id, limit, filter_errors, filter_non_errors):
    
    client = get_client()

    # cannot filter by both errors and non errors
    if filter_errors and filter_non_errors:
        raise click.UsageError("Cannot filter by both errors and non errors")

    elif filter_errors:
        filter_string = "is_error:1"

    elif filter_non_errors:
        filter_string = "is_error:0"

    else:
        filter_string = ""

    event_iterator = client.task_event_list(
        task_id, num_results=limit, filter=filter_string
    )

    def squashed_json_details(x):
        is_json = False
        try:
            loaded = json.loads(x["details"])
            is_json = True
        except ValueError:
            loaded = x["details"]

        if is_json:
            return json.dumps(loaded, separators=(",", ":"), sort_keys=True)
        else:
            return loaded.replace("\n", "\\n")

    formatted_print(
        event_iterator,
        fields=(
            ("Time", "time"),
            ("Code", "code"),
            ("Is Error", "is_error"),
            ("Details", squashed_json_details),
        ),
        json_converter=iterable_response_to_dict,
    )
109461
private void executeTasklet(final ExecutorService commandExecutor,
                              final ConcurrentMap<Integer, Future> futures,
                              final MasterToWorkerRequest masterToWorkerRequest) {
    final CountDownLatch latch = new CountDownLatch(1);
    final TaskletExecutionRequest taskletExecutionRequest = (TaskletExecutionRequest) masterToWorkerRequest;

    // Scheduler Thread: Pass the command to the worker thread pool to be executed
    // Record future to support cancellation.
    futures.put(
        taskletExecutionRequest.getTaskletId(),
        commandExecutor.submit(new Runnable() {
          @Override
          public void run() {
            final WorkerToMasterReports reports;
            final List<WorkerToMasterReport> holder = new ArrayList<>();

            try {
              // Command Executor: Execute the command
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletResultReport(taskletExecutionRequest.getTaskletId(), taskletExecutionRequest.execute());
              holder.add(workerToMasterReport);
            } catch (final InterruptedException ex) {
              // Assumes that user's thread follows convention that cancelled Futures
              // should throw InterruptedException.
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletCancelledReport(taskletExecutionRequest.getTaskletId());
              LOG.log(Level.WARNING, "Tasklet with ID {0} has been cancelled", taskletExecutionRequest.getTaskletId());
              holder.add(workerToMasterReport);
            } catch (Exception e) {
              // Command Executor: Tasklet throws an exception
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletFailureReport(taskletExecutionRequest.getTaskletId(), e);
              holder.add(workerToMasterReport);
            }

            reports = new WorkerToMasterReports(holder);
            workerReports.addLast(kryoUtils.serialize(reports));
            try {
              latch.await();
            } catch (final InterruptedException e) {
              LOG.log(Level.SEVERE, "Cannot wait for Future to be put.");
              throw new RuntimeException(e);
            }
            futures.remove(taskletExecutionRequest.getTaskletId());
            heartBeatTriggerManager.triggerHeartBeat();
          }
        }));

    // Signal that future is put.
    latch.countDown();
  }
838881
def from_node(cls, task):
        """"""
        new = super().from_node(task)

        new.update(
            executable=task.executable,
            #executable_version:
            #task_events=
            pseudos=[p.as_dict() for p in task.input.pseudos],
            #input=task.input
        )

        new.register_gridfs_files(
            run_abi=(task.input_file.path, "t"),
            run_abo=(task.output_file.path, "t"),
        )

        return new
377499
public void callExecuteTaskAsync(SimpleClientResponseAdapter.Callback cb, byte[] params) throws IOException {
        final String procedureName = "@ExecuteTask";
        Config procedureConfig = SystemProcedureCatalog.listing.get(procedureName);
        Procedure proc = procedureConfig.asCatalogProcedure();
        StoredProcedureInvocation spi = new StoredProcedureInvocation();
        spi.setProcName(procedureName);
        spi.setParams(params);
        spi.setClientHandle(m_executeTaskAdpater.registerCallback(cb));
        if (spi.getSerializedParams() == null) {
            spi = MiscUtils.roundTripForCL(spi);
        }
        synchronized (m_executeTaskAdpater) {
            m_dispatcher.createTransaction(m_executeTaskAdpater.connectionId(), spi,
                    proc.getReadonly(), proc.getSinglepartition(), proc.getEverysite(),
                    new int[] { 0 } /* Can provide anything for multi-part */,
                    spi.getSerializedSize(), System.nanoTime());
        }
    }
611861
public TaskCompletionEvent[] getTaskCompletionEvents(int startFrom
                                                       ) throws IOException {
    ensureState(JobState.RUNNING);
    return info.getTaskCompletionEvents(startFrom);
  }
1291617
def process(self, document):
        """"""
        self.logger.info("Processing group of tasks (parallel=%s)", self.get_parallel_mode())
        self.pipeline.data.env_list[2] = {}

        output, shells = [], []
        result = Adapter({'success': True, 'output': []})
        for task_entry in document:
            key, entry = list(task_entry.items())[0]

            if (not self.parallel or key == 'env') and len(shells) > 0:
                result = Adapter(self.process_shells(shells))
                output += result.output
                shells = []
                if not result.success:
                    break

            if key == 'env':
                self.pipeline.data.env_list[2].update(entry)

            elif key in ['shell', 'docker(container)', 'docker(image)', 'python',
                         'packer', 'ansible(simple)']:
                self.prepare_shell_data(shells, key, entry)

        if result.success:
            result = Adapter(self.process_shells(shells))
            output += result.output

        self.event.delegate(result.success)
        return {'success': result.success, 'output': output}
36147
private void doList() throws PageException {
	// if(tr ue) throw new PageRuntimeException("qqq");
	ScheduleTask[] tasks = scheduler.getAllScheduleTasks();
	final String v = "VARCHAR";
	String[] cols = new String[] { "task", "path", "file", "startdate", "starttime", "enddate", "endtime", "url", "port", "interval", "timeout", "username", "password",
		"proxyserver", "proxyport", "proxyuser", "proxypassword", "resolveurl", "publish", "valid", "paused", "autoDelete" };
	String[] types = new String[] { v, v, v, "DATE", "OTHER", "DATE", "OTHER", v, v, v, v, v, v, v, v, v, v, v, "BOOLEAN", v, "BOOLEAN", "BOOLEAN" };
	lucee.runtime.type.Query query = new QueryImpl(cols, types, tasks.length, "query");
	try {
	    for (int i = 0; i < tasks.length; i++) {
		int row = i + 1;
		ScheduleTask task = tasks[i];
		query.setAt(KeyConstants._task, row, task.getTask());
		if (task.getResource() != null) {
		    query.setAt(KeyConstants._path, row, task.getResource().getParent());
		    query.setAt(KeyConstants._file, row, task.getResource().getName());
		}
		query.setAt("publish", row, Caster.toBoolean(task.isPublish()));
		query.setAt("startdate", row, task.getStartDate());
		query.setAt("starttime", row, task.getStartTime());
		query.setAt("enddate", row, task.getEndDate());
		query.setAt("endtime", row, task.getEndTime());
		query.setAt(KeyConstants._url, row, printUrl(task.getUrl()));
		query.setAt(KeyConstants._port, row, Caster.toString(HTTPUtil.getPort(task.getUrl())));
		query.setAt("interval", row, task.getStringInterval());
		query.setAt("timeout", row, Caster.toString(task.getTimeout() / 1000));
		query.setAt("valid", row, Caster.toString(task.isValid()));
		if (task.hasCredentials()) {
		    query.setAt("username", row, task.getCredentials().getUsername());
		    query.setAt("password", row, task.getCredentials().getPassword());
		}
		ProxyData pd = task.getProxyData();
		if (ProxyDataImpl.isValid(pd)) {
		    query.setAt("proxyserver", row, pd.getServer());
		    if (pd.getPort() > 0) query.setAt("proxyport", row, Caster.toString(pd.getPort()));
		    if (ProxyDataImpl.hasCredentials(pd)) {
			query.setAt("proxyuser", row, pd.getUsername());
			query.setAt("proxypassword", row, pd.getPassword());
		    }
		}
		query.setAt("resolveurl", row, Caster.toString(task.isResolveURL()));

		query.setAt("paused", row, Caster.toBoolean(task.isPaused()));
		query.setAt("autoDelete", row, Caster.toBoolean(((ScheduleTaskImpl) task).isAutoDelete()));

	    }
	    pageContext.setVariable(result, query);
	}
	catch (DatabaseException e) {}

    }
122635
def task(name=None, t=INFO, *args, **kwargs):
    

    def c_run(name, f, t, args, kwargs):
        def run(*largs, **lkwargs):
            thread = __get_current_thread()
            old_name = __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY]
            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = name

            r = log(name, f, t, largs, lkwargs, *args, **kwargs)

            __THREAD_PARAMS[thread][__THREAD_PARAMS_FNAME_KEY] = old_name
            return r

        return run

    if callable(name):
        f = name
        name = f.__name__

        return c_run(name, f, t, args, kwargs)

    if name == None:
        def wrapped(f):
            name = f.__name__
            return c_run(name, f, t, args, kwargs)

        return wrapped
    else:
        return lambda f: c_run(name, f, t, args, kwargs)
907405
def Main():
  """"""
  multiprocessing.freeze_support()

  tool = psteal_tool.PstealTool()
  if not tool.ParseArguments():
    return False

  have_list_option = False

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_output_modules:
    tool.ListOutputModules()
    have_list_option = True

  if tool.list_timezones:
    tool.ListTimeZones()
    have_list_option = True

  if tool.list_parsers_and_plugins:
    tool.ListParsersAndPlugins()
    have_list_option = True

  if tool.list_hashers:
    tool.ListHashers()
    have_list_option = True

  if tool.list_language_identifiers:
    tool.ListLanguageIdentifiers()
    have_list_option = True

  if have_list_option:
    return True

  try:
    tool.ExtractEventsFromSources()
    tool.AnalyzeEvents()

  except (KeyboardInterrupt, errors.UserAbort):
    logging.warning('Aborted by user.')
    return False

  except errors.SourceScannerError as exception:
    logging.warning(exception)
    return False

  return True
715359
private void executeAggregateTasklet(final ExecutorService commandExecutor,
                                       final MasterToWorkerRequest masterToWorkerRequest) {
    final TaskletAggregateExecutionRequest taskletAggregateExecutionRequest =
        (TaskletAggregateExecutionRequest) masterToWorkerRequest;

    assert aggregates.containsKey(taskletAggregateExecutionRequest.getAggregateFunctionId());

    final AggregateContainer aggregateContainer =
        aggregates.get(taskletAggregateExecutionRequest.getAggregateFunctionId());
    final TaskletAggregationRequest aggregationRequest = aggregateContainer.getTaskletAggregationRequest();

    commandExecutor.submit(new Runnable() {
      @Override
      public void run() {
        try {
          aggregateContainer.scheduleTasklet(taskletAggregateExecutionRequest.getTaskletId());
          final Object result = aggregationRequest.executeFunction(taskletAggregateExecutionRequest.getInput());
          aggregateContainer.taskletComplete(taskletAggregateExecutionRequest.getTaskletId(), result);
        } catch (final Exception e) {
          aggregateContainer.taskletFailed(taskletAggregateExecutionRequest.getTaskletId(), e);
        }
      }
    });
  }
460486
function(list) {

        var i = self.tasksCount;

        if (i > list.length-1) {
            process.exit(0)
        }

        var err = false;
        var cb = ( typeof(list[i].cb) != 'undefined' ) ? list[i].cb : false;

        if (cb) {
            list[i].func( function done(err, data) {
                if (err) {
                    console.error(err.stack||err.message);
                    process.exit(1)
                } else {
                    if (data) {
                        //var str = data.toString();
                        console.info(data);
                    }
                    ++self.tasksCount;
                    run(list)
                }

            })
        } else {
            try {
                list[i].func();
                ++self.tasksCount;
                run(list)
            } catch (err) {
                console.error(err.stack);
                process.exit(1)
            }
        }
    }
158752
def list_tasks(collector):
    """"""
    print("Usage: aws_syncr <environment> <task>")
    print("")
    print("Available environments to choose from are")
    print("-----------------------------------------")
    print("")
    for environment in os.listdir(collector.configuration_folder):
        location = os.path.join(collector.configuration_folder, environment)
        if os.path.isdir(location) and not environment.startswith("."):
            print("\t{0}".format(environment))

    print("")
    print("Available tasks to choose from are:")
    print("-----------------------------------")
    print("")
    keygetter = lambda item: item[1].label
    tasks = sorted(available_actions.items(), key=keygetter)
    sorted_tasks = sorted(list(tasks), key=lambda item: len(item[0]))
    max_length = max(len(name) for name, _ in sorted_tasks)
    for key, task in sorted_tasks:
        desc = dedent(task.__doc__ or "").strip().split('\n')[0]
        print("\t{0}{1} :-: {2}".format(" " * (max_length-len(key)), key, desc))
    print("")
1282025
void sendTaskListToChannels(List<TaskRec> tasks) {
		// group by type
		//
		Map<String, List<TaskRec>> grouped = new HashMap<String, List<TaskRec>>();
		for (TaskRec taskRec : tasks) {
			List<TaskRec> tlist = grouped.get(taskRec.name);
			if (tlist == null) {
				tlist = new ArrayList<TaskRec>();
				grouped.put(taskRec.name, tlist);
			}
			tlist.add(taskRec);
		}

		// execute
		//
		for (String taskName : grouped.keySet()) {
			final List<TaskRec> taskList = grouped.get(taskName);
			TaskRec trec1 = taskList.get(0);
			Channel channel = context.registry.getChannel(trec1.channel);
			if (channel == null) { // should never happen
				logger.warn("Task channel '{}' not exists. Use channel MAIN (task={} taskId={})", trec1.channel, trec1.name, trec1.taskId);
				channel = context.registry.getChannel(Model.CHANNEL_MAIN);
			}
			TaskConfig taskConfig = context.registry.getTaskConfig(trec1.name);
			if (taskConfig == null) {
				handleUnknownTasks(taskList);
				continue;
			}

			for (final TaskRec taskRec : taskList) {
				logger.debug("got task: " + taskRec);
				context.stats.metrics.loadTask(taskRec.taskId, taskRec.name, taskRec.channel);
				channel.workers.execute(new TedRunnable(taskRec) {
					@Override
					public void run() {
						processTask(taskRec);
					}
				});
			}
		}
	}
1100662
def tasktiger_processor(logger, method_name, event_dict):
    

    if g['current_tasks'] is not None and not g['current_task_is_batch']:
        event_dict['task_id'] = g['current_tasks'][0].id

    return event_dict
1338266
def child_task(self, q, l, gq, gl):
        ''''''
        mp_util.child_close_fds()

        from ..lib import wx_processguard
        from ..lib.wx_loader import wx
        from MAVProxy.modules.mavproxy_misseditor import missionEditorFrame
        
        self.app = wx.App(False)
        self.app.frame = missionEditorFrame.MissionEditorFrame(parent=None,id=wx.ID_ANY)

        self.app.frame.set_event_queue(q)
        self.app.frame.set_event_queue_lock(l)
        self.app.frame.set_gui_event_queue(gq)
        self.app.frame.set_gui_event_queue_lock(gl)

        self.app.frame.Show()
        self.app.MainLoop()
755998
public void run(
      List<String> command,
      @Nullable Path workingDirectory,
      @Nullable Map<String, String> environment,
      ConsoleListener consoleListener)
      throws InterruptedException, CommandExitException, CommandExecutionException {
    ProcessExecutor processExecutor = processExecutorFactory.newProcessExecutor();
    try {
      int exitCode =
          processExecutor.run(
              command,
              workingDirectory,
              environment,
              streamHandlerFactory.newHandler(consoleListener),
              streamHandlerFactory.newHandler(consoleListener));
      if (exitCode != 0) {
        throw new CommandExitException(exitCode);
      }
    } catch (IOException ex) {
      throw new CommandExecutionException(ex);
    }
  }
453787
@Override
  public List<Task> executeList(CommandContext commandContext, Page page) {
    ensureOrExpressionsEvaluated();
    ensureVariablesInitialized();
    checkQueryOk();

    resetCachedCandidateGroups();

    //check if candidateGroup and candidateGroups intersect
    if (getCandidateGroup() != null && getCandidateGroupsInternal() != null && getCandidateGroups().isEmpty()) {
      return Collections.emptyList();
    }

    List<Task> taskList = commandContext
      .getTaskManager()
      .findTasksByQueryCriteria(this);

    if (initializeFormKeys) {
      for (Task task : taskList) {
        // initialize the form keys of the tasks
        ((TaskEntity) task).initializeFormKey();
      }
    }

    return taskList;
  }