Example #1
0
  /** tailSet returns set with keys in requested range */
  public void testTailSetContents() {
    NavigableSet set = set5();
    SortedSet sm = set.tailSet(two);
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertTrue(sm.contains(three));
    assertTrue(sm.contains(four));
    assertTrue(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer) (i.next());
    assertEquals(two, k);
    k = (Integer) (i.next());
    assertEquals(three, k);
    k = (Integer) (i.next());
    assertEquals(four, k);
    k = (Integer) (i.next());
    assertEquals(five, k);
    assertFalse(i.hasNext());

    SortedSet ssm = sm.tailSet(four);
    assertEquals(four, ssm.first());
    assertEquals(five, ssm.last());
    assertTrue(ssm.remove(four));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    assertEquals(4, set.size());
  }
Example #2
0
 public void testDescendingSubSetContents2() {
   NavigableSet set = dset5();
   SortedSet sm = set.subSet(m2, m3);
   assertEquals(1, sm.size());
   assertEquals(m2, sm.first());
   assertEquals(m2, sm.last());
   assertFalse(sm.contains(m1));
   assertTrue(sm.contains(m2));
   assertFalse(sm.contains(m3));
   assertFalse(sm.contains(m4));
   assertFalse(sm.contains(m5));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m2, k);
   assertFalse(i.hasNext());
   Iterator j = sm.iterator();
   j.next();
   j.remove();
   assertFalse(set.contains(m2));
   assertEquals(4, set.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertFalse(sm.remove(m3));
   assertEquals(4, set.size());
 }
Example #3
0
 public void testSubSetContents2() {
   NavigableSet set = set5();
   SortedSet sm = set.subSet(two, three);
   assertEquals(1, sm.size());
   assertEquals(two, sm.first());
   assertEquals(two, sm.last());
   assertFalse(sm.contains(one));
   assertTrue(sm.contains(two));
   assertFalse(sm.contains(three));
   assertFalse(sm.contains(four));
   assertFalse(sm.contains(five));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(two, k);
   assertFalse(i.hasNext());
   Iterator j = sm.iterator();
   j.next();
   j.remove();
   assertFalse(set.contains(two));
   assertEquals(4, set.size());
   assertEquals(0, sm.size());
   assertTrue(sm.isEmpty());
   assertFalse(sm.remove(three));
   assertEquals(4, set.size());
 }
Example #4
0
 /**
  * Inconsistency in TreeSet in contains with null parameter if empty --> nothing if not empty -->
  * throws NPE
  */
 @Test
 public void testSortedSetContainsNull() {
   SortedSet<Date> dates = new TreeSet<Date>();
   dates.contains(null);
   dates.add(new Date());
   dates.contains(null);
 }
 @GET
 public String doGetString(@QueryParam("args") SortedSet<BigDecimal> args) {
   assertTrue(args.contains(new BigDecimal("3.145")));
   assertTrue(args.contains(new BigDecimal("2.718")));
   assertTrue(args.contains(new BigDecimal("1.618")));
   return "content";
 }
Example #6
0
  /** tailSet returns set with keys in requested range */
  public void testDescendingTailSetContents() {
    NavigableSet set = dset5();
    SortedSet sm = set.tailSet(m2);
    assertFalse(sm.contains(m1));
    assertTrue(sm.contains(m2));
    assertTrue(sm.contains(m3));
    assertTrue(sm.contains(m4));
    assertTrue(sm.contains(m5));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer) (i.next());
    assertEquals(m2, k);
    k = (Integer) (i.next());
    assertEquals(m3, k);
    k = (Integer) (i.next());
    assertEquals(m4, k);
    k = (Integer) (i.next());
    assertEquals(m5, k);
    assertFalse(i.hasNext());

    SortedSet ssm = sm.tailSet(m4);
    assertEquals(m4, ssm.first());
    assertEquals(m5, ssm.last());
    assertTrue(ssm.remove(m4));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    assertEquals(4, set.size());
  }
Example #7
0
  @Test
  public void testGetAllGroups() throws LdapDAOException {
    SortedSet<String> groupIds = this.ldapManager.getAllGroups();

    assertTrue("GroupIds: " + groupIds, groupIds.contains("public"));
    assertTrue("GroupIds: " + groupIds, groupIds.contains("releases"));
    assertTrue("GroupIds: " + groupIds, groupIds.contains("snapshots"));
    assertEquals("GroupIds: " + groupIds, 3, groupIds.size());
  }
Example #8
0
  public void setDrumEnabled(int track, int drumId, boolean enabled) {
    if (isDrumEnabled(track, drumId) != enabled) {
      BitSet[] enabledSet;
      if (isCowbellPart()) {
        if (cowbellsEnabled == null) cowbellsEnabled = new BitSet[getTrackCount()];
        enabledSet = cowbellsEnabled;
      } else {
        if (drumsEnabled == null) drumsEnabled = new BitSet[getTrackCount()];
        enabledSet = drumsEnabled;
      }

      if (enabledSet[track] == null) {
        enabledSet[track] = new BitSet(MidiConstants.NOTE_COUNT);
        if (isCowbellPart()) {
          SortedSet<Integer> notesInUse =
              abcSong.getSequenceInfo().getTrackInfo(track).getNotesInUse();
          if (notesInUse.contains(MidiConstants.COWBELL_DRUM_ID))
            enabledSet[track].set(MidiConstants.COWBELL_DRUM_ID, true);
        } else {
          enabledSet[track].set(0, MidiConstants.NOTE_COUNT, true);
        }
      }
      enabledSet[track].set(drumId, enabled);
      fireChangeEvent(AbcPartProperty.DRUM_ENABLED);
    }
  }
Example #9
0
 /** @tests java.util.TreeSet#add(java.lang.Object) */
 public void test_addLjava_lang_Object() {
   // Test for method boolean java.util.TreeSet.add(java.lang.Object)
   ts.add(new Integer(-8));
   assertTrue("Failed to add Object", ts.contains(new Integer(-8)));
   ts.add(objArray[0]);
   assertTrue("Added existing element", ts.size() == objArray.length + 1);
 }
  /**
   * Add dependencies element for the given bundle to the string buffer.
   *
   * @param el element to add the dependencies to.
   * @param ba The bundle archive to defining the coordinates.
   * @param prefix Whitespace to add before the new element.
   */
  private void addDependencies(Element el, BundleArchive ba, String prefix) {
    final Element dependencies = el.getOwnerDocument().createElement("dependencies");
    final String prefix1 = prefix + "  ";
    final String prefix2 = prefix1 + "  ";

    el.appendChild(el.getOwnerDocument().createTextNode("\n" + prefix1));
    el.appendChild(dependencies);
    el.appendChild(el.getOwnerDocument().createTextNode("\n" + prefix));

    for (final Entry<BundleArchive, SortedSet<String>> depEntry : selectCtDeps(ba).entrySet()) {
      final BundleArchives.BundleArchive depBa = depEntry.getKey();
      final SortedSet<String> pkgNames = depEntry.getValue();

      dependencies.appendChild(el.getOwnerDocument().createTextNode("\n" + prefix2));
      dependencies.appendChild(el.getOwnerDocument().createComment(pkgNames.toString()));

      final Element dependency = el.getOwnerDocument().createElement("dependency");
      addMavenCoordinates(dependency, depBa);
      if (pkgNames.contains("org.osgi.framework")) {
        dependency.setAttribute("scope", "provided");
      }

      dependencies.appendChild(el.getOwnerDocument().createTextNode("\n" + prefix2));
      dependencies.appendChild(dependency);
      dependencies.appendChild(el.getOwnerDocument().createTextNode("\n"));
    }
    dependencies.appendChild(el.getOwnerDocument().createTextNode("\n" + prefix1));

    if (0 < ba.pkgUnprovidedMap.size()) {
      log("  Imports without any provider: " + ba.pkgUnprovidedMap, Project.MSG_DEBUG);
    }
  }
Example #11
0
  /** Fluffs the given nodeset and accepts it. */
  public boolean filter(MutableNodeSet nodeSet) {
    IntArray toAdd = new IntArray();
    Graph graph = nodeSet.getGraph();

    /* We won't fluff clusters smaller than five elements,
     * there's not enough evidence to extend it more.
     */
    if (nodeSet.size() < 5) return true;

    do {
      int minCount = (int) Math.floor(2.0 * nodeSet.size() / 3.0);
      SortedSet<Integer> members = nodeSet.getMembers();
      toAdd.clear();

      for (int node : nodeSet.getExternalBoundaryNodes()) {
        int[] neis = graph.getAdjacentNodeIndicesArray(node, Directedness.ALL);

        int intersectionSize = 0;
        for (int neighbor : neis) if (members.contains(neighbor)) intersectionSize++;

        if (intersectionSize >= minCount) toAdd.add(node);
      }

      nodeSet.add(toAdd.toArray());
    } while (iterative && toAdd.size() > 0);

    return true;
  }
  /**
   * Add the supplied DocumentRegion to the manager. Only runs in event thread after initialization?
   *
   * @param region the DocumentRegion to be inserted into the manager
   */
  public void addRegion(final R region) {
    final OpenDefinitionsDocument odd = region.getDocument();
    SortedSet<R> docRegions = _regions.get(odd);
    if (docRegions
        == null) { // if necessary create a Hashtable entry for odd and insert it in the _documents
      // set
      _documents.add(odd);
      docRegions = new TreeSet<R>();
      _regions.put(odd, docRegions);
    }

    // Check for duplicate region
    final boolean alreadyPresent = docRegions.contains(region);
    if (!alreadyPresent) { // region does not already exist in manager
      docRegions.add(region); // modifies docRegions, which is part of _regions
    }

    assert _documents.contains(odd);

    // only notify if the region was actually added
    if (!alreadyPresent) {
      // notify.  invokeLater unnecessary if it only runs in the event thread
      _lock.startRead();
      try {
        for (RegionManagerListener<R> l : _listeners) {
          l.regionAdded(region);
        }
      } finally {
        _lock.endRead();
      }
    }
  }
  /**
   * Starts and execute the ImmediateChecksParser for parsing those Variables/functions that should
   * be checked for security violation at every state.
   *
   * @param pFile the file to be parsed.
   */
  @SuppressWarnings("resource")
  public ImmediateChecksParser(LogManager pLogger, Path pFile) {
    set = new TreeSet<>();

    List<String> contents = null;
    try {
      contents = Files.readAllLines(pFile, Charset.defaultCharset());
    } catch (IOException e) {
      pLogger.logUserException(
          Level.WARNING, e, "Could not read intial security mapping from file named " + pFile);
      return;
    }

    for (String strLine : contents) {
      if (strLine.trim().isEmpty()) {
        continue;

      } else if (strLine.contains(";")) {
        int sem = strLine.indexOf(";");
        Variable var = new Variable(strLine.substring(0, sem));
        if (!set.contains(var)) {
          set.add(var);
        }
      }
    }
  }
Example #14
0
 /** @tests java.util.TreeSet#addAll(java.util.Collection) */
 public void test_addAllLjava_util_Collection() {
   // Test for method boolean
   // java.util.TreeSet.addAll(java.util.Collection)
   SortedSet s = db.createTreeSet("test");
   s.addAll(ts);
   assertTrue("Incorrect size after add", s.size() == ts.size());
   Iterator i = ts.iterator();
   while (i.hasNext()) assertTrue("Returned incorrect set", s.contains(i.next()));
 }
  // The implementing class can assume that the provided LogAbstraction
  // partialTrace is
  // of the same class, i.e. this.getClass().equals(partialTrace.getClass()) =
  // true
  //
  // The implementing class can assume that the LogEvent provided is in the
  // set returned by
  // getPossibleNextLogEvents(partialTrace), i.e. in all instances
  // represented by this abstraction, the given LogEvent is a possible
  // next step.
  public final Recommendation getRecommendation(
      LogEvent logEventToDo, LogAbstraction partialTrace, SortedSet<LogEvent> enabledEvents) {
    Recommendation rec = new Recommendation();
    rec.setTask(logEventToDo.getModelElementName());
    rec.setEventType(logEventToDo.getEventType());
    double weight = calculateFitness(partialTrace);

    if (weight > 0) {

      SortedSet<LogEvent> possibleEvents = getPossibleNextLogEvents(partialTrace);

      if (possibleEvents.contains(logEventToDo) && enabledEvents.contains(logEventToDo)) {

        // It is possible to do this event, so give a recommendation
        double[] vals = getAllValuesAndWeights(weight);
        rec.setDoExpectedValue(vals[0]);
        rec.setDoExpectedSquaredValue(vals[1]);
        rec.setDoWeight(vals[2]);
      } else {
        // It is not possible to do this event, so give a "negative"
        // recommendation
        double w = 0;
        double e = 0;
        double e2 = 0;
        for (LogEvent evt : possibleEvents) {
          if (!enabledEvents.contains(evt)) {
            continue;
          }
          // Event evt is not a possible event in this case,
          // but is enabled in the query
          double[] vals = getAllValuesAndWeights(weight);
          double newW = w + vals[2];
          e = (e * w + vals[0] * vals[2]) / newW;
          e2 = (e2 * w + vals[1] * vals[2]) / newW;
          w = newW;
        }
        rec.setDontExpectedValue(e);
        rec.setDontExpectedSquaredValue(e2);
        rec.setDontWeight(w);
      }
    }
    return rec;
  }
Example #16
0
 @Override
 public Boolean convert(final String value) {
   try {
     if (Integer.parseInt(value) > 0) {
       return true;
     }
   } catch (NumberFormatException e) {
     return $yes.contains(value.toLowerCase());
   }
   return false;
 }
Example #17
0
  /**
   * Handle responses from CCNNameEnumerator that give us a list of single-component child names.
   * Filter out the names new to us, add them to our list of known children, postprocess them with
   * processNewChildren(SortedSet<ContentName>), and signal waiters if we have new data.
   *
   * @param prefix Prefix used for name enumeration.
   * @param names The list of names returned in this name enumeration response.
   * @return int
   */
  public int handleNameEnumerator(ContentName prefix, ArrayList<ContentName> names) {

    if (Log.isLoggable(Level.INFO)) {
      if (!_enumerating) {
        // Right now, just log if we get data out of enumeration, don't drop it on the floor;
        // don't want to miss results in case we are started again.
        Log.info(
            "ENUMERATION STOPPED: but {0} new name enumeration results: our prefix: {1} returned prefix: {2}",
            names.size(), _namePrefix, prefix);
      } else {
        Log.info(
            names.size() + " new name enumeration results: our prefix: {0} returned prefix: {1}",
            _namePrefix,
            prefix);
      }
    }
    if (!prefix.equals(_namePrefix)) {
      Log.warning("Returned data doesn't match requested prefix!");
    }
    Log.info("Handling Name Iteration {0}", prefix);
    // the name enumerator hands off names to us, we own it now
    // DKS -- want to keep listed as new children we previously had
    synchronized (_childLock) {
      TreeSet<ContentName> thisRoundNew = new TreeSet<ContentName>();
      thisRoundNew.addAll(names);
      Iterator<ContentName> it = thisRoundNew.iterator();
      while (it.hasNext()) {
        ContentName name = it.next();
        if (_children.contains(name)) {
          it.remove();
        }
      }
      if (!thisRoundNew.isEmpty()) {
        if (null != _newChildren) {
          _newChildren.addAll(thisRoundNew);
        } else {
          _newChildren = thisRoundNew;
        }
        _children.addAll(thisRoundNew);
        _lastUpdate = new CCNTime();
        if (Log.isLoggable(Level.INFO)) {
          Log.info(
              "New children found: at {0} "
                  + thisRoundNew.size()
                  + " total children "
                  + _children.size(),
              _lastUpdate);
        }
        processNewChildren(thisRoundNew);
        _childLock.notifyAll();
      }
    }
    return 0;
  }
Example #18
0
  @Override
  public boolean addFolderChange(String folderId, FolderChange change) {
    // Redis command: ZADD
    SortedSet<FolderChange> changes = getFolderChanges(folderId);

    if (FolderID.getType(folderId).equals(FolderID.Type.Root) && changes.contains(change)) {
      return true;
    }

    return changes.add(change);
  }
Example #19
0
  @Test(
      dependsOnMethods = {
        "testContextAwareCounter",
        "testContextAwareMeter",
        "testContextAwareHistogram",
        "testContextAwareTimer",
        "testTaggableGauge"
      })
  public void testGetMetrics() {
    SortedSet<String> names = this.context.getNames();
    Assert.assertEquals(names.size(), 6);
    Assert.assertTrue(names.contains(RECORDS_PROCESSED));
    Assert.assertTrue(names.contains(RECORD_PROCESS_RATE));
    Assert.assertTrue(names.contains(RECORD_SIZE_DISTRIBUTION));
    Assert.assertTrue(names.contains(TOTAL_DURATION));
    Assert.assertTrue(names.contains(QUEUE_SIZE));

    SortedSet<String> childNames = this.childContext.getNames();
    Assert.assertEquals(childNames.size(), 4);
    Assert.assertTrue(childNames.contains(RECORDS_PROCESSED));
    Assert.assertTrue(childNames.contains(RECORD_PROCESS_RATE));
    Assert.assertTrue(childNames.contains(RECORD_SIZE_DISTRIBUTION));

    Map<String, Metric> metrics = this.context.getMetrics();
    Assert.assertEquals(metrics.size(), 6);
    Assert.assertTrue(metrics.containsKey(RECORDS_PROCESSED));
    Assert.assertTrue(metrics.containsKey(RECORD_PROCESS_RATE));
    Assert.assertTrue(metrics.containsKey(RECORD_SIZE_DISTRIBUTION));
    Assert.assertTrue(metrics.containsKey(TOTAL_DURATION));
    Assert.assertTrue(metrics.containsKey(QUEUE_SIZE));

    Map<String, Counter> counters = this.context.getCounters();
    Assert.assertEquals(counters.size(), 1);
    Assert.assertTrue(counters.containsKey(RECORDS_PROCESSED));

    Map<String, Meter> meters = this.context.getMeters();
    Assert.assertEquals(meters.size(), 1);
    Assert.assertTrue(meters.containsKey(RECORD_PROCESS_RATE));

    Map<String, Histogram> histograms = this.context.getHistograms();
    Assert.assertEquals(histograms.size(), 1);
    Assert.assertTrue(histograms.containsKey(RECORD_SIZE_DISTRIBUTION));

    Map<String, Timer> timers = this.context.getTimers();
    Assert.assertEquals(timers.size(), 2);
    Assert.assertTrue(timers.containsKey(TOTAL_DURATION));

    Map<String, Gauge> gauges = this.context.getGauges();
    Assert.assertEquals(gauges.size(), 1);
    Assert.assertTrue(gauges.containsKey(QUEUE_SIZE));
  }
Example #20
0
  @Override
  public boolean addChild(String folderId, String childId, long score) {
    // Redis command: ZADD + ZRANK
    SortedSet<FolderChild> children = getChildrenInner(folderId);

    FolderChild child = new FolderChild(childId, score);
    if (FolderID.getType(folderId).equals(FolderID.Type.Root) && children.contains(child)) {
      return true;
    }

    return children.add(child);
  }
  /**
   * Constructs a nullable set for the given grammar.
   *
   * @param g
   */
  public NullableNonterminals(CFG g) {
    super();

    // Construct Nullable Nonterminals
    List<Production> productions = g.productions();
    boolean changing = true;
    while (changing) {
      changing = false;
      for (Production p : productions) {
        Token left = p.leftHandSide();
        if (!nullable.contains(left)) {
          if (p.goesToEpsilon()) {
            nullable.add(left);
            changing = true;
          } else {
            List<Token> rhs = p.rightHandSide();
            boolean all_nullable = true;
            for (Token right : rhs) {
              if (!nullable.contains(right)) {
                all_nullable = false;
                break;
              }
            }

            if (all_nullable) {
              nullable.add(left);
              changing = true;
            }
          }
        }
      }
    }

    // ---------------------------------------------------------------------
    /*
     * Stores an immutable version of the non-terminal set to avoid
     * accidentally mutating it later.
     */
    this.nullable = Collections.unmodifiableSortedSet(nullable);
  }
Example #22
0
 /**
  * @param ts testsuite to validate
  * @return executable state of testsuite
  */
 public TestSuiteState validateSaveState(ITestSuitePO ts) {
   if (Plugin.getDefault().anyDirtyStar()) {
     boolean isSaved = Plugin.getDefault().showSaveEditorDialog();
     if (isSaved) {
       SortedSet<ITestSuitePO> allTestSuites = getAllTestSuites();
       if (allTestSuites.contains(ts)) {
         return TestSuiteState.complete;
       }
     }
     return TestSuiteState.incomplete;
   }
   return TestSuiteState.unchanged;
 }
Example #23
0
 /** headSet returns set with keys in requested range */
 public void testHeadSetContents() {
   NavigableSet set = set5();
   SortedSet sm = set.headSet(four);
   assertTrue(sm.contains(one));
   assertTrue(sm.contains(two));
   assertTrue(sm.contains(three));
   assertFalse(sm.contains(four));
   assertFalse(sm.contains(five));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(one, k);
   k = (Integer) (i.next());
   assertEquals(two, k);
   k = (Integer) (i.next());
   assertEquals(three, k);
   assertFalse(i.hasNext());
   sm.clear();
   assertTrue(sm.isEmpty());
   assertEquals(2, set.size());
   assertEquals(four, set.first());
 }
Example #24
0
 /** headSet returns set with keys in requested range */
 public void testDescendingHeadSetContents() {
   NavigableSet set = dset5();
   SortedSet sm = set.headSet(m4);
   assertTrue(sm.contains(m1));
   assertTrue(sm.contains(m2));
   assertTrue(sm.contains(m3));
   assertFalse(sm.contains(m4));
   assertFalse(sm.contains(m5));
   Iterator i = sm.iterator();
   Object k;
   k = (Integer) (i.next());
   assertEquals(m1, k);
   k = (Integer) (i.next());
   assertEquals(m2, k);
   k = (Integer) (i.next());
   assertEquals(m3, k);
   assertFalse(i.hasNext());
   sm.clear();
   assertTrue(sm.isEmpty());
   assertEquals(2, set.size());
   assertEquals(m4, set.first());
 }
Example #25
0
  /* (non-Javadoc)
   * @see addressbook.model.AddressBookAccess#deleteEntry(addressbook.model.Entry)
   */
  @Override
  public boolean deleteEntry(Entry entry) {

    // Check if entry exists
    if (entries.contains(entry)) {
      // Exists, remove entry
      entries.remove(entry);
      return true;
    } else {
      // No such entry
      return false;
    }
  }
Example #26
0
  public boolean addAck(int ack, int maxPacketSize) {
    if (ack < 0) throw new IllegalArgumentException("Got negative ack: " + ack);
    if (acks.contains(ack)) return true;

    acks.add(ack);
    int nearRangeCount = 0, farRangeCount = 0;

    Iterator<Integer> acksIterator = acks.iterator();
    int startRange = 0, endRange = -1;
    int nextAck = acksIterator.next();
    while (acksIterator.hasNext()) {
      if (nextAck - endRange > 254 && endRange != -1) {
        farRangeCount++;
      } else {
        nearRangeCount++;
      }
      endRange = startRange = nextAck;
      while (acksIterator.hasNext()
          && ((nextAck = acksIterator.next()) - endRange == 1)
          && (endRange - startRange < 254)) {
        endRange++;
      }
      // TODO: Add zero-cost dub-acks if any
    }
    if (nextAck != endRange) {
      if (nextAck - endRange < 254 || endRange == -1) {
        nearRangeCount++;
      } else {
        farRangeCount++;
      }
    }
    if (nearRangeCount + farRangeCount > 254) {
      acks.remove(ack);
      return false;
    }
    //              (start + offset) + (rangeCount-1)    *(1byte deltaFromPrevios + length) +
    // farRangeCount*(flag + 4byte packetSequenceNumber + length)
    int blockSize = 5 + (nearRangeCount - 1) * 2 + farRangeCount * 6;
    int finalLength = length + blockSize - ackBlockByteSize;
    if (finalLength > maxPacketSize) {
      acks.remove(ack);
      return false;
    }
    length = finalLength;
    ackBlockByteSize = blockSize;
    ackRangeCount = farRangeCount + nearRangeCount;

    return true;
  }
Example #27
0
 /**
  * Find a new name that isn't among the used names.
  *
  * @param prefix
  * @param usedNames
  * @return
  */
 public static String unusedName(String prefix, Iterator usedNames) {
   SortedSet u = new TreeSet();
   while (usedNames.hasNext()) {
     String curr = (String) usedNames.next();
     if (curr.startsWith(prefix)) {
       String postfix = curr.substring(prefix.length());
       u.add(postfix);
     }
   }
   int count = 0;
   while (u.contains(String.valueOf(count))) {
     count++;
   }
   return prefix + count;
 }
Example #28
0
  /* (non-Javadoc)
   * @see addressbook.model.AddressBookAccess#addEntry(addressbook.model.Entry)
   */
  @Override
  public boolean addEntry(Entry entry) throws SizeLimitReachedException {

    // Check size limit
    if (entries.size() >= sizeLimit) throw new SizeLimitReachedException("Limit is " + sizeLimit);

    // Does entry exist?
    if (entries.contains(entry)) {
      // Does exist
      return false;
    } else {
      // Store entry
      entries.add(entry);
      return true;
    }
  }
Example #29
0
  public static <T extends GraphNode<T>> Collection<Collection<T>> getConnectedComponents(
      Set<T> constraints) {
    Collection<T> unvisited = HashSetFactory.make();

    for (T constraint : constraints) {
      unvisited.add(constraint);
    }

    // DFS of the constraints graph
    LinkedList<T> rPostorder = new LinkedList<T>();
    while (!unvisited.isEmpty()) {
      Iterator<T> it = unvisited.iterator();
      T constraint = it.next();
      DFS(constraint, unvisited, rPostorder, false);
    }

    // Set nodes numbering in reverse postorder
    int id = 0;
    for (Iterator<T> it = rPostorder.iterator(); it.hasNext(); id++) {
      T node = it.next();
      node.id = id;
    }

    // DFS of the transpose graph in reverse postorder
    LinkedList<Collection<T>> components = new LinkedList<Collection<T>>();
    while (!rPostorder.isEmpty()) {
      LinkedList<T> temp = new LinkedList<T>();
      T constraint = rPostorder.removeFirst();
      DFS(constraint, rPostorder, temp, true);
      SortedSet<T> component = new TreeSet<T>();
      component.addAll(temp);
      for (Iterator<T> it = component.iterator(); it.hasNext(); ) {
        constraint = it.next();
        SortedSet<T> tempSet = new TreeSet<T>();
        for (Iterator<T> itDeps = constraint.dependents.iterator(); itDeps.hasNext(); ) {
          T dependent = itDeps.next();
          if (component.contains(dependent)) {
            tempSet.add(dependent);
            // constraint.strongDependents.add(dependent);
          }
        }
        constraint.setStrongDependents(tempSet);
      }
      components.add(new LinkedList<T>(component));
    }
    return components;
  }
Example #30
0
  public boolean addAck(int ack) {
    if (ack < 0) throw new IllegalArgumentException("Got negative ack: " + ack);
    if (acks.contains(ack)) return true;
    if (acks.size() >= 255) return false;

    if (acks.size() == 0) {
      length += 3;
    } else if (ack < acks.first()) {
      if ((acks.first() - ack) > 255) return false;
    } else if (ack > acks.last()) {
      if ((ack - acks.last()) > 255) return false;
    }
    acks.add(ack);
    length++;

    return true;
  }