/**
   * @param definitions
   * @return
   */
  private static FontDefinition[] addDefaulted(FontDefinition[] definitions) {
    IThemeRegistry registry = WorkbenchPlugin.getDefault().getThemeRegistry();
    FontDefinition[] allDefs = registry.getFonts();

    SortedSet set = addDefaulted(definitions, allDefs);
    return (FontDefinition[]) set.toArray(new FontDefinition[set.size()]);
  }
示例#2
0
  public void ImprimirColeccion() {
    int i;
    Usuario registro;

    /*
     * Se define un arreglo de tipo Object (la clase genérica Java)
     */
    Object[] arreglo;

    /*
     * Se convierte la colección pasada como parámetro a un array, que
     * es asignado al arreglo de tipo Object
     */
    arreglo = UsuariosRegistrados.toArray();

    System.out.println("DATOS");

    /*
     * Se hace un recorrido del arreglo de tipo Object y se imprime
     * la información de la casilla i
     */
    for (i = 0; i < arreglo.length; i++) {
      registro = (Usuario) arreglo[i];
      System.out.println("Nick: " + registro.getNickname());
      System.out.println("Clave: " + registro.getClave());
      System.out.println("Nombre" + registro.getNombre());
      System.out.println();
    }

    System.out.println("\n\n");
  }
示例#3
0
 static {
   try {
     MessageGenerator messageGenerator = new MessageGenerator();
     SortedSet sortingSet =
         new TreeSet(
             new Comparator() {
               public int compare(Object a, Object b) {
                 try {
                   Message message1 = (Message) a;
                   Message message2 = (Message) b;
                   int dateDelta = message1.getSentDate().compareTo(message2.getSentDate());
                   if (dateDelta != 0) {
                     return dateDelta;
                   }
                   return message1.toString().compareTo(message2.toString());
                 } catch (MessagingException ex) {
                   throw new RuntimeException(ex);
                 }
               }
             });
     for (int i = 0; i < MESSAGE_COUNT; ++i) {
       sortingSet.add(messageGenerator.generateMessage());
     }
     INBOX_MESSAGES = (Message[]) sortingSet.toArray(new Message[sortingSet.size()]);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
 }
示例#4
0
 public String[] findResources(String rootPackageName, ResourceFilter resourceFilter) {
   SortedSet<String> resources = new TreeSet<String>();
   for (ClassPath classPath : classPaths) {
     resources.addAll(asList(classPath.findResources(rootPackageName, resourceFilter)));
   }
   return (String[]) resources.toArray(new String[resources.size()]);
 }
示例#5
0
 public String[] listResources(String packageName) {
   SortedSet<String> resources = new TreeSet<String>();
   for (ClassPath classPath : classPaths) {
     resources.addAll(asList(classPath.listResources(packageName)));
   }
   return (String[]) resources.toArray(new String[resources.size()]);
 }
 public LineString nextLineString(final Envelope envelope) {
   final int n = getNumberOfNodesPerLine();
   final SortedSet<Coordinate> nodes = new TreeSet<Coordinate>();
   while (n > nodes.size()) {
     nodes.add(nextCoordinate(envelope));
   }
   return gf.createLineString(nodes.toArray(new Coordinate[0]));
 }
  @Override
  public void refresh() {
    super.refresh(); // update text field suggestions

    if (input != null) {
      SortedSet<String> names = new TreeSet<String>(input.toPropertyList());
      attribute.setItems(names.toArray(new String[names.size()]));
    }
  }
示例#8
0
 public static ImmutableSortedSet copyOfSorted(SortedSet paramSortedSet)
 {
   Comparator localComparator = SortedIterables.comparator(paramSortedSet);
   Object[] arrayOfObject = paramSortedSet.toArray();
   if (arrayOfObject.length == 0) {
     return emptySet(localComparator);
   }
   return new RegularImmutableSortedSet(ImmutableList.asImmutableList(arrayOfObject), localComparator);
 }
  public String[] listSubRegionPaths(boolean recursive) {
    SortedSet<String> subregionPaths = new TreeSet<String>();
    Set<Region<?, ?>> subregions = region.subregions(recursive);

    for (Region<?, ?> region : subregions) {
      subregionPaths.add(region.getFullPath());
    }
    return subregionPaths.toArray(new String[subregionPaths.size()]);
  }
 @Override
 public void refresh() {
   super.refresh();
   if (input != null) {
     // Set attribute options
     final SortedSet<String> names = new TreeSet<String>(input.toPropertyList());
     attribute.setItems(names.toArray(new String[names.size()]));
   }
 }
示例#11
0
 @OslcDescription(
     "The expected resource type URI of the resource that will be created using this creation factory. These would be the URIs found in the result resource's rdf:type property")
 @OslcName("resourceType")
 @OslcPropertyDefinition(OslcConstants.OSLC_CORE_NAMESPACE + "resourceType")
 @OslcReadOnly
 @OslcTitle("Resource Types")
 public URI[] getResourceTypes() {
   return resourceTypes.toArray(new URI[resourceTypes.size()]);
 }
  /**
   * Return the definitions that should have their default preference value set but nothing else.
   *
   * @param definitions the definitions that will be fully handled
   * @return the remaining definitions that should be defaulted
   */
  private static FontDefinition[] getDefaults(FontDefinition[] definitions) {
    IThemeRegistry registry = WorkbenchPlugin.getDefault().getThemeRegistry();
    FontDefinition[] allDefs = registry.getFonts();

    SortedSet set = new TreeSet(IThemeRegistry.ID_COMPARATOR);
    set.addAll(Arrays.asList(allDefs));
    set.removeAll(Arrays.asList(definitions));
    return (FontDefinition[]) set.toArray(new FontDefinition[set.size()]);
  }
示例#13
0
 @OslcDescription(
     "An identifier URI for the domain specified usage of this creation factory. If a service provides multiple creation factories, it may designate the primary or default one that should be used with a property value of http://open-services.net/ns/core#default")
 @OslcName("usage")
 @OslcPropertyDefinition(OslcConstants.OSLC_CORE_NAMESPACE + "usage")
 @OslcReadOnly
 @OslcTitle("Usages")
 public URI[] getUsages() {
   return usages.toArray(new URI[usages.size()]);
 }
示例#14
0
 @OslcDescription(
     "A creation factory may provide resource shapes that describe shapes of resources that may be created")
 @OslcName("resourceShape")
 @OslcPropertyDefinition(OslcConstants.OSLC_CORE_NAMESPACE + "resourceShape")
 @OslcRange(OslcConstants.TYPE_RESOURCE_SHAPE)
 @OslcReadOnly
 @OslcTitle("Resource Shapes")
 @OslcValueShape(OslcConstants.PATH_RESOURCE_SHAPES + "/" + OslcConstants.PATH_RESOURCE_SHAPE)
 public URI[] getResourceShapes() {
   return resourceShapes.toArray(new URI[resourceShapes.size()]);
 }
 public Item[] getAllConclusionItems() {
   SortedSet<Item> conclusions = new TreeSet<Item>();
   for (AssociationRule rule : this) {
     Iterator<Item> i = rule.getConclusionItems();
     while (i.hasNext()) {
       conclusions.add(i.next());
     }
   }
   Item[] itemArray = new Item[conclusions.size()];
   conclusions.toArray(itemArray);
   return itemArray;
 }
示例#16
0
  /**
   * Returns all supported sample rates.
   *
   * @return an array of sample rates, in Hertz, never <code>null</code>.
   */
  public Integer[] getSampleRates() {
    final String rawValue = this.properties.get(DEVICE_SAMPLERATES);
    final String[] values = rawValue.split(",\\s*");
    final SortedSet<Integer> result =
        new TreeSet<Integer>(
            NumberUtils.<Integer>createNumberComparator(false /* aSortAscending */));
    for (String value : values) {
      result.add(Integer.valueOf(value.trim()));
    }

    return result.toArray(new Integer[result.size()]);
  }
示例#17
0
 protected void populateNonSelectableAssertionIndexes() {
   getAssertionsTable().setSelectable(true);
   SortedSet<AssertionListEntry> assertionsList =
       getCategoriesAssertionsMap().get(getSelectedCategory());
   List<Integer> assertionsIndexList = new ArrayList<Integer>();
   for (int i = 0; i < assertionsList.size(); i++) {
     AssertionListEntry assertionListEntry = (AssertionListEntry) assertionsList.toArray()[i];
     if (!isAssertionApplicable(assertionListEntry.getTypeId())) {
       assertionsIndexList.add(i);
     }
   }
   getAssertionsTable().setNonSelectableIndexes(assertionsIndexList);
 }
  protected void initBindingMetadata() {
    final XmlListBinding annotation = property().definition().getAnnotation(XmlListBinding.class);
    final XmlNamespaceResolver xmlNamespaceResolver =
        ((XmlResource) property().element().resource()).getXmlNamespaceResolver();

    final SortedSet<ElementType> possible = this.possibleTypesService.types();
    this.modelElementTypes = possible.toArray(new ElementType[possible.size()]);

    if (annotation == null) {
      this.path = new XmlPath(property().name(), xmlNamespaceResolver);

      this.xmlElementNames = new QName[this.modelElementTypes.length];

      for (int i = 0; i < this.modelElementTypes.length; i++) {
        this.xmlElementNames[i] =
            createDefaultElementName(this.modelElementTypes[i], xmlNamespaceResolver);
      }
    } else {
      if (annotation.path().length() > 0) {
        this.path = new XmlPath(annotation.path(), xmlNamespaceResolver);
      }

      final XmlListBinding.Mapping[] mappings = annotation.mappings();
      this.xmlElementNames = new QName[this.modelElementTypes.length];

      for (int i = 0; i < this.modelElementTypes.length; i++) {
        final ElementType type = this.modelElementTypes[i];

        for (XmlListBinding.Mapping mapping : mappings) {
          if (mapping.type() == type.getModelElementClass()) {
            final String mappingElementName = mapping.element().trim();

            if (mappingElementName.length() == 0) {
              throw new RuntimeException(mustSpecifyElementNameMsg.text());
            }

            this.xmlElementNames[i] = createQualifiedName(mappingElementName, xmlNamespaceResolver);

            break;
          }
        }

        if (this.xmlElementNames[i] == null) {
          this.xmlElementNames[i] = createDefaultElementName(type, xmlNamespaceResolver);
        }
      }
    }
  }
示例#19
0
 protected String printMock(List<ServerAndLoad> balancedCluster) {
   SortedSet<ServerAndLoad> sorted = new TreeSet<ServerAndLoad>(balancedCluster);
   ServerAndLoad[] arr = sorted.toArray(new ServerAndLoad[sorted.size()]);
   StringBuilder sb = new StringBuilder(sorted.size() * 4 + 4);
   sb.append("{ ");
   for (int i = 0; i < arr.length; i++) {
     if (i != 0) {
       sb.append(" , ");
     }
     sb.append(arr[i].getServerName().getHostname());
     sb.append(":");
     sb.append(arr[i].getLoad());
   }
   sb.append(" }");
   return sb.toString();
 }
示例#20
0
 protected void populateSelectableCategoriesIndexes() {
   getCategoriesListTable().setSelectable(true);
   List<Integer> categoriesIndexList = new ArrayList<Integer>();
   Set<String> ctgs = getCategoriesAssertionsMap().keySet();
   for (int j = 0; j < ctgs.size(); j++) {
     String selCat = (String) ctgs.toArray()[j];
     SortedSet<AssertionListEntry> assertionsList = getCategoriesAssertionsMap().get(selCat);
     for (int i = 0; i < assertionsList.size(); i++) {
       AssertionListEntry assertionListEntry = (AssertionListEntry) assertionsList.toArray()[i];
       if (isAssertionApplicable(assertionListEntry.getTypeId())) {
         categoriesIndexList.add(j);
         break;
       }
     }
   }
   getCategoriesListTable().setSelectableIndexes(categoriesIndexList);
 }
示例#21
0
  @Test
  public void canGetAllKeysAsSortedSet() {
    Map<String, String> map = new HashMap<>();

    map.put("key2", "value2");
    map.put("key1", "value1");
    map.put("key3", "value3");

    SortedSet<String> keys = new TreeSet<String>(map.keySet());

    String[] keysa = new String[keys.size()];
    keys.toArray(keysa);

    assertEquals("key1", keysa[0]);
    assertEquals("key2", keysa[1]);
    assertEquals("key3", keysa[2]);
  }
  /**
   * Creates the description pool from the provided set of string descriptions and phone prefix map.
   */
  private void createDescriptionPool(
      SortedSet<String> descriptionsSet, SortedMap<Integer, String> phonePrefixMap) {
    descIndexSizeInBytes = getOptimalNumberOfBytesForValue(descriptionsSet.size() - 1);
    descriptionIndexes = ByteBuffer.allocate(numOfEntries * descIndexSizeInBytes);
    descriptionPool = new String[descriptionsSet.size()];
    descriptionsSet.toArray(descriptionPool);

    // Map the phone number prefixes to the descriptions.
    int index = 0;
    for (int i = 0; i < numOfEntries; i++) {
      int prefix = readWordFromBuffer(phoneNumberPrefixes, prefixSizeInBytes, i);
      String description = phonePrefixMap.get(prefix);
      int positionInDescriptionPool = Arrays.binarySearch(descriptionPool, description);
      storeWordInBuffer(descriptionIndexes, descIndexSizeInBytes, index, positionInDescriptionPool);
      ++index;
    }
  }
  private static boolean isEquiDistance(SortedSet<Double> set) {
    final double min = set.first();
    final double max = set.last();
    final double diff = (max - min) / (set.size() - 1);
    final double diff100000 = diff / 100000;
    final double maxDiff = diff + diff100000;
    final double minDiff = diff - diff100000;

    final Double[] values = set.toArray(new Double[set.size()]);
    for (int i = 1; i < values.length; i++) {
      final double currentDiff = values[i] - values[i - 1];
      if (currentDiff > maxDiff || currentDiff < minDiff) {
        return false;
      }
    }
    return true;
  }
  /** Moves a temporary file to a final log filename and enrolls it. */
  private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
    long t = System.currentTimeMillis();

    // Require each entry to have a unique timestamp; if there are entries
    // >10sec in the future (due to clock skew), drag them back to avoid
    // keeping them around forever.

    SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
    EntryFile[] future = null;
    if (!tail.isEmpty()) {
      future = tail.toArray(new EntryFile[tail.size()]);
      tail.clear(); // Remove from mAllFiles
    }

    if (!mAllFiles.contents.isEmpty()) {
      t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
    }

    if (future != null) {
      for (EntryFile late : future) {
        mAllFiles.blocks -= late.blocks;
        FileList tagFiles = mFilesByTag.get(late.tag);
        if (tagFiles != null && tagFiles.contents.remove(late)) {
          tagFiles.blocks -= late.blocks;
        }
        if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
          enrollEntry(new EntryFile(late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
        } else {
          enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
        }
      }
    }

    if (temp == null) {
      enrollEntry(new EntryFile(mDropBoxDir, tag, t));
    } else {
      enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
    }
    return t;
  }
示例#25
0
  public void testSortedSet(final SortedSet<TestMonitorable> s) {
    Debug.testStart("Active Sorted Set: " + s.getClass().getSimpleName());

    final int COUNT = 10000;

    final TestMonitorable[] mons = new TestMonitorable[COUNT];

    final Random rand = new Random();

    for (int i = 0; i < COUNT; i++) mons[i] = new TestMonitorable(rand.nextInt());

    for (final TestMonitorable m : mons) s.add(m);

    final long startTime = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
      if (rand.nextFloat() > .5) mons[rand.nextInt(COUNT)].increment();
      else mons[rand.nextInt(COUNT)].decrement();
    }
    final long endTime = System.currentTimeMillis();
    Debug.printLn("Time: " + ((endTime - startTime) / 1000.) + " sec");

    if (s.size() != COUNT)
      throw new Error(
          "Set is missing " + (COUNT - s.size()) + " elements (may be due to duplicates)");

    int last = Integer.MIN_VALUE;
    for (final TestMonitorable m : s.toArray(mons)) {
      if (m == null) break;
      // Debug.printDel (m.get ());
      if (last > m.get()) throw new Error("ActiveSortedSet out of order");
      last = m.get();
    }
    // Debug.printLn ("");

    Debug.testEnd("Active Sorted Set: " + s.getClass().getSimpleName());
  }
示例#26
0
 public Object getElementAt(int index) {
   return model.toArray()[index];
 }
示例#27
0
  public static void main(String[] args) {

    try {

      final Options options = new Options();

      {
        final Option d = new Option("d", "directory", true, "target directory");
        d.setArgName("directory");
        d.setArgs(1);
        d.setRequired(true);
        options.addOption(d);
      }

      {
        final Option ad = new Option("ad", "another-directory", true, "another target directory");
        ad.setArgName("another-directory");
        ad.setArgs(1);
        ad.setRequired(false);
        options.addOption(ad);
      }

      {
        final Option o = new Option("o", "output", true, "output file");
        o.setArgName("file");
        o.setArgs(1);
        o.setRequired(true);
        options.addOption(o);
      }

      {
        final Option s = new Option("s", "size", true, "size");
        s.setArgName("size");
        s.setArgs(1);
        s.setRequired(true);
        options.addOption(s);
      }

      {
        final Option t = new Option("t", "thread", true, "number of threads");
        t.setArgName("thread");
        t.setArgs(1);
        t.setRequired(false);
        options.addOption(t);
      }

      {
        final Option cross =
            new Option(
                "cross", "cross-project-only", true, "whether to detect cross project clones only");
        cross.setArgName("on or off");
        cross.setRequired(false);
        options.addOption(cross);
      }

      {
        final Option lowmem =
            new Option("lowmem", "low-memory-mode", true, "whether to run on the low memory mode");
        lowmem.setArgName("on or off");
        lowmem.setRequired(false);
        options.addOption(lowmem);
      }

      {
        final Option v = new Option("v", "verbose", true, "verbose output");
        v.setArgName("on or off");
        v.setRequired(false);
        options.addOption(v);
      }

      {
        final Option C = new Option("C", "control", true, "use of control dependency");
        C.setArgName("on or off");
        C.setArgs(1);
        C.setRequired(false);
        options.addOption(C);
      }

      {
        final Option D = new Option("D", "data", true, "use of data dependency");
        D.setArgName("on or off");
        D.setArgs(1);
        D.setRequired(false);
        options.addOption(D);
      }

      {
        final Option E = new Option("E", "execution", true, "use of execution dependency");
        E.setArgName("on or off");
        E.setArgs(1);
        E.setRequired(false);
        options.addOption(E);
      }

      {
        final Option M = new Option("M", "merging", true, "merging consecutive similar nodes");
        M.setArgName("on or off");
        M.setArgs(1);
        M.setRequired(false);
        options.addOption(M);
      }

      final CommandLineParser parser = new PosixParser();
      final CommandLine cmd = parser.parse(options, args);

      final File target = new File(cmd.getOptionValue("d"));
      if (!target.exists()) {
        System.err.println("specified directory or file does not exist.");
        System.exit(0);
      }

      final String output = cmd.getOptionValue("o");
      final int SIZE_THRESHOLD = Integer.parseInt(cmd.getOptionValue("s"));
      final int NUMBER_OF_THREADS =
          cmd.hasOption("t") ? Integer.parseInt(cmd.getOptionValue("t")) : 1;

      boolean useOfControl = !cmd.hasOption("C");
      if (!useOfControl) {
        if (cmd.getOptionValue("C").equals("on")) {
          useOfControl = true;
        } else if (cmd.getOptionValue("C").equals("off")) {
          useOfControl = false;
        } else {
          System.err.println("option of \"-C\" must be \"on\" or \"off\".");
        }
      }

      boolean useOfData = !cmd.hasOption("D");
      if (!useOfData) {
        if (cmd.getOptionValue("D").equals("on")) {
          useOfData = true;
        } else if (cmd.getOptionValue("D").equals("off")) {
          useOfData = false;
        } else {
          System.err.println("option of \"-D\" must be \"on\" or \"off\".");
        }
      }

      boolean useOfExecution = !cmd.hasOption("E");
      if (!useOfExecution) {
        if (cmd.getOptionValue("E").equals("on")) {
          useOfExecution = true;
        } else if (cmd.getOptionValue("E").equals("off")) {
          useOfExecution = false;
        } else {
          System.err.println("option of \"-E\" must be \"on\" or \"off\".");
        }
      }

      boolean useOfMerging = !cmd.hasOption("M");
      if (!useOfMerging) {
        if (cmd.getOptionValue("M").equals("on")) {
          useOfMerging = true;
        } else if (cmd.getOptionValue("M").equals("off")) {
          useOfMerging = false;
        } else {
          System.err.println("option of \"-M\" must be \"on\" or \"off\".");
        }
      }

      if (!useOfExecution && useOfMerging) {
        useOfMerging = false;
      }

      boolean crossProjectOnly = false;
      if (cmd.hasOption("cross")) {
        if (cmd.getOptionValue("cross").equals("on")) {
          crossProjectOnly = true;
        } else if (cmd.getOptionValue("cross").equals("off")) {
          crossProjectOnly = false;
        } else {
          System.err.println("option of \"-cross\" must be \"on\" or \"off\".");
        }
      }

      boolean lowMemoryMode = false;
      if (cmd.hasOption("lowmem")) {
        if (cmd.getOptionValue("lowmem").equals("on")) {
          lowMemoryMode = true;
        } else if (cmd.getOptionValue("lowmem").equals("off")) {
          lowMemoryMode = false;
        } else {
          System.err.println("option of \"-lowmem\" must be \"on\" or \"off\".");
        }
      }

      // default verbose level is "off"
      if (cmd.hasOption("v")) {
        if (cmd.getOptionValue("v").equals("on")) {
          Message.setVerbose(true);
        } else if (cmd.getOptionValue("v").equals("off")) {
          Message.setVerbose(false);
        } else {
          System.err.println("option of \"-v\" must be \"on\" or \"off\".");
        }
      }

      File anotherTarget = null;
      if (cmd.hasOption("ad")) {
        anotherTarget = new File(cmd.getOptionValue("ad"));
        if (!anotherTarget.exists()) {
          System.err.println("specified directory or file does not exist.");
          System.exit(0);
        }
      }

      if (crossProjectOnly && anotherTarget == null) {
        System.err.println(
            "detecting cross project only is ON, but no second directory or file has been specified");
        System.exit(0);
      }

      final long time1 = System.nanoTime();
      System.out.print("generating PDGs ... ");
      Message.log("");
      final PDG[] pdgArray;
      {
        final List<File> files = getFiles(target);

        if (anotherTarget != null) {
          files.addAll(getFiles(anotherTarget));
        }

        int count = 0;
        final int numOfFiles = files.size();

        final List<MethodInfo> methods = new ArrayList<MethodInfo>();
        for (final File file : files) {
          Message.log(
              "\t["
                  + (++count)
                  + "/"
                  + numOfFiles
                  + "] building an AST for "
                  + file.getAbsolutePath());

          final CompilationUnit unit = TinyPDGASTVisitor.createAST(file);
          final ASTVisitor visitor;

          if (lowMemoryMode) {
            visitor = new OffsetBasedTinyPDGASTVisitor(file.getAbsolutePath(), unit, methods);
          } else {
            visitor = new TinyPDGASTVisitor(file.getAbsolutePath(), unit, methods);
          }

          unit.accept(visitor);
        }

        long memoryElapsed = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.out.println("MEMORY: " + (memoryElapsed / 1024));

        final SortedSet<PDG> pdgs = Collections.synchronizedSortedSet(new TreeSet<PDG>());
        final CFGNodeFactory cfgNodeFactory = new CFGNodeFactory();
        final PDGNodeFactory pdgNodeFactory = new PDGNodeFactory();
        final Thread[] pdgGenerationThreads = new Thread[NUMBER_OF_THREADS];
        for (int i = 0; i < pdgGenerationThreads.length; i++) {
          pdgGenerationThreads[i] =
              new Thread(
                  new PDGGenerationThread(
                      methods,
                      pdgs,
                      cfgNodeFactory,
                      pdgNodeFactory,
                      useOfControl,
                      useOfData,
                      useOfExecution,
                      useOfMerging,
                      SIZE_THRESHOLD));
          pdgGenerationThreads[i].start();
        }
        for (final Thread thread : pdgGenerationThreads) {
          try {
            thread.join();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        pdgArray = pdgs.toArray(new PDG[0]);
      }
      System.out.print("done: ");
      final long time2 = System.nanoTime();
      printTime(time2 - time1);

      System.out.print("calculating hash values ... ");
      Message.log("");
      final SortedMap<PDG, SortedMap<PDGNode<?>, Integer>> mappingPDGToPDGNodes =
          Collections.synchronizedSortedMap(new TreeMap<PDG, SortedMap<PDGNode<?>, Integer>>());
      final SortedMap<PDG, SortedMap<PDGEdge, Integer>> mappingPDGToPDGEdges =
          Collections.synchronizedSortedMap(new TreeMap<PDG, SortedMap<PDGEdge, Integer>>());
      {
        final Thread[] hashCalculationThreads = new Thread[NUMBER_OF_THREADS];
        for (int i = 0; i < hashCalculationThreads.length; i++) {
          hashCalculationThreads[i] =
              new Thread(
                  new HashCalculationThread(pdgArray, mappingPDGToPDGNodes, mappingPDGToPDGEdges));
          hashCalculationThreads[i].start();
        }
        for (final Thread thread : hashCalculationThreads) {
          try {
            thread.join();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
      System.out.print("done: ");
      final long time3 = System.nanoTime();
      printTime(time3 - time2);

      System.out.print("detecting clone pairs ... ");
      Message.log("");
      final SortedSet<ClonePairInfo> clonepairs =
          Collections.synchronizedSortedSet(new TreeSet<ClonePairInfo>());
      {
        int numIgnored = 0;
        final List<PDGPairInfo> pdgpairs = new ArrayList<PDGPairInfo>();
        Message.log("\tmaking PDG pairs ... ");
        for (int i = 0; i < pdgArray.length; i++) {
          for (int j = i + 1; j < pdgArray.length; j++) {
            final PDG pdg1 = pdgArray[i];
            final PDG pdg2 = pdgArray[j];

            if (!crossProjectOnly || isCrossProject(pdg1, pdg2, target, anotherTarget)) {
              pdgpairs.add(new PDGPairInfo(pdgArray[i], pdgArray[j]));
            } else {
              // Message.log("\t\tignore the PDG pair \"" +
              // pdg1.unit.name + " in "
              // + pdg1.unit.path + "\" and \""
              // + pdg2.unit.name + " in " + pdg2.unit.path
              // + "\"");
              numIgnored++;
            }
          }
        }
        Message.log("\tdone: the number of ignored PDG pairs is " + numIgnored);

        final PDGPairInfo[] pdgpairArray = pdgpairs.toArray(new PDGPairInfo[0]);
        final Thread[] slicingThreads = new Thread[NUMBER_OF_THREADS];
        for (int i = 0; i < slicingThreads.length; i++) {
          slicingThreads[i] =
              new Thread(
                  new SlicingThread(
                      pdgpairArray,
                      pdgArray,
                      mappingPDGToPDGNodes,
                      mappingPDGToPDGEdges,
                      clonepairs,
                      SIZE_THRESHOLD,
                      crossProjectOnly));
          slicingThreads[i].start();
        }
        for (final Thread thread : slicingThreads) {
          try {
            thread.join();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
      System.out.print("done: ");
      final long time4 = System.nanoTime();
      printTime(time4 - time3);

      System.out.print("writing to a file ... ");
      final Writer writer = new BellonWriter(output, clonepairs);
      writer.write();
      System.out.print("done: ");
      final long time5 = System.nanoTime();
      printTime(time5 - time4);

      System.out.print("total elapsed time: ");
      printTime(time5 - time1);

      System.out.print("number of comparisons: ");
      printNumberOfComparison(Slicing.getNumberOfComparison());

    } catch (Exception e) {
      System.err.println(e.getMessage());
      System.exit(0);
    }
  }
 @Override
 public <T> T[] toArray(T[] a) {
   return attributes.toArray(a);
 }
 @Override
 public Object[] toArray() {
   return attributes.toArray();
 }
 static {
   SortedSet<Locale> languages =
       new TreeSet<Locale>(
           new Comparator<Locale>() {
             @Override
             public int compare(Locale o1, Locale o2) {
               if (o1.getDisplayLanguage().trim().compareTo(o2.getDisplayLanguage().trim()) == 0) {
                 return o1.getDisplayCountry().trim().compareTo(o2.getDisplayCountry().trim());
               } else {
                 return o1.getDisplayLanguage().trim().compareTo(o2.getDisplayLanguage().trim());
               }
             }
           });
   Collections.addAll(
       languages,
       new Locale("en", "US"),
       new Locale("de", "DE"),
       new Locale("zh", "CN"),
       new Locale("zh", "TW"),
       new Locale("cs", "CZ"),
       new Locale("nl", "BE"),
       new Locale("nl", "NL"),
       new Locale("en", "AU"),
       new Locale("en", "GB"),
       new Locale("en", "CA"),
       new Locale("en", "NZ"),
       new Locale("en", "SG"),
       new Locale("fr", "BE"),
       new Locale("fr", "CA"),
       new Locale("fr", "FR"),
       new Locale("fr", "CH"),
       new Locale("de", "AT"),
       new Locale("de", "LI"),
       new Locale("de", "CH"),
       new Locale("it", "IT"),
       new Locale("it", "CH"),
       new Locale("ja", "JP"),
       new Locale("ko", "KR"),
       new Locale("pl", "PL"),
       new Locale("ru", "RU"),
       new Locale("es", "ES"),
       new Locale("ar", "EG"),
       new Locale("ar", "IL"),
       new Locale("bg", "BG"),
       new Locale("ca", "ES"),
       new Locale("hr", "HR"),
       new Locale("da", "DK"),
       new Locale("en", "IN"),
       new Locale("en", "IE"),
       new Locale("en", "ZA"),
       new Locale("fi", "FI"),
       new Locale("el", "GR"),
       new Locale("iw", "IL"),
       new Locale("hi", "IN"),
       new Locale("hu", "HU"),
       new Locale("in", "ID"),
       new Locale("lv", "LV"),
       new Locale("lt", "LT"),
       new Locale("nb", "NO"),
       new Locale("pt", "BR"),
       new Locale("pt", "PT"),
       new Locale("ro", "RO"),
       new Locale("sr", "RS"),
       new Locale("sk", "SK"),
       new Locale("sl", "SI"),
       new Locale("es", "US"),
       new Locale("sv", "SE"),
       new Locale("tl", "PH"),
       new Locale("th", "TH"),
       new Locale("tr", "TR"),
       new Locale("uk", "UA"),
       new Locale("vi", "VN"));
   LOCALES = new Locale[languages.size()];
   languages.toArray(LOCALES);
 }