/*
https://groups.google.com/forum/#!topic/android-developers/H-DSQ4-tiac
@see android.app.Service#onTaskRemoved(android.content.Intent)
188731
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
  @Override
  public void onTaskRemoved(Intent rootIntent) {
    LOGGER.d("try to restart service on task Removed");

    if (isAutoWakeUp) {
      Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
      restartServiceIntent.setPackage(getPackageName());

      PendingIntent restartServicePendingIntent =
          PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent,
              PendingIntent.FLAG_UPDATE_CURRENT);
      AlarmManager alarmService =
          (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
      alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 500,
          restartServicePendingIntent);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
      super.onTaskRemoved(rootIntent);
    }
  }
121454
public static void postTaskError(final TaskCompletionListener completionListener, final String errorMessage) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (null != completionListener) {
                    completionListener.onError(errorMessage);
                }
            }
        });
    }
812545
function (result, cb) {
        var self = this;
        this.swfClient.respondActivityTaskCompleted({
            result: stringify(result),
            taskToken: this.config.taskToken
        }, function (err) {
            if (self.onDone) {
                self.onDone();
            }
            if (cb) {
                cb(err);
            }

        });

    }
244385
public static <T extends Callable<?> & Parcelable> Intent taskIntent(final Context context,
                                                                       final T task) {
    return taskIntent(context, Goro.DEFAULT_QUEUE, task);
  }
804174
public static void postTaskSuccess(final TaskCompletionListener completionListener) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (null != completionListener) {
                    completionListener.onSuccess();
                }
            }
        });
    }
543
public void addTask (ExecutorTask task)
    {
        for (int ii=0, nn=_queue.size(); ii < nn; ii++) {
            ExecutorTask taskOnQueue = _queue.get(ii);
            if (taskOnQueue.merge(task)) {
                return;
            }
        }

        // otherwise, add it on
        _queue.add(task);

        // and perhaps start it going now
        if (!_executingNow) {
            checkNext();
        }
    }
164924
function addTaskToFluence(task, done) {
        if (done) {
            done = "1"
        } else {
            done = "0"
        }
        const query = `INSERT INTO ${todoTable} VALUES ('${task}', ${done})`;
        session.request(query).result().then((r) => {
            console.log("task inserted")
        })
    }
286086
public void markTaskCompletion() {
    if (this.countDownLatch.isPresent()) {
      this.countDownLatch.get().countDown();
    }

    this.taskState.setProp(ConfigurationKeys.TASK_RETRIES_KEY, this.retryCount.get());
  }
866018
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
      final Continuation<TResult, Task<TContinuationResult>> continuation) {
    return onSuccessTask(continuation, IMMEDIATE_EXECUTOR);
  }
946866
private void processTask(ChildTaskContainer parent, MapRow row) throws IOException
   {
      Task task = parent.addTask();
      task.setName(row.getString("NAME"));
      task.setGUID(row.getUUID("UUID"));
      task.setText(1, row.getString("ID"));
      task.setDuration(row.getDuration("PLANNED_DURATION"));
      task.setRemainingDuration(row.getDuration("REMAINING_DURATION"));
      task.setHyperlink(row.getString("URL"));
      task.setPercentageComplete(row.getDouble("PERCENT_COMPLETE"));
      task.setNotes(getNotes(row.getRows("COMMENTARY")));
      task.setMilestone(task.getDuration().getDuration() == 0);

      ProjectCalendar calendar = m_calendarMap.get(row.getUUID("CALENDAR_UUID"));
      if (calendar != m_project.getDefaultCalendar())
      {
         task.setCalendar(calendar);
      }

      switch (row.getInteger("STATUS").intValue())
      {
         case 1: // Planned
         {
            task.setStart(row.getDate("PLANNED_START"));
            task.setFinish(task.getEffectiveCalendar().getDate(task.getStart(), task.getDuration(), false));
            break;
         }

         case 2: // Started
         {
            task.setActualStart(row.getDate("ACTUAL_START"));
            task.setStart(task.getActualStart());
            task.setFinish(row.getDate("ESTIMATED_FINISH"));
            if (task.getFinish() == null)
            {
               task.setFinish(row.getDate("PLANNED_FINISH"));
            }
            break;
         }

         case 3: // Finished
         {
            task.setActualStart(row.getDate("ACTUAL_START"));
            task.setActualFinish(row.getDate("ACTUAL_FINISH"));
            task.setPercentageComplete(Double.valueOf(100.0));
            task.setStart(task.getActualStart());
            task.setFinish(task.getActualFinish());
            break;
         }
      }

      setConstraints(task, row);

      processChildTasks(task, row);

      m_taskMap.put(task.getGUID(), task);

      List<MapRow> predecessors = row.getRows("PREDECESSORS");
      if (predecessors != null && !predecessors.isEmpty())
      {
         m_predecessorMap.put(task, predecessors);
      }

      List<MapRow> resourceAssignmnets = row.getRows("RESOURCE_ASSIGNMENTS");
      if (resourceAssignmnets != null && !resourceAssignmnets.isEmpty())
      {
         processResourceAssignments(task, resourceAssignmnets);
      }
   }
1051725
final public void deleteAsync(final OnDeletedCallback callback) {
		new AsyncTask<Model, Void, Void>() {

			protected Void doInBackground(Model... params) {
				params[0].delete();
				return null;
			}

			protected void onPostExecute(Void result) {
				if (callback != null) {
					callback.onDeleted();
				}
			}

		}.execute(this);
	}
1262224
public Long createTaskPostponed(String taskName, String data, String key1, String key2, int postponeSec) {
		return tedDriverImpl.createTaskPostponed(taskName, data, key1, key2, postponeSec);
	}
1257164
public void onClickRemoteAction(NotificationRemote remote, NotificationEntry entry,
                                    NotificationEntry.Action act) {
        if (DBG) Log.v(TAG, "onClickRemoteAction - " + entry.ID + ", " + act);
    }
1107158
public static Callable<?> getTaskFromExtras(final Intent intent) {
    if (!intent.hasExtra(EXTRA_TASK) && !intent.hasExtra(EXTRA_TASK_BUNDLE)) {
      return null;
    }

    Parcelable taskArg = intent.getParcelableExtra(EXTRA_TASK);
    if (taskArg == null) {
      Bundle bundle = intent.getBundleExtra(EXTRA_TASK_BUNDLE);
      if (bundle != null) {
        taskArg = bundle.getParcelable(EXTRA_TASK);
      }
    }

    if (!(taskArg instanceof Callable)) {
      throw new IllegalArgumentException("Task " + taskArg + " is not a Callable");
    }

    return (Callable<?>)taskArg;
  }
1040980
void registerTaskEnded(Task task) {
        synchronized (m_activeTasks) {
            String mapKey = createMapKey(task.getTenant(), task.getTaskID());
            if (m_activeTasks.remove(mapKey) == null) {
                m_logger.warn("Task {} registered as ended but was not running", mapKey);
            }
        }
    }
180773
@SuppressWarnings("deprecation")
  private boolean completedTaskUnprotected(TaskInProgress tip, TaskStatus status,
      TaskTrackerInfo ttStatus) {
    int oldNumAttempts = tip.getActiveTasks().size();
    // Metering
    meterTaskAttemptUnprotected(tip, status);

    // It _is_ safe to not decrement running{Map|Reduce}Tasks and
    // finished{Map|Reduce}Tasks variables here because one and only
    // one task-attempt of a TIP gets to completedTask. This is because
    // the TaskCommitThread in the JobTracker marks other, completed,
    // speculative tasks as _complete_.
    TaskAttemptID taskId = status.getTaskID();
    if (tip.isComplete()) {
      // Mark this task as KILLED
      tip.alreadyCompletedTask(taskId);
      return false;
    }

    LOG.info("Task '" + taskId + "' has completed " + tip.getTIPId() +
           " successfully.");
    // Mark the TIP as complete
    tip.completed(taskId);

    // Update jobhistory
    String taskType = getTaskType(tip);
    if (status.getIsMap()){
      jobHistory.logMapTaskStarted(status.getTaskID(), status.getStartTime(),
                                       status.getTaskTracker(),
                                       ttStatus.getHttpPort(),
                                       taskType);
      jobHistory.logMapTaskFinished(status.getTaskID(), status.getFinishTime(),
                                        ttStatus.getHost(), taskType,
                                        status.getStateString(),
                                        status.getCounters());
    }else{
      jobHistory.logReduceTaskStarted( status.getTaskID(), status.getStartTime(),
                                          status.getTaskTracker(),
                                          ttStatus.getHttpPort(),
                                          taskType);
      jobHistory.logReduceTaskFinished(status.getTaskID(), status.getShuffleFinishTime(),
                                           status.getSortFinishTime(), status.getFinishTime(),
                                           ttStatus.getHost(),
                                           taskType,
                                           status.getStateString(),
                                           status.getCounters());
    }
    jobHistory.logTaskFinished(tip.getTIPId(),
                                taskType,
                                tip.getExecFinishTime(),
                                status.getCounters());

    int newNumAttempts = tip.getActiveTasks().size();
    if (tip.isJobSetupTask()) {
      // setup task has finished. kill the extra setup tip
      killSetupTipUnprotected(!tip.isMapTask());
      setupCompleteUnprotected();
    } else if (tip.isJobCleanupTask()) {
      // cleanup task has finished. Kill the extra cleanup tip
      if (tip.isMapTask()) {
        // kill the reduce tip
        cleanup[1].kill();
      } else {
        cleanup[0].kill();
      }

      if (jobFailed) {
        terminateJob(JobStatus.FAILED);
      } else if (jobKilled) {
        terminateJob(JobStatus.KILLED);
      } else {
        jobCompleteUnprotected();
      }
    } else if (tip.isMapTask()) {
      runningMapTasks--;
      // Update locality counters.
      long inputBytes = tip.getCounters()
                .getGroup("org.apache.hadoop.mapred.Task$Counter")
                .getCounter("Map input bytes");
      jobStats.incTotalMapInputBytes(inputBytes);
      localityStats.record(tip, ttStatus.getHost(), inputBytes);
      // check if this was a speculative task.
      if (oldNumAttempts > 1) {
        speculativeMapTasks -= (oldNumAttempts - newNumAttempts);
        jobStats.incNumSpeculativeSucceededMaps();
      }
      finishedMapTasks += 1;
      jobStats.incNumMapTasksCompleted();
      if (!tip.isJobSetupTask() && hasSpeculativeMaps) {
        updateTaskTrackerStats(tip,ttStatus,trackerMapStats,mapTaskStats);
      }
      // remove the completed map from the resp running caches
      retireMapUnprotected(tip);
      if ((finishedMapTasks + failedMapTIPs) == (numMapTasks)) {
        this.status.setMapProgress(1.0f);
      }
    } else {
      runningReduceTasks -= 1;
      if (oldNumAttempts > 1) {
        speculativeReduceTasks -= (oldNumAttempts - newNumAttempts);
        jobStats.incNumSpeculativeSucceededReduces();
      }
      finishedReduceTasks += 1;
      jobStats.incNumReduceTasksCompleted();
      if (!tip.isJobSetupTask() && hasSpeculativeReduces) {
        updateTaskTrackerStats(tip,ttStatus,trackerReduceStats,reduceTaskStats);
      }
      // remove the completed reduces from the running reducers set
      retireReduceUnprotected(tip);
      if ((finishedReduceTasks + failedReduceTIPs) == (numReduceTasks)) {
        this.status.setReduceProgress(1.0f);
      }
    }

    // is job complete?
    if (!jobSetupCleanupNeeded && canLaunchJobCleanupTaskUnprotected()) {
      jobCompleteUnprotected();
    }

    return true;
  }
708808
void removeMarkedTasks(String taskTracker) {
    // Purge all the 'marked' tasks which were running at taskTracker
    Set<TaskAttemptID> markedTaskSet =
      trackerToMarkedTasksMap.get(taskTracker);
    if (markedTaskSet != null) {
      for (TaskAttemptID taskid : markedTaskSet) {
        removeTaskEntry(taskid);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Removed marked completed task '" + taskid + "' from '" +
                    taskTracker + "'");
        }
      }
      // Clear
      trackerToMarkedTasksMap.remove(taskTracker);
    }
  }