List of usage examples for java.util TreeMap size
int size
To view the source code for java.util TreeMap size.
Click Source Link
From source file:com.joliciel.talismane.posTagger.PosTaggerImpl.java
@Override public List<PosTagSequence> tagSentence(List<TokenSequence> tokenSequences) { MONITOR.startTask("tagSentence"); try {//from w w w .j av a2s . c o m MONITOR.startTask("apply filters"); try { for (TokenSequence tokenSequence : tokenSequences) { for (TokenSequenceFilter tokenFilter : this.preProcessingFilters) { tokenFilter.apply(tokenSequence); } } } finally { MONITOR.endTask("apply filters"); } int sentenceLength = tokenSequences.get(0).getText().length(); TreeMap<Double, PriorityQueue<PosTagSequence>> heaps = new TreeMap<Double, PriorityQueue<PosTagSequence>>(); PriorityQueue<PosTagSequence> heap0 = new PriorityQueue<PosTagSequence>(); for (TokenSequence tokenSequence : tokenSequences) { // add an empty PosTagSequence for each token sequence PosTagSequence emptySequence = this.getPosTaggerService().getPosTagSequence(tokenSequence, 0); emptySequence.setScoringStrategy(decisionMaker.getDefaultScoringStrategy()); heap0.add(emptySequence); } heaps.put(0.0, heap0); PriorityQueue<PosTagSequence> finalHeap = null; while (heaps.size() > 0) { Entry<Double, PriorityQueue<PosTagSequence>> heapEntry = heaps.pollFirstEntry(); if (LOG.isTraceEnabled()) { LOG.trace("heap key: " + heapEntry.getKey() + ", sentence length: " + sentenceLength); } if (heapEntry.getKey() == sentenceLength) { finalHeap = heapEntry.getValue(); break; } PriorityQueue<PosTagSequence> previousHeap = heapEntry.getValue(); // limit the breadth to K int maxSequences = previousHeap.size() > this.beamWidth ? this.beamWidth : previousHeap.size(); for (int j = 0; j < maxSequences; j++) { PosTagSequence history = previousHeap.poll(); Token token = history.getNextToken(); if (LOG.isTraceEnabled()) { LOG.trace("#### Next history ( " + heapEntry.getKey() + "): " + history.toString()); LOG.trace("Prob: " + df.format(history.getScore())); LOG.trace("Token: " + token.getText()); StringBuilder sb = new StringBuilder(); for (Token oneToken : history.getTokenSequence().listWithWhiteSpace()) { if (oneToken.equals(token)) sb.append("[" + oneToken + "]"); else sb.append(oneToken); } LOG.trace(sb.toString()); } PosTaggerContext context = this.getPosTaggerFeatureService().getContext(token, history); List<Decision<PosTag>> decisions = new ArrayList<Decision<PosTag>>(); // test the positive rules on the current token boolean ruleApplied = false; if (posTaggerPositiveRules != null) { MONITOR.startTask("check rules"); try { for (PosTaggerRule rule : posTaggerPositiveRules) { if (LOG.isTraceEnabled()) { LOG.trace("Checking rule: " + rule.getCondition().getName()); } RuntimeEnvironment env = this.featureService.getRuntimeEnvironment(); FeatureResult<Boolean> ruleResult = rule.getCondition().check(context, env); if (ruleResult != null && ruleResult.getOutcome()) { Decision<PosTag> positiveRuleDecision = TalismaneSession.getPosTagSet() .createDefaultDecision(rule.getTag()); decisions.add(positiveRuleDecision); positiveRuleDecision.addAuthority(rule.getCondition().getName()); ruleApplied = true; if (LOG.isTraceEnabled()) { LOG.trace("Rule applies. Setting posTag to: " + rule.getTag().getCode()); } break; } } } finally { MONITOR.endTask("check rules"); } } if (!ruleApplied) { // test the features on the current token List<FeatureResult<?>> featureResults = new ArrayList<FeatureResult<?>>(); MONITOR.startTask("analyse features"); try { for (PosTaggerFeature<?> posTaggerFeature : posTaggerFeatures) { MONITOR.startTask(posTaggerFeature.getCollectionName()); try { RuntimeEnvironment env = this.featureService.getRuntimeEnvironment(); FeatureResult<?> featureResult = posTaggerFeature.check(context, env); if (featureResult != null) featureResults.add(featureResult); } finally { MONITOR.endTask(posTaggerFeature.getCollectionName()); } } if (LOG.isTraceEnabled()) { for (FeatureResult<?> result : featureResults) { LOG.trace(result.toString()); } } } finally { MONITOR.endTask("analyse features"); } // evaluate the feature results using the maxent model MONITOR.startTask("make decision"); decisions = this.decisionMaker.decide(featureResults); MONITOR.endTask("make decision"); for (ClassificationObserver<PosTag> observer : this.observers) { observer.onAnalyse(token, featureResults, decisions); } // apply the negative rules Set<PosTag> eliminatedPosTags = new TreeSet<PosTag>(); if (posTaggerNegativeRules != null) { MONITOR.startTask("check negative rules"); try { for (PosTaggerRule rule : posTaggerNegativeRules) { if (LOG.isTraceEnabled()) { LOG.trace("Checking negative rule: " + rule.getCondition().getName()); } RuntimeEnvironment env = this.featureService.getRuntimeEnvironment(); FeatureResult<Boolean> ruleResult = rule.getCondition().check(context, env); if (ruleResult != null && ruleResult.getOutcome()) { eliminatedPosTags.add(rule.getTag()); if (LOG.isTraceEnabled()) { LOG.trace( "Rule applies. Eliminating posTag: " + rule.getTag().getCode()); } } } if (eliminatedPosTags.size() > 0) { List<Decision<PosTag>> decisionShortList = new ArrayList<Decision<PosTag>>(); for (Decision<PosTag> decision : decisions) { if (!eliminatedPosTags.contains(decision.getOutcome())) { decisionShortList.add(decision); } else { LOG.trace("Eliminating decision: " + decision.toString()); } } if (decisionShortList.size() > 0) { decisions = decisionShortList; } else { LOG.debug("All decisions eliminated! Restoring original decisions."); } } } finally { MONITOR.endTask("check negative rules"); } } // is this a known word in the lexicon? MONITOR.startTask("apply constraints"); try { if (LOG.isTraceEnabled()) { String posTags = ""; for (PosTag onePosTag : token.getPossiblePosTags()) { posTags += onePosTag.getCode() + ","; } LOG.trace("Token: " + token.getText() + ". PosTags: " + posTags); } List<Decision<PosTag>> decisionShortList = new ArrayList<Decision<PosTag>>(); for (Decision<PosTag> decision : decisions) { if (decision.getProbability() >= MIN_PROB_TO_STORE) { decisionShortList.add(decision); } } if (decisionShortList.size() > 0) { decisions = decisionShortList; } } finally { MONITOR.endTask("apply constraints"); } } // has a rule been applied? // add new TaggedTokenSequences to the heap, one for each outcome provided by MaxEnt MONITOR.startTask("heap sort"); for (Decision<PosTag> decision : decisions) { if (LOG.isTraceEnabled()) LOG.trace("Outcome: " + decision.getOutcome() + ", " + decision.getProbability()); PosTaggedToken posTaggedToken = this.getPosTaggerService().getPosTaggedToken(token, decision); PosTagSequence sequence = this.getPosTaggerService().getPosTagSequence(history); sequence.addPosTaggedToken(posTaggedToken); if (decision.isStatistical()) sequence.addDecision(decision); double heapIndex = token.getEndIndex(); // add another half for an empty token, to differentiate it from regular ones if (token.getStartIndex() == token.getEndIndex()) heapIndex += 0.5; // if it's the last token, make sure we end if (token.getIndex() == sequence.getTokenSequence().size() - 1) heapIndex = sentenceLength; if (LOG.isTraceEnabled()) LOG.trace("Heap index: " + heapIndex); PriorityQueue<PosTagSequence> heap = heaps.get(heapIndex); if (heap == null) { heap = new PriorityQueue<PosTagSequence>(); heaps.put(heapIndex, heap); } heap.add(sequence); } // next outcome for this token MONITOR.endTask("heap sort"); } // next history } // next atomic index // return the best sequence on the heap List<PosTagSequence> sequences = new ArrayList<PosTagSequence>(); int i = 0; while (!finalHeap.isEmpty()) { sequences.add(finalHeap.poll()); i++; if (i >= this.getBeamWidth()) break; } // apply post-processing filters LOG.debug("####Final postag sequences:"); int j = 1; for (PosTagSequence sequence : sequences) { if (LOG.isDebugEnabled()) { LOG.debug("Sequence " + (j++) + ", score=" + df.format(sequence.getScore())); LOG.debug("Sequence before filters: " + sequence); } for (PosTagSequenceFilter filter : this.postProcessingFilters) filter.apply(sequence); if (LOG.isDebugEnabled()) { LOG.debug("Sequence after filters: " + sequence); } } return sequences; } finally { MONITOR.endTask("tagSentence"); } }
From source file:au.org.ala.layers.web.TabulationService.java
private String[][] tabulationGridGenerator(List<Tabulation> tabulations, String fid1, String fid2, String wkt, String func) throws IOException { //determine x & y field names TreeMap<String, String> objects1 = new TreeMap<String, String>(); TreeMap<String, String> objects2 = new TreeMap<String, String>(); for (Tabulation t : tabulations) { objects1.put(t.getPid1(), t.getName1()); objects2.put(t.getPid2(), t.getName2()); }// w ww .j a va2s . c om int rows = Math.max(objects1.size(), objects2.size()); int columns = Math.min(objects1.size(), objects2.size()); String[][] grid = new String[rows + 1][columns + 1]; //populate grid if (objects1.size() <= objects2.size()) { //row and column sort order and labels TreeMap<String, Integer> order1 = new TreeMap<String, Integer>(); TreeMap<String, Integer> order2 = new TreeMap<String, Integer>(); int pos = 0; for (String s : objects1.keySet()) { order1.put(s, pos++); grid[0][pos] = objects1.get(s); } pos = 0; for (String s : objects2.keySet()) { order2.put(s, pos++); grid[pos][0] = objects2.get(s); } //grid for (Tabulation t : tabulations) { if (func.equals("area") || func.equals("arearow") || func.equals("areacolumn") || func.equals("areatotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String.format("%.1f", t.getArea() / 1000000.0); //convert sqm to sqkm } else if (func.equals("occurrences") || func.equals("occurrencesrow") || func.equals("occurrencescolumn") || func.equals("occurrencestotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String .valueOf(t.getOccurrences()); } else if (func.equals("species") || func.equals("speciesrow") || func.equals("speciescolumn") || func.equals("speciestotal")) { grid[order2.get(t.getPid2()) + 1][order1.get(t.getPid1()) + 1] = String.valueOf(t.getSpecies()); } } } else { //row and column sort order and labels TreeMap<String, Integer> order1 = new TreeMap<String, Integer>(); TreeMap<String, Integer> order2 = new TreeMap<String, Integer>(); int pos = 0; for (String s : objects1.keySet()) { order1.put(s, pos++); grid[pos][0] = objects1.get(s); } pos = 0; for (String s : objects2.keySet()) { order2.put(s, pos++); grid[0][pos] = objects2.get(s); } //grid for (Tabulation t : tabulations) { if (func.equals("area") || func.equals("arearow") || func.equals("areacolumn") || func.equals("areatotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String.format("%.1f", t.getArea() / 1000000.0); //convert sqm to sqkm } else if (func.equals("occurrences") || func.equals("occurrencesrow") || func.equals("occurrencescolumn") || func.equals("occurrencestotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String .valueOf(t.getOccurrences()); } else if (func.equals("species") || func.equals("speciesrow") || func.equals("speciescolumn") || func.equals("speciestotal")) { grid[order1.get(t.getPid1()) + 1][order2.get(t.getPid2()) + 1] = String.valueOf(t.getSpecies()); } } } return grid; }
From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java
private static void testWriteMapFileToHDFS(EventLoop eventLoop) { try {// w w w .ja v a 2s .co m // initialize log manager CrawlHistoryManager logManager = initializeTestLogManager(eventLoop, true); // initialize item list TreeMap<URLFP, ProxyCrawlHistoryItem> items = buildTestList(urlList1); final TreeMap<String, URLFP> urlToURLFPMap = new TreeMap<String, URLFP>(); for (Map.Entry<URLFP, ProxyCrawlHistoryItem> item : items.entrySet()) { urlToURLFPMap.put(item.getValue().getOriginalURL(), item.getKey()); } // add to local item map in log manager for (ProxyCrawlHistoryItem item : items.values()) { logManager.appendItemToLog(item); } // ok shutdown log manager ... logManager.shutdown(); // restart - reload log file ... logManager = initializeTestLogManager(eventLoop, false); // write to 'hdfs' logManager.doCheckpoint(); syncAndValidateItems(items, logManager); logManager.shutdown(); // restart logManager = initializeTestLogManager(eventLoop, false); // tweak original items updateTestItemStates(items); // ok append items for (ProxyCrawlHistoryItem item : items.values()) { logManager.appendItemToLog(item); } syncAndValidateItems(items, logManager); // ok now checkpoint the items logManager.doCheckpoint(); // ok now validate one last time syncAndValidateItems(items, logManager); // shutown logManager.shutdown(); logManager = null; { // start from scratch ... final CrawlHistoryManager logManagerTest = initializeTestLogManager(eventLoop, true); // create a final version of the tree map reference final TreeMap<URLFP, ProxyCrawlHistoryItem> itemList = items; // create filename File urlInputFile = new File(logManagerTest.getLocalDataDir(), "testURLS-" + System.currentTimeMillis()); // ok create a crawl list from urls CrawlList.generateTestURLFile(urlInputFile, urlList1); long listId = logManagerTest.loadList(urlInputFile, 0); CrawlList listObject = logManagerTest.getList(listId); final Semaphore listCompletionSemaphore = new Semaphore(-(itemList.size() - 1)); listObject.setEventListener(new CrawlList.CrawlListEvents() { @Override public void itemUpdated(URLFP itemFingerprint) { // TODO Auto-generated method stub listCompletionSemaphore.release(); } }); // ok start the appropriate threads logManagerTest.startLogWriterThread(0); logManagerTest.startListLoaderThread(); logManagerTest.startQueueLoaderThread(new CrawlQueueLoader() { @Override public void queueURL(URLFP urlfp, String url) { logManagerTest.crawlComplete( proxyCrawlHitoryItemToCrawlURL(itemList.get(urlToURLFPMap.get(url)))); } @Override public void flush() { // TODO Auto-generated method stub } }); LOG.info("Waiting for Release"); // and wait for the finish listCompletionSemaphore.acquireUninterruptibly(); LOG.info("Got Here"); } } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); } }
From source file:net.massbank.validator.RecordValidator.java
/** * ???/* w w w.ja va 2s . c om*/ * * @param op * PrintWriter? * @param resultMap * ?? * @return ? * @throws IOException */ private static boolean dispResult(PrintStream op, TreeMap<String, String> resultMap) throws IOException { // ---------------------------------------------------- // // ---------------------------------------------------- NumberFormat nf = NumberFormat.getNumberInstance(); int okCnt = 0; int warnCnt = 0; int errCnt = 0; for (Map.Entry<String, String> e : resultMap.entrySet()) { String statusStr = e.getValue().split("\t")[0]; if (statusStr.equals(STATUS_OK)) { okCnt++; } else if (statusStr.equals(STATUS_WARN)) { warnCnt++; } else if (statusStr.equals(STATUS_ERR)) { errCnt++; } } op.println(nf.format(okCnt) + " ok"); op.println(nf.format(warnCnt) + " warn"); op.println(nf.format(errCnt) + " error / " + nf.format(resultMap.size()) + " files"); op.println("Status"); op.println("Details"); // ---------------------------------------------------- // // ---------------------------------------------------- for (Map.Entry<String, String> e : resultMap.entrySet()) { String nameStr = e.getKey(); String statusStr = e.getValue().split("\t")[0]; String detailsStr = e.getValue().split("\t")[1].trim(); op.println(nameStr + " "); op.println(statusStr + ""); op.println(detailsStr + ""); } return true; }
From source file:my.mavenproject10.FileuploadController.java
@RequestMapping(method = RequestMethod.POST) ModelAndView upload(HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); String fileName = ""; int size = 0; ArrayList<String> result = new ArrayList<String>(); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {// w w w . j av a 2s . co m List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); fileName = item.getName(); System.out.println("file name " + item.getName()); JAXBContext jc = JAXBContext.newInstance(CustomersType.class); SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource( new InputStreamReader(item.getInputStream(), "UTF-8")); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller unmarshaller = jc.createUnmarshaller(); CustomersType data2 = (CustomersType) unmarshaller.unmarshal(source); //System.out.println("size " + data2.getCustomer().size()); size = data2.getCustomer().size(); for (CustomerType customer : data2.getCustomer()) { System.out.println(customer.toString()); } // double summ = 0.0; HashMap<Integer, Float> ordersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { for (OrderType orderType : customer.getOrders().getOrder()) { Float summPerOrder = 0.0f; //System.out.println(orderType); for (PositionType positionType : orderType.getPositions().getPosition()) { //System.out.println(positionType); summPerOrder += positionType.getCount() * positionType.getPrice(); summ += positionType.getCount() * positionType.getPrice(); } ordersMap.put(orderType.getId(), summPerOrder); } } summ = new BigDecimal(summ).setScale(2, RoundingMode.UP).doubleValue(); System.out.println(" " + summ); result.add(" " + summ); // HashMap<Integer, Float> customersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { Float summPerCust = 0.0f; customersMap.put(customer.getId(), summPerCust); for (OrderType orderType : customer.getOrders().getOrder()) { for (PositionType positionType : orderType.getPositions().getPosition()) { summPerCust += positionType.getCount() * positionType.getPrice(); } } //System.out.println(customer.getId() + " orders " + summPerCust); customersMap.put(customer.getId(), summPerCust); } TreeMap sortedMap = sortByValue(customersMap); System.out.println(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); result.add(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); // TreeMap sortedMapOrders = sortByValue(ordersMap); System.out.println(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); result.add(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); // System.out.println(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); result.add(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); // System.out.println(" " + sortedMapOrders.size()); result.add(" " + sortedMapOrders.size()); // ArrayList<Float> floats = new ArrayList<Float>(sortedMapOrders.values()); Float summAvg = 0.0f; Float avg = 0.0f; for (Float f : floats) { summAvg += f; } avg = new BigDecimal(summAvg / floats.size()).setScale(2, RoundingMode.UP).floatValue(); System.out.println(" " + avg); result.add(" " + avg); } } catch (FileUploadException e) { System.out.println("FileUploadException:- " + e.getMessage()); } catch (JAXBException ex) { //Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } } ModelAndView modelAndView = new ModelAndView("fileuploadsuccess"); modelAndView.addObject("files", result); modelAndView.addObject("name", fileName); modelAndView.addObject("size", size); return modelAndView; }
From source file:com.brejza.matt.habmodem.Dsp_service.java
@Override public void HabitatRx(TreeMap<Long, Telemetry_string> data, boolean success, String callsign, long startTime, long endTime, AscentRate as, double maxAltitude) { mapPayloads.get(callsign.toUpperCase()).setQueryOngoing(0); if (success) { String call = callsign.toUpperCase(); System.out.println("DEBUG: Got " + data.size() + " sentences for payload " + callsign); logEvent("Habitat Query Got " + data.size() + " Sentences For Payload " + callsign, true); if (mapPayloads.containsKey(call)) { Payload p = mapPayloads.get(call); //if havnt already got a telem_config, see if one exists in hab_con if (p.telemetryConfig == null) { if (hab_con.getTelemConfigs().containsKey(call)) { p.telemetryConfig = hab_con.getTelemConfigs().get(call); }//from w ww. ja v a 2 s .c o m } long lt = p.getLastTime(); p.setLastUpdated(endTime); p.putPackets(data); p.setIsActivePayload(true); if (p.colour == 0) p.setNewColour(newColour()); if (data.size() > 0) { if (lt < Long.valueOf(data.lastKey())) { if (as != null) { if (as.valid()) p.ascentRate = as; } } } } else { Payload p = new Payload(callsign, newColour(), true); if (hab_con.getTelemConfigs().containsKey(call)) { p.telemetryConfig = hab_con.getTelemConfigs().get(call); } p.setLastUpdated(endTime); p.data = data; mapPayloads.put(call, p); if (as != null) { if (as.valid()) mapPayloads.get(call).ascentRate = as; } } mapPayloads.get(call).putMaxAltitude(maxAltitude); Intent i = new Intent(HABITAT_NEW_DATA); if (data.size() > 0) i.putExtra(TELEM_STR, data.get(data.lastKey()).getSentence()); sendBroadcast(i); } else { logEvent("Habitat Query Failed - " + callsign, true); } }
From source file:edu.utexas.cs.tactex.MarketManagerTest.java
/** * Test //from ww w . j a va2 s . c om */ @Test public void test_initialize() { // initialize with arbitrary values ReflectionTestUtils.setField(marketManagerService, "marketTotalMwh", 1234.0); ReflectionTestUtils.setField(marketManagerService, "marketTotalPayments", 1234.0); ReflectionTestUtils.setField(marketManagerService, "lastOrder", null); ReflectionTestUtils.setField(marketManagerService, "marketMWh", null); ReflectionTestUtils.setField(marketManagerService, "marketPayments", null); ReflectionTestUtils.setField(marketManagerService, "predictedUsage", null); ReflectionTestUtils.setField(marketManagerService, "actualUsage", null); ReflectionTestUtils.setField(marketManagerService, "orderbooks", null); ReflectionTestUtils.setField(marketManagerService, "maxTradePrice", 1234); ReflectionTestUtils.setField(marketManagerService, "minTradePrice", 1234); ReflectionTestUtils.setField(marketManagerService, "supportingBidGroups", null); ReflectionTestUtils.setField(marketManagerService, "dpCache2013", null); ReflectionTestUtils.setField(marketManagerService, "shortBalanceTransactionsData", null); ReflectionTestUtils.setField(marketManagerService, "surplusBalanceTransactionsData", null); // initialize should set all fields correctly marketManagerService.initialize(brokerContext); // get fields from object and verify they are initialized correctly double marketTotalMwh = (Double) ReflectionTestUtils.getField(marketManagerService, "marketTotalMwh"); assertEquals("marketTotalMwh", 0.0, marketTotalMwh, 1e-6); double marketTotalPayments = (Double) ReflectionTestUtils.getField(marketManagerService, "marketTotalPayments"); assertEquals("marketTotalPayments", 0.0, marketTotalPayments, 1e-6); // map should be initialized to empty @SuppressWarnings("unchecked") HashMap<Integer, Order> lastOrder = (HashMap<Integer, Order>) ReflectionTestUtils .getField(marketManagerService, "lastOrder"); assertNotNull("lastOrder", lastOrder); assertEquals("lastOrder.length", 0, lastOrder.size()); // arrays are not null, of the right size, and initialized // with 0's int usageRecordLength = configuratorFactoryService.CONSTANTS.USAGE_RECORD_LENGTH(); double[] marketMWh = (double[]) ReflectionTestUtils.getField(marketManagerService, "marketMWh"); assertNotNull("marketMWh", marketMWh); assertEquals("length of marketMWh", usageRecordLength, marketMWh.length); assertArrayEquals(new double[usageRecordLength], marketMWh, 1e-6); double[] marketPayments = (double[]) ReflectionTestUtils.getField(marketManagerService, "marketPayments"); assertNotNull("marketPayments", marketPayments); assertEquals("length of marketPayments", usageRecordLength, marketPayments.length); assertArrayEquals(new double[usageRecordLength], marketPayments, 1e-6); double[][] predictedUsage = (double[][]) ReflectionTestUtils.getField(marketManagerService, "predictedUsage"); assertNotNull("predictedUsage", predictedUsage); assertEquals("predictedUsage.size", 24, predictedUsage.length); for (double[] p : predictedUsage) { assertNotNull("predictedUsage[i]", p); assertEquals("p.size", 2500, p.length); assertEquals("p[i]", (Integer) 0, p[0], 1e-6); } double[] actualUsage = (double[]) ReflectionTestUtils.getField(marketManagerService, "actualUsage"); assertNotNull("actualUsage", actualUsage); assertEquals("actualUsage.size", 2500, actualUsage.length); assertEquals("actualUsage[i]", 0, actualUsage[0], 1e-6); @SuppressWarnings("unchecked") HashMap<Integer, Orderbook> orderbooks = (HashMap<Integer, Orderbook>) ReflectionTestUtils .getField(marketManagerService, "orderbooks"); assertNotNull("orderbooks", orderbooks); assertEquals("orderbooks.length", 0, orderbooks.size()); double maxTradePrice = (Double) ReflectionTestUtils.getField(marketManagerService, "maxTradePrice"); assertEquals("maxTradePrice", -Double.MAX_VALUE, maxTradePrice, 1e-6); double minTradePrice = (Double) ReflectionTestUtils.getField(marketManagerService, "minTradePrice"); assertEquals("minTradePrice", Double.MAX_VALUE, minTradePrice, 1e-6); @SuppressWarnings("unchecked") TreeMap<Integer, TreeMap<Double, Double>> supportingBidGroups = (TreeMap<Integer, TreeMap<Double, Double>>) ReflectionTestUtils .getField(marketManagerService, "supportingBidGroups"); assertNotNull("supportingBidGroups", supportingBidGroups); assertEquals("supportingBidGroups.length", 0, supportingBidGroups.size()); MarketManagerService.DPCache dpCache2013 = (MarketManagerService.DPCache) ReflectionTestUtils .getField(marketManagerService, "dpCache2013"); assertNotNull("dpCache2013", dpCache2013); @SuppressWarnings("unchecked") ArrayList<Double> bestActions = (ArrayList<Double>) ReflectionTestUtils.getField(dpCache2013, "bestActions"); assertNotNull("dpCache2013.bestActions", bestActions); @SuppressWarnings("unchecked") ArrayList<Double> stateValues = (ArrayList<Double>) ReflectionTestUtils.getField(dpCache2013, "stateValues"); assertNotNull("dpCache2013.stateValues", stateValues); @SuppressWarnings("unchecked") HashMap<Integer, Boolean> validTimeslots = (HashMap<Integer, Boolean>) ReflectionTestUtils .getField(dpCache2013, "validTimeslots"); assertNotNull("dpCache2013.validTimeslots", validTimeslots); assertEquals("dpCache2013.bestActions", 0, dpCache2013.getBestActions().size()); assertEquals("dpCache2013.stateValues", 0, dpCache2013.getStateValues().size()); assertEquals("dpCache2013.valid(ts)", false, dpCache2013.isValid(currentTimeslot.getSerialNumber())); // map should be initialized to empty @SuppressWarnings("unchecked") ArrayList<PriceMwhPair> shortBalanceTransactionsData = (ArrayList<PriceMwhPair>) ReflectionTestUtils .getField(marketManagerService, "shortBalanceTransactionsData"); assertNotNull("shortBalanceTransactionsData", shortBalanceTransactionsData); assertEquals("shortBalanceTransactionsData.length", 0, shortBalanceTransactionsData.size()); @SuppressWarnings("unchecked") ArrayList<PriceMwhPair> surplusBalanceTransactionsData = (ArrayList<PriceMwhPair>) ReflectionTestUtils .getField(marketManagerService, "surplusBalanceTransactionsData"); assertNotNull("surplusBalanceTransactionsData", surplusBalanceTransactionsData); assertEquals("surplusBalanceTransactionsData.length", 0, surplusBalanceTransactionsData.size()); }
From source file:com.nextgis.rehacompdemo.RoutingActivity.java
@Override public void onLocationChanged(Location currentLocation) { GeoEnvelope area = getArea(currentLocation); Location nextLocation = new Location(LocationManager.GPS_PROVIDER); Location previousLocation = new Location(LocationManager.GPS_PROVIDER); TreeMap<Float, Location> perpendiculars = new TreeMap<>(); HashMap<Location, GeoLineString> snapsToSegments = new HashMap<>(); for (GeoLineString segment : mRouteSegments) if (area.intersects(segment.getEnvelope()) || area.contains(segment.getEnvelope())) { previousLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(0).getX())); previousLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(0).getY())); nextLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(1).getX())); nextLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(1).getY())); Location snap = snapToLine(previousLocation, nextLocation, currentLocation, false); Float perpendicular = currentLocation.distanceTo(snap); perpendiculars.put(perpendicular, snap); snapsToSegments.put(snap, segment); }/*from ww w .jav a 2 s . co m*/ if (perpendiculars.size() > 0 && snapsToSegments.size() > 0) { Location snappedLocation = perpendiculars.firstEntry().getValue(); GeoLineString segment = snapsToSegments.get(snappedLocation); previousLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(0).getX())); previousLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(0).getY())); nextLocation.setLongitude(Geo.mercatorToWgs84SphereX(segment.getPoint(1).getX())); nextLocation.setLatitude(Geo.mercatorToWgs84SphereY(segment.getPoint(1).getY())); GeoPoint point = segment.getPoint(1); if (snappedLocation.distanceTo(previousLocation) < snappedLocation.distanceTo(nextLocation)) { point = segment.getPoint(0); nextLocation.setLongitude(previousLocation.getLongitude()); nextLocation.setLatitude(previousLocation.getLatitude()); } if (snappedLocation.distanceTo(nextLocation) <= mActivationDistance) { long id = -1; for (IGeometryCacheItem cachePoint : mAllPoints) { if (point.equals(cachePoint.getGeometry())) id = cachePoint.getFeatureId(); } int position = mAdapter.getItemPosition(id); if (position != -1) { mSteps.requestFocusFromTouch(); mSteps.setSelection(position); } } } }
From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java
/** * Builds the inherited map.//w w w .j ava 2 s .co m * * @param relationshipClass the relationship class * @param relationshipMap the relationship map * @return the tree map */ private TreeMap<Integer, RelationshipBean> buildInheritedMap(final String relationshipClass, final TreeMap<Integer, RelationshipBean> relationshipMap) { TreeMap<Integer, RelationshipBean> fullSupervisorMap = new TreeMap<Integer, RelationshipBean>(); // Load the supervisor type map TreeMap<Integer, String> types = null; try { types = loadSupervisorRelationships(relationshipClass); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading the supervisor object types: " + wde.getMessage()); } int maxHierarchy = 0; if (types != null) { dataLogger.debug("Supervisor relationships: " + types.size()); for (Integer hierarchy : types.keySet()) { // Set the maxiumum hierarchy value by getting the last key if (hierarchy > maxHierarchy) { maxHierarchy = hierarchy; } } } dataLogger.debug("Maximum hierarchy: " + maxHierarchy); for (Integer hierarchy : types.keySet()) { final String typeName = types.get(hierarchy); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Hierarchy key is: " + hierarchy); dataLogger.debug("Type is: " + typeName); } if (!relationshipMap.containsKey(hierarchy)) { // If the relationship is missing we need to find one RelationshipBean newSup = null; for (int i = 1; i < maxHierarchy + 1; i++) { dataLogger.debug("Looking up key: " + i); if (newSup == null && relationshipMap.containsKey(i)) { RelationshipBean exSup = relationshipMap.get(i); newSup = exSup.clone(); newSup.setRelationshipType(typeName); } } if (newSup != null) { if (dataLogger.isDebugEnabled()) { dataLogger.debug("Adding a new supervisor"); dataLogger.debug("GUID: " + newSup.getGUID()); dataLogger.debug("Identifier: " + newSup.getIdentifier()); dataLogger.debug("Relationship Class: " + newSup.getRelationshipClass()); dataLogger.debug("Relationship Type: " + newSup.getRelationshipType()); } fullSupervisorMap.put(hierarchy, newSup); } } else { RelationshipBean extSup = relationshipMap.get(hierarchy); if (dataLogger.isDebugEnabled()) { dataLogger.debug("Adding an existing supervisor"); dataLogger.debug("GUID: " + extSup.getGUID()); dataLogger.debug("Identifier: " + extSup.getIdentifier()); dataLogger.debug("Relationship Class: " + extSup.getRelationshipClass()); dataLogger.debug("Relationship Type: " + extSup.getRelationshipType()); } fullSupervisorMap.put(hierarchy, extSup); } } return fullSupervisorMap; }
From source file:com.sfs.whichdoctor.dao.IsbEntityDAOImpl.java
/** * Check mandatory group membership.//from w w w .j a v a2 s .c o m * * @param entityGUID the entity guid * @param delete the entity reference if present (otherwise create if not) * @param privileges the privileges */ private void checkMandatoryGroups(final int entityGUID, final boolean delete, final PrivilegesBean privileges) { if (this.mandatoryGroups != null) { UserBean systemUser = getSystemUser("ISB", "System"); dataLogger.debug("Mandatory groups exist"); for (Integer groupGUID : this.mandatoryGroups.keySet()) { TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>(); String isbMapping = ""; try { final GroupBean group = this.groupDAO.loadGUID(groupGUID); isbMapping = group.getGroupDN(); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading the parent group: " + wde.getMessage()); } try { items = this.itemDAO.load(groupGUID, false, "Group", "Member", entityGUID, null, null); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error performing search for items: " + wde.getMessage()); } if (items != null && items.size() == 0 && !delete) { dataLogger.debug("Items do not exist and create selected"); // No items exist and create is requested. final ItemBean item = new ItemBean(); item.setObject1GUID(groupGUID); item.setObject2GUID(entityGUID); item.setWeighting(WEIGHTING); item.setPermission(PERMISSION); item.setItemType(ITEMTYPE); try { this.itemDAO.create(item, systemUser, privileges, isbMapping); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error creating the new item: " + wde.getMessage()); } } if (items != null && items.size() > 0 && delete) { // Items exist and delete is requested. dataLogger.debug("Items exist and delete selected"); for (String key : items.keySet()) { final ItemBean item = items.get(key); try { this.itemDAO.delete(item, systemUser, privileges, isbMapping); } catch (WhichDoctorDaoException wde) { dataLogger.error("Error deleting the existing item: " + wde.getMessage()); } } } } } }