public static List<List<Integer>> levelOrderBottom(TreeNode root) {
   if (root == null) {
     return new ArrayList<>();
   }
   List<List<Integer>> res = new ArrayList<>();
   List<Integer> level = new ArrayList<>();
   Queue<TreeNode> queue = new LinkedList<>(); // 新建一个queue,用来记录哪些nodes是目前的波前
   queue.add(root); // 向root注水作为波前
   queue.add(null); // 在波前队列queue加null作为Flag代表这层level已访问结束
   while (queue.size() != 0) {
     TreeNode u = queue.poll();
     if (u != null) {
       level.add(u.val);
       /*
        * 波前u向其所有有连同的node扩散
        * u是v的predecessor前驱 or parent
        * v是u的 descendent后记
        * */
       if (u.left != null) {
         queue.add(u.left);
       }
       if (u.right != null) {
         queue.add(u.right);
       }
     } else {
       res.add(level);
       level = new ArrayList<Integer>();
       if (!queue.isEmpty()) {
         queue.add(null);
       }
     }
   }
   Collections.reverse(res);
   return res;
 }
 private String mergePathLists(List<String> basePathSteps, List<String> filePathSteps) {
   Collections.reverse(basePathSteps);
   Collections.reverse(filePathSteps);
   List<String> result = new ArrayList<String>(basePathSteps);
   int i = 0;
   while (i < filePathSteps.size() && filePathSteps.get(i).equals("..")) {
     result.remove(result.size() - 1);
     i++;
   }
   for (int j = i; j < filePathSteps.size(); j++) {
     result.add(filePathSteps.get(j));
   }
   StringBuilder resultPath = new StringBuilder();
   for (int k = 0; k < result.size(); k++) {
     resultPath.append(result.get(k));
     if (k != result.size() - 1) {
       resultPath.append(File.separator);
     }
   }
   String resultString = resultPath.toString();
   if (!resultString.startsWith(SEPARATOR)) {
     resultString = SEPARATOR + resultString;
   }
   return resultString;
 }
 /**
  * Returns the normalized form of the URI, using the given multiple candidates (this means that
  * more than 2 modules had a matching name).
  *
  * @param uri The URI that is to be normalized.
  * @param candidateURIs URIs of the modules that can potentially be a match for <code>uri</code>.
  * @return the normalized form
  */
 private URI findBestMatchFor(URI uri, Set<URI> candidateURIs) {
   URI normalized = null;
   final Iterator<URI> candidatesIterator = candidateURIs.iterator();
   final List<String> referenceSegments = Arrays.asList(uri.segments());
   Collections.reverse(referenceSegments);
   int highestEqualFragments = 0;
   while (candidatesIterator.hasNext()) {
     final URI next = candidatesIterator.next();
     int equalFragments = 0;
     final List<String> candidateSegments = Arrays.asList(next.segments());
     Collections.reverse(candidateSegments);
     for (int i = 0; i < Math.min(candidateSegments.size(), referenceSegments.size()); i++) {
       if (candidateSegments.get(i) == referenceSegments.get(i)) {
         equalFragments++;
       } else {
         break;
       }
     }
     if (equalFragments > highestEqualFragments) {
       highestEqualFragments = equalFragments;
       normalized = next;
     }
   }
   return normalized;
 }
Beispiel #4
0
    @Override
    public void onPostExecute(String result) {
      timeFinished = System.currentTimeMillis();
      invalidateOptionsMenu();
      Collections.reverse(ScrappingMachine.allemails);
      for (EmailMessage m : ScrappingMachine.allemails)
        m.save(); // now all e-mails are in the database

      // allemails_main creates a temporary arraylist of all emails in
      InboxFragment.allemails_main =
          (ArrayList<EmailMessage>)
              SugarRecord.listAll(EmailMessage.class); // fetch all emails from the
      // database

      Collections.reverse(InboxFragment.allemails_main);
      ScrappingMachine.clear_AllEmailsAL();
      InboxFragment.mAdapter.notifyDataSetChanged();

      long timeTaken = timeFinished - timeStarted;
      new ServerLoader(getApplicationContext())
          .addActionDetails(
              username, Constants.ACTION_MASTERREFRESH, "" + timeTaken, Constants.TRUE);

      Toast.makeText(Main_Nav.this, "Successfully Refreshed", Toast.LENGTH_SHORT).show();
      progdialog.dismiss();
    }
Beispiel #5
0
  /**
   * This function expects to receive a list ordered by number (Ascending) and version (Descending)
   *
   * @param guides
   * @return The latest version for the guides
   */
  private List getLatestVersions(List guides) {
    List result = new ArrayList();
    Integer numberAux = null;

    Collections.reverse(guides);

    Iterator iterator = guides.iterator();
    while (iterator.hasNext()) {
      Guide guide = (Guide) iterator.next();

      if ((numberAux == null) || (numberAux.intValue() != guide.getNumber().intValue())) {
        numberAux = guide.getNumber();
        InfoGuide infoGuide =
            InfoGuideWithPersonAndExecutionDegreeAndContributor.newInfoFromDomain(guide);

        List infoReimbursementGuides = new ArrayList();
        if (guide.getReimbursementGuides() != null) {
          Iterator iter = guide.getReimbursementGuides().iterator();
          while (iter.hasNext()) {
            ReimbursementGuide reimbursementGuide = (ReimbursementGuide) iter.next();
            InfoReimbursementGuide infoReimbursementGuide =
                InfoReimbursementGuide.newInfoFromDomain(reimbursementGuide);
            infoReimbursementGuides.add(infoReimbursementGuide);
          }
        }
        infoGuide.setInfoReimbursementGuides(infoReimbursementGuides);
        result.add(infoGuide);
      }
    }
    Collections.reverse(result);
    return result;
  }
Beispiel #6
0
  /**
   * Reduces segment list to the smallest number of segments by joining connected segments. Empty
   * segments are removed.
   *
   * <p>Iff segment reversal is allowed, segments are joined even if they are connected head-to-head
   * or tail-to-tail. In such a case, we first reverse the vertices of one of the segments so that
   * they are joined head-to-tail, then append as usual.
   *
   * <p>Allowing segment reversal sacrifices any hope of use a segment's winding direction to infer
   * which side its interior is on, but helps with data in which winding direction is meaningless to
   * begin with.
   */
  private static void joinConnectedSegments(
      List<List<LandVertex>> segments, boolean allowSegmentReversal) {
    int joinlessLoopsRemaining = segments.size();
    while (joinlessLoopsRemaining > 0) {
      List<LandVertex> base = segments.remove(0);
      if (base.isEmpty()) {
        joinlessLoopsRemaining--;
        continue;
      }

      boolean anyJoins = false;
      for (Iterator<List<LandVertex>> i = segments.iterator(); i.hasNext(); ) {
        List<LandVertex> extension = i.next();

        if (extension.get(0).equals(base.get(base.size() - 1))) {
          base.addAll(extension);
          i.remove();
          anyJoins = true;
        } else if (allowSegmentReversal
            && extension.get(extension.size() - 1).equals(base.get(base.size() - 1))) {
          Collections.reverse(extension);
          base.addAll(extension);
          i.remove();
          anyJoins = true;
        } else if (allowSegmentReversal && extension.get(0).equals(base.get(0))) {
          Collections.reverse(base);
          base.addAll(extension);
          i.remove();
          anyJoins = true;
        }
      }
      segments.add(base);
      joinlessLoopsRemaining = (anyJoins ? segments.size() : joinlessLoopsRemaining - 1);
    }
  }
  private synchronized void sort(PyObject cmp, PyObject key, boolean reverse) {
    gListAllocatedStatus = -1;

    int size = list.size();
    final ArrayList<KV> decorated = new ArrayList<KV>(size);
    for (PyObject value : list) {
      decorated.add(new KV(key.__call__(value), value));
    }
    list.clear();
    KVComparator c = new KVComparator(this, cmp);
    if (reverse) {
      Collections.reverse(decorated); // maintain stability of sort by reversing first
    }
    Collections.sort(decorated, c);
    if (reverse) {
      Collections.reverse(decorated);
    }
    if (list instanceof ArrayList) {
      ((ArrayList) list).ensureCapacity(size);
    }
    for (KV kv : decorated) {
      list.add(kv.value);
    }
    gListAllocatedStatus = __len__();
  }
Beispiel #8
0
  public synchronized void initOrderList(@NotNull JSONArray orderArray) {

    synchronized (OrderListLock) {
      finishedOrderList = new ArrayList<OrderData>();
      unfinishedOrderList = new ArrayList<OrderData>();

      for (int i = 0; i < orderArray.length(); i++) {
        OrderData orderData = null;
        try {
          orderData = new OrderData(orderArray.getJSONObject(i));

          if (orderData.getStatus() == 0
              || orderData.getStatus() == 1
              || orderData.getStatus() == 2
              || orderData.getStatus() == 5) continue;

          if (orderData.getTradedVolume() > 0) {
            finishedOrderList.add(orderData);
          }
          if (orderData.getTradedVolume() < orderData.getOriginVolume()) {
            unfinishedOrderList.add(orderData);
          }

        } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }

      Collections.reverse(finishedOrderList);
      Collections.reverse(unfinishedOrderList);
    }
  }
  @NotNull
  public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) {

    JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();

    List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>();

    // prevent adding duplicate version on alias names
    Set<String> aliasBranches = new HashSet<>();

    // get alias version, in most common order
    for (String s : new String[] {"latest", "lts"}) {
      JsonElement asJsonObject = jsonObject.get(s);
      if (asJsonObject == null) {
        continue;
      }

      String asString = asJsonObject.getAsString();
      aliasBranches.add(asString);

      symfonyInstallerVersions.add(
          new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s)));
    }

    List<SymfonyInstallerVersion> branches = new ArrayList<>();
    Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();
    for (Map.Entry<String, JsonElement> entry : entries) {
      if (!entry.getKey().matches("^\\d+\\.\\d+$")) {
        continue;
      }

      // "2.8.0-dev", "2.8.0-DEV" is not supported
      String asString = entry.getValue().getAsString();
      if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) {
        continue;
      }

      branches.add(
          new SymfonyInstallerVersion(
              asString, String.format("%s (%s)", entry.getKey(), asString)));
    }

    branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion));

    Collections.reverse(branches);

    symfonyInstallerVersions.addAll(branches);

    // we need reverse order for sorting them on version string
    List<SymfonyInstallerVersion> installableVersions = new ArrayList<>();
    for (JsonElement installable : jsonObject.getAsJsonArray("installable")) {
      installableVersions.add(new SymfonyInstallerVersion(installable.getAsString()));
    }
    Collections.reverse(installableVersions);

    symfonyInstallerVersions.addAll(installableVersions);
    return symfonyInstallerVersions;
  }
 @Override
 public void caseAMethodDecl(AMethodDecl node) {
   inAMethodDecl(node);
   if (node.getN3() != null) {
     node.getN3().apply(this);
   }
   if (node.getEndid() != null) {
     node.getEndid().apply(this);
   }
   if (node.getEnd() != null) {
     node.getEnd().apply(this);
   }
   {
     List<PStmt> copy = new ArrayList<PStmt>(node.getStmt());
     Collections.reverse(copy);
     for (PStmt e : copy) {
       e.apply(this);
     }
   }
   if (node.getN2() != null) {
     node.getN2().apply(this);
   }
   if (node.getBegin() != null) {
     node.getBegin().apply(this);
   }
   {
     List<PVarDecl> copy = new ArrayList<PVarDecl>(node.getVarDecl());
     Collections.reverse(copy);
     for (PVarDecl e : copy) {
       e.apply(this);
     }
   }
   if (node.getN1() != null) {
     node.getN1().apply(this);
   }
   if (node.getIs() != null) {
     node.getIs().apply(this);
   }
   if (node.getOptType() != null) {
     node.getOptType().apply(this);
   }
   if (node.getRPar() != null) {
     node.getRPar().apply(this);
   }
   if (node.getArgumentDeclList() != null) {
     node.getArgumentDeclList().apply(this);
   }
   if (node.getLPar() != null) {
     node.getLPar().apply(this);
   }
   if (node.getStid() != null) {
     node.getStid().apply(this);
   }
   outAMethodDecl(node);
 }
Beispiel #11
0
 /**
  * 列出指定目录下的所有子目录
  *
  * @param startDirPath the start dir path
  * @param excludeDirs the exclude dirs
  * @param sortType the sort type
  * @return file [ ]
  */
 public static File[] listDirs(String startDirPath, String[] excludeDirs, SortType sortType) {
   LogUtils.debug(String.format("list dir %s", startDirPath));
   ArrayList<File> dirList = new ArrayList<File>();
   File startDir = new File(startDirPath);
   if (!startDir.isDirectory()) {
     return new File[0];
   }
   File[] dirs =
       startDir.listFiles(
           new FileFilter() {
             public boolean accept(File f) {
               if (f == null) {
                 return false;
               }
               if (f.isDirectory()) {
                 return true;
               }
               return false;
             }
           });
   if (dirs == null) {
     return new File[0];
   }
   if (excludeDirs == null) {
     excludeDirs = new String[0];
   }
   for (File dir : dirs) {
     File file = dir.getAbsoluteFile();
     if (!Arrays.deepToString(excludeDirs).contains(file.getName())) {
       dirList.add(file);
     }
   }
   if (sortType.equals(SortType.BY_NAME_ASC)) {
     Collections.sort(dirList, new SortByName());
   } else if (sortType.equals(SortType.BY_NAME_DESC)) {
     Collections.sort(dirList, new SortByName());
     Collections.reverse(dirList);
   } else if (sortType.equals(SortType.BY_TIME_ASC)) {
     Collections.sort(dirList, new SortByTime());
   } else if (sortType.equals(SortType.BY_TIME_DESC)) {
     Collections.sort(dirList, new SortByTime());
     Collections.reverse(dirList);
   } else if (sortType.equals(SortType.BY_SIZE_ASC)) {
     Collections.sort(dirList, new SortBySize());
   } else if (sortType.equals(SortType.BY_SIZE_DESC)) {
     Collections.sort(dirList, new SortBySize());
     Collections.reverse(dirList);
   } else if (sortType.equals(SortType.BY_EXTENSION_ASC)) {
     Collections.sort(dirList, new SortByExtension());
   } else if (sortType.equals(SortType.BY_EXTENSION_DESC)) {
     Collections.sort(dirList, new SortByExtension());
     Collections.reverse(dirList);
   }
   return dirList.toArray(new File[dirList.size()]);
 }
  private static List<CompletionVariant> computeVariants(
      @NotNull final Editor editor, @Nullable final String prefix) {
    final PrefixMatcher matcher = new CamelHumpMatcher(prefix == null ? "" : prefix);

    final CharSequence chars = editor.getDocument().getCharsSequence();

    final ArrayList<CompletionVariant> words = new ArrayList<CompletionVariant>();
    final List<CompletionVariant> afterWords = new ArrayList<CompletionVariant>();

    IdTableBuilding.scanWords(
        new IdTableBuilding.ScanWordProcessor() {
          public void run(final CharSequence chars, final int start, final int end) {
            final int caretOffset = editor.getCaretModel().getOffset();
            if (start <= caretOffset && end >= caretOffset) return; // skip prefix itself

            final String word = chars.subSequence(start, end).toString();
            if (!matcher.prefixMatches(word)) return;
            final CompletionVariant v = new CompletionVariant(word, start);

            if (end > caretOffset) {
              afterWords.add(v);
            } else {
              words.add(v);
            }
          }
        },
        chars,
        0,
        chars.length());

    Set<String> allWords = new HashSet<String>();
    List<CompletionVariant> result = new ArrayList<CompletionVariant>();

    Collections.reverse(words);

    for (CompletionVariant variant : words) {
      if (!allWords.contains(variant.variant)) {
        result.add(variant);
        allWords.add(variant.variant);
      }
    }

    Collections.reverse(result);

    allWords.clear();
    for (CompletionVariant variant : afterWords) {
      if (!allWords.contains(variant.variant)) {
        result.add(variant);
        allWords.add(variant.variant);
      }
    }

    return result;
  }
 private synchronized void sort(boolean reverse) {
   gListAllocatedStatus = -1;
   if (reverse) {
     Collections.reverse(list); // maintain stability of sort by reversing first
   }
   Collections.sort(list, new PyObjectDefaultComparator(this));
   if (reverse) {
     Collections.reverse(list); // maintain stability of sort by reversing first
   }
   gListAllocatedStatus = __len__();
 }
Beispiel #14
0
 /**
  * 列出指定目录下的所有文件
  *
  * @param startDirPath the start dir path
  * @param filterPattern the filter pattern
  * @param sortType the sort type
  * @return the file [ ]
  */
 public static File[] listFiles(
     String startDirPath, final Pattern filterPattern, SortType sortType) {
   LogUtils.debug(String.format("list file %s", startDirPath));
   ArrayList<File> fileList = new ArrayList<File>();
   File f = new File(startDirPath);
   if (!f.isDirectory()) {
     return new File[0];
   }
   File[] files =
       f.listFiles(
           new FileFilter() {
             public boolean accept(File f) {
               if (f == null) {
                 return false;
               }
               if (f.isDirectory()) {
                 return false;
               }
               if (filterPattern == null) {
                 return true;
               }
               return filterPattern.matcher(f.getName()).find();
             }
           });
   if (files == null) {
     return new File[0];
   }
   for (File file : files) {
     fileList.add(file.getAbsoluteFile());
   }
   if (sortType.equals(SortType.BY_NAME_ASC)) {
     Collections.sort(fileList, new SortByName());
   } else if (sortType.equals(SortType.BY_NAME_DESC)) {
     Collections.sort(fileList, new SortByName());
     Collections.reverse(fileList);
   } else if (sortType.equals(SortType.BY_TIME_ASC)) {
     Collections.sort(fileList, new SortByTime());
   } else if (sortType.equals(SortType.BY_TIME_DESC)) {
     Collections.sort(fileList, new SortByTime());
     Collections.reverse(fileList);
   } else if (sortType.equals(SortType.BY_SIZE_ASC)) {
     Collections.sort(fileList, new SortBySize());
   } else if (sortType.equals(SortType.BY_SIZE_DESC)) {
     Collections.sort(fileList, new SortBySize());
     Collections.reverse(fileList);
   } else if (sortType.equals(SortType.BY_EXTENSION_ASC)) {
     Collections.sort(fileList, new SortByExtension());
   } else if (sortType.equals(SortType.BY_EXTENSION_DESC)) {
     Collections.sort(fileList, new SortByExtension());
     Collections.reverse(fileList);
   }
   return fileList.toArray(new File[fileList.size()]);
 }
 private synchronized void sort(PyObject compare, boolean reverse) {
   gListAllocatedStatus = -1;
   if (reverse) {
     Collections.reverse(list); // maintain stability of sort by reversing first
   }
   PyObjectComparator c = new PyObjectComparator(this, compare);
   Collections.sort(list, c);
   if (reverse) {
     Collections.reverse(list);
   }
   gListAllocatedStatus = __len__();
 }
Beispiel #16
0
 public static void clear(PolyBase in) {
   if (in.decomposition.size() > 1) {
     Collections.reverse(in.decomposition);
     while (in.decomposition.get(in.decomposition.size() - 1) == 0) {
       if (in.decomposition.size() < 2) {
         break;
       }
       in.decomposition.remove(in.decomposition.size() - 1);
     }
     Collections.reverse(in.decomposition);
   }
 }
Beispiel #17
0
 public static PolyBase gornerMeth(PolyBase a, PolyBase b, Integer fl) {
   PolyBase temp = a;
   PolyBase result = one(fl);
   Collections.reverse(b.decomposition);
   for (int i = 0; i < b.decomposition.size(); i++) {
     if (b.decomposition.get(i) == 1) {
       result = multiplication(result, temp);
     }
     temp = square(temp);
   }
   Collections.reverse(b.decomposition);
   return result;
 }
  @Override
  public List<String> getSuggestions(String query) {
    try {
      if (artistName == null) {
        return NamedData.namedDataListToNameList(
            internetSearchEngine.searchAudios(query, maxCount, 1).elements);
      } else {
        List<String> result = new ArrayList<>();
        List<Audio> audios = internetSearchEngine.searchAudios(query, maxCount * 2, 1).elements;
        audios = NamedData.uniqueNames(audios);

        int removedCount = 0;
        for (int i = audios.size() - 1; i >= 0; i--) {
          Audio audio = audios.get(i);
          if (result.size() - removedCount > minCount
              && !Strings.equalsIgnoreCase(audio.getArtistName(), artistName)) {
            removedCount++;
          } else {
            result.add(audio.getName());
          }
        }

        Collections.reverse(result);
        return result;
      }
    } catch (IOException e) {
      return Collections.emptyList();
    }
  }
Beispiel #19
0
 /** Destroy all services. */
 public void destroy() {
   XLog log = new XLog(LogFactory.getLog(getClass()));
   log.trace("Shutting down");
   boolean deleteRuntimeDir = false;
   if (conf != null) {
     deleteRuntimeDir = conf.getBoolean(CONF_DELETE_RUNTIME_DIR, false);
   }
   if (services != null) {
     List<Service> list = new ArrayList<Service>(services.values());
     Collections.reverse(list);
     for (Service service : list) {
       try {
         log.trace("Destroying service[{0}]", service.getInterface());
         if (service.getInterface() == XLogService.class) {
           log.info("Shutdown");
         }
         service.destroy();
       } catch (Throwable ex) {
         log.error(
             "Error destroying service[{0}], {1}", service.getInterface(), ex.getMessage(), ex);
       }
     }
   }
   if (deleteRuntimeDir) {
     try {
       IOUtils.delete(new File(runtimeDir));
     } catch (IOException ex) {
       log.error("Error deleting runtime directory [{0}], {1}", runtimeDir, ex.getMessage(), ex);
     }
   }
   services = null;
   conf = null;
   SERVICES = null;
 }
Beispiel #20
0
  public static String getAbsolutePath(PortletRequest portletRequest, long mbCategoryId)
      throws PortalException, SystemException {

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    if (mbCategoryId == MBCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {
      return themeDisplay.translate("home");
    }

    MBCategory mbCategory = MBCategoryLocalServiceUtil.fetchMBCategory(mbCategoryId);

    List<MBCategory> categories = mbCategory.getAncestors();

    Collections.reverse(categories);

    StringBundler sb = new StringBundler((categories.size() * 3) + 5);

    sb.append(themeDisplay.translate("home"));
    sb.append(StringPool.SPACE);

    for (MBCategory curCategory : categories) {
      sb.append(StringPool.RAQUO);
      sb.append(StringPool.SPACE);
      sb.append(curCategory.getName());
    }

    sb.append(StringPool.RAQUO);
    sb.append(StringPool.SPACE);
    sb.append(mbCategory.getName());

    return sb.toString();
  }
 public List<Double> getImproperDihedralParams(List<String> atoms) {
   List<String> key = new ArrayList<String>(atoms);
   List<String> key2 = new ArrayList<String>(atoms);
   Collections.reverse(key2);
   List<Double> value = improperDihedralParams.get(key);
   if (value == null) {
     value = improperDihedralParams.get(key2);
   }
   if (value == null) {
     key.set(0, "X");
     value = improperDihedralParams.get(key);
   }
   if (value == null) {
     key2.set(0, "X");
     value = improperDihedralParams.get(key2);
   }
   if (value == null) {
     key.set(1, "X");
     value = improperDihedralParams.get(key);
   }
   if (value == null) {
     key2.set(1, "X");
     value = improperDihedralParams.get(key2);
   }
   return value;
 }
  @Override
  public Object provide(Object source, Object currentValue) {

    final ExecutionYear currentYear = ExecutionYear.readCurrentExecutionYear();
    final ExecutionYear previousYear = currentYear.getPreviousExecutionYear();
    final List<ExecutionSemester> executionSemesters = new ArrayList<ExecutionSemester>();

    SpecialSeasonStudentEnrollmentBean bean = (SpecialSeasonStudentEnrollmentBean) source;
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(currentYear.getLastExecutionPeriod())) {
      executionSemesters.add(currentYear.getLastExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(currentYear.getFirstExecutionPeriod())) {
      executionSemesters.add(currentYear.getFirstExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(previousYear.getLastExecutionPeriod())) {
      executionSemesters.add(previousYear.getLastExecutionPeriod());
    }
    if (bean.getScp()
        .getDegreeCurricularPlan()
        .hasOpenSpecialSeasonEnrolmentPeriod(previousYear.getFirstExecutionPeriod())) {
      executionSemesters.add(previousYear.getFirstExecutionPeriod());
    }

    Collections.sort(executionSemesters, ExecutionSemester.COMPARATOR_BY_SEMESTER_AND_YEAR);
    Collections.reverse(executionSemesters);
    return executionSemesters;
  }
  @SuppressWarnings("deprecation")
  protected void afterEnd(Map flags, Task<?> task) {
    activeTaskCount.decrementAndGet();
    incompleteTaskCount.decrementAndGet();

    if (log.isTraceEnabled()) log.trace(this + " afterEnd, task: " + task);
    ExecutionUtils.invoke(flags.get("newTaskEndCallback"), task);
    List l = (List) flags.get("tagLinkedPreprocessors");
    Collections.reverse(l);
    for (Object li : l) {
      TaskPreprocessor t = (TaskPreprocessor) li;
      t.onEnd(flags, task);
    }

    PerThreadCurrentTaskHolder.perThreadCurrentTask.remove();
    ((BasicTask) task).endTimeUtc = System.currentTimeMillis();
    // clear thread _after_ endTime set, so we won't get a null thread when there is no end-time
    if (RENAME_THREADS) {
      String newThreadName = "brooklyn-" + LanguageUtils.newUid();
      ((BasicTask) task).thread.setName(newThreadName);
    }
    ((BasicTask) task).thread = null;
    synchronized (task) {
      task.notifyAll();
    }

    ExpirationPolicy expirationPolicy = (ExpirationPolicy) flags.get("expirationPolicy");
    if (expirationPolicy == null) expirationPolicy = ExpirationPolicy.IMMEDIATE;
    if (expirationPolicy == ExpirationPolicy.IMMEDIATE) {
      for (Object t : ((BasicTask) task).tags) {
        getMutableTasksWithTag(t).remove(task);
      }
    }
  }
  @Override
  public List<ExtRepositoryFileVersion> getExtRepositoryFileVersions(
      ExtRepositoryFileEntry extRepositoryFileEntry) throws PortalException {

    try {
      Drive drive = getDrive();

      Drive.Revisions driveRevisions = drive.revisions();

      Drive.Revisions.List driveRevisionsList =
          driveRevisions.list(extRepositoryFileEntry.getExtRepositoryModelKey());

      RevisionList revisionList = driveRevisionsList.execute();

      List<Revision> revisions = revisionList.getItems();

      List<ExtRepositoryFileVersion> extRepositoryFileVersions = new ArrayList<>(revisions.size());

      for (int i = 0; i < revisions.size(); i++) {
        Revision revision = revisions.get(i);

        extRepositoryFileVersions.add(
            new GoogleDriveFileVersion(
                revision, extRepositoryFileEntry.getExtRepositoryModelKey(), i + 1));
      }

      Collections.reverse(extRepositoryFileVersions);

      return extRepositoryFileVersions;
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int count = sc.nextInt();
    int digitsNum;

    for (int i = 0; i < count; i++) {
      ArrayList<Integer> digits = new ArrayList<>();
      digitsNum = sc.nextInt();
      int result = 0;

      while (digitsNum > 0) {
        digits.add(digitsNum % 10);
        digitsNum = digitsNum / 10;
      }

      Collections.reverse(digits);

      for (int j = 0; j < digits.size(); j++) {
        int digit = digits.get(j);
        result += digit * (j + 1);
      }

      System.out.print(result + " ");
    }

    sc.close();
  }
Beispiel #26
0
  /**
   * Parse the footer lines (e.g. "Signed-off-by") for machine processing.
   *
   * <p>This method splits all of the footer lines out of the last paragraph of the commit message,
   * providing each line as a key-value pair, ordered by the order of the line's appearance in the
   * commit message itself.
   *
   * <p>A footer line's key must match the pattern {@code ^[A-Za-z0-9-]+:}, while the value is
   * free-form, but must not contain an LF. Very common keys seen in the wild are:
   *
   * <ul>
   *   <li>{@code Signed-off-by} (agrees to Developer Certificate of Origin)
   *   <li>{@code Acked-by} (thinks change looks sane in context)
   *   <li>{@code Reported-by} (originally found the issue this change fixes)
   *   <li>{@code Tested-by} (validated change fixes the issue for them)
   *   <li>{@code CC}, {@code Cc} (copy on all email related to this change)
   *   <li>{@code Bug} (link to project's bug tracking system)
   * </ul>
   *
   * @return ordered list of footer lines; empty list if no footers found.
   */
  public final List<FooterLine> getFooterLines() {
    final byte[] raw = buffer;
    int ptr = raw.length - 1;
    while (raw[ptr] == '\n') // trim any trailing LFs, not interesting
    ptr--;

    final int msgB = RawParseUtils.commitMessage(raw, 0);
    final ArrayList<FooterLine> r = new ArrayList<FooterLine>(4);
    final Charset enc = getEncoding();
    for (; ; ) {
      ptr = RawParseUtils.prevLF(raw, ptr);
      if (ptr <= msgB) break; // Don't parse commit headers as footer lines.

      final int keyStart = ptr + 2;
      if (raw[keyStart] == '\n') break; // Stop at first paragraph break, no footers above it.

      final int keyEnd = RawParseUtils.endOfFooterLineKey(raw, keyStart);
      if (keyEnd < 0) continue; // Not a well formed footer line, skip it.

      // Skip over the ': *' at the end of the key before the value.
      //
      int valStart = keyEnd + 1;
      while (valStart < raw.length && raw[valStart] == ' ') valStart++;

      // Value ends at the LF, and does not include it.
      //
      int valEnd = RawParseUtils.nextLF(raw, valStart);
      if (raw[valEnd - 1] == '\n') valEnd--;

      r.add(new FooterLine(raw, enc, keyStart, keyEnd, valStart, valEnd));
    }
    Collections.reverse(r);
    return r;
  }
Beispiel #27
0
 /**
  * Hit test Point p against the Model's list of shapes
  *
  * @param p The point to test
  * @return The last drawn shape "hit" by the point, or null if no shape was hit
  */
 public Shape hitShapeTest(Point worldP) {
   List<Shape> shapes = new ArrayList<Shape>(Model.singleton().getShapes());
   Collections.reverse(shapes);
   for (Shape shape : shapes) {
     Point p = MatrixMaker.getObjectFromWorld(worldP, shape);
     switch (shape.getType()) {
       case CIRCLE:
         if (hitCircle(p, (Circle) shape)) return shape;
         break;
       case ELLIPSE:
         if (hitEllipse(p, (Ellipse) shape)) return shape;
         break;
       case LINE:
         if (hitLine(p, (Line) shape)) return shape;
         break;
       case RECTANGLE:
         if (hitRectangle(p, (Rectangle) shape)) return shape;
         break;
       case SQUARE:
         if (hitSquare(p, (Square) shape)) return shape;
         break;
       case TRIANGLE:
         if (hitTriangle(p, (Triangle) shape)) return shape;
         break;
     }
   }
   return null;
 }
Beispiel #28
0
    @Override
    public void renderTo(Target<?> target) {

      /* render fence */

      List<VectorXYZ> pointsWithEle = line.getElevationProfile().getPointsWithEle();

      List<VectorXYZ> vsFence = createVerticalTriangleStrip(pointsWithEle, 0, height);
      List<List<VectorXZ>> texCoordListsFence = wallTexCoordLists(vsFence, CHAIN_LINK_FENCE);

      target.drawTriangleStrip(CHAIN_LINK_FENCE, vsFence, texCoordListsFence);

      List<VectorXYZ> pointsWithEleBack = new ArrayList<VectorXYZ>(pointsWithEle);
      Collections.reverse(pointsWithEleBack);

      List<VectorXYZ> vsFenceBack = createVerticalTriangleStrip(pointsWithEleBack, 0, height);
      List<List<VectorXZ>> texCoordListsFenceBack =
          wallTexCoordLists(vsFenceBack, CHAIN_LINK_FENCE);

      target.drawTriangleStrip(CHAIN_LINK_FENCE, vsFenceBack, texCoordListsFenceBack);

      /* render poles */

      List<VectorXZ> polePositions =
          GeometryUtil.equallyDistributePointsAlong(
              2f, false, line.getStartNode().getPos(), line.getEndNode().getPos());

      for (VectorXZ polePosition : polePositions) {

        VectorXYZ base = polePosition.xyz(line.getElevationProfile().getEleAt(polePosition));
        target.drawColumn(CHAIN_LINK_FENCE_POST, null, base, height, width, width, false, true);
      }
    }
Beispiel #29
0
  public void doIt() {
    Iterator iter;
    Collection ref;

    ref = new ArrayList();
    Populator.fillIt(ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Collections.reverse((List) ref);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();

    Comparator aComparator = Collections.reverseOrder();
    Collections.sort((List) ref, aComparator);
    iter = ref.iterator();
    while (iter.hasNext()) {
      System.out.print(iter.next() + " ");
    } // end while loop
    System.out.println();
  } // end doIt()
 public List<ClusteredResult> standardcluster(
     List<OptMapResultNode> mapList, boolean processConfidence) {
   if (mapList.isEmpty()) return new ArrayList<ClusteredResult>();
   List<ClusteredResult> clusteredResultList;
   switch (clustermode) {
     case 0:
       clusteredResultList = standardnocluster(mapList);
       break;
     case 1:
       clusteredResultList = standardindelcluster(mapList);
       break;
     case 2:
       clusteredResultList = standardinversioncluster(mapList);
       break;
     case 3:
       clusteredResultList = standardtransloccluster(mapList);
       break;
     default:
       clusteredResultList = standardnocluster(mapList);
   }
   Collections.sort(clusteredResultList);
   Collections.reverse(clusteredResultList);
   if (processConfidence) processConfidence(clusteredResultList);
   clusteredResultList = filterClusteredResult(clusteredResultList);
   if (!overlapCluster) this.removeOverlap(clusteredResultList);
   if (maxClusterItem != -1)
     while (clusteredResultList.size() > maxClusterItem)
       clusteredResultList.remove(clusteredResultList.size() - 1);
   return clusteredResultList;
 }