List of usage examples for java.util SortedMap entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:com.cloudera.oryx.als.common.candidate.LocationSensitiveHashIT.java
private static List<Long> findTopRecommendations(LongObjectMap<float[]> Y, float[] userVec) { SortedMap<Double, Long> allScores = new TreeMap<>(Collections.reverseOrder()); for (LongObjectMap.MapEntry<float[]> entry : Y.entrySet()) { double dot = SimpleVectorMath.dot(entry.getValue(), userVec); allScores.put(dot, entry.getKey()); }// w w w. ja v a 2s . c om List<Long> topRecommendations = new ArrayList<>(); for (Map.Entry<Double, Long> entry : allScores.entrySet()) { topRecommendations.add(entry.getValue()); if (topRecommendations.size() == NUM_RECS) { return topRecommendations; } } return topRecommendations; }
From source file:net.myrrix.online.candidate.LocationSensitiveHashTest.java
private static List<Long> findTopRecommendations(FastByIDMap<float[]> Y, float[] userVec) { SortedMap<Double, Long> allScores = Maps.newTreeMap(Collections.reverseOrder()); for (FastByIDMap.MapEntry<float[]> entry : Y.entrySet()) { double dot = SimpleVectorMath.dot(entry.getValue(), userVec); allScores.put(dot, entry.getKey()); }/*from ww w.j ava2 s . co m*/ List<Long> topRecommendations = Lists.newArrayList(); for (Map.Entry<Double, Long> entry : allScores.entrySet()) { topRecommendations.add(entry.getValue()); if (topRecommendations.size() == NUM_RECS) { return topRecommendations; } } return topRecommendations; }
From source file:com.cloudera.oryx.als.common.lsh.LocationSensitiveHashIT.java
private static List<Long> findTopRecommendations(LongObjectMap<float[]> Y, float[] userVec) { SortedMap<Double, Long> allScores = Maps.newTreeMap(Collections.reverseOrder()); for (LongObjectMap.MapEntry<float[]> entry : Y.entrySet()) { double dot = SimpleVectorMath.dot(entry.getValue(), userVec); allScores.put(dot, entry.getKey()); }/*from ww w .j av a2 s . c o m*/ List<Long> topRecommendations = Lists.newArrayList(); for (Map.Entry<Double, Long> entry : allScores.entrySet()) { topRecommendations.add(entry.getValue()); if (topRecommendations.size() == NUM_RECS) { return topRecommendations; } } return topRecommendations; }
From source file:co.cask.cdap.data.tools.ReplicationStatusTool.java
private static void dumpClusterChecksums() throws IOException { System.out.println("\nThis is all the File Checksums on the Cluster:"); SortedMap<String, String> checksumMap = getClusterChecksumMap(); for (Map.Entry<String, String> checksumEntry : checksumMap.entrySet()) { System.out.println("File:" + checksumEntry.getKey() + " Checksum:" + checksumEntry.getValue()); }//from ww w .j a v a 2s. com }
From source file:org.matsim.contrib.common.stats.StatsWriter.java
/** * Writes a table with columns map-key and statistical indicators mean, median, min, max and number of samples. Rows * are sorted according to the natural order of the map key. * * @param statsMap a map with {@code DescriptiveStatistics} objects * @param filename the filename//from w w w . j av a2 s .c om * @throws IOException */ public static void writeStatistics(Map<String, DescriptiveStatistics> statsMap, String filename) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("property"); writer.write(TAB); writer.write("mean"); writer.write(TAB); writer.write("median"); writer.write(TAB); writer.write("min"); writer.write(TAB); writer.write("max"); writer.write(TAB); writer.write("n"); writer.newLine(); writer.newLine(); SortedMap<String, DescriptiveStatistics> sortedMap = new TreeMap<>(statsMap); for (Entry<String, DescriptiveStatistics> entry : sortedMap.entrySet()) { writer.write(entry.getKey()); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getMean())); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getPercentile(50))); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getMin())); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getMax())); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getN())); writer.write("\t"); writer.write(String.valueOf(entry.getValue().getVariance())); writer.newLine(); } writer.close(); }
From source file:org.apache.accumulo.server.fs.VolumeUtil.java
/** * This method does two things. First, it switches any volumes a tablet is using that are configured in instance.volumes.replacements. Second, if a tablet dir * is no longer configured for use it chooses a new tablet directory. */// w ww . j a v a 2s. c om public static TabletFiles updateTabletVolumes(AccumuloServerContext context, ZooLock zooLock, VolumeManager vm, KeyExtent extent, TabletFiles tabletFiles, boolean replicate) throws IOException { List<Pair<Path, Path>> replacements = ServerConstants.getVolumeReplacements(); log.trace("Using volume replacements: " + replacements); List<LogEntry> logsToRemove = new ArrayList<LogEntry>(); List<LogEntry> logsToAdd = new ArrayList<LogEntry>(); List<FileRef> filesToRemove = new ArrayList<FileRef>(); SortedMap<FileRef, DataFileValue> filesToAdd = new TreeMap<FileRef, DataFileValue>(); TabletFiles ret = new TabletFiles(); for (LogEntry logEntry : tabletFiles.logEntries) { LogEntry switchedLogEntry = switchVolumes(logEntry, replacements); if (switchedLogEntry != null) { logsToRemove.add(logEntry); logsToAdd.add(switchedLogEntry); ret.logEntries.add(switchedLogEntry); log.debug("Replacing volume " + extent + " : " + logEntry.filename + " -> " + switchedLogEntry.filename); } else { ret.logEntries.add(logEntry); } } if (extent.isRootTablet()) { ret.datafiles = tabletFiles.datafiles; } else { for (Entry<FileRef, DataFileValue> entry : tabletFiles.datafiles.entrySet()) { String metaPath = entry.getKey().meta().toString(); String switchedPath = switchVolume(metaPath, FileType.TABLE, replacements); if (switchedPath != null) { filesToRemove.add(entry.getKey()); FileRef switchedRef = new FileRef(switchedPath, new Path(switchedPath)); filesToAdd.put(switchedRef, entry.getValue()); ret.datafiles.put(switchedRef, entry.getValue()); log.debug("Replacing volume " + extent + " : " + metaPath + " -> " + switchedPath); } else { ret.datafiles.put(entry.getKey(), entry.getValue()); } } } String tabletDir = tabletFiles.dir; String switchedDir = switchVolume(tabletDir, FileType.TABLE, replacements); if (switchedDir != null) { log.debug("Replacing volume " + extent + " : " + tabletDir + " -> " + switchedDir); tabletDir = switchedDir; } if (logsToRemove.size() + filesToRemove.size() > 0 || switchedDir != null) { MetadataTableUtil.updateTabletVolumes(extent, logsToRemove, logsToAdd, filesToRemove, filesToAdd, switchedDir, zooLock, context); if (replicate) { Status status = StatusUtil.fileClosed(); log.debug("Tablet directory switched, need to record old log files " + logsToRemove + " " + ProtobufUtil.toString(status)); // Before deleting these logs, we need to mark them for replication for (LogEntry logEntry : logsToRemove) { ReplicationTableUtil.updateFiles(context, extent, logEntry.filename, status); } } } ret.dir = decommisionedTabletDir(context, zooLock, vm, extent, tabletDir); if (extent.isRootTablet()) { SortedMap<FileRef, DataFileValue> copy = ret.datafiles; ret.datafiles = new TreeMap<>(); for (Entry<FileRef, DataFileValue> entry : copy.entrySet()) { ret.datafiles.put(new FileRef(new Path(ret.dir, entry.getKey().path().getName()).toString()), entry.getValue()); } } // method this should return the exact strings that are in the metadata table return ret; }
From source file:com.zimbra.cs.mailbox.Metadata.java
private static StringBuilder prettyEncode(StringBuilder sb, Object object, int indentLevel) { if (object instanceof Map) { SortedMap<?, ?> tree = object instanceof SortedMap ? (SortedMap<?, ?>) object : new TreeMap<Object, Object>((Map<?, ?>) object); sb.append("{\n"); for (Map.Entry<?, ?> entry : tree.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { appendIndent(sb, indentLevel + 1); sb.append(entry.getKey()).append(" = "); prettyEncode(sb, entry.getValue(), indentLevel + 1); }/* ww w .ja va 2s. co m*/ } appendIndent(sb, indentLevel); sb.append("}\n"); } else if (object instanceof List) { sb.append("[\n"); for (Object value : ((List<?>) object)) { if (value != null) { appendIndent(sb, indentLevel + 1); prettyEncode(sb, value, indentLevel + 1); } } appendIndent(sb, indentLevel); sb.append("]\n"); } else if (object instanceof Long || object instanceof Integer || object instanceof Short || object instanceof Byte) { sb.append(object).append("\n"); } else if (object != null) { sb.append(object.toString()).append("\n"); } return sb; }
From source file:org.openlaszlo.sc.ScriptCompiler.java
/** Writes a LaszloScript object literal whose properties are the * keys of the map and whose property values are the LaszloScript * representations of the map's values./* ww w . ja v a 2 s.co m*/ * * The elements of the map are strings that represent JavaScript * expressions, not values. That is, the value "foo" will compile * to a reference to the variable named foo; "'foo'" or "\"foo\"" * is necessary to enter a string in the map. * * @param map String -> Object * @param writer an appendable * @return a string */ private static <V> void writeMap(Map<String, Object> map, Appendable writer) throws IOException { writer.append("{"); // Sort the keys, so that regression tests aren't sensitive to // the undefined order of iterating a (non-TreeMap) Map. SortedMap<String, Object> smap = new TreeMap<String, Object>(map); for (Iterator<Map.Entry<String, Object>> iter = smap.entrySet().iterator(); iter.hasNext();) { Map.Entry<String, Object> entry = iter.next(); String key = entry.getKey(); Object value = entry.getValue(); if (!isIdentifier(key)) key = quote(key); writer.append(key).append(": "); writeObject(value, writer); if (iter.hasNext()) { writer.append(", "); } } writer.append("}"); }
From source file:org.runnerup.export.format.RunKeeper.java
public static ActivityEntity parseToActivity(JSONObject response, double unitMeters) throws JSONException { ActivityEntity newActivity = new ActivityEntity(); newActivity.setSport(RunKeeperSynchronizer.runkeeper2sportMap.get(response.getString("type")).getDbValue()); if (response.has("notes")) { newActivity.setComment(response.getString("notes")); }// w w w .j ava2 s . c o m newActivity.setTime((long) Float.parseFloat(response.getString("duration"))); newActivity.setDistance(Float.parseFloat(response.getString("total_distance"))); String startTime = response.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { newActivity.setStartTime(format.parse(startTime)); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } List<LapEntity> laps = new ArrayList<LapEntity>(); List<LocationEntity> locations = new ArrayList<LocationEntity>(); JSONArray distance = response.getJSONArray("distance"); JSONArray path = response.getJSONArray("path"); JSONArray hr = response.getJSONArray("heart_rate"); SortedMap<Long, HashMap<String, String>> pointsValueMap = createPointsMap(distance, path, hr); Iterator<Map.Entry<Long, HashMap<String, String>>> points = pointsValueMap.entrySet().iterator(); //lap hr int maxHr = 0; int sumHr = 0; int count = 0; //point speed long time = 0; float meters = 0.0f; //activity hr int maxHrOverall = 0; int sumHrOverall = 0; int countOverall = 0; while (points.hasNext()) { Map.Entry<Long, HashMap<String, String>> timePoint = points.next(); HashMap<String, String> values = timePoint.getValue(); LocationEntity lv = new LocationEntity(); lv.setActivityId(newActivity.getId()); lv.setTime(TimeUnit.SECONDS.toMillis(newActivity.getStartTime()) + timePoint.getKey()); String dist = values.get("distance"); if (dist == null) { continue; } String lat = values.get("latitude"); String lon = values.get("longitude"); String alt = values.get("altitude"); String heart = values.get("heart_rate"); String type = values.get("type"); if (lat == null || lon == null) { continue; } else { lv.setLatitude(Double.valueOf(lat)); lv.setLongitude(Double.valueOf(lon)); } if (alt != null) { lv.setAltitude(Double.valueOf(alt)); } if (pointsValueMap.firstKey().equals(timePoint.getKey())) { lv.setType(DB.LOCATION.TYPE_START); } else if (!points.hasNext()) { lv.setType(DB.LOCATION.TYPE_END); } else if (type != null) { lv.setType(RunKeeperSynchronizer.POINT_TYPE.get(type)); } // lap and activity max and avg hr if (heart != null) { lv.setHr(Integer.valueOf(heart)); maxHr = Math.max(maxHr, lv.getHr()); maxHrOverall = Math.max(maxHrOverall, lv.getHr()); sumHr += lv.getHr(); sumHrOverall += lv.getHr(); count++; countOverall++; } meters = Float.valueOf(dist) - meters; time = timePoint.getKey() - time; if (time > 0) { float speed = meters / (float) TimeUnit.MILLISECONDS.toSeconds(time); BigDecimal s = new BigDecimal(speed); s = s.setScale(2, BigDecimal.ROUND_UP); lv.setSpeed(s.floatValue()); } // create lap if distance greater than configured lap distance if (Float.valueOf(dist) >= unitMeters * laps.size()) { LapEntity newLap = new LapEntity(); newLap.setLap(laps.size()); newLap.setDistance(Float.valueOf(dist)); newLap.setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey())); newLap.setActivityId(newActivity.getId()); laps.add(newLap); // update previous lap with duration and distance if (laps.size() > 1) { LapEntity previousLap = laps.get(laps.size() - 2); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap.setTime( (int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } maxHr = 0; sumHr = 0; count = 0; } } // update last lap with duration and distance if (!points.hasNext()) { LapEntity previousLap = laps.get(laps.size() - 1); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap .setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } } lv.setLap(laps.size() - 1); locations.add(lv); } // calculate avg and max hr // update the activity newActivity.setMaxHr(maxHrOverall); if (countOverall > 0) { newActivity.setAvgHr(sumHrOverall / countOverall); } newActivity.putPoints(locations); newActivity.putLaps(laps); return newActivity; }
From source file:org.wso2.extension.siddhi.store.rdbms.util.RDBMSTableUtils.java
/** * Util method used throughout the RDBMS Event Table implementation which accepts a compiled condition (from * compile-time) and uses values from the runtime to populate the given {@link PreparedStatement}. * * @param stmt the {@link PreparedStatement} instance which has already been build with '?' * parameters to be filled. * @param compiledCondition the compiled condition which was built during compile time and now is being provided * by the Siddhi runtime. * @param conditionParameterMap the map which contains the runtime value(s) for the condition. * @param seed the integer factor by which the ordinal count will be incremented when populating * the {@link PreparedStatement}. * @throws SQLException in the unlikely case where there are errors when setting values to the statement * (e.g. type mismatches) *//*from ww w.ja v a 2 s . c o m*/ public static void resolveCondition(PreparedStatement stmt, RDBMSCompiledCondition compiledCondition, Map<String, Object> conditionParameterMap, int seed) throws SQLException { SortedMap<Integer, Object> parameters = compiledCondition.getParameters(); for (Map.Entry<Integer, Object> entry : parameters.entrySet()) { Object parameter = entry.getValue(); if (parameter instanceof Constant) { Constant constant = (Constant) parameter; populateStatementWithSingleElement(stmt, seed + entry.getKey(), constant.getType(), constant.getValue()); } else { Attribute variable = (Attribute) parameter; populateStatementWithSingleElement(stmt, seed + entry.getKey(), variable.getType(), conditionParameterMap.get(variable.getName())); } } }