Java Code Examples for java.util.TreeSet#remove()

The following examples show how to use java.util.TreeSet#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GenericEntity.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
public boolean isPrimaryKey(boolean requireValue) {
    TreeSet<String> fieldKeys = new TreeSet<>(this.fields.keySet());
    for (ModelField curPk: this.getModelEntity().getPkFieldsUnmodifiable()) {
        String fieldName = curPk.getName();
        if (requireValue) {
            if (this.fields.get(fieldName) == null) {
                return false;
            }
        } else {
            if (!this.fields.containsKey(fieldName)) {
                return false;
            }
        }
        fieldKeys.remove(fieldName);
    }
    if (!fieldKeys.isEmpty()) {
        return false;
    }
    return true;
}
 
Example 2
Source File: RemoveBorderLabelsPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static final Collection<Integer> findBorderLabelsFront(ImageStack image) {
	int sizeX = image.getWidth();
	int sizeY = image.getHeight();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();

	for (int y = 0; y < sizeY; y++) {
		for (int x = 0; x < sizeX; x++) {
			labelSet.add((int) image.getVoxel(x, y, 0));
		}
	}
	
	// remove label for the background
	labelSet.remove(0);
			
	return labelSet;
}
 
Example 3
Source File: OrderBook.java    From parity with Apache License 2.0 6 votes vote down vote up
/**
 * Cancel a quantity of an order in this order book. The size refers
 * to the new order size. If the new order size is set to zero, the
 * order is deleted from this order book.
 *
 * <p>A Cancel event is triggered.</p>
 *
 * <p>If the order identifier is unknown, do nothing.</p>
 *
 * @param orderId the order identifier
 * @param size the new size
 */
public void cancel(long orderId, long size) {
    Order order = orders.get(orderId);
    if (order == null)
        return;

    long remainingQuantity = order.getRemainingQuantity();

    if (size >= remainingQuantity)
        return;

    if (size > 0) {
        order.resize(size);
    } else {
        TreeSet<Order> queue = order.getSide() == Side.BUY ? bids : asks;

        queue.remove(order);
        orders.remove(orderId);
    }

    listener.cancel(orderId, remainingQuantity - size, size);
}
 
Example 4
Source File: RemoveBorderLabelsPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static final Collection<Integer> findBorderLabelsLeft(ImageStack image) {
	int sizeY = image.getHeight();
	int sizeZ = image.getSize();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();

	for (int z = 0; z < sizeZ; z++) {
		for (int y = 0; y < sizeY; y++) {
			labelSet.add((int) image.getVoxel(0, y, z));
		}
	}

	// remove label for the background
	labelSet.remove(0);
			
	return labelSet;
}
 
Example 5
Source File: RemoveBorderLabelsPlugin.java    From MorphoLibJ with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static final Collection<Integer> findBorderLabelsBottom(ImageStack image) {
	int sizeX = image.getWidth();
	int sizeY = image.getHeight();
	int sizeZ = image.getSize();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();

	for (int z = 0; z < sizeZ; z++) {
		for (int x = 0; x < sizeX; x++) {
			labelSet.add((int) image.getVoxel(x, sizeY - 1, z));
		}
	}

	// remove label for the background
	labelSet.remove(0);
			
	return labelSet;
}
 
Example 6
Source File: Top.java    From jstorm with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public TreeSet<T> update(Number object, TreeSet<T> cache, Object... others) {
    // TODO Auto-generated method stub
    if (cache == null) {
        cache = new TreeSet<T>(comparator);
    }

    cache.add((T) object);

    if (cache.size() > n) {
        cache.remove(cache.last());
    }

    return cache;
}
 
Example 7
Source File: SlidingWindowMedian.java    From cs-summary-reflection with Apache License 2.0 6 votes vote down vote up
void add(TreeSet<Node> minheap, TreeSet<Node> maxheap, int size, Node node) {
    if (minheap.size() < size) {
        minheap.add(node);
    } else {
        maxheap.add(node);
    }
    if (minheap.size() == size) {
        if (maxheap.size() > 0 && minheap.last().val > maxheap.first().val) {
            Node s = minheap.last();
            Node b = maxheap.first();
            minheap.remove(s);
            maxheap.remove(b);
            minheap.add(b);
            maxheap.add(s);
        }
    }
}
 
Example 8
Source File: UserDictionaryAddWordContents.java    From openboard with GNU General Public License v3.0 6 votes vote down vote up
public ArrayList<LocaleRenderer> getLocalesList(final Activity activity) {
    final TreeSet<String> locales = UserDictionaryList.getUserDictionaryLocalesSet(activity);
    // Remove our locale if it's in, because we're always gonna put it at the top
    locales.remove(mLocale); // mLocale may not be null
    final String systemLocale = Locale.getDefault().toString();
    // The system locale should be inside. We want it at the 2nd spot.
    locales.remove(systemLocale); // system locale may not be null
    locales.remove(""); // Remove the empty string if it's there
    final ArrayList<LocaleRenderer> localesList = new ArrayList<>();
    // Add the passed locale, then the system locale at the top of the list. Add an
    // "all languages" entry at the bottom of the list.
    addLocaleDisplayNameToList(activity, localesList, mLocale);
    if (!systemLocale.equals(mLocale)) {
        addLocaleDisplayNameToList(activity, localesList, systemLocale);
    }
    for (final String l : locales) {
        // TODO: sort in unicode order
        addLocaleDisplayNameToList(activity, localesList, l);
    }
    if (!"".equals(mLocale)) {
        // If mLocale is "", then we already inserted the "all languages" item, so don't do it
        addLocaleDisplayNameToList(activity, localesList, ""); // meaning: all languages
    }
    localesList.add(new LocaleRenderer(activity, null)); // meaning: select another locale
    return localesList;
}
 
Example 9
Source File: TreeCursorNoDuplicatesTest.java    From xodus with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertDeletes() {
    final ByteIterable value = value("value");
    final TreeSet<String> keys = new TreeSet<>();
    tm = createMutableTree(false, 1);
    for (int i = 0; i < 10000; ++i) {
        final String key = rndString();
        if (keys.add(key)) {
            Assert.assertTrue(tm.add(key(key), value));
        }
        if (keys.size() > 1000) {
            final String obsoleteKey = keys.first();
            keys.remove(obsoleteKey);
            Assert.assertTrue(tm.delete(key(obsoleteKey)));
        }
    }
    testCursorOrder(keys);
}
 
Example 10
Source File: 12504 Updating a Dictionary.java    From UVA with GNU General Public License v3.0 5 votes vote down vote up
public static void main (String [] args) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int testCaseCount=Integer.parseInt(br.readLine());
	for (int i=0;i<testCaseCount;i++) {
		TreeMap<String,String> oldDict=new TreeMap<>();
		TreeMap<String,String> newDict=new TreeMap<>();
		
		updateDict(oldDict,br.readLine());
		updateDict(newDict,br.readLine());
		
		TreeSet<String> newKeys=new TreeSet<>();
		newKeys.addAll(newDict.keySet());
		newKeys.removeAll(oldDict.keySet());
		
		TreeSet<String> removedKeys=new TreeSet<>();
		removedKeys.addAll(oldDict.keySet());
		removedKeys.removeAll(newDict.keySet());
		
		TreeSet<String> changedKeys=new TreeSet<>();
		changedKeys.addAll(oldDict.keySet());
		changedKeys.retainAll(newDict.keySet());
		String [] changedKeysAry=changedKeys.toArray(new String [changedKeys.size()]);
		for (String s : changedKeysAry) if (oldDict.get(s).equals(newDict.get(s))) changedKeys.remove(s);
		
		StringBuilder sb=new StringBuilder();
		sb.append(toStr("+",newKeys));
		sb.append(toStr("-",removedKeys));
		sb.append(toStr("*",changedKeys));
		
		if (sb.length()==0) sb.append("No changes\n");
		
		System.out.println(sb.toString());
	}
}
 
Example 11
Source File: CFSA2Serializer.java    From morfologik-stemming with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Compute a set of labels to be integrated with the flags field.
 */
private void computeLabelsIndex(final FSA fsa) {
  // Compute labels count.
  final int[] countByValue = new int[256];

  fsa.visitAllStates(new StateVisitor() {
    public boolean accept(int state) {
      for (int arc = fsa.getFirstArc(state); arc != 0; arc = fsa.getNextArc(arc))
        countByValue[fsa.getArcLabel(arc) & 0xff]++;
      return true;
    }
  });

  // Order by descending frequency of counts and increasing label value.
  Comparator<IntIntHolder> comparator = new Comparator<IntIntHolder>() {
    public int compare(IntIntHolder o1, IntIntHolder o2) {
      int countDiff = o2.b - o1.b;
      if (countDiff == 0) {
        countDiff = o1.a - o2.a;
      }
      return countDiff;
    }
  };

  TreeSet<IntIntHolder> labelAndCount = new TreeSet<IntIntHolder>(comparator);
  for (int label = 0; label < countByValue.length; label++) {
    if (countByValue[label] > 0) {
      labelAndCount.add(new IntIntHolder(label, countByValue[label]));
    }
  }

  labelsIndex = new byte[1 + Math.min(labelAndCount.size(), CFSA2.LABEL_INDEX_SIZE)];
  labelsInvIndex = new int[256];
  for (int i = labelsIndex.length - 1; i > 0 && !labelAndCount.isEmpty(); i--) {
    IntIntHolder p = labelAndCount.first();
    labelAndCount.remove(p);
    labelsInvIndex[p.a] = i;
    labelsIndex[i] = (byte) p.a;
  }
}
 
Example 12
Source File: HMDBGateway.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public String[] findCompounds(double mass, MZTolerance mzTolerance, int numOfResults,
    ParameterSet parameters) throws IOException {

  Range<Double> toleranceRange = mzTolerance.getToleranceRange(mass);

  String queryAddress = hmdbSeachAddress + "&query_from=" + toleranceRange.lowerEndpoint()
      + "&query_to=" + toleranceRange.upperEndpoint();

  URL queryURL = new URL(queryAddress);

  // Submit the query
  logger.finest("Loading URL " + queryAddress);
  String queryResult = InetUtils.retrieveData(queryURL);

  // Organize the IDs as a TreeSet to keep them sorted
  TreeSet<String> results = new TreeSet<String>();

  // Find IDs in the HTML data
  Pattern pat = Pattern.compile("metabolites/(HMDB[0-9]{5,})");
  Matcher matcher = pat.matcher(queryResult);
  while (matcher.find()) {
    String hmdbID = matcher.group(1);
    results.add(hmdbID);
  }

  // Remove all except first numOfResults IDs. The reason why we first
  // retrieve all results and then remove those above numOfResults is to
  // keep the lowest HDMB IDs - these may be the most interesting ones.
  while (results.size() > numOfResults) {
    String lastItem = results.last();
    results.remove(lastItem);
  }

  return results.toArray(new String[0]);

}
 
Example 13
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static final int[] findBorderLabels(ImageProcessor image) 
{
	int sizeX = image.getWidth();
	int sizeY = image.getHeight();
	
	TreeSet<Integer> labelSet = new TreeSet<Integer>();

	// find labels in top and bottom borders
	for (int x = 0; x < sizeX; x++)
	{
		labelSet.add((int) image.getf(x, 0));
		labelSet.add((int) image.getf(x, sizeY - 1));
	}

	// find labels in left and right borders
	for (int y = 0; y < sizeY; y++) 
	{
		labelSet.add((int) image.getf(0, y));
		labelSet.add((int) image.getf(sizeX - 1, y));
	}

	// remove label for the background
	labelSet.remove(0);
	
	// convert to an array of int
	int[] labels = new int[labelSet.size()];
	int i = 0 ;
	Iterator<Integer> iter = labelSet.iterator();
	while(iter.hasNext()) 
	{
		labels[i++] = (int) iter.next();
	}
	
	return labels;
}
 
Example 14
Source File: AvailablePluginsManagerMain.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public DefaultActionGroup createPopupActionGroup(JComponent component) {
  final TreeSet<String> availableCategories = ((AvailablePluginsTableModel)myPluginsModel).getAvailableCategories();
  final DefaultActionGroup gr = new DefaultActionGroup();
  gr.add(createFilterByCategoryAction(AvailablePluginsTableModel.ALL));
  final boolean noCategory = availableCategories.remove(N_A);
  for (final String availableCategory : availableCategories) {
    gr.add(createFilterByCategoryAction(availableCategory));
  }
  if (noCategory) {
    gr.add(createFilterByCategoryAction(N_A));
  }
  return gr;
}
 
Example 15
Source File: LabelImages.java    From MorphoLibJ with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
   * Returns the set of unique labels existing in the given image, excluding 
   * the value zero (used for background).
* 
* @param image
*            a label image
* @return the list of unique labels present in image (without background)
   */
  public final static int[] findAllLabels(ImageProcessor image)
  {
      int sizeX = image.getWidth();
      int sizeY = image.getHeight();
      
      TreeSet<Integer> labels = new TreeSet<Integer> ();
      
      // iterate on image pixels
      if (image instanceof FloatProcessor) 
      {
      	// For float processor, use explicit case to int from float value  
      	for (int y = 0; y < sizeY; y++) 
      	{
      		for (int x = 0; x < sizeX; x++) 
      			labels.add((int) image.getf(x, y));
      	}
      } 
      else
      {
      	// for integer-based images, simply use integer result
      	for (int y = 0; y < sizeY; y++) 
      	{
      		for (int x = 0; x < sizeX; x++) 
      			labels.add(image.get(x, y));
      	}
      }
      
      // remove 0 if it exists
      if (labels.contains(0))
          labels.remove(0);
      
      // convert to array of integers
      int[] array = new int[labels.size()];
      Iterator<Integer> iterator = labels.iterator();
      for (int i = 0; i < labels.size(); i++) 
          array[i] = iterator.next();
      
      return array;
  }
 
Example 16
Source File: LocatorLoadSnapshot.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private List/* <LoadHolder> */findBestServers(Map groupServers,
    Set excludedServers, int count) {
  TreeSet bestEntries = new TreeSet(new Comparator() {
    public int compare(Object o1, Object o2) {
      LoadHolder l1 = (LoadHolder)o1;
      LoadHolder l2 = (LoadHolder)o2;
      int difference = Float.compare(l1.getLoad(), l2.getLoad());
      if (difference != 0) {
        return difference;
      }
      ServerLocation sl1 = l1.getLocation();
      ServerLocation sl2 = l2.getLocation();
      return sl1.compareTo(sl2);
    }
  });

  float lastBestLoad = Float.MAX_VALUE;
  for (Iterator itr = groupServers.entrySet().iterator(); itr.hasNext();) {
    Map.Entry next = (Entry)itr.next();
    ServerLocation location = (ServerLocation)next.getKey();
    if (excludedServers.contains(location)) {
      continue;
    }
    LoadHolder nextLoadReference = (LoadHolder)next.getValue();
    float nextLoad = nextLoadReference.getLoad();

    if (bestEntries.size() < count || count == -1 || nextLoad < lastBestLoad) {
      bestEntries.add(nextLoadReference);
      if (count != -1 && bestEntries.size() > count) {
        bestEntries.remove(bestEntries.last());
      }
      LoadHolder lastBestHolder = (LoadHolder)bestEntries.last();
      lastBestLoad = lastBestHolder.getLoad();
    }
  }

  return new ArrayList(bestEntries);
}
 
Example 17
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean containsNearbyAlmostDuplicate2(int[] nums, int k, int t) {
    // 极端条件判断
    int len = nums.length;
    if (len == 0 || k <= 0 || t < 0) {
        return false;
    }
    TreeSet<Long> treeSet = new TreeSet<>();
    for (int i = 0; i < len; i++) {
        Long floor = treeSet.floor((long) nums[i] + t);
        if ((floor != null && floor >= nums[i])) {
            return true;
        }

        Long ceiling = treeSet.ceiling((long) nums[i] - t);
        if ((ceiling != null && ceiling <= nums[i])) {
            return true;
        }
        // 超过 k 的时候,就要移除之前的元素
        // k = 3
        // 0,1,2,3
        if (i >= k) {
            treeSet.remove((long) nums[i - k]);
        }
        treeSet.add((long) nums[i]);
    }
    return false;
}
 
Example 18
Source File: LocatorLoadSnapshot.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private List/* <LoadHolder> */findBestServers(Map groupServers,
    Set excludedServers, int count) {
  TreeSet bestEntries = new TreeSet(new Comparator() {
    public int compare(Object o1, Object o2) {
      LoadHolder l1 = (LoadHolder)o1;
      LoadHolder l2 = (LoadHolder)o2;
      int difference = Float.compare(l1.getLoad(), l2.getLoad());
      if (difference != 0) {
        return difference;
      }
      ServerLocation sl1 = l1.getLocation();
      ServerLocation sl2 = l2.getLocation();
      return sl1.compareTo(sl2);
    }
  });

  float lastBestLoad = Float.MAX_VALUE;
  for (Iterator itr = groupServers.entrySet().iterator(); itr.hasNext();) {
    Map.Entry next = (Entry)itr.next();
    ServerLocation location = (ServerLocation)next.getKey();
    if (excludedServers.contains(location)) {
      continue;
    }
    LoadHolder nextLoadReference = (LoadHolder)next.getValue();
    float nextLoad = nextLoadReference.getLoad();

    if (bestEntries.size() < count || count == -1 || nextLoad < lastBestLoad) {
      bestEntries.add(nextLoadReference);
      if (count != -1 && bestEntries.size() > count) {
        bestEntries.remove(bestEntries.last());
      }
      LoadHolder lastBestHolder = (LoadHolder)bestEntries.last();
      lastBestLoad = lastBestHolder.getLoad();
    }
  }

  return new ArrayList(bestEntries);
}
 
Example 19
Source File: FontCSSServlet.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	HttpSession session = ((HttpServletRequest)request).getSession(true);
	synchronized (session) {
		session.setMaxInactiveInterval(300);
		
		String url = ((HttpServletRequest)request).getRequestURL().toString();
		String font = url.substring(url.lastIndexOf("/") + 1).replace('_', ' ');

		int substr_end= font.indexOf(";jsessionid", 0);
		if(substr_end > -1){
			//Trim off jsessionid if present
			font = font.substring(0, substr_end);
		}
		if(expectedFonts.contains(font)){
			//System.out.println("Requested: " + font);
			TreeSet<String> fontsNotRequested = (TreeSet<String>)session.getAttribute("fontsNotRequested");
			if(fontsNotRequested == null){
				fontsNotRequested = new TreeSet<String>(expectedFonts);
				session.setAttribute("fontsNotRequested", fontsNotRequested);
			}
			
			fontsNotRequested.remove(font);
		}
		response.sendError(404);
	}
}
 
Example 20
Source File: BinaryHeapQuickRemovals.java    From Algorithms with MIT License 4 votes vote down vote up
private void mapRemove(T value, int index) {
  TreeSet<Integer> set = map.get(value);
  set.remove(index); // TreeSets take O(log(n)) removal time
  if (set.size() == 0) map.remove(value);
}