/**
  * Return certificates for signed bundle, otherwise null.
  *
  * @return An array of certificates or null.
  */
 public ArrayList getCertificateChains(boolean onlyTrusted) {
   if (checkCerts) {
     Certificate[] c = archive.getCertificates();
     checkCerts = false;
     if (c != null) {
       ArrayList failed = new ArrayList();
       untrustedCerts = Util.getCertificateChains(c, failed);
       if (!failed.isEmpty()) {
         // NYI, log Bundle archive has invalid certificates
         untrustedCerts = null;
       }
     }
   }
   ArrayList res = trustedCerts;
   if (!onlyTrusted && untrustedCerts != null) {
     if (res == null) {
       res = untrustedCerts;
     } else {
       res = new ArrayList(trustedCerts.size() + untrustedCerts.size());
       res.addAll(trustedCerts);
       res.addAll(untrustedCerts);
     }
   }
   return res;
 }
  /* Scan the files in the new directory, and store them in the filelist.
   * Update the UI by refreshing the list adapter.
   */
  private void loadDirectory(String newdirectory) {
    if (newdirectory.equals("../")) {
      try {
        directory = new File(directory).getParent();
      } catch (Exception e) {
      }
    } else {
      directory = newdirectory;
    }
    SharedPreferences.Editor editor = getPreferences(0).edit();
    editor.putString("lastBrowsedDirectory", directory);
    editor.commit();
    directoryView.setText(directory);

    filelist = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedDirs = new ArrayList<FileUri>();
    ArrayList<FileUri> sortedFiles = new ArrayList<FileUri>();
    if (!newdirectory.equals(rootdir)) {
      String parentDirectory = new File(directory).getParent() + "/";
      Uri uri = Uri.parse("file://" + parentDirectory);
      sortedDirs.add(new FileUri(uri, parentDirectory));
    }
    try {
      File dir = new File(directory);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          if (file == null) {
            continue;
          }
          String filename = file.getName();
          if (file.isDirectory()) {
            Uri uri = Uri.parse("file://" + file.getAbsolutePath() + "/");
            FileUri fileuri = new FileUri(uri, uri.getPath());
            sortedDirs.add(fileuri);
          } else if (filename.endsWith(".mid")
              || filename.endsWith(".MID")
              || filename.endsWith(".midi")
              || filename.endsWith(".MIDI")) {

            Uri uri = Uri.parse("file://" + file.getAbsolutePath());
            FileUri fileuri = new FileUri(uri, uri.getLastPathSegment());
            sortedFiles.add(fileuri);
          }
        }
      }
    } catch (Exception e) {
    }

    if (sortedDirs.size() > 0) {
      Collections.sort(sortedDirs, sortedDirs.get(0));
    }
    if (sortedFiles.size() > 0) {
      Collections.sort(sortedFiles, sortedFiles.get(0));
    }
    filelist.addAll(sortedDirs);
    filelist.addAll(sortedFiles);
    adapter = new IconArrayAdapter<FileUri>(this, android.R.layout.simple_list_item_1, filelist);
    this.setListAdapter(adapter);
  }
Пример #3
0
  /**
   * Creates a java process that executes the given main class and waits for the process to
   * terminate.
   *
   * @return a {@link ProcessOutputReader} that can be used to get the exit code and stdout+stderr
   *     of the terminated process.
   */
  public static ProcessOutputReader fg(Class main, String[] vmArgs, String[] mainArgs)
      throws IOException {
    File javabindir = new File(System.getProperty("java.home"), "bin");
    File javaexe = new File(javabindir, "java");

    int bits = Integer.getInteger("sun.arch.data.model", 0).intValue();
    String vmKindArg = (bits == 64) ? "-d64" : null;

    ArrayList argList = new ArrayList();
    argList.add(javaexe.getPath());
    if (vmKindArg != null) {
      argList.add(vmKindArg);
    }
    // argList.add("-Dgemfire.systemDirectory=" +
    // GemFireConnectionFactory.getDefaultSystemDirectory());
    argList.add("-Djava.class.path=" + System.getProperty("java.class.path"));
    argList.add("-Djava.library.path=" + System.getProperty("java.library.path"));
    if (vmArgs != null) {
      argList.addAll(Arrays.asList(vmArgs));
    }
    argList.add(main.getName());
    if (mainArgs != null) {
      argList.addAll(Arrays.asList(mainArgs));
    }
    String[] cmd = (String[]) argList.toArray(new String[argList.size()]);
    return new ProcessOutputReader(Runtime.getRuntime().exec(cmd));
  }
Пример #4
0
  public static void main(String args[]) {
    int N;
    Scanner in = new Scanner(System.in);
    N = in.nextInt();
    int arr[] = new int[N];
    ArrayList even = new ArrayList();
    ArrayList odd = new ArrayList();
    ArrayList list = new ArrayList();

    for (int i = 0; i < N; i++) {
      arr[i] = in.nextInt();
    }
    int evenSum = 0;
    int oddSum = 0;
    for (int i = 0; i < N; i++) {
      if (arr[i] % 2 == 0) {
        even.add(arr[i]);
        evenSum = evenSum + arr[i];
      } else {
        odd.add(arr[i]);
        oddSum = oddSum + arr[i];
      }
    }
    even.add(evenSum);
    odd.add(oddSum);
    Collections.sort(even);
    Collections.sort(odd);
    list.addAll(even);
    list.addAll(odd);
    Iterator itr = list.iterator();
    while (itr.hasNext()) {
      System.out.println(itr.next());
    }
  }
Пример #5
0
 /* Recursive, returns an array list
  * containing this node and all child nodes */
 public ArrayList<avPair> enumeratePairs() {
   ArrayList<avPair> myAV = new ArrayList<avPair>();
   if (leaf) {
     myAV.add(this);
     return myAV;
   } else {
     myAV.add(this);
     myAV.addAll(leftChild.enumeratePairs());
     myAV.addAll(rightChild.enumeratePairs());
     return myAV;
   }
 }
Пример #6
0
  /**
   * getEquippedEnchantedCreatures.
   *
   * @param cards a {@link java.util.ArrayList} object.
   * @return a {@link java.util.ArrayList} object.
   */
  public static ArrayList<Card> getEquippedEnchantedCreatures(ArrayList<Card> cards) {
    ArrayList<Card> ret = new ArrayList<Card>();
    for (Card c : cards) {
      if (c.isCreature() && (c.isEquipped() || c.isEnchanted())) {
        if (c.isEquipped()) ret.addAll(c.getEquippedBy());
        if (c.isEnchanted()) ret.addAll(c.getEnchantedBy());

        ret.add(c);
      }
    }
    return ret;
  }
Пример #7
0
 public static boolean callCheat(ArrayList<Card> caller) {
   // If the last person cheated
   if (lastPlayerCheated) {
     // gives the person who cheated the card
     lastPlayerHand.addAll(pile);
     pile.clear();
     return true;
   } else {
     // If the last person did not cheat
     // Gives the cards to the caller
     caller.addAll(pile);
     pile.clear();
     return false;
   }
 }
  /**
   * helper: recursively scan given directory.
   *
   * @return list of files found (might be empty)
   */
  private ArrayList<File> scanDirectory(File path) {
    Debug.trace("scanning directory " + path.getAbsolutePath());

    ArrayList<File> scan_result = new ArrayList<File>();

    if (!path.isDirectory()) {
      return scan_result;
    }

    File[] entries = path.listFiles();

    for (File file : entries) {
      if (file == null) {
        continue;
      }

      if (file.isDirectory()) {
        scan_result.addAll(scanDirectory(file));
      } else if ((file.isFile()) && (file.getName().toLowerCase().endsWith(".java"))) {
        scan_result.add(file);
      }
    }

    return scan_result;
  }
 /** Expand the current node and return the list of leaves (MaterialVO objects). */
 private ArrayList getComponents(DefaultMutableTreeNode node) {
   ArrayList list = new ArrayList();
   for (int i = 0; i < node.getChildCount(); i++)
     list.addAll(getComponents((DefaultMutableTreeNode) node.getChildAt(i)));
   if (node.isLeaf()) list.add(node.getUserObject());
   return list;
 }
Пример #10
0
  public Bundle(File dir) throws IOException {
    if (!dir.exists()) {
      throw new IllegalArgumentException(String.format("%s does not exist", dir.getAbsolutePath()));
    }
    if (!dir.canRead()) {
      throw new IllegalArgumentException(String.format("%s cannot be read", dir.getAbsolutePath()));
    }
    if (!dir.isDirectory()) {
      throw new IllegalArgumentException(
          String.format("%s is not a directory", dir.getAbsolutePath()));
    }

    this.dir = dir;

    config = new BundleConfig(new File(dir, "Config.pl"));

    dataFiles = new ArrayList<File>();

    dataFiles.addAll(
        Arrays.asList(
            dir.listFiles(
                new FilenameFilter() {
                  public boolean accept(File dir, String name) {
                    String upper = name.toUpperCase();
                    return (upper.endsWith(".rdf")
                            || upper.endsWith(".owl")
                            || upper.endsWith(".n3")
                            || upper.endsWith(".ttl"))
                        && new File(dir, name).canRead();
                  }
                })));
  }
Пример #11
0
  /**
   * Return top K authorities (result from SALSA), but do not include users in the removeList
   *
   * @param K
   * @param removeList
   * @return
   */
  public ArrayList<SalsaVertex> topAuthorities(int K, HashSet<Integer> removeList) {
    // TODO: faster top-K implementation
    ArrayList<SalsaVertex> all = new ArrayList<SalsaVertex>(authorities.size());
    all.addAll(authorities.values());
    Collections.sort(
        all,
        new Comparator<SalsaVertex>() {
          @Override
          public int compare(SalsaVertex salsaVertex, SalsaVertex salsaVertex1) {
            if (salsaVertex.value < salsaVertex1.value) return 1;
            else return (salsaVertex.value > salsaVertex1.value ? -1 : 0);
          }
        });

    ArrayList<SalsaVertex> result = new ArrayList<SalsaVertex>(K);
    int i = 0;
    while (result.size() < K) {
      if (i < all.size()) {
        SalsaVertex x = all.get(i);
        if (!removeList.contains(x.id)) result.add(x);
      } else {
        break;
      }
      i++;
    }
    return result;
  }
Пример #12
0
  public static void main(String[] args) throws IOException {
    String line = "";
    ArrayList<String> list = new ArrayList<>();
    try (Scanner scanner = new Scanner(System.in);
        BufferedReader reader = new BufferedReader(new FileReader(scanner.nextLine()))) {
      while ((line = reader.readLine()) != null) {
        list.addAll(Arrays.asList(line.split(" ")));
      }

      for (int i = 0; i < list.size(); i++) {
        String s = list.get(i);
        String reverse = new StringBuffer(s).reverse().toString();
        if (list.indexOf(reverse) != -1 & !s.equals("") & !s.equals(reverse)) {
          result.add(new Pair(s, reverse));
          list.remove(s);
          list.remove(reverse);
        }
      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #13
0
 public int totalNQueens(int n) {
   StringBuilder[] board = new StringBuilder[n];
   for (int i = 0; i < n; i++) {
     board[i] = new StringBuilder();
     for (int j = 0; j < n; j++) {
       board[i].append('.');
     }
   }
   for (int i = 0; i < n / 2; i++) {
     board[0].setCharAt(i, 'Q');
     dfs(n, 1, board);
     board[0].setCharAt(i, '.');
   }
   ArrayList<String[]> aux = new ArrayList<String[]>();
   for (String[] k : res) {
     String[] tmp = new String[n];
     for (int i = 0; i < n; i++) {
       StringBuilder sb = new StringBuilder(k[i]).reverse();
       tmp[i] = sb.toString();
     }
     aux.add(tmp);
   }
   res.addAll(aux);
   if (n % 2 != 0) {
     board[0].setCharAt(n / 2, 'Q');
     dfs(n, 1, board);
     board[0].setCharAt(n / 2, '.');
   }
   return res.size();
 }
Пример #14
0
  public void run() throws IOException {
    Scanner in = new Scanner(new File("partitions.in"));
    PrintWriter out = new PrintWriter(new File("partitions.out"));

    int sum = 0;
    while (true) {
      int n = in.nextInt();
      sum += n;
      int k = in.nextInt();
      if (n == 0 && k == 0) {
        break;
      }
      in.nextLine();
      ArrayList<Integer>[] set = new ArrayList[k];
      for (int i = 0; i < k; i++) {
        set[i] = new ArrayList<Integer>();
        String t = in.nextLine();
        Scanner sc = new Scanner(t);
        while (sc.hasNextInt()) {
          int q = 0;
          set[i].add(q = sc.nextInt() - 1);
        }
      }
      ArrayList<Integer> free = new ArrayList<Integer>();
      int keep = 0;
      for (int i = k - 1; i >= 0; i--) {
        ArrayList<Integer> nxt = next(set[i], free);
        if (nxt != null) {
          set[i] = nxt;
          keep = i + 1;
          break;
        } else {
          free.addAll(set[i]);
          Collections.sort(free);
        }
      }
      int newk = keep + free.size();
      out.println(n + " " + newk);
      for (int i = 0; i < keep; i++) {
        for (int j = 0; j < set[i].size(); j++) {
          if (j > 0) {
            out.print(" ");
          }
          out.print(set[i].get(j) + 1);
        }
        out.println();
      }
      Collections.sort(free);
      for (int i = 0; i < free.size(); i++) {
        out.println(free.get(i) + 1);
      }
      out.println();
    }

    assert sum <= 2000;

    in.close();
    out.close();
  }
Пример #15
0
  /** Gets all Genomic Data. */
  private ProfileDataSummary getGenomicData(
      String cancerStudyId,
      HashMap<String, GeneticProfile> defaultGeneticProfileSet,
      SampleList defaultSampleSet,
      String geneListStr,
      ArrayList<SampleList> sampleList,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException, DaoException {

    // parse geneList, written in the OncoPrintSpec language (except for changes by XSS clean)
    double zScore =
        ZScoreUtil.getZScore(
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            request);
    double rppaScore = ZScoreUtil.getRPPAScore(request);

    ParserOutput theOncoPrintSpecParserOutput =
        OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
            geneListStr,
            new HashSet<String>(defaultGeneticProfileSet.keySet()),
            new ArrayList<GeneticProfile>(defaultGeneticProfileSet.values()),
            zScore,
            rppaScore);

    ArrayList<String> geneList = new ArrayList<String>();
    geneList.addAll(theOncoPrintSpecParserOutput.getTheOncoPrintSpecification().listOfGenes());

    ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
    Set<String> warningUnion = new HashSet<String>();

    for (GeneticProfile profile : defaultGeneticProfileSet.values()) {
      try {
        GetProfileData remoteCall =
            new GetProfileData(
                profile, geneList, StringUtils.join(defaultSampleSet.getSampleList(), " "));
        ProfileData pData = remoteCall.getProfileData();
        warningUnion.addAll(remoteCall.getWarnings());
        profileDataList.add(pData);
      } catch (IllegalArgumentException e) {
        e.getStackTrace();
      }
    }

    ProfileMerger merger = new ProfileMerger(profileDataList);
    ProfileData mergedProfile = merger.getMergedProfile();

    ProfileDataSummary dataSummary =
        new ProfileDataSummary(
            mergedProfile,
            theOncoPrintSpecParserOutput.getTheOncoPrintSpecification(),
            zScore,
            rppaScore);
    return dataSummary;
  }
Пример #16
0
 /**
  * getEnchantedLands.
  *
  * @param cards a {@link java.util.ArrayList} object.
  * @return a {@link java.util.ArrayList} object.
  */
 public static ArrayList<Card> getEnchantedLands(ArrayList<Card> cards) {
   ArrayList<Card> ret = new ArrayList<Card>();
   for (Card c : cards) {
     if (c.isLand() && c.isEnchanted()) {
       ret.addAll(c.getEnchantedBy());
       ret.add(c);
     }
   }
   return ret;
 }
Пример #17
0
 private static Field[] getAllFields(Class cls) {
   ArrayList<Field> res = new ArrayList<>();
   Class c = cls;
   while (c != View.class) {
     assert Utils.check(c != null);
     res.addAll(Arrays.asList(c.getDeclaredFields()));
     c = c.getSuperclass();
   }
   return res.toArray(new Field[res.size()]);
 }
Пример #18
0
  /*
   * Convert an array of signers into an array of concatenated certificate
   * arrays.
   */
  private static java.security.cert.Certificate[] mapSignersToCertArray(CodeSigner[] signers) {

    if (signers != null) {
      ArrayList certChains = new ArrayList();
      for (int i = 0; i < signers.length; i++) {
        certChains.addAll(signers[i].getSignerCertPath().getCertificates());
      }

      // Convert into a Certificate[]
      return (java.security.cert.Certificate[])
          certChains.toArray(new java.security.cert.Certificate[certChains.size()]);
    }
    return null;
  }
 @NotNull
 public static List<File> findFilesByMask(@NotNull Pattern pattern, @NotNull File dir) {
   final ArrayList<File> found = new ArrayList<File>();
   final File[] files = dir.listFiles();
   if (files != null) {
     for (File file : files) {
       if (file.isDirectory()) {
         found.addAll(findFilesByMask(pattern, file));
       } else if (pattern.matcher(file.getName()).matches()) {
         found.add(file);
       }
     }
   }
   return found;
 }
  /**
   * Returns the <code>Format.Field</code> constants associated with the text at <code>offset</code>
   * . If <code>offset</code> is not a valid location into the current text, this will return an
   * empty array.
   *
   * @param offset offset into text to be examined
   * @return Format.Field constants associated with the text at the given position.
   */
  public Format.Field[] getFields(int offset) {
    if (getAllowsInvalid()) {
      // This will work if the currently edited value is valid.
      updateMask();
    }

    Map attrs = getAttributes(offset);

    if (attrs != null && attrs.size() > 0) {
      ArrayList al = new ArrayList();

      al.addAll(attrs.keySet());
      return (Format.Field[]) al.toArray(EMPTY_FIELD_ARRAY);
    }
    return EMPTY_FIELD_ARRAY;
  }
Пример #21
0
  public void processInput() {

    ClassLoader classLoader = getClass().getClassLoader();
    File englishStopWords =
        new File(classLoader.getResource("DEFAULT_ENGLISH_STOP_WORDS").getFile());

    processedInput = new ArrayList<String>();
    lemmatizedInput = new ArrayList<String>();

    // tokenize and stop word removal operations

    initStopWordList(englishStopWords);

    CharArraySet stopwords = new CharArraySet(stopWordPool, true);
    StandardAnalyzer analyzer = new StandardAnalyzer(stopwords);
    TokenStream stream;
    try {
      stream = analyzer.tokenStream(null, new StringReader(input));
      CharTermAttribute cattr = stream.addAttribute(CharTermAttribute.class);
      stream.reset();
      while (stream.incrementToken()) {
        if (!processedInput.contains(cattr.toString())) processedInput.add(cattr.toString());
      }
      stream.end();
      stream.close();

      // System.out.println("In input processing " + "      "
      // + processedInput);
      setProcessedInput(processedInput);

      // for lemmatization concatinate input strings and send to Standford
      // NLP processor

      for (int i = 0; i < processedInput.size(); i++) {
        lemmatizedInput.addAll(new StanfordLemmatizer().lemmatize(processedInput.get(i)));
      }

      // System.out.println("In input processing " + "      "
      // + lemmatizedInput);

      setLemmatizedInput(lemmatizedInput);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Пример #22
0
    public List<NavigationTile> navTilesVisible(
        DrawContext dc, double minDistSquared, double maxDistSquared) {
      ArrayList<NavigationTile> navList = new ArrayList<NavigationTile>();
      if (this.isNavSectorVisible(dc, minDistSquared, maxDistSquared)) {
        if (this.level > 0 && !this.hasSubTiles()) this.buildSubNavTiles();

        if (this.hasSubTiles()) {
          for (NavigationTile nav : subNavTiles) {
            navList.addAll(nav.navTilesVisible(dc, minDistSquared, maxDistSquared));
          }
        } else // at bottom level navigation tile
        {
          navList.add(this);
        }
      }

      return navList;
    }
Пример #23
0
 static public ArrayList<File> findFilesInFolder(File folder, String extension,
                                                 boolean recurse) {
   ArrayList<File> files = new ArrayList<File>();
   
   if (folder.listFiles() == null) return files;
   
   for (File file : folder.listFiles()) {
     if (file.getName().startsWith(".")) continue; // skip hidden files
     
     if (file.getName().endsWith("." + extension))
       files.add(file);
       
     if (recurse && file.isDirectory()) {
       files.addAll(findFilesInFolder(file, extension, true));
     }
   }
   
   return files;
 }
Пример #24
0
 private static void solve1(Scanner sc, PrintWriter pw) {
   ArrayList<Long> list = new ArrayList<Long>();
   int n = sc.nextInt();
   int[] a = new int[n];
   for (int i = 0; i < n; i++) {
     a[i] = sc.nextInt();
   }
   for (int i = 0; i < n; i++) {
     ArrayList<Long> ret = findPrimes(a[i]);
     if (ret.size() > 0) {
       list.addAll(ret);
     }
   }
   if (list.size() < 2) {
     pw.println(-1);
   } else {
     Collections.sort(list);
     pw.println((long) list.get(0) * list.get(1));
   }
 }
  /**
   * Validate the response is in expected yaml format
   *
   * @param response response
   * @return Collection of job data maps if format is correct and there is no error
   * @throws com.dtolabs.client.services.CentralDispatcherServerRequestException if the format is
   *     incorrect, or the response indicates an error response.
   */
  private Collection<Map> validateJobsResponseYAML(final WebserviceResponse response)
      throws CentralDispatcherServerRequestException {
    if (null == response) {
      throw new CentralDispatcherServerRequestException("Response was null");
    }

    if (null != response.getResponseMessage()) {
      logger.info("Response: " + response.getResponseMessage());
    }
    String resultContentType = response.getResultContentType();
    if (resultContentType.contains(";")) {
      resultContentType = resultContentType.substring(0, resultContentType.indexOf(";"));
    }
    if (!resultContentType.endsWith("/yaml")) {
      throw new CentralDispatcherServerRequestException(
          "Expected YAML response, unexpected content type: " + response.getResultContentType());
    }
    final ArrayList<Map> dataset = new ArrayList<Map>();
    final Object resobj;
    try {
      final Yaml yaml = new Yaml(new SafeConstructor());
      resobj = yaml.load(response.getResults());
    } catch (YAMLException e) {
      throw new CentralDispatcherServerRequestException(
          "Failed to parse YAML: " + e.getMessage(), e);
    }
    if (resobj instanceof Collection) {
      dataset.addAll((Collection) resobj);
    } else {
      throw new CentralDispatcherServerRequestException(
          "Response had unexpected content type: " + resobj);
    }

    for (final Map map : dataset) {
      if (!map.containsKey("name") || !map.containsKey("id") && !map.containsKey("uuid")) {
        throw new CentralDispatcherServerRequestException(
            "Response had unexpected dataset: " + resobj);
      }
    }
    return dataset;
  }
Пример #26
0
  @Override
  protected void doRender(DrawContext dc) {
    this.referencePoint = this.computeReferencePoint(dc);

    int serviceCount = this.placeNameServiceSet.getServiceCount();
    for (int i = 0; i < serviceCount; i++) {
      PlaceNameService placeNameService = this.placeNameServiceSet.getService(i);
      if (!isServiceVisible(dc, placeNameService)) continue;

      double minDistSquared =
          placeNameService.getMinDisplayDistance() * placeNameService.getMinDisplayDistance();
      double maxDistSquared =
          placeNameService.getMaxDisplayDistance() * placeNameService.getMaxDisplayDistance();

      if (isSectorVisible(
          dc, placeNameService.getMaskingSector(), minDistSquared, maxDistSquared)) {
        ArrayList<Tile> baseTiles = new ArrayList<Tile>();
        NavigationTile navTile = this.navTiles.get(i);
        // drill down into tiles to find bottom level navTiles visible
        List<NavigationTile> list = navTile.navTilesVisible(dc, minDistSquared, maxDistSquared);
        for (NavigationTile nt : list) {
          baseTiles.addAll(nt.getTiles());
        }

        for (Tile tile : baseTiles) {
          try {
            drawOrRequestTile(dc, tile, minDistSquared, maxDistSquared);
          } catch (Exception e) {
            Logging.logger()
                .log(
                    Level.FINE,
                    Logging.getMessage("layers.PlaceNameLayer.ExceptionRenderingTile"),
                    e);
          }
        }
      }
    }

    this.sendRequests();
    this.requestQ.clear();
  }
Пример #27
0
  @SuppressWarnings("static-access")
  @Override
  public EventSet createEventSet(Document doc) {
    EventSet es = new EventSet(doc.getAuthor());
    char[] text = doc.getProcessedText();
    String stringText = new String(text);

    // use MaxentPOSTagsEventDriver's tagger
    // initialize tagger and return empty event set if encountered a problem
    if (tagger == null) {
      tagger = MaxentPOSTagsEventDriver.initTagger();
      if (tagger == null) return es;
    }

    List<List<HasWord>> sentences =
        tagger.tokenizeText(new BufferedReader(new StringReader(stringText)));
    ArrayList<TaggedWord> tagged = new ArrayList<TaggedWord>();
    for (List<HasWord> sentence : sentences) tagged.addAll(tagger.tagSentence(sentence));

    int i, j, n;
    try {
      n = Integer.parseInt(getParameter("N"));
    } catch (NumberFormatException e) {
      n = 2;
    }
    String curr;
    for (i = 0; i < tagged.size() - n + 1; i++) {
      curr = "(" + tagged.get(i).tag() + ")";
      for (j = 1; j < n; j++) {
        curr += "-(" + tagged.get(i + j).tag() + ")";
      }
      es.addEvent(new Event(curr));
    }

    sentences.clear();
    sentences = null;
    return es;
  }
  /**
   * Check if components required by specified products are available.
   *
   * @param products list of ProdOrderProductVO objects
   * @params compAltComps collection of <component item code,HashSet of alternative component item
   *     codes>; filled by this method (and given back by reference)
   * @return VOListResponse of ProdOrderComponentVO objects
   */
  public final Response checkComponentsAvailability(
      Connection conn,
      Hashtable compAltComps,
      ArrayList products,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
    try {

      // retrieve internationalization settings (Resources object)...
      ServerResourcesFactory factory =
          (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
      Resources resources = factory.getResources(userSessionPars.getLanguageId());

      if (products.size() == 0) {
        return new VOListResponse(new ArrayList(), false, 0);
      }

      // fill in comps hashtable with the collection of required components...
      ItemPK pk = null;
      ProdOrderProductVO prodVO = null;
      ArrayList components = null;
      MaterialVO compVO = null;
      Response res = null;
      ProdOrderComponentVO componentVO = null;
      Hashtable comps =
          new Hashtable(); // collection of <component item code,ProdOrderComponentVO object>
      for (int i = 0; i < products.size(); i++) {
        // retrieve bill of materials for each product...
        prodVO = (ProdOrderProductVO) products.get(i);
        pk = new ItemPK(prodVO.getCompanyCodeSys01DOC23(), prodVO.getItemCodeItm01DOC23());
        res =
            bean.getBillOfMaterials(
                conn, pk, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          return res;
        }

        // extract components only (leaf nodes)...
        components =
            getComponents(
                (DefaultMutableTreeNode) ((TreeModel) ((VOResponse) res).getVo()).getRoot());
        for (int j = 0; j < components.size(); j++) {
          compVO = (MaterialVO) components.get(j);
          componentVO = (ProdOrderComponentVO) comps.get(compVO.getItemCodeItm01ITM03());
          if (componentVO == null) {
            componentVO = new ProdOrderComponentVO();
            comps.put(compVO.getItemCodeItm01ITM03(), componentVO);
            componentVO.setAvailableQty(new BigDecimal(0));
            componentVO.setCompanyCodeSys01DOC24(compVO.getCompanyCodeSys01ITM03());
            componentVO.setDescriptionSYS10(compVO.getDescriptionSYS10());
            componentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
            componentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
            componentVO.setItemCodeItm01DOC24(compVO.getItemCodeItm01ITM03());
            componentVO.setMinSellingQtyUmCodeReg02ITM01(compVO.getMinSellingQtyUmCodeReg02ITM01());
            componentVO.setQtyDOC24(new BigDecimal(0));
          }
          componentVO.setQtyDOC24(
              componentVO.getQtyDOC24().add(compVO.getQtyITM03().multiply(prodVO.getQtyDOC23())));
        }
      }

      // check components availability in the specified warehouse...
      Enumeration en = comps.keys();
      GridParams gridParams = new GridParams();
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.COMPANY_CODE_SYS01, prodVO.getCompanyCodeSys01DOC23());
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.WAREHOUSE_CODE, prodVO.getWarehouseCodeWar01DOC22());
      gridParams.getOtherGridParams().put(ApplicationConsts.LOAD_ALL, Boolean.TRUE);
      ItemAvailabilityVO availVO = null;
      BigDecimal availability, altAvailability, delta;
      String itemCode = null;
      ArrayList list, availList;
      AltComponentVO altVO = null;
      ArrayList alternativeComps = new ArrayList();
      ArrayList compsToRemove = new ArrayList();
      ProdOrderComponentVO altComponentVO = null;
      HashSet altCodes = null; // list of alternative component item codes...
      BigDecimal altQty = null;
      while (en.hasMoreElements()) {
        itemCode = en.nextElement().toString();
        componentVO = (ProdOrderComponentVO) comps.get(itemCode);

        gridParams
            .getOtherGridParams()
            .put(
                ApplicationConsts.ITEM_PK, new ItemPK(prodVO.getCompanyCodeSys01DOC23(), itemCode));
        res =
            avail.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (res.isError()) return res;

        availList = ((VOListResponse) res).getRows();
        componentVO.setAvailabilities(availList);
        availability = new BigDecimal(0);
        for (int i = 0; i < availList.size(); i++) {
          availVO = (ItemAvailabilityVO) availList.get(i);
          availability = availability.add(availVO.getAvailableQtyWAR03());
        }
        componentVO.setAvailableQty(availability);

        if (componentVO.getQtyDOC24().doubleValue() > componentVO.getAvailableQty().doubleValue()) {
          // check if there exist some alternative component...
          res =
              altComps.executeCommand(
                  gridParams, userSessionPars, request, response, userSession, context);
          if (res.isError()) return res;
          list = ((VOListResponse) res).getRows();
          for (int i = 0; i < list.size(); i++) {
            altVO = (AltComponentVO) list.get(i);
            gridParams
                .getOtherGridParams()
                .put(
                    ApplicationConsts.ITEM_PK,
                    new ItemPK(prodVO.getCompanyCodeSys01DOC23(), altVO.getItemCodeItm01ITM04()));
            res =
                avail.executeCommand(
                    gridParams, userSessionPars, request, response, userSession, context);
            if (res.isError()) return res;
            availList = ((VOListResponse) res).getRows();
            altAvailability = new BigDecimal(0);
            for (int j = 0; j < availList.size(); j++) {
              availVO = (ItemAvailabilityVO) availList.get(j);
              altAvailability = altAvailability.add(availVO.getAvailableQtyWAR03());
            }
            if (altAvailability.doubleValue() > 0) {
              altComponentVO = new ProdOrderComponentVO();
              altComponentVO.setAvailabilities(availList);
              altComponentVO.setAvailableQty(altAvailability);
              altComponentVO.setCompanyCodeSys01DOC24(altVO.getCompanyCodeSys01ITM04());
              altComponentVO.setDescriptionSYS10(altVO.getDescriptionSYS10());
              altComponentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
              altComponentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
              altComponentVO.setItemCodeItm01DOC24(altVO.getItemCodeItm01ITM04());
              altComponentVO.setMinSellingQtyUmCodeReg02ITM01(
                  altVO.getMinSellingQtyUmCodeReg02ITM01());
              altQty =
                  conv.convertQty(
                      altVO.getMinSellingQtyUmCodeReg02ITM01(),
                      componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                      altAvailability,
                      userSessionPars,
                      request,
                      response,
                      userSession,
                      context);
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue()
                  > altQty.doubleValue()) {
                delta = altQty;
                altComponentVO.setQtyDOC24(altAvailability);
              } else {
                delta = componentVO.getQtyDOC24();
                altComponentVO.setQtyDOC24(
                    conv.convertQty(
                        componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                        altVO.getMinSellingQtyUmCodeReg02ITM01(),
                        delta,
                        userSessionPars,
                        request,
                        response,
                        userSession,
                        context));
              }
              componentVO.setQtyDOC24(componentVO.getQtyDOC24().subtract(delta));
              alternativeComps.add(altComponentVO);

              altCodes = (HashSet) compAltComps.get(itemCode);
              if (altCodes == null) {
                altCodes = new HashSet();
                compAltComps.put(itemCode, altCodes);
              }
              altCodes.add(altVO.getItemCodeItm01ITM04());

              if (componentVO.getQtyDOC24().doubleValue() == 0) {
                compsToRemove.add(componentVO);
                break;
              }
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue() == 0) break;
            }
          }
        }
      }

      list = new ArrayList(comps.values());
      list.addAll(alternativeComps);
      list.removeAll(compsToRemove);
      return new VOListResponse(list, false, list.size());
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "checkComponentsAvailability",
          "Error while retrieving components availability for the specified production order",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
Пример #29
0
  public void service(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    Connection con = null;

    String bnm[] = req.getParameterValues("Comics");

    String qty[] = new String[bnm.length];
    ArrayList al1 = new ArrayList();
    ArrayList al2 = new ArrayList();
    for (int i = 0; i < bnm.length; i++) {
      qty[i] = req.getParameter(bnm[i]);
      al1.add(bnm[i]);
      al2.add(qty[i]);
    }

    HttpSession HSession = req.getSession(true);

    ArrayList alo1 = (ArrayList) HSession.getValue("bNames");
    ArrayList alo2 = (ArrayList) HSession.getValue("bQty");

    al1.addAll(alo1);
    al2.addAll(alo2);

    HSession.putValue("bNames", al1);
    HSession.putValue("bQty", al2);

    out.println("<html>");
    out.println("<title>Categories..</title>");
    out.println("<body bgcolor=gold >");

    out.println("<b><font face=\"Papyrus\" size=36 color= #806F7E><center>");
    out.println("<big>Category</big></center>");

    out.println("<ul type=disc>");
    out.println("<font face=\"Maiandra GD\" color=black size=4>");
    out.println("<li type=square>Choose your category..");
    out.println("</li></font><br>");

    out.println(
        "<A href=\"FictionClick\"><font face=\"Mistral\" size=8 color=#208234><b>Fiction</b></A><br>");

    out.println(
        "<A href=\"NonFictionClick\"><font face=\"Mistral\" size=8 color=#208234><b>Non-Fiction</b></A><br>");

    out.println(
        "<A href=\"AutobiographyClick\"><font face=\"Mistral\" size=8 color=#208234><b>Autobiography</b></A><br>");

    out.println(
        "<A href=\"HistoryClick\"><font face=\"Mistral\" size=8 color=#208234><b>History</b></A><br>");

    out.println(
        "<A href=\"ComicsClick\"><font face=\"Mistral\" size=8 color=#208234><b>Comics</b></A></font><br><br>");

    out.println("<center><form action=\"http://localhost:8080/servlet/FinalList\">");
    out.println("<input type=submit value=\" Finalize List >>\"></form>");

    out.println("<font face=\"Maiandra GD\" color=black size=4>");
    out.println("Moves to final List..</center>");

    out.println("</font></body>");
    out.println("</html>");
  } // service
  public static void main(String[] args) throws Exception {
    int V, E, s, u, v, w;

    /* // Graph in Figure 4.17
    5 7 2
    2 1 2
    2 3 7
    2 0 6
    1 3 3
    1 4 6
    3 4 5
    0 4 1
        */

    Scanner sc = new Scanner(System.in);
    V = sc.nextInt();
    E = sc.nextInt();
    s = sc.nextInt();

    AdjList.clear();
    for (int i = 0; i < V; i++) {
      ArrayList<IntegerPair> Neighbor = new ArrayList<IntegerPair>();
      AdjList.add(Neighbor); // add neighbor list to Adjacency List
    }

    for (int i = 0; i < E; i++) {
      u = sc.nextInt();
      v = sc.nextInt();
      w = sc.nextInt();
      AdjList.get(u).add(new IntegerPair(v, w)); // first time using weight
    }

    // Dijkstra routine
    ArrayList<Integer> dist = new ArrayList<>();
    // INF = 1*10^9 not MAX_INT to avoid overflow
    dist.addAll(Collections.nCopies(V, INF));
    dist.set(s, 0);
    PriorityQueue<IntegerPair> pq =
        new PriorityQueue<IntegerPair>(
            1,
            new Comparator<IntegerPair>() { // overriding the compare method
              public int compare(IntegerPair i, IntegerPair j) {
                return i.dfs - j.dfs;
              }
            });
    pq.offer(new IntegerPair(s, 0)); // sort based on increasing distance

    while (!pq.isEmpty()) { // main loop
      IntegerPair top = pq.poll(); // greedy: pick shortest unvisited vertex
      int d = top.dfs;
      u = top.vn;
      if (d > dist.get(u)) continue; // We want to process vertex u only once!
      Iterator it = AdjList.get(u).iterator();
      while (it.hasNext()) { // all outgoing edges from u
        IntegerPair p = (IntegerPair) it.next();
        v = p.vn;
        int weight_u_v = p.dfs;
        if (dist.get(u) + weight_u_v < dist.get(v)) { // if can relax
          // (note: Record SP spanning tree here if needed. This is similar)
          dist.set(v, dist.get(u) + weight_u_v); // relax
          pq.offer(new IntegerPair(v, dist.get(v))); //   (as printpath in BFS)
          // enqueue this neighbor regardless whether it is already in pq or not
        }
      }
    }

    for (int i = 0; i < V; i++) // index + 1 for final answer
    System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i));
  }