/** Test method for {@link org.apache.niolex.commons.test.Counter#inc()}. */ @Test public void testInc() { Counter c = new Counter(); c.inc(); c.inc(); assertEquals(2, c.cnt()); }
public void count( Counter counter, int times, String name, Map<String, Object> context, Writer writer, Writer discardWriter, OutputStream discardStream) throws Exception { counter.beginning(); GroupTemplate group = new GroupTemplate(); group.enableOptimize(); group.enableNativeCall(); counter.initialized(); Template template = group.getReaderTemplate( new InputStreamReader( BeetlCase.class.getClassLoader().getResourceAsStream("performance/books.btl"))); for (Map.Entry<String, Object> entry : context.entrySet()) { template.set(entry.getKey(), entry.getValue()); } counter.compiled(); template.getText(writer); counter.executed(); if (discardStream != null) { for (int i = times; i >= 0; i--) { template.getText(discardStream); } } else { for (int i = times; i >= 0; i--) { template.getText(discardWriter); } } counter.finished(); }
/* * cambia la dificultad cada cierto tiempo (maximo nivel = 5) */ public int cambioDific() { // System.out.println(time.millisElapsed()); if (time.millisElapsed() >= 30000 && nivelActual == 1) { varDific = 250; contLV.setValue(2); nivelActual = 2; velExtra = 1; } else if (time.millisElapsed() >= 50000 && nivelActual == 2) { varDific = 100; contLV.setValue(3); nivelActual = 3; velExtra = 2; } else if (time.millisElapsed() >= 100000 && nivelActual == 3) { varDific = 70; contLV.setValue(4); nivelActual = 4; // velExtra=2; } else if (time.millisElapsed() >= 150000 && nivelActual == 4) { varDific = 50; contLV.setValue(5); nivelActual = 5; if (velExtra < 3) velExtra = 3; } return (varDific); }
private Word findTrg(Word tg, int pos2, BasicChunk bs) { int pos1 = tg.pos; if (pos2 - pos1 > 10) { return null; } Chunk c1 = bs.getChunk(pos1); Chunk c2 = bs.getChunk(pos2); int begin = c1.begin; int end = c2.end; for (Chunk c : bs.chunkList) { if (c.begin >= begin && c.end <= end) { for (Word w : c.trigs) { if (!validTG.contains(w) && w.pos > pos1) { return w; } else if (validTG.contains(w) && w.pos > pos1) { String key = tg.word + tg.pos_tag; Map<String, Counter> ct = sharedTG.get(key); if (ct == null) { ct = new HashMap<String, Counter>(); sharedTG.put(key, ct); } Counter count = ct.get(w.word + w.pos_tag); if (count == null) { count = new Counter(1); ct.put(w.word + w.pos_tag, count); } else { count.inc(); } } } } } return null; }
/** * Simple sparse dot product method. Try to put the sparser <code>Counter</code> as the <code>x * </code> parameter since we iterate over those keys and search for them in the <code>y</code> * parameter. * * @param x * @param y * @return dotProduct */ public static <E> double dotProduct(Counter<E> x, Counter<E> y) { double total = 0.0; for (E keyX : x.keySet()) { total += x.getCount(keyX) * y.getCount(keyX); } return total; }
/* * crea los contadores, mensajes, personaje y tiempos del juego */ public void creanivel() { time = new SimpleTimer(); time.mark(); Barr = new Barra(); sound2.stop(); bandBarra = 0; varDific = 450; nivelActual = 1; velExtra = 0; orbPj = new Orb(); addObject(orbPj, 390, 463); addObject(new Mensaje("Nivel"), 623, 93); addObject(new Mensaje("Vida"), 623, 151); addObject(new Mensaje("Tiempo"), 623, 31); addObject(new Mensaje("Color seleccionado"), 687, 439); contLV = new Counter(); addObject(contLV, 686, 92); contLV.setValue(1); contHP = new Counter(); addObject(contHP, 686, 150); contHP.setValue(orbPj.getHP()); contTime = new Counter(); addObject(contTime, 686, 30); muestraColor = new acColor(); addObject(muestraColor, 691, 497); sound.playLoop(); }
/** Unit tests the <tt>com.akieus.algos.coursera.lib.Interval2D</tt> data type. */ public static void main(String[] args) { double xlo = Double.parseDouble(args[0]); double xhi = Double.parseDouble(args[1]); double ylo = Double.parseDouble(args[2]); double yhi = Double.parseDouble(args[3]); int T = Integer.parseInt(args[4]); Interval1D xinterval = new Interval1D(xlo, xhi); Interval1D yinterval = new Interval1D(ylo, yhi); Interval2D box = new Interval2D(xinterval, yinterval); box.draw(); Counter counter = new Counter("hits"); for (int t = 0; t < T; t++) { double x = StdRandom.uniform(0.0, 1.0); double y = StdRandom.uniform(0.0, 1.0); Point2D p = new Point2D(x, y); if (box.contains(p)) counter.increment(); else p.draw(); } StdOut.println(counter); StdOut.printf("box area = %.2f\n", box.area()); }
public void update(Game game, City city) { cityName.setText(city.getName()); gold.setNumber(game.getMoney().getAmount()); population.setNumber(city.getTotalPopulation()); population.setCeiling(CityStats.totalHouseCapacity(city)); year.setNumber(game.getYear()); }
@Test public void test() { List<Integer> keys = new ArrayList<>(); for (int i = 0; i < 100; i++) { keys.add(i); } Collections.shuffle(keys); AVLTree<Integer, Object> t = AVLTree.create(); for (Integer key : keys) { t = t.add(key); assertThat(t.add(key)).isSameAs(t); } assertThat(Counter.countSet(t)).isEqualTo(100); assertThat(Counter.countMap(t)).isEqualTo(100); assertThat(t.height()).isGreaterThanOrEqualTo(8).isLessThanOrEqualTo(10); for (Integer key : keys) { assertThat(t.contains(key)).isTrue(); t = t.remove(key); assertThat(t.remove(key)).isSameAs(t); } assertThat(Counter.countSet(t)).isEqualTo(0); assertThat(Counter.countMap(t)).isEqualTo(0); }
public IotHubMessageResult execute(Message msg, Object context) { Counter counter = (Counter) context; System.out.println( "Received message " + counter.toString() + " with content: " + new String(msg.getBytes(), Message.DEFAULT_IOTHUB_MESSAGE_CHARSET)); int switchVal = counter.get() % 3; IotHubMessageResult res; switch (switchVal) { case 0: res = IotHubMessageResult.COMPLETE; break; case 1: res = IotHubMessageResult.ABANDON; break; case 2: res = IotHubMessageResult.REJECT; break; default: // should never happen. throw new IllegalStateException("Invalid message result specified."); } System.out.println("Responding to message " + counter.toString() + " with " + res.name()); counter.increment(); return res; }
public void testGetDistributionFromLogValues() { Counter<String> c1 = new DefaultCounter<String>(); c1.setCount("p", 1.0); c1.setCount("q", 2.0); c1.setCount("r", 3.0); c1.setCount("s", 4.0); // take log Counters.logInPlace(c1); // now call distribution Distribution<String> distribution = Distribution.getDistributionFromLogValues(c1); // test assertEquals(distribution.keySet().size(), 4); // size // keys assertEquals(distribution.containsKey("p"), true); assertEquals(distribution.containsKey("q"), true); assertEquals(distribution.containsKey("r"), true); assertEquals(distribution.containsKey("s"), true); // values assertEquals(distribution.getCount("p"), 1.0E-1, 1E-10); assertEquals(distribution.getCount("q"), 2.0E-1, 1E-10); assertEquals(distribution.getCount("r"), 3.0E-1, 1E-10); assertEquals(distribution.getCount("s"), 4.0E-1, 1E-10); }
public double getCount(K token) { if (!lm.keySet().contains(token)) { System.err.println(lm.keySet().size()); throw new RuntimeException("token not in keyset"); } return lm.getCount(token); }
public void act() // sean { if (!played) { burningSteppes.playLoop(); played = !played; } // makeSmokeFireball(); counterDelay++; if (Greenfoot.isKeyDown("h") && delay > 10) { clickSound.play(); Menu menu = new Menu(getThisWorld()); Greenfoot.setWorld(menu); delay = 0; } if (getObjects(Ninja.class).size() != 0 && counterDelay >= 10) { healthCounter.setValue(ninja.getNINJAHP()); shurikenCounter.setValue(ninja.getSHURIKENNUMBER()); powerCounter.setValue(ninja.getPOWERBAR()); checkDoor(); counterDelay -= 10; /**/ // TEMPORAY FUNCTIONS FOR HAYDEN TO CHANGE LEVELS TO MAKE THEM /**/ /**/ // TEMPORAY FUNCTIONS FOR HAYDEN TO CHANGE LEVELS TO MAKE THEM /**/ } delay++; fireballDelay++; }
private void tallyTree( Tree<String> tree, Counter<String> symbolCounter, Counter<UnaryRule> unaryRuleCounter, Counter<BinaryRule> binaryRuleCounter) { if (tree.isLeaf()) return; if (tree.isPreTerminal()) return; if (tree.getChildren().size() == 1) { UnaryRule unaryRule = makeUnaryRule(tree); symbolCounter.incrementCount(tree.getLabel(), 1.0); unaryRuleCounter.incrementCount(unaryRule, 1.0); } if (tree.getChildren().size() == 2) { BinaryRule binaryRule = makeBinaryRule(tree); symbolCounter.incrementCount(tree.getLabel(), 1.0); binaryRuleCounter.incrementCount(binaryRule, 1.0); } if (tree.getChildren().size() < 1 || tree.getChildren().size() > 2) { throw new RuntimeException( "Attempted to construct a Grammar with an illegal tree: " + tree); } for (Tree<String> child : tree.getChildren()) { tallyTree(child, symbolCounter, unaryRuleCounter, binaryRuleCounter); } }
public static void main(String[] args) { TaskManager tm = new TaskManager(); tm.setSearchURL(1000); tm.setNetDeepth(3); tm.setResultToDb(true); tm.setResultToFile(false); tm.setRecords(1000); PrintUtil.debug("设置的搜索容量为 " + tm.getSearchURL()); PrintUtil.debug("设置的搜索深度为 " + tm.getNetDeepth()); PrintUtil.debug( "结果保存在" + (tm.isResultToDb() ? "数据库中" : " ") + (tm.isResultToFile() ? "文件中" : "")); // 保存文件 Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); tm.setUrlfilename("url-" + month + "-" + day + ".txt"); // 添加初始网址 Address a = new Address(); String url = "http://www.bilibili.com/"; a.setUrl(url); a.setTitle(url); tm.initAdd(a); tm.start(); // 计时器 Timer t = new Timer(); Counter counter = new Counter(); counter.setTm(tm); t.schedule(counter, 3000, 5000); }
/** * Test. * * @throws IOException e */ @Test public void testRootContexts() throws IOException { HtmlReport htmlReport; // addRequest pour que CounterRequestContext.getCpuTime() soit appelée counter.addRequest("first request", 100, 100, false, 1000); TestCounter.bindRootContexts("first request", counter, 3); sqlCounter.bindContext("sql", "sql", null, -1); htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.TOUT, writer); htmlReport.toHtml("message a", null); assertNotEmptyAndClear(writer); final Counter myCounter = new Counter("http", null); final Collector collector2 = new Collector("test 2", Arrays.asList(myCounter)); myCounter.bindContext("my context", "my context", null, -1); htmlReport = new HtmlReport(collector2, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message b", null); assertNotEmptyAndClear(writer); final HtmlCounterRequestContextReport htmlCounterRequestContextReport = new HtmlCounterRequestContextReport( collector2.getRootCurrentContexts(collector2.getCounters()), null, new ArrayList<ThreadInformations>(), false, 500, writer); htmlCounterRequestContextReport.toHtml(); assertNotEmptyAndClear(writer); }
private boolean CheckVertical() { if (isGameOver()) return true; System.out.println("Vertical"); Counter _occurrence = new Counter(3, 0); /* * Horizontal scan */ for (int y = 0; y < BOARD_HEIGHT; y++) { _occurrence.reset(0); int _prevState = _board[0][y]; for (int x = 0; x < BOARD_HEIGHT; x++) { int _currentState = _board[x][y]; if (Counter.ComparePointAndCount(_prevState, _currentState, _occurrence)) { if (_occurrence.isAtMax()) { System.out.println("Game over, VERTICALSTAGE0"); GameOver(_prevState); return true; } } _prevState = _currentState; } } return false; }
/** * Builds a Trellis over a sentence, by starting at the state State, and advancing through all * legal extensions of each state already in the trellis. You should not have to modify this * code (or even read it, really). */ private Trellis<State> buildTrellis(List<String> sentence) { Trellis<State> trellis = new Trellis<State>(); trellis.setStartState(State.getStartState()); State stopState = State.getStopState(sentence.size() + 2); trellis.setStopState(stopState); Set<State> states = Collections.singleton(State.getStartState()); for (int position = 0; position <= sentence.size() + 1; position++) { Set<State> nextStates = new HashSet<State>(); for (State state : states) { if (state.equals(stopState)) continue; LocalTrigramContext localTrigramContext = new LocalTrigramContext( sentence, position, state.getPreviousPreviousTag(), state.getPreviousTag()); Counter<String> tagScores = localTrigramScorer.getLogScoreCounter(localTrigramContext); for (String tag : tagScores.keySet()) { double score = tagScores.getCount(tag); State nextState = state.getNextState(tag); trellis.setTransitionCount(state, nextState, score); nextStates.add(nextState); } } // System.out.println("States: "+nextStates); states = nextStates; } return trellis; }
/** * Test. * * @throws IOException e */ @Test public void testPeriodeNonTout() throws IOException { // counter avec période non TOUT et des requêtes collector.collectWithoutErrors(javaInformationsList); final String requestName = "test 1"; counter.bindContext(requestName, "complete test 1", null, -1); sqlCounter.addRequest("sql1", 10, 10, false, -1); counter.addRequest(requestName, 0, 0, false, 1000); counter.addRequest("test2", 1000, 500, false, 1000); counter.addRequest("test3", 10000, 500, true, 10000); collector.collectWithoutErrors(javaInformationsList); final HtmlReport htmlReport = new HtmlReport(collector, null, javaInformationsList, Period.SEMAINE, writer); htmlReport.toHtml("message 6", null); assertNotEmptyAndClear(writer); // période personnalisée final HtmlReport htmlReportRange = new HtmlReport( collector, null, javaInformationsList, Range.createCustomRange(new Date(), new Date()), writer); htmlReportRange.toHtml("message 6", null); assertNotEmptyAndClear(writer); }
/* * Matrix mult but with min-plus, and iterative. Each min-plus operation * that changes the path inserts it into a new queue */ public SparseMatrix apsp() { SparseMatrix shortestPaths = new SparseMatrix(this); SparseMatrix currentPairs = new SparseMatrix(this.rowDim, this.colDim); SparseMatrix newPairs = new SparseMatrix(this.rowDim, this.colDim); newPairs = new SparseMatrix(this); for (int d = 0; d < this.rowDim; d++) { shortestPaths.set(d, d, 0.0); } for (int d = 0; d < this.rowDim; d++) { newPairs.set(d, d, 0.0); } while (!newPairs.isEmpty()) { currentPairs = new SparseMatrix(newPairs); newPairs = new SparseMatrix(this.rowDim, this.colDim); for (int r : currentPairs.rows) { Counter row = currentPairs.getRow(r); for (int c : row.keySet()) { Counter oRow = this.getRow(c); for (int oc : oRow.keySet()) { double pathLength = currentPairs.get(r, c) + oRow.get(oc); if (pathLength < shortestPaths.getPath(r, oc)) { newPairs.set(r, oc, pathLength); shortestPaths.set(r, oc, pathLength); } } } } } return shortestPaths; }
/* * Takes a set of sketch nodes, and returns an ArrayList<Integer> such that * arr.get(i) gives the index of the sketch node that node i is closest too. * * Need to work the return values a little bit. Make a proper data * structure. */ public ArrayList<ArrayList<Integer>> distSketch(int len, Counter sketchNodes) { ArrayList<Integer> closestIndex = new ArrayList<Integer>(); for (int i = 0; i < len; i++) closestIndex.set(i, -1); ArrayList<Double> closestDist = new ArrayList<Double>(); for (int i = 0; i < len; i++) closestDist.set(i, Double.MAX_VALUE); ArrayList<ArrayList<Integer>> sketchReverseIndex = new ArrayList<ArrayList<Integer>>(); for (int index : sketchNodes.keySet()) { Counter distances = this.bfs(index); for (int j = 0; j < len; j++) { double curDist = closestDist.get(j); double dist = distances.getPath(index); if (dist < curDist) { closestIndex.set(j, index); } } sketchReverseIndex.add(new ArrayList<Integer>()); } for (int j = 0; j < len; j++) { int closest = closestIndex.get(j); sketchReverseIndex.get(closest).add(j); } // Return sketchReverseIndex, closestIndex forward index, and index // correspondence bimap return sketchReverseIndex; }
public void add(int r, int c, double v) { Counter newRow = new Counter(); newRow.add(c, v); this.addRow(r, newRow); rows.add(r); cols.add(c); }
/** * Tests that invocation on a stateful session bean fails, if a session hasn't been created * * @throws Exception */ @Test @Ignore( "No longer appropriate, since a proxy can no longer be created without a session, for a SFSB. " + "Need to think if there's a different way to test this. Else just remove this test") public void testSFSBAccessFailureWithoutSession() throws Exception { // create a locator without a session final StatefulEJBLocator<Counter> locator = new StatefulEJBLocator<Counter>( Counter.class, APP_NAME, MODULE_NAME, CounterBean.class.getSimpleName(), "", null, Affinity.NONE, null); final Counter counter = EJBClient.createProxy(locator); Assert.assertNotNull("Received a null proxy", counter); // invoke the bean without creating a session try { final int initialCount = counter.getCount(); Assert.fail( "Expected a EJBException for calling a stateful session bean without creating a session"); } catch (EJBException ejbe) { // expected logger.info("Received the expected exception", ejbe); } }
@Override public void run() { while (this.running) { try { Thread.sleep(this.runInterval); } catch (Exception e) { Log.exception("CountLogger.run: error in Thread.sleep", e); } final boolean logging = this.logging && Log.getLogLevel() <= this.logLevel; String s = ""; synchronized (this.counters) { for (final Counter counter : this.counters) { final long delta = counter.count - counter.lastCount; if (delta == 0L && !this.showAllNonzeroCounters) { continue; } if (logging) { if (!s.equals("")) { s += ", "; } if (this.showAllNonzeroCounters) { s = s + counter.name + " " + delta + "|" + counter.count; } else { s = s + counter.name + " " + delta; } } counter.lastCount = counter.count; } } if (logging) { Log.logAtLevel( this.logLevel, this.name + ": " + (s.equals("") ? "No non-zero counters" : s)); } } }
public void testPauseCountingAt() { c.mCountingFrom = f; c.mIsCounting = true; c.pauseCountingAt(t); assertEquals(t, c.mCountingFrom); assertEquals(v + (t - f), c.mValue); }
public SparseMatrix multiply(double f) { SparseMatrix multMat = new SparseMatrix(this.rowDim, this.colDim); for (int r : this.rows) { Counter row = this.getRow(r); multMat.addRow(r, row.multiplyImmutable(f)); } return multMat; }
protected void processLeftOvers(Member member, boolean force) { MessageOrder tmp = incoming.get(member); if (force) { Counter cnt = getInCounter(member); cnt.setCounter(Integer.MAX_VALUE); } if (tmp != null) processIncoming(tmp); }
public void removeEntries(SparseMatrix redundant) { for (int r : redundant.getRows()) { Counter row = redundant.getRow(r); for (int c : row.keySet()) { this.remove(r, c); } } }
/** {@inheritDoc} */ @Override public synchronized void incrAllCounters(AbstractCounters<Counter, CounterGroup> other) { for (CounterGroup group : other) { for (Counter counter : group) { findCounter(group.getName(), counter.getName()).increment(counter.getValue()); } } }
public static void main(String args[]) { Counter demo = new Counter(); demo.counterReset(); demo.countUp(5); demo.countUp(10); demo.countDown(20); }