private Task mapTask(
     PuzzleDto puzzle,
     ChallengeTemplate challengeTemplate,
     Organization organization,
     Map<String, ByteArrayOutputStream> files,
     Duration gameDuration,
     Runner runner,
     Endpoint endpoint,
     Set<Language> languages)
     throws IOException {
   Task task = new Task();
   task.setCanonicalName(
       fixCanonicalName(challengeTemplate.getCanonicalName() + "-" + puzzle.getCanonicalName()));
   task.setName(puzzle.getCanonicalName());
   task.setEndpoint(endpoint);
   task.setDescription(puzzle.getCanonicalName());
   task.setInstructions(
       storage.uploadPublic(
           instructionsBucket,
           instructionsFileName(challengeTemplate, puzzle.getInstructionsFile()),
           new ByteArrayInputStream(files.get(puzzle.getInstructionsFile()).toByteArray()),
           "application/pdf"));
   task.setDuration(gameDuration);
   task.setRunner(runner);
   task.setLanguages(languages);
   task.setOrganization(organization);
   return task;
 }
Exemple #2
0
 public static void sendModeration(String name, float point) {
   Task t = new Task(name, point);
   t.status = TaskStatus.PENDING;
   t.suggestedBy = SUser.findByEmail(Auth.connected());
   t.save();
   thanks();
 }
Exemple #3
0
  /*
   * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setValidateByModel(boolean)'
   */
  public void testSetValidateByModel() {
    progtask.setValidateByModel(true);
    assert (progtask.isValidateByModel());

    progtask.setValidateByModel(false);
    assert (!progtask.isValidateByModel());
  }
Exemple #4
0
  /*
   * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setFillInTask(boolean)'
   */
  public void testSetFillInTask() {
    progtask.setFillInTask(true);
    assert (progtask.isFillInTask());

    progtask.setFillInTask(false);
    assert (progtask.isProgrammingTask());
  }
  @Override
  protected void doHadoopWork() throws BuildException {
    Tuple tuple = ContextManager.getCurrentTuple();
    if (tuple == null) {
      throw new BuildException(
          this.getTaskName()
              + " should be put inside task container which provides tuple to execution context");
    }

    try {
      if (tuple.getType(fieldNumber) != DataType.TUPLE
          || !(tuple.get(fieldNumber) instanceof Tuple)) {
        throw new BuildException("Tuple field " + fieldNumber + " doesn't represent a Tuple");
      }

      ContextManager.setCurrentTupleContext((Tuple) tuple.get(fieldNumber));

      try {
        for (Task task : tasks) {
          task.perform();
        }
      } finally {
        ContextManager.resetCurrentTupleContext();
      }
    } catch (ExecException e) {
      throw new BuildException("Failed to check type of tuple field " + fieldNumber, e);
    }
  }
Exemple #6
0
 public static void main(String[] args) {
   A2 instance = new A2();
   Task solver = instance.new Task();
   solver.solve();
   instance.out.close();
   System.exit(0);
 }
  private void doUpdate(@Nullable Runnable onComplete) {
    try {
      List<Task> issues =
          getIssuesFromRepositories(
              null, myConfig.updateIssuesCount, 0, false, new EmptyProgressIndicator());
      if (issues == null) return;

      synchronized (myIssueCache) {
        myIssueCache.clear();
        for (Task issue : issues) {
          myIssueCache.put(issue.getId(), issue);
        }
      }
      // update local tasks
      synchronized (myTasks) {
        for (Map.Entry<String, LocalTask> entry : myTasks.entrySet()) {
          Task issue = myIssueCache.get(entry.getKey());
          if (issue != null) {
            entry.getValue().updateFromIssue(issue);
          }
        }
      }
    } finally {
      if (onComplete != null) {
        onComplete.run();
      }
      myUpdating = false;
    }
  }
Exemple #8
0
  /*
   * Test method for 'fi.helsinki.cs.kohahdus.trainer.Task.setHasSucceeded(boolean)'
   */
  public void testSetHasSucceeded() {
    progtask.setHasSucceeded(true);
    assert (progtask.isHasSucceeded());

    progtask.setHasSucceeded(false);
    assert (!progtask.isHasSucceeded());
  }
  private void verifyCurrentUserIsAuthorized(Process process, Task task)
      throws ForbiddenError, BadRequestError {
    if (process == null) throw new BadRequestError(Constants.ExceptionCodes.process_does_not_exist);

    String taskId = task != null ? task.getTaskInstanceId() : null;

    Entity principal = identityHelper.getPrincipal();
    if (principal == null || StringUtils.isEmpty(principal.getEntityId())) {
      LOG.error(
          "Forbidden: Unauthorized user or user with no userId (e.g. system user) attempting to create a request for task: "
              + taskId);
      throw new ForbiddenError();
    }

    if (!principal.hasRole(process, AuthorizationRole.OVERSEER)) {
      if (task != null && !task.isCandidateOrAssignee(principal)) {
        LOG.warn(
            "Forbidden: Unauthorized principal "
                + principal.toString()
                + " attempting to access task "
                + taskId);
        throw new ForbiddenError();
      }
    }
  }
  /*
   * Helper methods
   */
  public static Activity activity(Process process, ProcessInstance instance, Task task)
      throws StatusCodeError {
    Activity activity = null;
    if (process.isAllowPerInstanceActivities()
        && task != null
        && task.getTaskDefinitionKey() != null
        && instance != null) {
      Map<String, Activity> activityMap = instance.getActivityMap();
      if (activityMap != null) activity = activityMap.get(task.getTaskDefinitionKey());

      if (activity != null) return activity;
    }

    ProcessDeployment deployment = process.getDeployment();
    if (deployment == null)
      throw new InternalServerError(Constants.ExceptionCodes.process_is_misconfigured);

    String activityKey = deployment.getStartActivityKey();
    if (task != null) activityKey = task.getTaskDefinitionKey();

    if (activityKey != null) activity = deployment.getActivity(activityKey);

    if (activity != null) return activity;

    throw new InternalServerError(Constants.ExceptionCodes.process_is_misconfigured);
  }
 public List<Task> doTaskSearch(String query, int user_id) {
   List<TaskEntry> list = taskEntryRepository.findByTitleOrDescription(query, query);
   List<Task> ret = new ArrayList<>();
   for (TaskEntry entry : list) {
     System.out.println(
         "entry userID = "
             + entry.getUser_id()
             + " required UserID = "
             + Integer.toString(user_id));
     System.out.println(entry.getType());
     String type = entry.getType();
     if ((type.equals("task") || type.equals("taskItem"))
         && entry.getUser_id().equals(Integer.toString(user_id))) {
       if (type.equals("task")) {
         Task task = OrganizerDAO.getTaskByTitle(user_id, entry.getTitle());
         ret.add(task);
       }
       if (type.equals("taskItem")) {
         TaskItem item = OrganizerDAO.getTaskId(Integer.parseInt(entry.getObj_id()));
         Task task = OrganizerDAO.getTaskById(item.getTask_id());
         List<TaskItem> taskList = OrganizerDAO.getTaskItems(task.getId());
         if (taskList != null) {
           task.setTaskList(taskList);
           task.setTaskListSize(taskList.size());
         }
         ret.add(task);
       }
     }
   }
   return ret;
 }
Exemple #12
0
 /** Create a task */
 public static Task create(Integer project, String folder, String title) {
   Task task = new Task();
   task.project = Project.find.ref(project);
   task.folder = folder;
   task.title = title;
   task.save();
   return task;
 }
 public void runTask(Class<? extends Task> clazz) {
   try {
     Task task = clazz.newInstance();
     task.run(this);
   } catch (ReflectiveOperationException e) {
     handleException(e);
   }
 }
Exemple #14
0
  public void run() {
    if (!checkRealizeable()) {
      System.out.println("Project is not realizeable, quitting");
      System.exit(1);
    }

    int t = 0;
    ArrayList<Task> active_tasks = findTaskWithIndegreeZero();
    System.out.println("---------------- Starting project from");
    for (Task task : active_tasks) {
      System.out.println(task.toString());
      task.start(t);
    }
    boolean finished = false;
    while (true) {

      ArrayList<Task> to_be_removed = new ArrayList<>();
      ArrayList<Task> to_be_added = new ArrayList<>();
      for (Task task : active_tasks) {

        if (task.isFinished(t)) {
          for (Edge edge : task.outEdges) {
            if (edge.w.tell_finished_prerequisite(t)) {
              to_be_added.add(edge.w);
            }
          }
          to_be_removed.add(task);
        }
      }
      active_tasks.removeAll(to_be_removed);
      active_tasks.addAll(to_be_added);
      int current_staff = 0;

      for (Task task : active_tasks) {
        current_staff += task.staff;
      }
      System.out.println("Current staff: " + Integer.toString(current_staff));

      if (active_tasks.size() == 0) {
        for (Task task : tasks) {
          if (task.finished_at == -1) {
            System.out.println("Task " + Integer.toString(task.id) + " was not able to finish!");
          }
        }
        break;
      }
      t++;
      System.out.println(" ");
      System.out.println("t: " + Integer.toString(t));
    }
    minimum_completion_time = t;
    System.out.println(
        "*** Shortest possible execution time is "
            + Integer.toString(minimum_completion_time)
            + " ***");

    setSlack();
  }
 // compare duedate and priority and ??duration??
 public int compareTo(Task other) {
   if (duedate.compareTo(other.getDueDate()) != 0) {
     return duedate.compareTo(other.getDueDate());
   } else if (priority != other.getPriority()) {
     return (int) (other.getPriority() - priority);
   } else {
     return (int) (other.getDuration() - duration);
   }
 }
Exemple #16
0
 public void addTask(int id, String name, int time, int staff, int[] dependencies) {
   Task tmp = new Task(id, this);
   if (!tasks.contains(tmp)) {
     addTask(tmp);
   } else {
     tmp = getTask(tmp);
   }
   tmp.setParameters(name, time, staff, dependencies);
 }
  public FormRequest create(
      RequestDetails requestDetails,
      Process process,
      ProcessInstance processInstance,
      Task task,
      ActionType actionType,
      FormValidation validation)
      throws StatusCodeError {
    Activity activity = activity(process, processInstance, task);

    // Don't allow anyone to issue a create request for a task that's not open
    if (actionType == ActionType.CREATE
        && task != null
        && task.getTaskStatus() != null
        && !task.getTaskStatus().equals(Constants.TaskStatuses.OPEN)) actionType = ActionType.VIEW;

    FormRequest.Builder formRequestBuilder =
        new FormRequest.Builder()
            .processDefinitionKey(process.getProcessDefinitionKey())
            .instance(processInstance)
            .task(task)
            .activity(activity)
            .action(actionType);

    if (requestDetails != null) {
      String contentType =
          requestDetails.getContentType() != null
              ? requestDetails.getContentType().toString()
              : null;

      formRequestBuilder
          .remoteAddr(requestDetails.getRemoteAddr())
          .remoteHost(requestDetails.getRemoteHost())
          .remotePort(requestDetails.getRemotePort())
          .remoteUser(requestDetails.getRemoteUser())
          .actAsUser(requestDetails.getActAsUser())
          .certificateIssuer(requestDetails.getCertificateIssuer())
          .certificateSubject(requestDetails.getCertificateSubject())
          .contentType(contentType)
          .referrer(requestDetails.getReferrer())
          .userAgent(requestDetails.getUserAgent());

      List<MediaType> acceptableMediaTypes = requestDetails.getAcceptableMediaTypes();
      if (acceptableMediaTypes != null) {
        for (MediaType acceptableMediaType : acceptableMediaTypes) {
          formRequestBuilder.acceptableMediaType(acceptableMediaType.toString());
        }
      }
    }

    if (validation != null) {
      formRequestBuilder.messages(validation.getResults());
    }

    return requestRepository.save(formRequestBuilder.build());
  }
 public String suggestBranchName(Task task) {
   if (task.isIssue() && StringUtil.isNotEmpty(task.getNumber())) {
     return task.getId().replace(' ', '-');
   } else {
     String summary = task.getSummary();
     List<String> words = StringUtil.getWordsIn(summary);
     String[] strings = ArrayUtil.toStringArray(words);
     return StringUtil.join(strings, 0, Math.min(2, strings.length), "-");
   }
 }
Exemple #19
0
  public void flip() {
    Task tmp = v;
    this.w.addEdge(this);
    this.v.removeEdge(this);

    this.v = w;
    this.w = tmp;
    w.addPredecessor();
    v.removePredecessor();
  }
Exemple #20
0
 public Task removeTask(String taskName) {
   for (int i = 0; i < tasks.size(); i++) {
     Task task = tasks.get(i);
     if (StringUtils.equals(task.getName(), taskName)) {
       tasks.remove(i);
       return task;
     }
   }
   return null;
 }
Exemple #21
0
 // Overriding the compare method to sort the dueDate
 public int compare(Task t1, Task t2) {
   int result = 1;
   Date d1 = t1.getDueDate();
   Date d2 = t2.getDueDate();
   if (d1 != null & d2 != null) {
     result = t1.getDueDate().compareTo(t2.getDueDate());
   } else if (d1 == null) {
     result = -1;
   }
   return result;
 }
Exemple #22
0
 public Builder taskSubresources(String processDefinitionKey, Task task, ViewContext context) {
   this.assignment =
       context != null && task != null && task.getTaskInstanceId() != null
           ? context.getApplicationUri(
               Task.Constants.ROOT_ELEMENT_NAME,
               processDefinitionKey,
               task.getTaskInstanceId(),
               "assign")
           : null;
   this.task = task;
   return this;
 }
Exemple #23
0
 public void saveTask(Task task) {
   Task oldTask = findTask(task.getName());
   if (oldTask == null) {
     tasks.add(task);
   } else {
     for (int i = 0; i < tasks.size(); i++) {
       if (StringUtils.equals(tasks.get(i).getName(), task.getName())) {
         tasks.set(i, task);
       }
     }
   }
 }
  private UUID createChallengeTemplate(
      CodingContestGameDto dto, UUID organizationId, Map<String, ByteArrayOutputStream> files)
      throws IOException {
    ChallengeTemplate challengeTemplate =
        challengeTemplateRepository.findOneByCanonicalName(dto.getCanonicalName());
    if (challengeTemplate != null) {
      return challengeTemplate.getId();
    }
    Organization organization = organizationRepository.findOne(organizationId);
    if (organization == null) {
      throw new CodunoIllegalArgumentException("organization.invalid");
    }

    if (dto.getPuzzles()
        .stream()
        .findAny()
        .filter(puzzleDto -> puzzleDto.getValidationClass() != null)
        .isPresent()) {
      throw new CodunoIllegalArgumentException("ccc.game.structure.unsuported");
    }

    Runner runner = getRunner("/io");
    Endpoint taskEndpoint = getEndpoint("CCC general task", "ccc-io-task");
    Set<Language> languages = new HashSet<>(languageRepository.findAll());
    Duration gameDuration = parseGameDuration(dto.getTimeframe());

    challengeTemplate = mapChallengeTemplate(dto, organization, gameDuration);

    for (PuzzleDto puzzle : dto.getPuzzles()) {
      Task task =
          mapTask(
              puzzle,
              challengeTemplate,
              organization,
              files,
              gameDuration,
              runner,
              taskEndpoint,
              languages);
      Map<String, ByteArrayOutputStream> testFiles = null;
      if (puzzle.getInputFilePath() != null) {
        testFiles = unzip(files.get(puzzle.getInputFilePath()).toByteArray());
      }
      for (PuzzleTestDto puzzleTest : puzzle.getTests()) {
        Test test = mapTest(puzzleTest, runner, testFiles);
        task.addTest(test);
      }
      task = taskRepository.save(task);
      challengeTemplate.addTask(task);
    }
    return challengeTemplateRepository.save(challengeTemplate).getId();
  }
Exemple #25
0
  /* Devolve lista com o tipo de tarefas */
  public List<String> listTask() {
    ArrayList<String> tasklist = new ArrayList<>();

    lock.lock();
    try {
      for (Task task : this.tasks.values()) {
        tasklist.add(task.getType());
      }
      return tasklist;
    } finally {
      lock.unlock();
    }
  }
Exemple #26
0
 private void setTimeBackwards(Task task, int t_) {
   int t = t_ - task.time;
   if (task.latest_start_suggestion == -1) task.latest_start_suggestion = t;
   else {
     if (t < task.latest_start_suggestion) {
       task.latest_start_suggestion = t;
     }
   }
   for (Edge edge : task.outEdges) {
     setTimeBackwards(edge.w, t);
   }
   return;
 }
Exemple #27
0
 public static void main(String[] args) throws IOException {
   // InputStream inputStream = new FileInputStream("replaceme.in");
   // OutputStream outputStream = new FileOutputStream("replaceme.out");
   /////////////////////////////////////////////////////////////////////
   InputStream inputStream = System.in;
   OutputStream outputStream = System.out;
   InputReader in = new InputReader(inputStream);
   OutputWriter out = new OutputWriter(outputStream);
   Task solver = new Task();
   solver.solve(1, in, out);
   out.close();
   System.exit(0);
 }
Exemple #28
0
 private boolean iterateTask(Task task) {
   if (task.on_stack) {
     System.out.println("Identified cycle containing task: " + Integer.toString(task.id));
     return false;
   }
   task.on_stack = true;
   for (Edge edge : task.outEdges) {
     boolean retval = iterateTask(edge.w);
     task.on_stack = false;
     return retval;
   }
   task.on_stack = false;
   return true;
 }
Exemple #29
0
 protected final void releaseAllLocks(Component host_) {
   String old_ = state;
   setState(State_UNLOCKING);
   for (LockPack p_ = (LockPack) host_.locks; p_ != null; p_ = p_.next)
     if (p_.holder == this) {
       // unlock(host_, p_.target, true);
       // below is copied from unlock()
       synchronized (p_) {
         p_.holder = null;
         p_.counter = -1;
         // p_.counter is not zero, see Note 1 above
         if (p_.lockReqCount == 0) {
           continue;
         }
         p_.lockReqCount--;
         synchronized (aruntime) {
           if (aruntime.getWorkforce()) {
             p_.notify(); // dont know who's going to wake up
             aruntime.nthreadsWaiting--;
           } else aruntime.newTask(Task.createNotify(p_), this);
         }
       }
     }
   setState(old_);
 }
Exemple #30
0
 // Notifies all the threads waiting on the object.
 protected final void notifyAll(Component host_, Object o_) {
   if (o_ == null) return;
   String old_ = state;
   setState(State_NOTIFYING);
   // sleepOn = o_;
   LockPack p_ = lookforLock(host_, o_);
   synchronized (o_) {
     // setState(State_NOTIFYING2);
     // sleepOn = null;
     if (p_.waitCount == 0) return;
     // runtime._notifyMany(o_, p_.waitCount, this);
     synchronized (aruntime) {
       if (aruntime.getWorkforce(p_.waitCount)) {
         o_.notifyAll(); // dont know who's going to wake up
         aruntime.nthreadsWaiting -= p_.waitCount;
       } else {
         int remainingWorkforce_ = aruntime.getRemainingWorkforce();
         // notify "remainingWorkforce_" threads
         for (int i = 0; i < remainingWorkforce_; i++) o_.notify();
         aruntime.nthreadsWaiting -= remainingWorkforce_;
         for (int i = p_.waitCount - remainingWorkforce_; i > 0; i--)
           aruntime.newTask(Task.createNotify(o_), this);
       }
     }
     p_.waitCount = 0;
   }
   setState(old_);
 }