List of usage examples for java.util TreeMap put
public V put(K key, V value)
From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java
public ApiResponse enterOrder(String type, CurrencyPair pair, double amount, double rate) { ApiResponse apiResponse = new ApiResponse(); String order_id = ""; String url = API_BASE_URL; String method = API_TRADE;/*from ww w . ja va2 s. c o m*/ boolean isGet = false; TreeMap<String, String> query_args = new TreeMap<>(); query_args.put("side", type.toLowerCase()); query_args.put("volume", Double.toString(amount)); query_args.put("price", Double.toString(rate)); query_args.put("market", pair.toString()); query_args.put("canonical_verb", "POST"); query_args.put("canonical_uri", method); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); if (httpAnswerJson.containsKey("id")) { order_id = httpAnswerJson.get("id").toString(); apiResponse.setResponseObject(order_id); } } else { apiResponse = response; } return apiResponse; }
From source file:edu.nyu.vida.data_polygamy.standard_techniques.CorrelationTechniquesReducer.java
@SuppressWarnings("unchecked") @Override/* w w w. j a v a2 s . c om*/ public void reduce(PairAttributeWritable key, Iterable<SpatioTemporalValueWritable> values, Context context) throws IOException, InterruptedException { resolutionHandler(key.getSpatialResolution(), key.getTemporalResolution()); int size = 0; switch (spatial) { case FrameworkUtils.NBHD: size = spatialGraph.nbNodes(); break; case FrameworkUtils.ZIP: size = zipGraph.nbNodes(); break; case FrameworkUtils.GRID: size = gridSize; break; case FrameworkUtils.CITY: size = 1; break; default: size = 1; break; } timeSeries = (ArrayList<TreeMap<Integer, Float>>[]) new ArrayList[size]; for (int i = 0; i < size; i++) { ArrayList<TreeMap<Integer, Float>> spatialTimeSeries = new ArrayList<TreeMap<Integer, Float>>(); spatialTimeSeries.add(new TreeMap<Integer, Float>()); // 0 spatialTimeSeries.add(new TreeMap<Integer, Float>()); // 1 timeSeries[i] = spatialTimeSeries; } // initializing some variables dataset1 = key.getFirstDataset(); dataset2 = key.getSecondDataset(); fileName = datasets.get(dataset1) + "-" + datasets.get(dataset2) + "/" + utils.temporalResolutionStr(key.getTemporalResolution()) + "-" + utils.spatialResolutionStr(key.getSpatialResolution()) + "/data"; Iterator<SpatioTemporalValueWritable> it = values.iterator(); SpatioTemporalValueWritable st; while (it.hasNext()) { st = it.next(); int dataset = st.getDataset(); int temporal = st.getTemporal(); int spatial = st.getSpatial(); float val = st.getValue(); int datasetKey = 0; if (dataset == dataset1) datasetKey = dataset1Key; else datasetKey = dataset2Key; TreeMap<Integer, Float> map = timeSeries[spatial].get(datasetKey); map.put(temporal, val); timeSeries[spatial].set(datasetKey, map); } double corr = 0; // Pearsons Correlations double mi = 0; // Mutual Information double dtw = 0; // DTW int count = 0; for (int i = 0; i < size; i++) { double[] tempValues = computeCorrelationTechniques(timeSeries, i, i, false); if (tempValues == null) continue; corr += tempValues[0]; mi += tempValues[1]; dtw += tempValues[2]; count++; } if (count == 0) return; corr = corr / count; mi = mi / count; dtw = dtw / count; /* * Monte Carlo Permutation Test */ double pValueCorr = 0; double pValueMI = 0; double pValueDTW = 0; ArrayList<Integer[]> pairs = new ArrayList<Integer[]>(); switch (spatial) { case FrameworkUtils.NBHD: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = bfsShift(true); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.ZIP: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = bfsShift(false); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.GRID: for (int j = 0; j < repetitions; j++) { double mcCorr = 0; pairs.clear(); pairs = toroidalShift(); count = 0; for (int i = 0; i < pairs.size(); i++) { Integer[] pair = pairs.get(i); double[] tempValues = computeCorrelationTechniques(timeSeries, pair[0], pair[1], false); if (tempValues == null) continue; corr += tempValues[0]; //mi += tempValues[1]; //dtw += tempValues[2]; count++; } mcCorr = (count == 0) ? 0 : mcCorr / count; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (pValueCorr > (alpha * repetitions)) break; // pruning } pValueCorr = pValueCorr / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; case FrameworkUtils.CITY: for (int j = 0; j < repetitions; j++) { double[] tempValues = computeCorrelationTechniques(timeSeries, 0, 0, true); double mcCorr = (tempValues == null) ? 0 : tempValues[0]; double mcMI = (tempValues == null) ? 0 : tempValues[1]; double mcDTW = (tempValues == null) ? 0 : tempValues[2]; if (corr > 0) { if (mcCorr >= corr) pValueCorr += 1; } else { if (mcCorr <= corr) pValueCorr += 1; } if (mcMI >= mi) pValueMI += 1; if (dtw > 0) { if (mcDTW >= dtw) pValueDTW += 1; } else { if (mcDTW <= dtw) pValueDTW += 1; } } pValueCorr = pValueCorr / ((double) (repetitions)); pValueMI = pValueMI / ((double) (repetitions)); pValueDTW = pValueDTW / ((double) (repetitions)); emitKeyValue(key, corr, mi, dtw, pValueCorr, pValueMI, pValueDTW); break; default: // do nothing break; } }
From source file:com.netflix.discovery.shared.Applications.java
/** * Populates the provided instance count map. The instance count map is used as part of the general * app list synchronization mechanism./*w w w. j a v a2 s. c om*/ * @param instanceCountMap the map to populate */ public void populateInstanceCountMap(TreeMap<String, AtomicInteger> instanceCountMap) { for (Application app : this.getRegisteredApplications()) { for (InstanceInfo info : app.getInstancesAsIsFromEureka()) { AtomicInteger instanceCount = instanceCountMap.get(info.getStatus().name()); if (instanceCount == null) { instanceCount = new AtomicInteger(0); instanceCountMap.put(info.getStatus().name(), instanceCount); } instanceCount.incrementAndGet(); } } }
From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java
@Override public ApiResponse getOrderDetail(String orderID) { ApiResponse apiResponse = new ApiResponse(); Order order = null;/*from ww w. j a va 2 s .co m*/ String url = API_BASE_URL; String method = API_ORDER; boolean isGet = true; TreeMap<String, String> query_args = new TreeMap<>(); query_args.put("canonical_verb", "GET"); query_args.put("canonical_uri", "/api/v2/order"); query_args.put("id", orderID); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); if (httpAnswerJson.containsKey("error")) { JSONObject error = (JSONObject) httpAnswerJson.get("error"); int code = ~(Integer) error.get("code"); String msg = error.get("message").toString(); apiResponse.setError(new ApiError(code, msg)); return apiResponse; } /*Sample result * {"id":7,"side":"sell","price":"3100.0","avg_price":"3101.2","state":"wait","market":"btccny","created_at":"2014-04-18T02:02:33Z","volume":"100.0","remaining_volume":"89.8","executed_volume":"10.2","trades":[{"id":2,"price":"3100.0","volume":"10.2","market":"btccny","created_at":"2014-04-18T02:04:49Z","side":"sell"}]} */ apiResponse.setResponseObject(parseOrder(httpAnswerJson)); } else { apiResponse = response; } return apiResponse; }
From source file:edu.utexas.cs.tactex.utilityestimation.UtilityEstimatorDefaultForConsumption.java
@Override public TreeMap<Double, TariffSpecification> estimateRevokeUtilities( List<TariffSpecification> consideredTariffActions, HashMap<TariffSpecification, HashMap<CustomerInfo, Integer>> tariffSubscriptions, List<TariffSpecification> competingTariffs, HashMap<CustomerInfo, HashMap<TariffSpecification, Double>> customer2RelevantTariffCharges, HashMap<CustomerInfo, HashMap<TariffSpecification, ShiftedEnergyData>> customer2ShiftedEnergy, HashMap<CustomerInfo, ArrayRealVector> customer2NonShiftedEnergy, MarketPredictionManager marketPredictionManager, CostCurvesPredictor costCurvesPredictor, int currentTimeslot, Broker me) { TreeMap<Double, TariffSpecification> utility2spec = new TreeMap<Double, TariffSpecification>(); // all possible tariff actions: {suggestedSpeces} U {no-op} // a value of null means no-op for (TariffSpecification spec : consideredTariffActions) { double utility = predictRevokeUtility(spec, customer2RelevantTariffCharges, tariffSubscriptions, competingTariffs, currentTimeslot, customer2ShiftedEnergy, customer2NonShiftedEnergy, marketPredictionManager, costCurvesPredictor); utility2spec.put(utility + revokeFee(spec), spec); }/* w ww . j a v a 2s . c o m*/ return utility2spec; }
From source file:cc.slda.DisplayTopic.java
@SuppressWarnings("unchecked") public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(Settings.HELP_OPTION, false, "print the help message"); options.addOption(OptionBuilder.withArgName(Settings.PATH_INDICATOR).hasArg() .withDescription("input beta file").create(Settings.INPUT_OPTION)); options.addOption(OptionBuilder.withArgName(Settings.PATH_INDICATOR).hasArg() .withDescription("term index file").create(ParseCorpus.INDEX)); options.addOption(OptionBuilder.withArgName(Settings.INTEGER_INDICATOR).hasArg() .withDescription("display top terms only (default - 10)").create(TOP_DISPLAY_OPTION)); String betaString = null;//w w w .j a v a 2 s. co m String indexString = null; int topDisplay = TOP_DISPLAY; CommandLineParser parser = new GnuParser(); HelpFormatter formatter = new HelpFormatter(); try { CommandLine line = parser.parse(options, args); if (line.hasOption(Settings.HELP_OPTION)) { formatter.printHelp(ParseCorpus.class.getName(), options); System.exit(0); } if (line.hasOption(Settings.INPUT_OPTION)) { betaString = line.getOptionValue(Settings.INPUT_OPTION); } else { throw new ParseException("Parsing failed due to " + Settings.INPUT_OPTION + " not initialized..."); } if (line.hasOption(ParseCorpus.INDEX)) { indexString = line.getOptionValue(ParseCorpus.INDEX); } else { throw new ParseException("Parsing failed due to " + ParseCorpus.INDEX + " not initialized..."); } if (line.hasOption(TOP_DISPLAY_OPTION)) { topDisplay = Integer.parseInt(line.getOptionValue(TOP_DISPLAY_OPTION)); } } catch (ParseException pe) { System.err.println(pe.getMessage()); formatter.printHelp(ParseCorpus.class.getName(), options); System.exit(0); } catch (NumberFormatException nfe) { System.err.println(nfe.getMessage()); System.exit(0); } JobConf conf = new JobConf(DisplayTopic.class); FileSystem fs = FileSystem.get(conf); Path indexPath = new Path(indexString); Preconditions.checkArgument(fs.exists(indexPath) && fs.isFile(indexPath), "Invalid index path..."); Path betaPath = new Path(betaString); Preconditions.checkArgument(fs.exists(betaPath) && fs.isFile(betaPath), "Invalid beta path..."); SequenceFile.Reader sequenceFileReader = null; try { IntWritable intWritable = new IntWritable(); Text text = new Text(); Map<Integer, String> termIndex = new HashMap<Integer, String>(); sequenceFileReader = new SequenceFile.Reader(fs, indexPath, conf); while (sequenceFileReader.next(intWritable, text)) { termIndex.put(intWritable.get(), text.toString()); } PairOfIntFloat pairOfIntFloat = new PairOfIntFloat(); // HMapIFW hmap = new HMapIFW(); HMapIDW hmap = new HMapIDW(); TreeMap<Double, Integer> treeMap = new TreeMap<Double, Integer>(); sequenceFileReader = new SequenceFile.Reader(fs, betaPath, conf); while (sequenceFileReader.next(pairOfIntFloat, hmap)) { treeMap.clear(); System.out.println("=============================="); System.out.println( "Top ranked " + topDisplay + " terms for Topic " + pairOfIntFloat.getLeftElement()); System.out.println("=============================="); Iterator<Integer> itr1 = hmap.keySet().iterator(); int temp1 = 0; while (itr1.hasNext()) { temp1 = itr1.next(); treeMap.put(-hmap.get(temp1), temp1); if (treeMap.size() > topDisplay) { treeMap.remove(treeMap.lastKey()); } } Iterator<Double> itr2 = treeMap.keySet().iterator(); double temp2 = 0; while (itr2.hasNext()) { temp2 = itr2.next(); if (termIndex.containsKey(treeMap.get(temp2))) { System.out.println(termIndex.get(treeMap.get(temp2)) + "\t\t" + -temp2); } else { System.out.println("How embarrassing! Term index not found..."); } } } } finally { IOUtils.closeStream(sequenceFileReader); } return 0; }
From source file:com.nubits.nubot.trading.wrappers.BitSparkWrapper.java
@Override public ApiResponse cancelOrder(String orderID, CurrencyPair pair) { ApiResponse apiResponse = new ApiResponse(); String url = API_BASE_URL; String method = API_CANCEL_ORDER; boolean isGet = false; TreeMap<String, String> query_args = new TreeMap<>(); query_args.put("id", orderID); query_args.put("canonical_verb", "POST"); query_args.put("canonical_uri", method); ApiResponse response = getQuery(url, method, query_args, true, isGet); if (response.isPositive()) { JSONObject httpAnswerJson = (JSONObject) response.getResponseObject(); if (httpAnswerJson.containsKey("error")) { JSONObject error = (JSONObject) httpAnswerJson.get("error"); int code = (Integer) error.get("code"); String msg = error.get("message").toString(); apiResponse.setError(new ApiError(code, msg)); return apiResponse; }/*from ww w.ja v a2 s.co m*/ /*Sample result * Cancel order is an asynchronous operation. A success response only means your cancel * request has been accepted, it doesn't mean the order has been cancelled. * You should always use /api/v2/order or websocket api to get order's latest state. */ apiResponse.setResponseObject(true); } else { apiResponse = response; } return apiResponse; }
From source file:org.apache.storm.metricstore.rocksdb.RocksDbMetricsWriter.java
@Override public void close() { this.shutdown = true; // get all metadata from the cache to put into the database TreeMap<RocksDbKey, RocksDbValue> batchMap = new TreeMap<>(); // use a new map to prevent threading issues with writer thread for (Map.Entry entry : stringMetadataCache.entrySet()) { String metadataString = (String) entry.getKey(); StringMetadata val = (StringMetadata) entry.getValue(); RocksDbValue rval = new RocksDbValue(val.getLastTimestamp(), metadataString); for (KeyType type : val.getMetadataTypes()) { // save the metadata for all types of strings it matches RocksDbKey rkey = new RocksDbKey(type, val.getStringId()); batchMap.put(rkey, rval); }/*from www.j a va 2 s. c o m*/ } try { processBatchInsert(batchMap); } catch (MetricException e) { LOG.error("Failed to insert all metadata", e); } // flush db to disk try (FlushOptions flushOps = new FlushOptions()) { flushOps.setWaitForFlush(true); store.db.flush(flushOps); } catch (RocksDBException e) { LOG.error("Failed ot flush RocksDB", e); if (this.failureMeter != null) { this.failureMeter.mark(); } } }
From source file:com.sfs.whichdoctor.dao.WhichDoctorDAOImpl.java
/** * Load siblings./*ww w .j a v a2 s . co m*/ * * @param guid the GUID of the object * @param type the ObjectType of the object * * @return TreeMap containing sibling details for the identified object * * @throws WhichDoctorDaoException the which doctor dao exception */ public final TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>> loadSiblings(final int guid, final String type) throws WhichDoctorDaoException { if (type == null) { throw new NullPointerException("The type parameter cannot be null"); } dataLogger.info("History of GUID: " + guid + " requested"); // Load siblings TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>> siblings = new TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>>(); TreeMap<Integer, Collection<WhichDoctorBean>> memos = loadSiblingBeans(guid, "memo"); siblings.put("Memos", memos); if (type.compareToIgnoreCase("person") == 0 || type.compareToIgnoreCase("organisation") == 0) { siblings.put("Addresses", loadSiblingBeans(guid, "address")); siblings.put("Phone Numbers", loadSiblingBeans(guid, "phone")); siblings.put("Email Addresses", loadSiblingBeans(guid, "email")); siblings.put("Specialties", loadSiblingBeans(guid, "specialty")); } if (type.compareToIgnoreCase("person") == 0) { siblings.put("Membership", loadSiblingBeans(guid, "membership")); siblings.put("Workshops", loadSiblingBeans(guid, "workshop")); siblings.put("Rotations", loadSiblingBeans(guid, "rotation")); siblings.put("Projects", loadSiblingBeans(guid, "project")); siblings.put("Exams", loadSiblingBeans(guid, "exam")); siblings.put("Qualifications", loadSiblingBeans(guid, "qualification")); } if (type.compareToIgnoreCase("rotation") == 0) { siblings.put("Assessments", loadSiblingBeans(guid, "assessment")); siblings.put("Reports", loadSiblingBeans(guid, "report")); siblings.put("Accreditations", loadSiblingBeans(guid, "accreditation")); } if (type.compareToIgnoreCase("reimbursement") == 0) { siblings.put("Expense Claims", loadSiblingBeans(guid, "expenseclaim")); } if (type.compareToIgnoreCase("receipt") == 0) { siblings.put("Payments", loadSiblingBeans(guid, "payment")); } return siblings; }
From source file:com.simiacryptus.mindseye.models.Hdf5Archive.java
/** * Gets attributes./* www . j av a 2 s . c o m*/ * * @param group the group * @return the attributes */ @Nonnull public Map<CharSequence, Object> getAttributes(@Nonnull Group group) { int numAttrs = group.getNumAttrs(); @Nonnull TreeMap<CharSequence, Object> attributes = new TreeMap<>(); for (int i = 0; i < numAttrs; i++) { Attribute attribute = group.openAttribute(i); CharSequence name = attribute.getName().getString(); int typeId = attribute.getTypeClass(); if (typeId == 0) { attributes.put(name, getI64(attribute)); } else { System.out.println(name + " type = " + typeId); attributes.put(name, getString(attribute)); } attribute.deallocate(); } return attributes; }