/*
Implement Samza task
776587
@Override
	public void init(Config config, TaskContext context) throws Exception {
		String yarnConfHome = config.get(SamzaConfigFactory.YARN_CONF_HOME_KEY);
		if (yarnConfHome != null && yarnConfHome.length() > 0) // if the property is set , otherwise, assume we are running in
            													// local mode and ignore this
			SystemsUtils.setHadoopConfigHome(yarnConfHome);
		
		String filename = config.get(SamzaConfigFactory.FILE_KEY);
		String filesystem = config.get(SamzaConfigFactory.FILESYSTEM_KEY);
		this.setName(config.get(SamzaConfigFactory.JOB_NAME_KEY));
		SerializationProxy wrapper = (SerializationProxy) SystemsUtils.deserializeObjectFromFileAndKey(filesystem, filename, this.getName());
		this.setProcessor(wrapper.processor);
		this.outputStreams = wrapper.outputStreams;
		
		// Init Processor and Streams
		this.getProcessor().onCreate(0);
		for (SamzaStream stream:this.outputStreams) {
			stream.onCreate();
		}
		
	}
513063
public List<Task> executeList(CommandContext commandContext, Map<String, Object> parameterMap, int firstResult, int maxResults) {
    return commandContext
      .getTaskManager()
      .findTasksByNativeQuery(parameterMap, firstResult, maxResults);
  }
361246
protected void addSeed(URI uri, String method) {
		// Check if the uri was processed already
		String visitedURI;
		try {
			visitedURI = URLCanonicalizer.buildCleanedParametersURIRepresentation(uri, spider.getSpiderParam()
					.getHandleParameters(), spider.getSpiderParam().isHandleODataParametersVisited());
		} catch (URIException e) {
			return;
		}
		synchronized (visitedGet) {
			if (visitedGet.contains(visitedURI)) {
				log.debug("URI already visited: " + visitedURI);
				return;
			} else {
				visitedGet.add(visitedURI);
			}
		}
		// Create and submit the new task
		SpiderTask task = new SpiderTask(spider, null, uri, 0, method);
		spider.submitTask(task);
		// Add the uri to the found list
		spider.notifyListenersFoundURI(uri.toString(), method, FetchStatus.SEED);
	}
880554
protected void executeGetAsync(HttpCallback callback, String url, Object tag, StrParam... strParams) {
        Request.Builder builder = mBuilder.builderGet(url, strParams);
        async(builder, tag, callback);
    }
62408
@Override
  public byte[] call(final byte[] memento) throws Exception {
    final ExecutorService schedulerThread = Executors.newSingleThreadExecutor();
    final ExecutorService commandExecutor = Executors.newFixedThreadPool(numOfThreads);
    final ConcurrentMap<Integer, Future> futures = new ConcurrentHashMap<>();

    // Scheduling thread starts
    schedulerThread.execute(new Runnable() {
      @SuppressWarnings("InfiniteLoopStatement") // Scheduler is supposed to run forever.
      @Override
      public void run() {
        while (true) {
          // Scheduler Thread: Pick a command to execute (For now, simple FIFO order)
          final byte[] message;
          try {
            message = pendingRequests.takeFirst();
          } catch (InterruptedException e) {
            throw new RuntimeException(e);
          }

          // Command Executor: Deserialize the command
          final MasterToWorkerRequest masterToWorkerRequest = (MasterToWorkerRequest)kryoUtils.deserialize(message);

          switch (masterToWorkerRequest.getType()) {
            case AggregateTasklets:
              final TaskletAggregationRequest taskletAggregationRequest =
                  (TaskletAggregationRequest) masterToWorkerRequest;
              aggregates.put(taskletAggregationRequest.getAggregateFunctionId(),
                  new AggregateContainer(heartBeatTriggerManager, kryoUtils, workerReports,
                      taskletAggregationRequest));
              break;
            case ExecuteAggregateTasklet:
              executeAggregateTasklet(commandExecutor, masterToWorkerRequest);
              break;
            case ExecuteTasklet:
              executeTasklet(commandExecutor, futures, masterToWorkerRequest);
              break;
            case CancelTasklet:
              final TaskletCancellationRequest cancellationRequest = (TaskletCancellationRequest) masterToWorkerRequest;
              LOG.log(Level.FINE, "Cancelling Tasklet with ID {0}.", cancellationRequest.getTaskletId());
              final Future future = futures.get(cancellationRequest.getTaskletId());
              if (future != null) {
                future.cancel(true);
              }
              break;
            default:
              throw new RuntimeException("Unknown Command");
          }
        }
      }
    });

    terminated.await();
    return null;
  }
593816
@TaskAction
    void taskAction(IncrementalTaskInputs inputs) throws Exception {
        initDesugarJar(getProject().getExtensions().findByType(JFXMobileExtension.class).getAndroidExtension().getBuildCache());

        if (Files.notExists(inputDir.toPath())) {
            PathUtils.deleteIfExists(outputDir.toPath());
        } else {
            processSingle(inputDir.toPath(), outputDir.toPath(), Collections.emptySet());

        }
        waitableExecutor.waitForTasksWithQuickFail(true);

        processNonCachedOnes(getClasspath());
        waitableExecutor.waitForTasksWithQuickFail(true);
    }
757627
protected void buildSamlResponse(final HttpServletResponse response,
                                     final HttpServletRequest request,
                                     final Pair<AuthnRequest, MessageContext> authenticationContext,
                                     final Assertion casAssertion,
                                     final String binding) {

        val authnRequest = authenticationContext.getKey();
        val pair = getRegisteredServiceAndFacade(authnRequest);

        val entityId = pair.getValue().getEntityId();
        LOGGER.debug("Preparing SAML response for [{}]", entityId);
        samlProfileHandlerConfigurationContext.getResponseBuilder().build(authnRequest, request, response, casAssertion,
            pair.getKey(), pair.getValue(), binding, authenticationContext.getValue());
        LOGGER.info("Built the SAML response for [{}]", entityId);
    }
1060060
private static TaskHandle createTaskHandle(
            TaskStateMachine taskStateMachine,
            TaskContext taskContext,
            OutputBuffer outputBuffer,
            LocalExecutionPlan localExecutionPlan,
            TaskExecutor taskExecutor)
    {
        TaskHandle taskHandle = taskExecutor.addTask(
                taskStateMachine.getTaskId(),
                outputBuffer::getUtilization,
                getInitialSplitsPerNode(taskContext.getSession()),
                getSplitConcurrencyAdjustmentInterval(taskContext.getSession()),
                getMaxDriversPerTask(taskContext.getSession()));
        taskStateMachine.addStateChangeListener(state -> {
            if (state.isDone()) {
                taskExecutor.removeTask(taskHandle);
                for (DriverFactory factory : localExecutionPlan.getDriverFactories()) {
                    factory.noMoreDrivers();
                }
            }
        });
        return taskHandle;
    }
1088253
private void populateTask(Row row, Task task)
   {
      task.setUniqueID(row.getInteger("Z_PK"));
      task.setName(row.getString("ZTITLE"));
      task.setPriority(Priority.getInstance(row.getInt("ZPRIORITY")));
      task.setMilestone(row.getBoolean("ZISMILESTONE"));
      task.setActualFinish(row.getTimestamp("ZGIVENACTUALENDDATE_"));
      task.setActualStart(row.getTimestamp("ZGIVENACTUALSTARTDATE_"));
      task.setNotes(row.getString("ZOBJECTDESCRIPTION"));
      task.setDuration(row.getDuration("ZGIVENDURATION_"));
      task.setOvertimeWork(row.getWork("ZGIVENWORKOVERTIME_"));
      task.setWork(row.getWork("ZGIVENWORK_"));
      task.setLevelingDelay(row.getDuration("ZLEVELINGDELAY_"));
      task.setActualOvertimeWork(row.getWork("ZGIVENACTUALWORKOVERTIME_"));
      task.setActualWork(row.getWork("ZGIVENACTUALWORK_"));
      task.setRemainingWork(row.getWork("ZGIVENACTUALWORK_"));
      task.setGUID(row.getUUID("ZUNIQUEID"));

      Integer calendarID = row.getInteger("ZGIVENCALENDAR");
      if (calendarID != null)
      {
         ProjectCalendar calendar = m_project.getCalendarByUniqueID(calendarID);
         if (calendar != null)
         {
            task.setCalendar(calendar);
         }
      }

      populateConstraints(row, task);

      // Percent complete is calculated bottom up from assignments and actual work vs. planned work

      m_eventManager.fireTaskReadEvent(task);
   }
1278131
public void execute() throws MojoExecutionException {
        
        if (skip) {
            getLog().info("Skipping ceylon:sdk-download");
            return;
        }
        
        if (System.getProperty("ceylon.repo") != null) {
            throw new MojoExecutionException("Ceylon system repo (ceylon.repo system property) is already set to: "
                + System.getProperty("ceylon.repo"));
        }
        

            
        if ("{user.home}/.ceylon".equals(downloadTo)) { // replace placeholder
            downloadTo = System.getProperty("user.home") 
               + File.separator + ".ceylon";
            getLog().debug("downloadTo property not set, using default");
        }
        
        sysRepo = downloadSdk(downloadTo);
        
        if (sysRepo == null || !sysRepo.exists()) {
            String message = "Download specified but target directory exists or could not be created";
            getLog().info(message);
        } else {
            System.setProperty("ceylon.repo", sysRepo.getAbsolutePath());
            getLog().debug("Downloaded Ceylon SDK and set Ceylon system repo to: " + System.getProperty("ceylon.repo"));
        }  
    }
207729
void prepareDisplayTaskFor(ImageAware imageAware, String memoryCacheKey) {
		cacheKeysForImageAwares.put(imageAware.getId(), memoryCacheKey);
	}
491824
public synchronized void executeTask(long jobId, int taskId, JobConfig jobConfig,
      Serializable taskArgs, RunTaskContext context) {
    Future<?> future = mTaskExecutionService
        .submit(new TaskExecutor(jobId, taskId, jobConfig, taskArgs, context, this));
    Pair<Long, Integer> id = new Pair<>(jobId, taskId);
    mTaskFutures.put(id, future);
    TaskInfo.Builder taskInfo = TaskInfo.newBuilder();
    taskInfo.setJobId(jobId);
    taskInfo.setTaskId(taskId);
    taskInfo.setStatus(Status.RUNNING);
    mUnfinishedTasks.put(id, taskInfo);
    mTaskUpdates.put(id, taskInfo.build());
    LOG.info("Task {} for job {} started", taskId, jobId);
  }
42044
public void process(String name) throws Exception
   {
      ProjectFile file = new UniversalProjectReader().read(name);
      for (Task task : file.getTasks())
      {
         if (!task.getSummary())
         {
            System.out.print(task.getWBS());
            System.out.print("\t");
            System.out.print(task.getName());
            System.out.print("\t");
            System.out.print(format(task.getStart()));
            System.out.print("\t");
            System.out.print(format(task.getActualStart()));
            System.out.print("\t");
            System.out.print(format(task.getFinish()));
            System.out.print("\t");
            System.out.print(format(task.getActualFinish()));
            System.out.println();
         }
      }
   }
889829
static <S, I, O> Optional<ADSNode<S, I, O>> compute(final MealyMachine<S, I, ?, O> automaton,
                                                        final Alphabet<I> input,
                                                        final SplitTree<S, I, O> node) throws IllegalArgumentException {

        if (node.getPartition().isEmpty()) {
            throw new IllegalArgumentException("Empty partitions should be handled by the specific algorithm");
        } else if (node.getPartition().size() == 1) {

            final S state = node.getPartition().iterator().next();

            if (!node.getMapping().containsKey(state)) {
                throw new IllegalStateException();
            }

            final ADSNode<S, I, O> result = new ADSLeafNode<>(null, node.getMapping().get(state));
            return Optional.of(result);
        } else if (node.getPartition().size() == 2) {
            return StateEquivalence.compute(automaton, input, node);
        } else if (node.getPartition().size() == automaton.getStates().size()) {
            throw new IllegalArgumentException("Call LeeYannakakis directly");
        } else {
            return BacktrackingSearch.compute(automaton, input, node);
        }
    }
5151
public void execute(final CCTask task, final List<File> sources, final Map<String, TargetInfo> targets,
      final TargetInfo linkTarget) {
    try {
      this.projectWriter.writeProject(this.outFile, task, this, sources, targets, linkTarget);
    } catch (final BuildException ex) {
      if (this.failOnError) {
        throw ex;
      } else {
        task.log(ex.toString());
      }
    } catch (final Exception ex) {
      if (this.failOnError) {
        throw new BuildException(ex);
      } else {
        task.log(ex.toString());
      }
    }
  }
1344909
public static void init(final AuthAPI authzAPI, AuthzFacade facade) throws Exception {
		////////
		// Overall APIs
		///////
		authzAPI.route(HttpMethods.GET,"/api",API.API,new Code(facade,"Document API", true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				Result<Void> r = context.getAPI(trans,resp,authzAPI);
				if(r.isOK()) {
					resp.setStatus(HttpStatus.OK_200);
				} else {
					context.error(trans,resp,r);
				}
			}
		});

		////////
		// Overall Examples
		///////
		authzAPI.route(HttpMethods.GET,"/api/example/*",API.VOID,new Code(facade,"Document API", true) {
			@Override
			public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
				String pathInfo = req.getPathInfo();
				int question = pathInfo.lastIndexOf('?');
				
				pathInfo = pathInfo.substring(13, question<0?pathInfo.length():question);// IMPORTANT, this is size of "/api/example/"
				String nameOrContextType=Symm.base64noSplit.decode(pathInfo);
				Result<Void> r = context.getAPIExample(trans,resp,nameOrContextType,
						question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1))
						);
				if(r.isOK()) {
					resp.setStatus(HttpStatus.OK_200);
				} else {
					context.error(trans,resp,r);
				}
			}
		});

	}
677170
private void processChildTasks(Task parentTask) throws SQLException
   {
      List<Row> rows = getRows("select * from zscheduleitem where zparentactivity_=? and z_ent=? order by zorderinparentactivity", parentTask.getUniqueID(), m_entityMap.get("Activity"));
      for (Row row : rows)
      {
         Task task = parentTask.addTask();
         populateTask(row, task);
         processChildTasks(task);
      }
   }