List of usage examples for java.util TreeMap lastKey
public K lastKey()
From source file:org.alfresco.repo.content.cleanup.ContentStoreCleaner.java
/** * /*from www . ja v a 2s . co m*/ * @param maxTimeExclusive the max orphan time (exclusive) * @param batchSize the maximum number of orphans to process * @return Returns the last processed orphan ID or <tt>null</tt> if nothing was processed */ private Long cleanBatch(final long maxTimeExclusive, final int batchSize) { // Get a bunch of cleanable URLs final TreeMap<Long, String> urlsById = new TreeMap<Long, String>(); ContentUrlHandler contentUrlHandler = new ContentUrlHandler() { @Override public void handle(Long id, String contentUrl, Long orphanTime) { urlsById.put(id, contentUrl); } }; // Get a bunch of cleanable URLs contentDataDAO.getContentUrlsOrphaned(contentUrlHandler, maxTimeExclusive, batchSize); // Shortcut, if necessary if (urlsById.size() == 0) { return null; } // Compile list of IDs and do a mass delete, recording the IDs to find the largest Long lastId = urlsById.lastKey(); List<Long> ids = new ArrayList<Long>(urlsById.keySet()); contentDataDAO.deleteContentUrls(ids); // No problems, so far (ALF-1998: contentStoreCleanerJob leads to foreign key exception) // Now attempt to physically delete the URLs for (Long id : ids) { String contentUrl = urlsById.get(id); // Handle failures boolean deleted = eagerContentStoreCleaner.deleteFromStores(contentUrl); if (!deleted) { switch (deletionFailureAction) { case KEEP_URL: // Keep the URL, but with an orphan time of 0 so that it is recorded contentDataDAO.createContentUrlOrphaned(contentUrl, new Date(0L)); case IGNORE: break; default: throw new IllegalStateException("Unknown deletion failure action: " + deletionFailureAction); } } } // Done return lastId; }
From source file:disko.flow.analyzers.ParseSelectAnalyzer.java
public void process(AnalysisContext<TextDocument> ctx, Ports ports) throws InterruptedException { final HyperGraph graph = this.graph != null ? this.graph : ctx.getGraph(); RelationCountFactory.createCountingIndices(graph); InputPort<EntityMaintainer> entityInput = ports.getInput(EntityAnalyzer.ENTITY_CHANNEL); InputPort<Set<SentenceInterpretation>> sentenceInput = ports .getInput(ToRelOccAnalyzer.SENTENCE_INTERPRETATIONS); OutputPort<SentenceInterpretation> out = ports.getOutput(SELECTED_PARSE_CHANNEL); for (Set<SentenceInterpretation> iset = sentenceInput.take(); !sentenceInput .isEOS(iset); iset = sentenceInput.take()) { EntityMaintainer em = entityInput.take(); if (entityInput.isEOS(em)) break; HashMap<String, String> entityTypes = RelationCountFactory.getEntityTypes(em); TreeMap<Double, SentenceInterpretation> ranked = new TreeMap<Double, SentenceInterpretation>(); for (SentenceInterpretation i : iset) { ArrayList<RelationCount> relationCounts = new ArrayList<RelationCount>(); for (RelOccurrence occ : i.getRelOccs()) { if (occ.getArity() < 3) continue; List<String> components = occ.getComponents(ctx.getGraph()); relationCounts.add(//www.j a v a 2s. c o m RelationCountFactory.getRelationCount(entityTypes, components, occ.getPositions())); } // RelationCountFactory.getRelationCounts(entityTypes, i.getParse()); double score = computeScores(graph, relationCounts); ranked.put(score, i); } SentenceInterpretation best = ranked.get(ranked.lastKey()); out.put(best); } out.close(); }
From source file:com.asakusafw.directio.hive.parquet.DataModelMaterializer.java
private List<Mapping> computeMapping(DataModelDescriptor descriptor, MessageType schema, DataModelMapping configuration) { List<Mapping> mappings; switch (configuration.getFieldMappingStrategy()) { case NAME:// w ww .jav a 2 s. c om mappings = computeMappingByName(descriptor, schema); break; case POSITION: mappings = computeMappingByPosition(descriptor, schema); break; default: throw new AssertionError(configuration.getFieldMappingStrategy()); } TreeMap<Integer, Mapping> propertyMap = new TreeMap<>(); for (Mapping mapping : mappings) { if (checkMapping(descriptor, mapping, configuration)) { assert mapping.source != null; assert mapping.target != null; if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Map Parquet column: {0}:{1} -> {2}:{3}", //$NON-NLS-1$ mapping.source.getPath()[0], mapping.source.getType(), mapping.target.getFieldName(), mapping.target.getTypeInfo())); } int index = schema.getFieldIndex(mapping.source.getPath()[0]); propertyMap.put(index, mapping); } } int lastIndex = -1; if (propertyMap.isEmpty() == false) { lastIndex = propertyMap.lastKey(); } Mapping[] results = new Mapping[lastIndex + 1]; for (Map.Entry<Integer, Mapping> entry : propertyMap.entrySet()) { results[entry.getKey()] = entry.getValue(); } return Arrays.asList(results); }
From source file:org.starfishrespect.myconsumption.server.business.sensors.SensorsDataRetriever.java
/** * Retrieves and stores the data for one user * * @param onlyThisSensorId retrieve only data for one sensor with this id * @return false if something goes wrong; true otherwise *//* w w w . ja va 2 s. c om*/ public boolean retrieve(List<Sensor> sensors, String onlyThisSensorId) { boolean allSuccessful = true; for (Sensor sensor : sensors) { System.out.println("Retrieve data for sensor " + sensor.getId()); try { valuesRepository.setSensor(sensor.getId()); valuesRepository.init(); if (onlyThisSensorId != null) { if (!sensor.getId().equals(onlyThisSensorId)) { continue; } } HashMap<Integer, HashMap<Integer, Integer>> sortedValues = new HashMap<Integer, HashMap<Integer, Integer>>(); Date lastValue = sensor.getLastValue(); SensorRetriever retriever = null; if (sensor instanceof FluksoSensor) { retriever = new FluksoRetriever((FluksoSensor) sensor); } if (retriever == null) { System.out.println("This sensor type has not been found!"); continue; } TreeMap<Integer, Integer> data = retriever.getDataSince(lastValue).getData(); if (data.size() != 0) { for (int key : data.keySet()) { int hour = key - key % 3600; HashMap<Integer, Integer> hourData = sortedValues.get(hour); if (hourData == null) { hourData = new HashMap<Integer, Integer>(); sortedValues.put(hour, hourData); } hourData.put(key % 3600, data.get(key)); } for (int key : sortedValues.keySet()) { Date dateKey = new Date(key * 1000L); SensorDataset newValue = new SensorDataset(dateKey); newValue.addAllValues(sortedValues.get(key)); valuesRepository.insertOrUpdate(newValue); } if (sensor.getLastValue().before(new Date(data.lastKey() * 1000L))) { sensor.setLastValue(new Date(data.lastKey() * 1000L)); } if (sensor.getFirstValue().after(new Date(data.firstKey() * 1000L)) || sensor.getFirstValue().getTime() == 0) { sensor.setFirstValue(new Date(data.firstKey() * 1000L)); } // sync operation, this avoid to insert a sensor who would have been deleted // while retrieving its data int currentUsageCount = sensorRepository.getUsageCount(sensor.getId()); if (currentUsageCount > -1) { // update, the field may have been incremented during retrieving sensor.setUsageCount(currentUsageCount); sensor.setDead(false); sensorRepository.updateSensor(sensor); } System.out.println("Retrieve successful"); } else { System.out.println("No values retrieved for this sensor"); if (!sensor.isDead()) { // test if sensor is dead ? Calendar cal = new GregorianCalendar(); cal.add(Calendar.HOUR, -6); if (sensor.getLastValue().before(new Date(cal.getTimeInMillis()))) { System.out.println( "Sensor has not sent anything in the last 6 hours! Set its status as dead."); sensor.setDead(true); sensorRepository.updateSensor(sensor); } } else { System.out.println("Sensor is still dead"); } } } catch (RetrieveException | DaoException e) { System.err.println(e.getMessage()); allSuccessful = false; } } return allSuccessful; }
From source file:com.google.gwt.benchmarks.viewer.server.ReportImageServer.java
private JFreeChart createChart(String testName, Result result, String title, List<Result> comparativeResults) { // Find the maximum values across both axes for all of the results // (this chart's own results, plus all comparative results). ///*from w w w .ja va 2s .co m*/ // This is a stop-gap solution that helps us compare different charts for // the same benchmark method (usually with different user agents) until we // get real comparative functionality in version two. double maxTime = 0; for (Result r : comparativeResults) { for (Trial t : r.getTrials()) { maxTime = Math.max(maxTime, t.getRunTimeMillis()); } } // Determine the number of variables in this benchmark method List<Trial> trials = result.getTrials(); Trial firstTrial = new Trial(); int numVariables = 0; if (trials.size() > 0) { firstTrial = trials.get(0); numVariables = firstTrial.getVariables().size(); } // Display the trial data. // // First, pick the domain and series variables for our graph. // Right now we only handle up to two "user" variables. // We set the domain variable to the be the one containing the most unique // values. // This might be easier if the results had meta information telling us // how many total variables there are, what types they are of, etc.... String domainVariable = null; String seriesVariable = null; Map<String, Set<String>> variableValues = null; if (numVariables == 1) { domainVariable = firstTrial.getVariables().keySet().iterator().next(); } else { // TODO(tobyr): Do something smarter, like allow the user to specify which // variables are domain and series, along with the variables which are // held constant. variableValues = new HashMap<String, Set<String>>(); for (int i = 0; i < trials.size(); ++i) { Trial trial = trials.get(i); Map<String, String> variables = trial.getVariables(); for (Map.Entry<String, String> entry : variables.entrySet()) { String variable = entry.getKey(); Set<String> set = variableValues.get(variable); if (set == null) { set = new TreeSet<String>(); variableValues.put(variable, set); } set.add(entry.getValue()); } } TreeMap<Integer, List<String>> numValuesMap = new TreeMap<Integer, List<String>>(); for (Map.Entry<String, Set<String>> entry : variableValues.entrySet()) { Integer numValues = new Integer(entry.getValue().size()); List<String> variables = numValuesMap.get(numValues); if (variables == null) { variables = new ArrayList<String>(); numValuesMap.put(numValues, variables); } variables.add(entry.getKey()); } if (numValuesMap.values().size() > 0) { domainVariable = numValuesMap.get(numValuesMap.lastKey()).get(0); seriesVariable = numValuesMap.get(numValuesMap.firstKey()).get(0); } } String valueTitle = "time (ms)"; // This axis is time across all charts. if (numVariables == 0) { // Show a bar graph, with a single centered simple bar // 0 variables means there is only 1 trial DefaultCategoryDataset data = new DefaultCategoryDataset(); data.addValue(firstTrial.getRunTimeMillis(), "result", "result"); JFreeChart chart = ChartFactory.createBarChart(title, testName, valueTitle, data, PlotOrientation.VERTICAL, false, false, false); CategoryPlot p = chart.getCategoryPlot(); ValueAxis axis = p.getRangeAxis(); axis.setUpperBound(maxTime + maxTime * 0.1); return chart; } else if (numVariables == 1) { // Show a line graph with only 1 series // Or.... choose between a line graph and a bar graph depending upon // whether the type of the domain is numeric. XYSeriesCollection data = new XYSeriesCollection(); XYSeries series = new XYSeries(domainVariable); for (Trial trial : trials) { double time = trial.getRunTimeMillis(); String domainValue = trial.getVariables().get(domainVariable); series.add(Double.parseDouble(domainValue), time); } data.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1); double maxDomainValue = getMaxValue(comparativeResults, domainVariable); plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1); return chart; } else if (numVariables == 2) { // Show a line graph with two series XYSeriesCollection data = new XYSeriesCollection(); Set<String> seriesValues = variableValues.get(seriesVariable); for (String seriesValue : seriesValues) { XYSeries series = new XYSeries(seriesValue); for (Trial trial : trials) { Map<String, String> variables = trial.getVariables(); if (variables.get(seriesVariable).equals(seriesValue)) { double time = trial.getRunTimeMillis(); String domainValue = trial.getVariables().get(domainVariable); series.add(Double.parseDouble(domainValue), time); } } data.addSeries(series); } // TODO(tobyr) - Handle graphs above 2 variables JFreeChart chart = ChartFactory.createXYLineChart(title, domainVariable, valueTitle, data, PlotOrientation.VERTICAL, true, true, false); XYPlot plot = chart.getXYPlot(); plot.getRangeAxis().setUpperBound(maxTime + maxTime * 0.1); double maxDomainValue = getMaxValue(comparativeResults, domainVariable); plot.getDomainAxis().setUpperBound(maxDomainValue + maxDomainValue * 0.1); return chart; } throw new RuntimeException("The ReportImageServer is not yet able to " + "create charts for benchmarks with more than two variables."); // Sample JFreeChart code for creating certain charts: // Leaving this around until we can handle multivariate charts in dimensions // greater than two. // Code for creating a category data set - probably better with a bar chart // instead of line chart /* * DefaultCategoryDataset data = new DefaultCategoryDataset(); String series * = domainVariable; * * for ( Iterator it = trials.iterator(); it.hasNext(); ) { Trial trial = * (Trial) it.next(); double time = trial.getRunTimeMillis(); String * domainValue = (String) trial.getVariables().get( domainVariable ); * data.addValue( time, series, domainValue ); } * * String title = ""; String categoryTitle = domainVariable; PlotOrientation * orientation = PlotOrientation.VERTICAL; * * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle, * data, orientation, true, true, false ); */ /* * DefaultCategoryDataset data = new DefaultCategoryDataset(); String * series1 = "firefox"; String series2 = "ie"; * * data.addValue( 1.0, series1, "1024"); data.addValue( 2.0, series1, * "2048"); data.addValue( 4.0, series1, "4096"); data.addValue( 8.0, * series1, "8192"); * * data.addValue( 2.0, series2, "1024"); data.addValue( 4.0, series2, * "2048"); data.addValue( 8.0, series2, "4096"); data.addValue( 16.0, * series2,"8192"); * * String title = ""; String categoryTitle = "size"; PlotOrientation * orientation = PlotOrientation.VERTICAL; * * chart = ChartFactory.createLineChart( title, categoryTitle, valueTitle, * data, orientation, true, true, false ); */ }
From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java
private String reformatPath(String path, String currentExpression, String targetExpression, String newResourceVersion) throws RegistryException { TreeMap<Integer, String> indexMap = new TreeMap<Integer, String>(); String returnPath = targetExpression; String prefix;// www . ja v a 2s. co m if (currentExpression.equals(targetExpression)) { return path; } indexMap.put(currentExpression.indexOf(RESOURCE_NAME), RESOURCE_NAME); indexMap.put(currentExpression.indexOf(RESOURCE_PATH), RESOURCE_PATH); indexMap.put(currentExpression.indexOf(RESOURCE_VERSION), RESOURCE_VERSION); String tempExpression = currentExpression; while (indexMap.lastKey() < tempExpression.lastIndexOf(RegistryConstants.PATH_SEPARATOR)) { tempExpression = tempExpression.substring(0, tempExpression.lastIndexOf(RegistryConstants.PATH_SEPARATOR)); path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR)); } prefix = currentExpression.substring(0, currentExpression.indexOf(indexMap.get(indexMap.higherKey(-1)))); if (!path.startsWith(prefix)) { return path; } path = path.replace(prefix, ""); while (true) { if (indexMap.firstKey() < 0) { indexMap.pollFirstEntry(); } else { break; } } while (true) { if (indexMap.size() == 0) { break; } Map.Entry lastEntry = indexMap.pollLastEntry(); if (lastEntry.getValue().equals(RESOURCE_PATH)) { String pathValue = path; for (int i = 0; i < indexMap.size(); i++) { // pathValue = formatPath(pathValue.substring(path.indexOf(RegistryConstants.PATH_SEPARATOR))); pathValue = formatPath( pathValue.substring(pathValue.indexOf(RegistryConstants.PATH_SEPARATOR))); } if (!pathValue.equals("")) { returnPath = returnPath.replace(RESOURCE_PATH, formatPath(pathValue)); path = path.replace(pathValue, ""); } else { returnPath = returnPath.replace("/" + lastEntry.getValue(), ""); } continue; } if (lastEntry.getValue().equals(RESOURCE_VERSION)) { returnPath = returnPath.replace(RESOURCE_VERSION, newResourceVersion); if (path.contains("/")) { path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR)); } else { path = ""; } continue; } String tempPath; if (path.contains("/")) { tempPath = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1); } else { tempPath = path; } if (!tempPath.equals("")) { returnPath = returnPath.replace((String) lastEntry.getValue(), formatPath(tempPath)); if (path.contains("/")) { path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR)); } else { path = ""; } } else { returnPath = returnPath.replace("/" + lastEntry.getValue(), ""); if (path.contains("/")) { path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR)); } } } // Adding the version validation here. if (!newResourceVersion.matches("^\\d+[.]\\d+[.]\\d+(-[a-zA-Z0-9]+)?$")) { String message = "Invalid version found for " + RegistryUtils.getResourceName(path); log.error(message); throw new RegistryException(message); } if (returnPath.contains(RESOURCE_VERSION)) { return returnPath.replace(RESOURCE_VERSION, newResourceVersion); } return returnPath; }
From source file:org.eclipse.dataset.Stats.java
public static double[] outlierValuesMap(final Dataset a, int nl, int nh) { final TreeMap<Double, Integer> lMap = new TreeMap<Double, Integer>(); final TreeMap<Double, Integer> hMap = new TreeMap<Double, Integer>(); int ml = 0;/*from w ww . ja v a 2s .com*/ int mh = 0; IndexIterator it = a.getIterator(); while (it.hasNext()) { Double x = a.getElementDoubleAbs(it.index); Integer i; if (ml == nl) { Double k = lMap.lastKey(); if (x < k) { i = lMap.get(k) - 1; if (i == 0) { lMap.remove(k); } else { lMap.put(k, i); } i = lMap.get(x); if (i == null) { lMap.put(x, 1); } else { lMap.put(x, i + 1); } } } else { i = lMap.get(x); if (i == null) { lMap.put(x, 1); } else { lMap.put(x, i + 1); } ml++; } if (mh == nh) { Double k = hMap.firstKey(); if (x > k) { i = hMap.get(k) - 1; if (i == 0) { hMap.remove(k); } else { hMap.put(k, i); } i = hMap.get(x); if (i == null) { hMap.put(x, 1); } else { hMap.put(x, i + 1); } } } else { i = hMap.get(x); if (i == null) { hMap.put(x, 1); } else { hMap.put(x, i + 1); } mh++; } } // Attempt to make values distinct double lx = lMap.lastKey(); double hx = hMap.firstKey(); if (lx >= hx) { Double h = hMap.higherKey(lx); if (h != null) { hx = h; mh--; } else { Double l = lMap.lowerKey(hx); if (l != null) { lx = l; ml--; } } } return new double[] { lMap.lastKey(), hMap.firstKey(), ml, mh }; }
From source file:org.eclipse.january.dataset.Stats.java
static double[] outlierValuesMap(final Dataset a, int nl, int nh) { final TreeMap<Double, Integer> lMap = new TreeMap<Double, Integer>(); final TreeMap<Double, Integer> hMap = new TreeMap<Double, Integer>(); int ml = 0;/* w ww. j a v a 2 s. c om*/ int mh = 0; IndexIterator it = a.getIterator(); while (it.hasNext()) { Double x = a.getElementDoubleAbs(it.index); Integer i; if (ml == nl) { Double k = lMap.lastKey(); if (x < k) { i = lMap.get(k) - 1; if (i == 0) { lMap.remove(k); } else { lMap.put(k, i); } i = lMap.get(x); if (i == null) { lMap.put(x, 1); } else { lMap.put(x, i + 1); } } } else { i = lMap.get(x); if (i == null) { lMap.put(x, 1); } else { lMap.put(x, i + 1); } ml++; } if (mh == nh) { Double k = hMap.firstKey(); if (x > k) { i = hMap.get(k) - 1; if (i == 0) { hMap.remove(k); } else { hMap.put(k, i); } i = hMap.get(x); if (i == null) { hMap.put(x, 1); } else { hMap.put(x, i + 1); } } } else { i = hMap.get(x); if (i == null) { hMap.put(x, 1); } else { hMap.put(x, i + 1); } mh++; } } // Attempt to make values distinct double lx = lMap.lastKey(); double hx = hMap.firstKey(); if (lx >= hx) { Double h = hMap.higherKey(lx); if (h != null) { hx = h; mh--; } else { Double l = lMap.lowerKey(hx); if (l != null) { lx = l; ml--; } } } return new double[] { lMap.lastKey(), hMap.firstKey(), ml, mh }; }
From source file:org.openmicroscopy.shoola.agents.measurement.view.IntensityView.java
/** * Outputs the summary information from the shape map. * /* w w w . j ava 2s .c o m*/ * @param writer The Excel writer. * @param shapeMap see above. * @throws IOException */ private void outputSummary(ExcelWriter writer, TreeMap<Coord3D, ROIShape> shapeMap) { int rowIndex = 0; printSummaryHeader(writer, rowIndex); rowIndex++; Coord3D start = shapeMap.firstKey(); Coord3D end = shapeMap.lastKey(); Coord3D coord; List<Integer> channels = new ArrayList<Integer>(channelName.keySet()); Set<Coord3D> keys; Iterator<Coord3D> i; for (Integer c : channels) { keys = shapeMap.keySet(); i = keys.iterator(); while (i.hasNext()) { coord = (Coord3D) i.next(); populateData(coord, c); outputSummaryRow(writer, rowIndex, c, coord.getZSection(), coord.getTimePoint()); rowIndex++; } } }
From source file:hydrograph.ui.dataviewer.filter.FilterHelper.java
/** * Checks if column is modifiable./*from w ww .ja v a 2 s . c o m*/ * * @param groupSelectionMap * the group selection map * @param selectionList * the selection list * @return true, if is column modifiable */ public boolean isColumnModifiable(TreeMap<Integer, List<List<Integer>>> groupSelectionMap, List<Integer> selectionList) { boolean retValue = false; for (int i = groupSelectionMap.lastKey(); i >= 0; i--) { retValue = true; List<List<Integer>> groups = new ArrayList<>(groupSelectionMap.get(i)); for (List<Integer> grp : groups) { if (ListUtils.intersection(selectionList, grp).size() > 0) { retValue = false; } } if (retValue) { groupSelectionMap.get(i).add(selectionList); break; } } return retValue; }