// Metoden createLabels - Skapar de grafiska komponenterna för scorelistan public void createLabels() { // Om det är fler än en spelare, sortera listan efter score if (players.size() > 1) { players = sortPlayers(players); } // Lägg till labels med förbestämd text for (int i = 0; i < 3; i++) { panel.add(new JLabel(labeltext[i])); } // Lägg till labels med placering, nick och poäng för spelarna for (int i = 3; i < 7; i++) { if (players.size() > i - 3) { panel.add(new JLabel(labeltext[i])); panel.add(new JLabel(players.get(i - 3).nick)); panel.add(new JLabel(players.get(i - 3).score + "")); } } // Lägger till några tomma labels i panelen för att skapa mellanrum och symetri for (int i = 0; i < 4; i++) { panel.add(new JLabel(" ")); } // Lägger till avslutaknappen panel.add(exit); exit.addActionListener(this); }
// Test adjacency at entrance to rooms @Test public void testAdjacencyDoorways() { // Test beside a door direction RIGHT LinkedList<Integer> testList = board.getAdjList(board.calcIndex(4, 4)); Assert.assertTrue(testList.contains(board.calcIndex(4, 3))); Assert.assertTrue(testList.contains(board.calcIndex(4, 5))); Assert.assertTrue(testList.contains(board.calcIndex(5, 4))); Assert.assertEquals(3, testList.size()); // Test beside a door direction DOWN testList = board.getAdjList(board.calcIndex(6, 15)); Assert.assertTrue(testList.contains(board.calcIndex(5, 15))); Assert.assertTrue(testList.contains(board.calcIndex(6, 14))); Assert.assertTrue(testList.contains(board.calcIndex(6, 16))); Assert.assertEquals(3, testList.size()); // Test beside a door direction LEFT testList = board.getAdjList(board.calcIndex(15, 17)); Assert.assertTrue(testList.contains(board.calcIndex(15, 16))); Assert.assertTrue(testList.contains(board.calcIndex(15, 18))); Assert.assertTrue(testList.contains(board.calcIndex(14, 17))); Assert.assertTrue(testList.contains(board.calcIndex(16, 17))); Assert.assertEquals(4, testList.size()); // Test beside a door direction UP testList = board.getAdjList(board.calcIndex(13, 11)); Assert.assertTrue(testList.contains(board.calcIndex(13, 10))); Assert.assertTrue(testList.contains(board.calcIndex(13, 12))); Assert.assertTrue(testList.contains(board.calcIndex(12, 11))); Assert.assertTrue(testList.contains(board.calcIndex(14, 11))); Assert.assertEquals(4, testList.size()); }
@RequestMapping(value = "/customerTips", method = RequestMethod.GET) public ModelAndView customerTips(@RequestParam("uid") UserIdentifier uid) { ModelAndView mav = new ModelAndView(); Customer currentCustomer = (Customer) GmbPersistenceManager.get(uid); mav.setViewName("customer/tips/tip_customerTips"); LinkedList<WeeklyLottoSTT> weeklySTTList = new LinkedList<WeeklyLottoSTT>(); LinkedList<TotoSTT> totoSTTList = new LinkedList<TotoSTT>(); LinkedList<DailyLottoSTT> dailyLottoSTTList = new LinkedList<DailyLottoSTT>(); for (TotoSTT tSTT : currentCustomer.getTotoSTTs()) { if (!tSTT.getTip().getDraw().getEvaluated()) totoSTTList.add(tSTT); } for (DailyLottoSTT dLSTT : currentCustomer.getDailyLottoSTTs()) { if (!dLSTT.getTip().getDraw().getEvaluated()) dailyLottoSTTList.add(dLSTT); } for (WeeklyLottoSTT wLSTT : currentCustomer.getWeeklyLottoSTTs()) { if (!wLSTT.getTip().getDraw().getEvaluated()) weeklySTTList.add(wLSTT); } mav.addObject("weeklySTTList", (weeklySTTList.size() > 0) ? weeklySTTList : null); mav.addObject("totoSTTList", (totoSTTList.size() > 0) ? totoSTTList : null); mav.addObject("dailySTTList", (dailyLottoSTTList.size() > 0) ? dailyLottoSTTList : null); mav.addObject( "weeklyPTTList", (currentCustomer.getWeeklyLottoPTTs().size() > 0) ? currentCustomer.getWeeklyLottoPTTs() : null); mav.addObject( "dailyPTTList", (currentCustomer.getDailyLottoPTTs().size() > 0) ? currentCustomer.getDailyLottoPTTs() : null); mav.addObject("currentUser", currentCustomer); return mav; }
/** * Remove all empty and {@code null} string elements from the given <var>names</var> and * optionally all redundant information like "." and "..". * * @param names names to check * @param canonical if {@code true}, remove redundant elements as well. * @return a possible empty array of names all with a length > 0. */ private static String[] normalize(String[] names, boolean canonical) { LinkedList<String> res = new LinkedList<String>(); if (names == null || names.length == 0) { return new String[0]; } for (int i = 0; i < names.length; i++) { if (names[i] == null || names[i].length() == 0) { continue; } if (canonical) { if (names[i].equals("..")) { if (!res.isEmpty()) { res.removeLast(); } } else if (names[i].equals(".")) { continue; } else { res.add(names[i]); } } else { res.add(names[i]); } } return res.size() == names.length ? names : res.toArray(new String[res.size()]); }
protected static Predicate getPredicate( final Class clazz, final Map<String, String[]> searchTerms, Root<Persistable> root, CriteriaBuilder cb) { LinkedList<Predicate> predicates = new LinkedList<Predicate>(); Predicate predicate; if (!CollectionUtils.isEmpty(searchTerms)) { Set<String> propertyNames = searchTerms.keySet(); // put aside nested AND/OR param groups NestedJunctions junctions = new NestedJunctions(); for (String propertyName : propertyNames) { String[] values = searchTerms.get(propertyName); if (!junctions.addIfNestedJunction(propertyName, values)) { addPredicate(clazz, root, cb, predicates, values, propertyName); } } // add nested AND/OR param groups Map<String, Map<String, String[]>> andJunctions = junctions.getAndJunctions(); addJunctionedParams(clazz, root, cb, predicates, andJunctions, AND); Map<String, Map<String, String[]>> orJunctions = junctions.getOrJunctions(); addJunctionedParams(clazz, root, cb, predicates, orJunctions, OR); } if (searchTerms.containsKey(SEARCH_MODE) && searchTerms.get(SEARCH_MODE)[0].equalsIgnoreCase(OR)) { predicate = cb.or(predicates.toArray(new Predicate[predicates.size()])); } else { predicate = cb.and(predicates.toArray(new Predicate[predicates.size()])); } return predicate; }
public KMeansResult cluster(double[][] centroids, double[][] instances, double threshold) { int itr = -1; // initialize the result KMeansResult result = new KMeansResult(); LinkedList<Double> distortionList = new LinkedList<Double>(); result.clusterAssignment = new int[instances.length]; boolean completed = false; // loop until finally done while (!completed) { // increment iteration itr++; // call the assignInstance method to assign the instances to centroids assignInstance(centroids, instances, result); // check orphaned centroid boolean noOrphaned = false; while (!noOrphaned) { int orphanNum = -1; orphanNum = checkOrphan(centroids, result); // if the centroid is orphaned, then assign it as scenario requores if (orphanNum >= 0) { assignOrphan(orphanNum, centroids, instances, result); } else { noOrphaned = true; } } // update centroids updateCentroids(centroids, instances, result); // compute new distortion double distortion = calculateDistortion(centroids, instances, result); // track the distortion distortionList.add(distortion); // check whether the algorithm should terminate if (itr > 0 && Math.abs( (distortionList.get(itr) - distortionList.get(itr - 1)) / distortionList.get(itr - 1)) < threshold) { completed = true; } } // set centroids to KMeansResult final centroids array result.centroids = centroids; // initialize result's distortion array result.distortionIterations = new double[distortionList.size()]; // record distortionList into result of distortion array for (int i = 0; i < distortionList.size(); i++) { result.distortionIterations[i] = distortionList.get(i); } return result; }
public String printEroList() { StringBuffer sb = new StringBuffer(2000); for (int i = 0; i < eroList.size(); i++) { LinkedList<EROSubobject> erosublist = eroList.get(i).getEROSubobjectList(); for (int j = 0; j < erosublist.size(); j++) { if (erosublist.get(j).getType() == SubObjectValues.ERO_SUBOBJECT_IPV4PREFIX) { sb.append( ((IPv4prefixEROSubobject) erosublist.get(j)) .getIpv4address() .getHostAddress() .toString() + "\t"); } else if (erosublist.get(j).getType() == SubObjectValues.ERO_SUBOBJECT_UNNUMBERED_IF_ID) { sb.append( ((UnnumberIfIDEROSubobject) erosublist.get(j)) .getRouterID() .getHostAddress() .toString() + "\t"); } else if (erosublist.get(j).getType() == SubObjectValues.ERO_SUBOBJECT_LABEL) { sb.append( ((GeneralizedLabelEROSubobject) erosublist.get(j)).getDwdmWavelengthLabel().toString() + "\t"); } } sb.append("\n"); } return sb.toString(); }
@Test public void appenderStoresMessages() { MemoryAppender appender = new MemoryAppender(); BasicConfigurator.configure(appender); Logger logger = Logger.getLogger(TEST_CATEGORY); logger.setLevel(Level.ERROR); logger.error(TEST_MESSAGE); LinkedList<LoggingEvent> events = appender.getEvents(); assertEquals(1, events.size()); LoggingEvent event = events.getFirst(); assertEquals(Level.ERROR, event.getLevel()); assertEquals(TEST_CATEGORY, event.getLoggerName()); assertEquals(TEST_MESSAGE, event.getMessage()); assertEquals(TEST_LOCATION, event.getLocationInformation().getClassName()); appender.clear(); assertEquals(0, events.size()); logger.error(TEST_MESSAGE); assertEquals(1, appender.getEvents().size()); }
private void submit() { String hospital = mEtHospital.getText().toString(); if (TextUtils.isEmpty(hospital)) { mActivity.showToast("请填写医疗机构"); return; } String checkDate = DateFormatUtils.timeToLongString(mTvDate.getText().toString()); PostAddReportItem postAddReportItem = new PostAddReportItem(); if (mImageFilePaths.size() > 0) { List<File> files = new LinkedList<>(); for (int i = 0; i < mImageFilePaths.size() - 1; i++) // -1的目的去除默认的+ { File file = new File(mImageFilePaths.get(i)); if (file != null && file.exists()) { files.add(file); } } postAddReportItem.files = files; } postAddReportItem.checkTime = checkDate; postAddReportItem.name = mTvDate.getText().toString() + "的检查报告"; postAddReportItem.institution = hospital; postAddReportItem.userId = RSAUtil.clientEncrypt(mActivity.getLoginSuccessItem().id); SubmitAddReportPresenter submitAddReportPresenter = new SubmitAddReportPresenterImpl(mActivity, this, REQUEST_SUBMIT_TAG); submitAddReportPresenter.doAddReport(postAddReportItem); }
public boolean pk(String db, String table, LinkedList<String> pk) { String currentDB = currentDB(); LinkedList<String> res = executeCommand("/tapi /use_db " + db); res = executeCommand("/dbschema"); String sPk = ""; for (int i = 0; i < pk.size(); i++) sPk += pk.get(i) + ", "; sPk = sPk.substring(0, sPk.length() - 2); String command = "/tapi :-pk(" + table + ", [" + sPk + "])"; res = executeCommand(command); executeCommand("/tapi /use_db " + currentDB); if (res.size() == 0) return true; if (res.get(0).contains("$error")) return false; return true; }
void tryToDeleteSegment(Point p) { if (points.size() < 3) return; LatLon start; start = findBigSegment(p); ListIterator<LatLon> it = points.listIterator(); LatLon pp; boolean f = false; int i = 0, idx = -1; while (it.hasNext()) { pp = it.next(); if (f && (fixed.contains(pp))) { // if end of line fragment reached lastIdx = idx; return; } if (f && (!it.hasNext())) { // if end of whole line reached closedFlag = false; it.remove(); lastIdx = points.size() - 1; return; } // if we are deleting this segment if (f) it.remove(); if (pp == start) { f = true; idx = i; } // next node should be removed i++; } lastIdx = points.size() - 1; }
private LinkedList<Location> createLocationList(Location start, Job j) { LinkedList<Location> path = new LinkedList<Location>(); Location[][] positions = new Location[bestRoute.size()][2]; for (int x = 0; x < bestRoute.size(); x++) { positions[x][0] = bestRoute.get(x).getStart(); positions[x][1] = bestRoute.get(x).getEnd(); } path = addNext(start, positions, path, j); LinkedList<Location> finalPath = new LinkedList<Location>(); int totalWeight = 0; for (Location l : path) { for (ItemPickup item : j.pickups) { if (item.location.x == l.x && item.location.y == l.y) { totalWeight += item.weight; } } if (totalWeight >= 50) { finalPath.add(j.dropLocation); totalWeight = 0; } finalPath.add(l); } return finalPath; }
/** * Notification that its safe to update the node now with any operations that could potentially * effect the node's bounds. * * @param src The node or Node Component that is to be updated. */ public void updateNodeBoundsChanges(Object src) { Node kid; int size = (removedChildren == null) ? 0 : removedChildren.size(); for (int i = 0; i < size; i++) { kid = (Node) removedChildren.get(i); implGroup.removeChild(kid); } size = (addedChildren == null) ? 0 : addedChildren.size(); for (int i = 0; i < size; i++) { kid = (Node) addedChildren.get(i); implGroup.addChild(kid); } addedChildren.clear(); removedChildren.clear(); if (maskChanged) { implGroup.setMask(vfVisible); maskChanged = false; } }
// Metoden updateLabels - Uppdaterar labels med vems tur det är samt poängställningen public void updateLabels(boolean in) { for (int i = 0; i < players.size(); i++) { // Om spelaren vars tur det är väljer rätt kort ges en poäng, och spelaren får försöka en gång // till if (players.get(i).myTurn && in) { players.get(i).score++; scorelabels.get(i).setText(players.get(i).score + ""); // Om det finns kort kvar, starta AIHandlern för att eventuellt AI ska göra sitt drag if (isCards()) { AIh.interrupt(); } else { this.dispose(); new Scorelist(players); } break; } // Om spelaren vars tur det är väljer fel kort blir det nästa spelares tur else if (players.get(i).myTurn && !in) { players.get(i).myTurn = false; players.get((i + 1) % players.size()).myTurn = true; playerlabels.get(i).setForeground(Color.BLACK); playerlabels.get((i + 1) % players.size()).setForeground(Color.GREEN); // Starta AIHandlern AIh.interrupt(); break; } } }
/** * Replaces the entire stack with this fragment. * * @param args Arguments to be set on the fragment using {@link * Fragment#setArguments(android.os.Bundle)}. */ public void replace(Class<?> fragment, String tag, Bundle args) { Fragment first = stack.peekFirst(); if (first != null && tag.equals(first.getTag())) { if (stack.size() > 1) { ensureTransaction(); fragmentTransaction.setCustomAnimations(popStackEnterAnimation, popStackExitAnimation); while (stack.size() > 1) { removeFragment(stack.pollLast()); } attachFragment(stack.peek(), tag); } return; } Fragment f = fragmentManager.findFragmentByTag(tag); if (f == null) { f = Fragment.instantiate(activity, fragment.getName(), args); } ensureTransaction(); fragmentTransaction.setCustomAnimations(enterAnimation, exitAnimation); clear(); attachFragment(f, tag); stack.add(f); topLevelTags.add(tag); }
private void readFile(BufferedReader br) { String line; String token_line; StringTokenizer st; int numElementBefore = 0; boolean notAdd; try { line = br.readLine(); while (br != null && line != null) { notAdd = false; st = new StringTokenizer(line); while (st.hasMoreTokens()) { token_line = st.nextToken(); if (token_line.charAt(0) == '#') { notAdd = true; break; } else { fileList.add(token_line); } } if (!notAdd) { numRow.add(fileList.size() - numElementBefore); numElementBefore = fileList.size(); } line = br.readLine(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * 随机生成卡片 * * @param cards */ public void randomCard() { System.out.println("GameLayout-------->randomCard()"); LinkedList<Integer> ll = new LinkedList<Integer>(); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (cardMap[i][j] != null) { if (cardMap[i][j].getValue() == 0) { ll.add(4 * i + j); } } } } Random rd = new Random(); Log.i("gamelayout", "ll.size() = " + ll.size()); if (ll.size() == 0) return; int index = rd.nextInt(ll.size()); int x = ll.get(index) / 4; int y = ll.get(index) - 4 * x; int value; // 10分之1的概率生成4 if (rd.nextInt(10) == 4) { value = 2; } else { value = 1; } cardMap[x][y].setValue(value); }
public static void main(String[] args) throws IOException { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); ArrayList<ArrayList<Pair>> G; int T = Integer.parseInt(inp.readLine()); int startVertex = 0; int graphSize = 50; for (int test = 0; test < T; ++test) { int numberOfEdges = Integer.parseInt(inp.readLine()); G = new ArrayList<ArrayList<Pair>>(); for (int index = 0; index < graphSize; ++index) G.add(new ArrayList<Pair>()); for (int edge = 0; edge < numberOfEdges; ++edge) { String[] tokens = inp.readLine().split("\\s"); int u = Integer.parseInt(tokens[0]); --u; int v = Integer.parseInt(tokens[1]); --v; startVertex = u; G.get(u).add(new Pair(v, 1)); G.get(v).add(new Pair(u, 1)); } System.out.println("Case #" + (test + 1)); if (isEulerian(G)) { LinkedList<Integer> path = new LinkedList<Integer>(); eulerPath(G, path.listIterator(), startVertex); for (int index = 0; index < path.size() - 1; ++index) System.out.println((path.get(index) + 1) + " " + (path.get(index + 1) + 1)); if (path.size() > 0) System.out.println((path.get(path.size() - 1) + 1) + " " + (path.get(0) + 1)); } else System.out.println("some beads may be lost"); if (test != T - 1) System.out.println(); } }
@Override public boolean incrementToken() throws IOException { while (!done && queue.size() < windowSize) { if (!input.incrementToken()) { done = true; break; } // reverse iterating for better efficiency since we know the // list is already sorted, and most token start offsets will be too. ListIterator<OrderedToken> iter = queue.listIterator(queue.size()); while (iter.hasPrevious()) { if (offsetAtt.startOffset() >= iter.previous().startOffset) { // insertion will be before what next() would return (what // we just compared against), so move back one so the insertion // will be after. iter.next(); break; } } OrderedToken ot = new OrderedToken(); ot.state = captureState(); ot.startOffset = offsetAtt.startOffset(); iter.add(ot); } if (queue.isEmpty()) { return false; } else { restoreState(queue.removeFirst().state); return true; } }
/** Sets the current document to be the next document in the list. */ public void next() { if (_docs.size() > 0) { _current++; if (_current >= _docs.size()) _current = 0; show(_current); } }
/** * this method removes the last element of the formula, and returns whether the element removed is * an operator or an input: * * @return true if it is an operator, false otherwise * @exception SyntaxErrorException TO COMMENT FURTHER */ public boolean removeFromFormula() throws SyntaxErrorException { boolean isOperator = true; TreeCell currentCell; if (nextEntry == 0) // only one value { currentCell = opList.get(0); } else if ((nextEntry < opList.size()) && (opList.get(nextEntry).getstatusCell() != TreeCell.NOT_COMPLETED)) { currentCell = opList.get(nextEntry); } else { currentCell = opList.get(nextEntry - 1); // get the current cell that we will be using } try { isOperator = currentCell.removeInCell(); if (!isOperator) this.removeLeaveTotal(); if (currentCell.getstatusCell() == TreeCell.NOT_COMPLETED) { if (nextEntry > 0) nextEntry--; if (nextEntry < opList.size()) opList.remove(currentCell); } else if ((currentCell.getstatusCell() == TreeCell.LEFT_COMPLETED)) nextEntry = this.opList.size(); else if (nextEntry < opList.size()) { nextEntry++; } return isOperator; } catch (SyntaxErrorException e) { throw e; } }
/** Sets the current document to be the previous document in the list. */ public void prev() { if (_docs.size() > 0) { _current--; if (_current < 0) _current = _docs.size() - 1; show(_current); } }
public static void readOneLineFromFile() throws RuntimeException { // TODO: read 1 line of the file LinkedList<String> stringsOfFile = FileManager.readFromFile(); // Each line contains, type, question, answer if (stringsOfFile == null) { System.out.println("Line read from file is null"); throw new RuntimeException("File doesn't exist"); } System.out.println("This list has " + stringsOfFile.size() + " strings"); for (int i = 0; i < stringsOfFile.size() - 1; ) { Wrapper current = new Wrapper(); // Put the linked list to the wrapper class consecutively current.questionType = stringsOfFile.get(i++); current.question = stringsOfFile.get(i++); current.answer = stringsOfFile.get(i++); // Add this question to the question collection questionCollection.add(current); } // Load the first question currentQuestion = questionCollection.get(currentQuestionIndex); // Update the question count questionCount = questionCollection.size(); // Parse the line System.out.println("Finished parsing file"); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.detalles_if36); inten = new Intent(this, BBVAfechaj3Activity.class); TextView encabezado = (TextView) findViewById(R.id.resti36); TextView g = (TextView) findViewById(R.id.dgi36); TextView ta = (TextView) findViewById(R.id.dai36); TextView tr = (TextView) findViewById(R.id.dri36); TextView l = (TextView) findViewById(R.id.dlsi36); LinkedList<BBVAfechaj7Activity> list = Bundfechaj9Activity.getInstancia().getListDTODti(getApplicationContext()); if (list.size() != 0) { String result = list.get(35).getDetalle(); String[] r = result.split("/"); if (r.length != 0 && !list.get(35).getDetalle().equalsIgnoreCase(" ")) { encabezado.setText(r[0]); g.setText(r[1]); ta.setText(r[2]); tr.setText(r[3]); l.setText(r[4]); } else if (r.length == 0) { encabezado.setText(" "); g.setText(" "); ta.setText(" "); tr.setText(" "); l.setText(" "); } } else if (list.size() == 0) { Log.d("Error", "No se ha cargado la Base de Dtos"); } }
protected static Predicate getPredicate( final Class clazz, final Restriction searchTerms, Root<Persistable> root, CriteriaBuilder cb) { LinkedList<Predicate> predicates = new LinkedList<Predicate>(); Predicate predicate; // process child restrictions if (!CollectionUtils.isEmpty(searchTerms.getRestrictions())) { for (Restriction restriction : searchTerms.getRestrictions()) { predicates.add(getPredicate(clazz, restriction, root, cb)); } } // process main restriction if (StringUtils.isNotBlank(searchTerms.getField())) { String propertyName = searchTerms.getField(); addPredicate( clazz, root, cb, predicates, searchTerms.getValues().toArray(new String[searchTerms.getValues().size()]), propertyName); } if (searchTerms.getJunction().equals(Restriction.Junction.OR)) { predicate = cb.or(predicates.toArray(new Predicate[predicates.size()])); } else { predicate = cb.and(predicates.toArray(new Predicate[predicates.size()])); } return predicate; }
@Override public float[] getBlock(int timeout) { // TODO Auto-generated method stub float[] frame = null; lock.lock(); try { if (listFrame.size() > 0) { frame = listFrame.removeFirst(); } if (frame == null && timeout != 0) { try { if (timeout > 0) { condition.await(timeout, TimeUnit.MILLISECONDS); } else { condition.await(); } } catch (InterruptedException e) { // TODO: handle exception } } if (listFrame.size() > 0) { frame = listFrame.removeFirst(); } } finally { lock.unlock(); } return frame; }
public TraversePointInfo startTraverse(Point hitPoint, float maxDistance) { float distance = 9999, smallestDistance = 9999; nodes = renderNodes; PathNode t = null; for (int i = 0; i < nodes.size(); i++) { distance = nodes.get(i).getLocation().distancePoint2Point(hitPoint); // Helper.printKeyVal("PathNode: ", nodes.get(i).getLocation().toString()); // Helper.printKeyVal("Distance", distance); if (distance < smallestDistance) { // Helper.printKeyVal("New smallest point: ", nodes.get(i).getLocation().toString()); // Helper.printKeyVal("New smallest Distance", distance); smallestDistance = distance; t = nodes.get(i); } } if (smallestDistance > maxDistance) return null; TraversePointInfo info = new TraversePointInfo(); info.setPathNode(t); info.setTraverseLocation(t.getLocation()); info.setDistance(0); distance = 0; for (int i = 0; i < nodes.size(); i++) { if (nodes.get(i).equals(t)) break; distance += nodes.get(i).getRightDistance(); } info.setTotalDistanceInPath(distance); // Helper.printKeyVal("Total Distance Set: ", info.getTotalDistanceInPath()); info.setPath(this); return info; }
/** * Fills {@link #inputWindow} with input stream tokens, if available, shifting to the right if the * window was previously full. * * <p>Resets {@link #gramSize} to its minimum value. * * @throws IOException if there's a problem getting the next token */ private void shiftInputWindow() throws IOException { InputWindowToken firstToken = null; if (inputWindow.size() > 0) { firstToken = inputWindow.removeFirst(); } while (inputWindow.size() < maxShingleSize) { if (null != firstToken) { // recycle the firstToken, if available if (null != getNextToken(firstToken)) { inputWindow.add(firstToken); // the firstToken becomes the last firstToken = null; } else { break; // end of input stream } } else { InputWindowToken nextToken = getNextToken(null); if (null != nextToken) { inputWindow.add(nextToken); } else { break; // end of input stream } } } if (outputUnigramsIfNoShingles && noShingleOutput && gramSize.minValue > 1 && inputWindow.size() < minShingleSize) { gramSize.minValue = 1; } gramSize.reset(); isOutputHere = false; }
/* * check to see if hit the limit for max # completed apps kept */ protected synchronized void checkAppNumCompletedLimit() { // check apps kept in state store. while (completedAppsInStateStore > this.maxCompletedAppsInStateStore) { ApplicationId removeId = completedApps.get(completedApps.size() - completedAppsInStateStore); RMApp removeApp = rmContext.getRMApps().get(removeId); LOG.info( "Max number of completed apps kept in state store met:" + " maxCompletedAppsInStateStore = " + maxCompletedAppsInStateStore + ", removing app " + removeApp.getApplicationId() + " from state store."); rmContext.getStateStore().removeApplication(removeApp); completedAppsInStateStore--; } // check apps kept in memorty. while (completedApps.size() > this.maxCompletedAppsInMemory) { ApplicationId removeId = completedApps.remove(); LOG.info( "Application should be expired, max number of completed apps" + " kept in memory met: maxCompletedAppsInMemory = " + this.maxCompletedAppsInMemory + ", removing app " + removeId + " from memory: "); rmContext.getRMApps().remove(removeId); this.applicationACLsManager.removeApplication(removeId); } }
/** * Flush a specified ledger * * @param ledger Ledger Id * @throws IOException */ private void flushSpecificLedger(long ledger) throws IOException { LinkedList<Long> firstEntryList = pageMapAndList.getFirstEntryListToBeFlushed(ledger); // flush ledger index file header if necessary indexPersistenceManager.flushLedgerHeader(ledger); if (null == firstEntryList || firstEntryList.size() == 0) { LOG.debug("Nothing to flush for ledger {}.", ledger); // nothing to do return; } // Now flush all the pages of a ledger List<LedgerEntryPage> entries = new ArrayList<LedgerEntryPage>(firstEntryList.size()); try { for (Long firstEntry : firstEntryList) { LedgerEntryPage lep = getLedgerEntryPage(ledger, firstEntry, true); if (lep != null) { entries.add(lep); } } indexPersistenceManager.flushLedgerEntries(ledger, entries); } finally { for (LedgerEntryPage lep : entries) { lep.releasePage(); } } }