List of usage examples for java.util TreeSet add
public boolean add(E e)
From source file:net.spfbl.core.Analise.java
public static synchronized TreeSet<String> getNameSet() { TreeSet<String> queue = new TreeSet<String>(); for (String name : MAP.keySet()) { try {//from ww w . j a v a2s. c o m name = URLDecoder.decode(name, "UTF-8"); } catch (Exception ex) { Server.logError(ex); } finally { queue.add(name); } } return queue; }
From source file:com.inmobi.conduit.local.LocalStreamService.java
protected String getCurrentFile(FileSystem fs, FileStatus[] files, TreeSet<FileStatus> sortedFiles) { // Proposed Algo :-> Sort files based on timestamp // if there are no files) // then null (implying process this file as non-current file) // else//from w ww . j a va 2s .c om // return last file as the current file if (files == null || files.length == 0) return null; for (FileStatus file : files) { sortedFiles.add(file); } // get last file from set FileStatus lastFile = sortedFiles.last(); long diff = (System.currentTimeMillis() - lastFile.getModificationTime()) / MILLISECONDS_IN_MINUTE; if (diff > timeoutToProcessLastCollectorFile) { processLastFile = true; } else { processLastFile = false; } return lastFile.getPath().getName(); }
From source file:com.thoughtworks.go.server.dao.PipelineSqlMapDao.java
private void addActiveAsLatest(Stage stage, Map<CaseInsensitiveString, TreeSet<Long>> activePipelinesToIds, CaseInsensitiveString pipelineName) { if (stage.getState().isActive()) { TreeSet<Long> ids = initializePipelineInstances(activePipelinesToIds, pipelineName); removeCurrentLatestIfNoLongerActive(stage, ids); ids.add(stage.getPipelineId()); }// w w w . j a v a 2 s .co m }
From source file:gate.gui.docview.AnnotationStack.java
/** * Draw the annotation stack in a JPanel with a GridBagLayout. */// w w w . ja v a 2 s . c o m public void drawStack() { // clear the panel removeAll(); boolean textTooLong = text.length() > maxTextLength; int upperBound = text.length() - (maxTextLength / 2); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.BOTH; /********************** * First row of text * *********************/ gbc.gridwidth = 1; gbc.insets = new java.awt.Insets(10, 10, 10, 10); JLabel labelTitle = new JLabel("Context"); labelTitle.setOpaque(true); labelTitle.setBackground(Color.WHITE); labelTitle.setBorder(new CompoundBorder( new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250), new Color(250, 250, 250).darker()), new EmptyBorder(new Insets(0, 2, 0, 2)))); labelTitle.setToolTipText("Expression and its context."); add(labelTitle, gbc); gbc.insets = new java.awt.Insets(10, 0, 10, 0); int expressionStart = contextBeforeSize; int expressionEnd = text.length() - contextAfterSize; // for each character for (int charNum = 0; charNum < text.length(); charNum++) { gbc.gridx = charNum + 1; if (textTooLong) { if (charNum == maxTextLength / 2) { // add ellipsis dots in case of a too long text displayed add(new JLabel("..."), gbc); // skip the middle part of the text if too long charNum = upperBound + 1; continue; } else if (charNum > upperBound) { gbc.gridx -= upperBound - (maxTextLength / 2) + 1; } } // set the text and color of the feature value JLabel label = new JLabel(text.substring(charNum, charNum + 1)); if (charNum >= expressionStart && charNum < expressionEnd) { // this part is matched by the pattern, color it label.setBackground(new Color(240, 201, 184)); } else { // this part is the context, no color label.setBackground(Color.WHITE); } label.setOpaque(true); // get the word from which belongs the current character charNum int start = text.lastIndexOf(" ", charNum); int end = text.indexOf(" ", charNum); String word = text.substring((start == -1) ? 0 : start, (end == -1) ? text.length() : end); // add a mouse listener that modify the query label.addMouseListener(textMouseListener.createListener(word)); add(label, gbc); } /************************************ * Subsequent rows with annotations * ************************************/ // for each row to display for (StackRow stackRow : stackRows) { String type = stackRow.getType(); String feature = stackRow.getFeature(); if (feature == null) { feature = ""; } String shortcut = stackRow.getShortcut(); if (shortcut == null) { shortcut = ""; } gbc.gridy++; gbc.gridx = 0; gbc.gridwidth = 1; gbc.insets = new Insets(0, 0, 3, 0); // add the header of the row JLabel annotationTypeAndFeature = new JLabel(); String typeAndFeature = type + (feature.equals("") ? "" : ".") + feature; annotationTypeAndFeature.setText(!shortcut.equals("") ? shortcut : stackRow.getSet() != null ? stackRow.getSet() + "#" + typeAndFeature : typeAndFeature); annotationTypeAndFeature.setOpaque(true); annotationTypeAndFeature.setBackground(Color.WHITE); annotationTypeAndFeature .setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250), new Color(250, 250, 250).darker()), new EmptyBorder(new Insets(0, 2, 0, 2)))); if (feature.equals("")) { annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type)); } else { annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type, feature)); } gbc.insets = new java.awt.Insets(0, 10, 3, 10); add(annotationTypeAndFeature, gbc); gbc.insets = new java.awt.Insets(0, 0, 3, 0); // add all annotations for this row HashMap<Integer, TreeSet<Integer>> gridSet = new HashMap<Integer, TreeSet<Integer>>(); int gridyMax = gbc.gridy; for (StackAnnotation ann : stackRow.getAnnotations()) { gbc.gridx = ann.getStartNode().getOffset().intValue() - expressionStartOffset + contextBeforeSize + 1; gbc.gridwidth = ann.getEndNode().getOffset().intValue() - ann.getStartNode().getOffset().intValue(); if (gbc.gridx == 0) { // column 0 is already the row header gbc.gridwidth -= 1; gbc.gridx = 1; } else if (gbc.gridx < 0) { // annotation starts before displayed text gbc.gridwidth += gbc.gridx - 1; gbc.gridx = 1; } if (gbc.gridx + gbc.gridwidth > text.length()) { // annotation ends after displayed text gbc.gridwidth = text.length() - gbc.gridx + 1; } if (textTooLong) { if (gbc.gridx > (upperBound + 1)) { // x starts after the hidden middle part gbc.gridx -= upperBound - (maxTextLength / 2) + 1; } else if (gbc.gridx > (maxTextLength / 2)) { // x starts in the hidden middle part if (gbc.gridx + gbc.gridwidth <= (upperBound + 3)) { // x ends in the hidden middle part continue; // skip the middle part of the text } else { // x ends after the hidden middle part gbc.gridwidth -= upperBound - gbc.gridx + 2; gbc.gridx = (maxTextLength / 2) + 2; } } else { // x starts before the hidden middle part if (gbc.gridx + gbc.gridwidth < (maxTextLength / 2)) { // x ends before the hidden middle part // do nothing } else if (gbc.gridx + gbc.gridwidth < upperBound) { // x ends in the hidden middle part gbc.gridwidth = (maxTextLength / 2) - gbc.gridx + 1; } else { // x ends after the hidden middle part gbc.gridwidth -= upperBound - (maxTextLength / 2) + 1; } } } if (gbc.gridwidth == 0) { gbc.gridwidth = 1; } JLabel label = new JLabel(); Object object = ann.getFeatures().get(feature); String value = (object == null) ? " " : Strings.toString(object); if (value.length() > maxFeatureValueLength) { // show the full text in the tooltip label.setToolTipText((value.length() > 500) ? "<html><textarea rows=\"30\" cols=\"40\" readonly=\"readonly\">" + value.replaceAll("(.{50,60})\\b", "$1\n") + "</textarea></html>" : ((value.length() > 100) ? "<html><table width=\"500\" border=\"0\" cellspacing=\"0\">" + "<tr><td>" + value.replaceAll("\n", "<br>") + "</td></tr></table></html>" : value)); if (stackRow.getCrop() == CROP_START) { value = "..." + value.substring(value.length() - maxFeatureValueLength - 1); } else if (stackRow.getCrop() == CROP_END) { value = value.substring(0, maxFeatureValueLength - 2) + "..."; } else {// cut in the middle value = value.substring(0, maxFeatureValueLength / 2) + "..." + value.substring(value.length() - (maxFeatureValueLength / 2)); } } label.setText(value); label.setBackground(AnnotationSetsView.getColor(stackRow.getSet(), ann.getType())); label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1)); label.setOpaque(true); label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type, String.valueOf(ann.getId()))); // show the feature values in the tooltip if (!ann.getFeatures().isEmpty()) { String width = (Strings.toString(ann.getFeatures()).length() > 100) ? "500" : "100%"; String toolTip = "<html><table width=\"" + width + "\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">"; Color color = (Color) UIManager.get("ToolTip.background"); float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null); color = Color.getHSBColor(hsb[0], hsb[1], Math.max(0f, hsb[2] - hsb[2] * 0.075f)); // darken the color String hexColor = Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen()) + Integer.toHexString(color.getBlue()); boolean odd = false; // alternate background color every other row List<Object> features = new ArrayList<Object>(ann.getFeatures().keySet()); //sort the features into alphabetical order Collections.sort(features, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { return o1.toString().compareToIgnoreCase(o2.toString()); } }); for (Object key : features) { String fv = Strings.toString(ann.getFeatures().get(key)); toolTip += "<tr align=\"left\"" + (odd ? " bgcolor=\"#" + hexColor + "\"" : "") + "><td><strong>" + key + "</strong></td><td>" + ((fv.length() > 500) ? "<textarea rows=\"20\" cols=\"40\" cellspacing=\"0\">" + StringEscapeUtils .escapeHtml(fv.replaceAll("(.{50,60})\\b", "$1\n")) + "</textarea>" : StringEscapeUtils.escapeHtml(fv).replaceAll("\n", "<br>")) + "</td></tr>"; odd = !odd; } label.setToolTipText(toolTip + "</table></html>"); } else { label.setToolTipText("No features."); } if (!feature.equals("")) { label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type, feature, Strings.toString(ann.getFeatures().get(feature)), String.valueOf(ann.getId()))); } // find the first empty row span for this annotation int oldGridy = gbc.gridy; for (int y = oldGridy; y <= (gridyMax + 1); y++) { // for each cell of this row where spans the annotation boolean xSpanIsEmpty = true; for (int x = gbc.gridx; (x < (gbc.gridx + gbc.gridwidth)) && xSpanIsEmpty; x++) { xSpanIsEmpty = !(gridSet.containsKey(x) && gridSet.get(x).contains(y)); } if (xSpanIsEmpty) { gbc.gridy = y; break; } } // save the column x and row y of the current value TreeSet<Integer> ts; for (int x = gbc.gridx; x < (gbc.gridx + gbc.gridwidth); x++) { ts = gridSet.get(x); if (ts == null) { ts = new TreeSet<Integer>(); } ts.add(gbc.gridy); gridSet.put(x, ts); } add(label, gbc); gridyMax = Math.max(gridyMax, gbc.gridy); gbc.gridy = oldGridy; } // add a button at the end of the row gbc.gridwidth = 1; if (stackRow.getLastColumnButton() != null) { // last cell of the row gbc.gridx = Math.min(text.length(), maxTextLength) + 1; gbc.insets = new Insets(0, 10, 3, 0); gbc.fill = GridBagConstraints.NONE; gbc.anchor = GridBagConstraints.WEST; add(stackRow.getLastColumnButton(), gbc); gbc.insets = new Insets(0, 0, 3, 0); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.CENTER; } // set the new gridy to the maximum row we put a value gbc.gridy = gridyMax; } if (lastRowButton != null) { // add a configuration button on the last row gbc.insets = new java.awt.Insets(0, 10, 0, 10); gbc.gridx = 0; gbc.gridy++; add(lastRowButton, gbc); } // add an empty cell that takes all remaining space to // align the visible cells at the top-left corner gbc.gridy++; gbc.gridx = Math.min(text.length(), maxTextLength) + 1; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.weighty = 1; add(new JLabel(""), gbc); validate(); updateUI(); }
From source file:darks.learning.word2vec.Word2Vec.java
/** * Calculate specify word's nearest or relate words * /* www.jav a 2 s . c o m*/ * @param word Specify word * @param topCount Result size * @return Nearest or relate words */ public Set<WordEntry> distance(String word, int topCount) { int resultSize = FastMath.min(topCount, wordNodes.size()); TreeSet<WordEntry> result = new TreeSet<WordEntry>(); WordNode node = wordNodes.get(word); if (node != null) { double minSim = Double.MIN_VALUE; for (WordNode target : wordNodes.values()) { if (target.name.equals(word)) { continue; } double sim = target.feature.dot(node.feature); if (sim > minSim) { result.add(new WordEntry(target.name, sim)); if (result.size() > resultSize) { result.pollLast(); } minSim = result.last().similar; } } } return result; }
From source file:geogebra.common.kernel.EquationSolver.java
/** * Calculates all roots of a polynomial given by eqn using Laguerres method. * Polishes roots found. The roots are stored in eqn again. *//* w w w . j a v a2s. c o m*/ @SuppressWarnings("deprecation") private int laguerreAllComplex(double[] real, double[] complex) { Complex[] complexRoots = null; try { if (laguerreSolver == null) { laguerreSolver = new LaguerreSolver(); } complexRoots = laguerreSolver.solveAll(real, LAGUERRE_START); } catch (Exception e) { App.debug("Problem solving with LaguerreSolver" + e.getLocalizedMessage()); return 0; } // sort by real part & remove duplicates TreeSet<Complex> sortedSet = new TreeSet<Complex>(getComparatorReal()); for (int i = 0; i < complexRoots.length; i++) { sortedSet.add(complexRoots[i]); } int roots = 0; Complex temp; Iterator<Complex> iterator = sortedSet.iterator(); while (iterator.hasNext()) { temp = iterator.next(); real[roots] = temp.getReal(); complex[roots] = temp.getImaginary(); roots++; } return roots; }
From source file:com.ecyrd.jspwiki.plugin.PluginManager.java
/** * {@inheritDoc}/*from w w w . ja v a 2 s.c o m*/ */ public Collection modules() { TreeSet<WikiModuleInfo> ls = new TreeSet<WikiModuleInfo>(); for (Iterator i = m_pluginClassMap.values().iterator(); i.hasNext();) { WikiModuleInfo wmi = (WikiModuleInfo) i.next(); if (!ls.contains(wmi)) ls.add(wmi); } return ls; }
From source file:com.imaginary.home.controller.CloudService.java
public void fetchCommands() throws CommunicationException, ControllerException { boolean hasCommands; do {//from w w w . j a v a2 s . c o m HttpClient client = getClient(endpoint, proxyHost, proxyPort); HttpPut method = new HttpPut(endpoint + "/command"); long timestamp = System.currentTimeMillis(); method.addHeader("Content-Type", "application/json"); method.addHeader("x-imaginary-version", VERSION); method.addHeader("x-imaginary-timestamp", String.valueOf(timestamp)); method.addHeader("x-imaginary-api-key", serviceId); if (token == null) { authenticate(); } String stringToSign = "put:/command:" + serviceId + ":" + token + ":" + timestamp + ":" + VERSION; try { method.addHeader("x-imaginary-signature", sign(apiKeySecret.getBytes("utf-8"), stringToSign)); } catch (Exception e) { throw new ControllerException(e); } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { e.printStackTrace(); throw new CommunicationException(e); } if (status.getStatusCode() != HttpServletResponse.SC_OK) { parseError(response); // this will throw an exception } Header h = response.getFirstHeader("x-imaginary-has-commands"); String val = (h == null ? "false" : h.getValue()); hasCommands = (val != null && val.equalsIgnoreCase("true")); HttpEntity entity = response.getEntity(); if (entity == null) { throw new CommunicationException(response.getStatusLine().getStatusCode(), "An error was returned without explanation"); } String json; try { json = EntityUtils.toString(entity); } catch (IOException e) { throw new CommunicationException(e); } try { HashMap<String, Map<String, List<JSONObject>>> commandGroups = new HashMap<String, Map<String, List<JSONObject>>>(); JSONArray list = new JSONArray(json); for (int i = 0; i < list.length(); i++) { JSONObject remoteCommand = list.getJSONObject(i); String groupId; if (remoteCommand.has("groupId") && !remoteCommand.isNull("groupId")) { groupId = remoteCommand.getString("groupId"); } else { continue; } long timeout = ((remoteCommand.has("timeout") && !remoteCommand.isNull("timeout")) ? remoteCommand.getLong("timeout") : (CalendarWrapper.MINUTE * 5L)); String commandString; if (remoteCommand.has("command") && !remoteCommand.isNull("command")) { commandString = remoteCommand.getString("command"); } else { continue; } JSONObject commandObject = new JSONObject(commandString); String command = commandObject.getString("command"); JSONArray arguments = null; if (commandObject.has("arguments") && !commandObject.isNull("arguments")) { arguments = commandObject.getJSONArray("arguments"); } String commandId; if (remoteCommand.has("commandId") && !remoteCommand.isNull("commandId")) { commandId = remoteCommand.getString("commandId"); } else { continue; } if (remoteCommand.has("devices") && !remoteCommand.isNull("devices")) { Map<String, TreeSet<String>> systemMapping = new HashMap<String, TreeSet<String>>(); JSONArray arr = remoteCommand.getJSONArray("devices"); for (int j = 0; j < arr.length(); j++) { JSONObject d = arr.getJSONObject(j); String deviceId = d.getString("deviceId"); String systemId = d.getString("systemId"); TreeSet<String> deviceIds; if (systemMapping.containsKey(systemId)) { deviceIds = systemMapping.get(systemId); } else { deviceIds = new TreeSet<String>(); systemMapping.put(systemId, deviceIds); } deviceIds.add(deviceId); } Map<String, List<JSONObject>> groupMap; if (commandGroups.containsKey(groupId)) { groupMap = commandGroups.get(groupId); } else { groupMap = new HashMap<String, List<JSONObject>>(); commandGroups.put(groupId, groupMap); } for (String systemId : systemMapping.keySet()) { List<JSONObject> cmds; if (groupMap.containsKey(systemId)) { cmds = groupMap.get(systemId); } else { cmds = new ArrayList<JSONObject>(); groupMap.put(systemId, cmds); } HashMap<String, Object> map = new HashMap<String, Object>(); map.put("commandId", commandId); map.put("resourceIds", systemMapping.get(systemId)); map.put("systemId", systemId); map.put("timeout", timeout); map.put("command", command); if (arguments != null) { map.put("arguments", arguments); } else { map.put("arguments", new ArrayList<JSONObject>()); } cmds.add(new JSONObject(map)); } } } for (String groupId : commandGroups.keySet()) { Map<String, List<JSONObject>> systemCommands = commandGroups.get(groupId); for (String systemId : systemCommands.keySet()) { List<JSONObject> commands = systemCommands.get(systemId); if (commands != null && commands.size() > 0) { HomeController.getInstance().queueCommands(this, commands.toArray(new JSONObject[commands.size()])); } } } } catch (JSONException e) { throw new CommunicationException(e); } } while (hasCommands); }
From source file:com.openedit.users.filesystem.XmlUserArchive.java
/** * @see com.openedit.users.UserManager#getGroups() *//*from w w w. ja v a 2 s. c om*/ public HitTracker getGroups() { Collection ids = listGroupIds(); TreeSet treeSet = new java.util.TreeSet(new GroupComparator()); for (Iterator iterator = ids.iterator(); iterator.hasNext();) { String id = (String) iterator.next(); treeSet.add(getGroup(id)); } ListHitTracker list = new ListHitTracker(new ArrayList(treeSet)); list.setHitsName("groups"); list.setCatalogId(getCatalogId()); return list; }
From source file:net.spfbl.core.Analise.java
public static TreeSet<Analise> getAnaliseCloneSet() { TreeSet<Analise> queue = new TreeSet<Analise>(); for (String name : getNameSet()) { Analise analise = get(name, false); if (analise != null) { try { Analise clone = analise.duplicate(); if (clone != null) { queue.add(clone); }/*from w w w.j a va 2 s.co m*/ } catch (InterruptedException ex) { Server.logError(ex); } } } return queue; }