@Test
 public void getUsage() {
   Count count = new Count();
   String actual = count.getUsage();
   String expected = "-count [-q] [-h] [-v] [-t [<storage type>]] <path> ...";
   assertEquals("Count.getUsage", expected, actual);
 }
Пример #2
0
  public static void main(String args[]) throws Exception {
    Count.start(1);
    Count.setMaxRowNums(1000);
    // 0=sleep time,1=thread num

    if (args.length >= 1) {
      sleepTime = Long.parseLong(args[0]);
    }
    if (args.length >= 2) {
      threads = Integer.parseInt(args[1]);
    }
    if (args.length >= 3) {
      hostStr = args[2];
    }
    if (args.length >= 4) {
      port = Integer.parseInt(args[3]);
    }
    hosts = hostStr.split(",");
    System.out.println("");
    System.out.println("request sleep time(ms): " + sleepTime);
    System.out.println("request thread num: " + threads);
    System.out.println("hosts: " + hostStr);
    System.out.println("port: " + port);
    System.out.println("");
    Thread[] ts = new Thread[threads];
    for (int i = 0; i < threads; i++) {
      ts[i] = new Thread(new WriteReadMain(), "WriteReadTest-" + i);
    }
    for (int j = 0; j < ts.length; j++) {
      ts[j].start();
      System.out.println("start thread:" + ts[j].getName());
    }
  }
 @Test
 public void getReplacementCommand() {
   Count count = new Count();
   String actual = count.getReplacementCommand();
   String expected = null;
   assertEquals("Count.getReplacementCommand", expected, actual);
 }
 @Test
 public void getName() {
   Count count = new Count();
   String actual = count.getName();
   String expected = "count";
   assertEquals("Count.getName", expected, actual);
 }
  @Test
  public void processPathWithQuotasByMultipleStorageTypesContent() throws Exception {
    Path path = new Path("mockfs:/test");

    when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);
    PathData pathData = new PathData(path.toString(), conf);

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    LinkedList<String> options = new LinkedList<String>();
    options.add("-q");
    options.add("-t");
    options.add("SSD,DISK");
    options.add("dummy");
    count.processOptions(options);
    count.processPath(pathData);
    String withStorageType =
        BYTES
            + StorageType.SSD.toString()
            + " "
            + StorageType.DISK.toString()
            + " "
            + pathData.toString();
    verify(out).println(withStorageType);
    verifyNoMoreInteractions(out);
  }
 @Test
 public void isDeprecated() {
   Count count = new Count();
   boolean actual = count.isDeprecated();
   boolean expected = false;
   assertEquals("Count.isDeprecated", expected, actual);
 }
  @Test
  public void processPathWithQuotasByQTVH() throws Exception {
    Path path = new Path("mockfs:/test");

    when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    LinkedList<String> options = new LinkedList<String>();
    options.add("-q");
    options.add("-t");
    options.add("-v");
    options.add("-h");
    options.add("dummy");
    count.processOptions(options);
    String withStorageTypeHeader =
        // <----13---> <-------17------>
        "    SSD_QUOTA     REM_SSD_QUOTA "
            + "   DISK_QUOTA    REM_DISK_QUOTA "
            + "ARCHIVE_QUOTA REM_ARCHIVE_QUOTA "
            + "PATHNAME";
    verify(out).println(withStorageTypeHeader);
    verifyNoMoreInteractions(out);
  }
  @Override
  public void meet(Count node) throws RuntimeException {
    builder.append("COUNT(");

    if (node.isDistinct()) {
      builder.append("DISTINCT ");
    }

    if (node.getArg() == null) {
      // this is a weird special case where we need to expand to all variables selected in the query
      // wrapped
      // by the group; we cannot simply use "*" because the concept of variables is a different one
      // in SQL,
      // so instead we construct an ARRAY of the bindings of all variables

      List<String> countVariables = new ArrayList<>();
      for (SQLVariable v : parent.getVariables().values()) {
        if (v.getProjectionType() == ValueType.NONE) {
          Preconditions.checkState(
              v.getExpressions().size() > 0, "no expressions available for variable");

          countVariables.add(v.getExpressions().get(0));
        }
      }
      builder.append("ARRAY[");
      Joiner.on(',').appendTo(builder, countVariables);
      builder.append("]");

    } else {
      optypes.push(ValueType.NODE);
      node.getArg().visit(this);
      optypes.pop();
    }
    builder.append(")");
  }
 // check no options is handled correctly
 @Test
 public void processOptionsNoOptions() {
   LinkedList<String> options = new LinkedList<String>();
   options.add("dummy");
   Count count = new Count();
   count.processOptions(options);
   assertFalse(count.isShowQuotas());
 }
Пример #10
0
 private boolean increment(T arg0) {
   Count count = data.get(arg0);
   if (count == null) {
     data.put(arg0, new Count(1));
   } else {
     count.inc();
   }
   return true;
 }
 // check missing arguments is handled correctly
 @Test
 public void processOptionsMissingArgs() {
   LinkedList<String> options = new LinkedList<String>();
   Count count = new Count();
   try {
     count.processOptions(options);
     fail("Count.processOptions - NotEnoughArgumentsException not thrown");
   } catch (NotEnoughArgumentsException e) {
   }
   assertFalse(count.isShowQuotas());
 }
Пример #12
0
 private boolean decrement(T arg0) {
   Count count = data.get(arg0);
   if (count == null) {
     return false;
   } else {
     count.dec();
     if (count.getCount() == 0) {
       data.remove(arg0);
     }
   }
   return true;
 }
Пример #13
0
 @Override
 public void startCount(final Count count, final BufferedWriter out) throws IOException {
   out.write("\t<count");
   out.write(" loc_id=\"" + count.getLocId() + "\"");
   out.write(" cs_id=\"" + count.getCsId() + "\"");
   if (count.getCoord() != null) {
     final Coord coord = coordinateTransformation.transform(count.getCoord());
     out.write(" x=\"" + coord.getX() + "\"");
     out.write(" y=\"" + coord.getY() + "\"");
   }
   out.write(">\n");
 }
Пример #14
0
 public static void main(String[] args) {
   System.out.println("Word Count Demo: ");
   Count.wordCount("SteveJobsCommencementSpeech.txt");
   System.out.println("");
   Count.wordCount("Koran.txt");
   System.out.println("\nWord Count Analysis: ");
   System.out.println("--------------------------------------------");
   System.out.println("Average time in milliseconds after 10 runs: ");
   System.out.println("Steve's Job's Commencement with 2,290 Total Words:");
   Count.averageWordCount("SteveJobsCommencementSpeech.txt");
   System.out.println("The Koran with 168,106 Total Words");
   Count.averageWordCount("Koran.txt");
   System.out.println("Wikipedia Snippet with 1,061 Total Words:");
   Count.averageWordCount("computer.txt");
 }
Пример #15
0
  public RuneflareTrap(GameState state) {
    super(state);

    // If an opponent drew three or more cards this turn, you may pay (R)
    // rather than pay Runeflare Trap's mana cost.
    state.ensureTracker(new CardsDrawn());
    SetGenerator opponents = OpponentsOf.instance(You.instance());
    SetGenerator cardsDrawn = MaximumPerPlayer.instance(CardsDrawn.class, opponents);
    SetGenerator trapCondition = Intersect.instance(cardsDrawn, Between.instance(3, null));
    this.addAbility(
        new Trap(
            state,
            this.getName(),
            trapCondition,
            "If an opponent drew three or more cards this turn",
            "(R)"));

    // Runeflare Trap deals damage to target player equal to the number of
    // cards in that player's hand.
    Target target = this.addTarget(Players.instance(), "target player");

    SetGenerator amount = Count.instance(InZone.instance(HandOf.instance(targetedBy(target))));
    this.addEffect(
        spellDealDamage(
            amount,
            targetedBy(target),
            "Runeflare Trap deals damage to target player equal to the number of cards in that player's hand."));
  }
Пример #16
0
  public ArrowVolleyTrap(GameState state) {
    super(state);

    SetGenerator trapCondition =
        Intersect.instance(Between.instance(4, null), Count.instance(Attacking.instance()));
    this.addAbility(
        new org.rnd.jmagic.abilities.Trap(
            state,
            this.getName(),
            trapCondition,
            "If four or more creatures are attacking",
            "(1)(W)"));

    Target target = this.addTarget(Attacking.instance(), "up to five target attacking creatures");
    target.setNumber(1, 5);

    this.setDivision(Union.instance(numberGenerator(5), Identity.instance("damage")));
    EventType.ParameterMap damageParameters = new EventType.ParameterMap();
    damageParameters.put(EventType.Parameter.SOURCE, This.instance());
    damageParameters.put(
        EventType.Parameter.TAKER,
        ChosenTargetsFor.instance(Identity.instance(target), This.instance()));
    this.addEffect(
        new EventFactory(
            EventType.DISTRIBUTE_DAMAGE,
            damageParameters,
            "Arrow Volley Trap deals 5 damage divided as you choose among any number of target attacking creatures."));
  }
Пример #17
0
 @Override
 public PercolateShardResponse doPercolate(
     PercolateShardRequest request, PercolateContext context) {
   long count = 0;
   Engine.Searcher percolatorSearcher = context.indexShard().acquireSearcher("percolate");
   try {
     Count countCollector = count(logger, context);
     queryBasedPercolating(percolatorSearcher, context, countCollector);
     count = countCollector.counter();
   } catch (Throwable e) {
     logger.warn("failed to execute", e);
   } finally {
     percolatorSearcher.close();
   }
   return new PercolateShardResponse(count, context, request.index(), request.shardId());
 }
Пример #18
0
    public AgadeemOccultistAbility0(GameState state) {
      super(
          state,
          "(T): Put target creature card from an opponent's graveyard onto the battlefield under your control if its converted mana cost is less than or equal to the number of Allies you control.");
      this.costsTap = true;

      SetGenerator creatureCards = HasType.instance(Type.CREATURE);
      SetGenerator inOpponentsYard =
          InZone.instance(GraveyardOf.instance(OpponentsOf.instance(You.instance())));
      Target t =
          this.addTarget(
              Intersect.instance(creatureCards, inOpponentsYard),
              "target creature card from an opponent's graveyard");

      EventFactory move =
          new EventFactory(
              EventType.PUT_ONTO_BATTLEFIELD,
              "Put target creature card from an opponent's graveyard onto the battlefield under your control");
      move.parameters.put(EventType.Parameter.CAUSE, This.instance());
      move.parameters.put(EventType.Parameter.CONTROLLER, You.instance());
      move.parameters.put(EventType.Parameter.OBJECT, targetedBy(t));

      SetGenerator lessThanOrEqualNumAllies =
          Between.instance(null, Count.instance(ALLIES_YOU_CONTROL));
      SetGenerator condition =
          Intersect.instance(ConvertedManaCostOf.instance(targetedBy(t)), lessThanOrEqualNumAllies);

      EventFactory effect =
          new EventFactory(
              EventType.IF_CONDITION_THEN_ELSE,
              "Put target creature card from an opponent's graveyard onto the battlefield under your control if its converted mana cost is less than or equal to the number of Allies you control.");
      effect.parameters.put(EventType.Parameter.IF, condition);
      effect.parameters.put(EventType.Parameter.THEN, Identity.instance(move));
      this.addEffect(effect);
    }
  /**
   * Applies {@code ApproximateUnique(sampleSize)} verifying that the estimation error falls within
   * the maximum allowed error of {@code 2/sqrt(sampleSize)}.
   */
  private static void runApproximateUniquePipeline(int sampleSize) {
    Pipeline p = TestPipeline.create();

    PCollection<String> input = p.apply(Create.of(TEST_LINES));
    PCollection<Long> approximate = input.apply(ApproximateUnique.<String>globally(sampleSize));
    final PCollectionView<Long> exact =
        input
            .apply(RemoveDuplicates.<String>create())
            .apply(Count.<String>globally())
            .apply(View.<Long>asSingleton());

    PCollection<KV<Long, Long>> approximateAndExact =
        approximate.apply(
            ParDo.of(
                    new DoFn<Long, KV<Long, Long>>() {
                      @Override
                      public void processElement(ProcessContext c) {
                        c.output(KV.of(c.element(), c.sideInput(exact)));
                      }
                    })
                .withSideInputs(exact));

    DataflowAssert.that(approximateAndExact).satisfies(new VerifyEstimatePerKeyFn(sampleSize));

    p.run();
  }
Пример #20
0
  @Override
  public void run() {
    Count.setStartWriteNum(startWriteNum);
    Config cfg = new Config();
    Ploy ploy = new LoopPloy();
    JedisShards redis = new JedisShards("127.0.0.1:6379,127.0.0.1:6379", 3000, ploy, cfg);

    //
    RedisCommand read = redis.create(RedisCommand.class);
    RedisCommand write = redis.create(RedisCommand.class, Selector.Write);
    try {
      final WriteReadService writeRead = new WriteReadService(write, read);

      while (true) {

        try {

          writeRead.read();
        } catch (Exception e1) {
          e1.printStackTrace();
        }
        try {
          Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #21
0
 @Test
 public void backwardsEnqueue_inadequateCount() {
   new LogicAsserter()
       .stream(
           conj(Queue.O.last(42, B, Queue.of(Count.of(null), new Var())), Queue.O.last(42, A, B)))
       .workUnits(1)
       .test();
 }
Пример #22
0
 public ElspethTirelAbility0(GameState state) {
   super(state, +2, "You gain 1 life for each creature you control.");
   this.addEffect(
       gainLife(
           You.instance(),
           Count.instance(CREATURES_YOU_CONTROL),
           "You gain 1 life for each creature you control."));
 }
Пример #23
0
  @Test
  public void backwardsEnqueue_success() {
    DiffList<Cons<Var, Cons<Var, Var>>, Var> startList =
        DiffList.of(Cons.of(new Var(), Cons.of(new Var(), new Var())), new Var());

    new LogicAsserter()
        .stream(
            conj(
                Queue.O.last(10, A, Queue.of(Count.of(Count.of(null)), startList)),
                Queue.O.last(20, EMPTY, A),
                same(startList.head().cdr().cdr(), null),
                same(C, startList.head())))
        .workUnits(2)
        .addRequestedVar(C)
        .startSubst()
        .put(C, Cons.list(Arrays.asList(20, 10)))
        .test();
  }
Пример #24
0
    public PsychosisCrawlerAbility0(GameState state) {
      super(
          state,
          "Psychosis Crawler's power and toughness are each equal to the number of cards in your hand.",
          Characteristics.Characteristic.POWER,
          Characteristics.Characteristic.TOUGHNESS);

      SetGenerator number = Count.instance(InZone.instance(HandOf.instance(You.instance())));
      this.addEffectPart(setPowerAndToughness(This.instance(), number, number));
    }
  // check the correct header is produced with no quotas (-v)
  @Test
  public void processOptionsHeaderNoQuotas() {
    LinkedList<String> options = new LinkedList<String>();
    options.add("-v");
    options.add("dummy");

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    count.processOptions(options);

    String noQuotasHeader =
        // <----12----> <----12----> <-------18------->
        "   DIR_COUNT   FILE_COUNT       CONTENT_SIZE PATHNAME";
    verify(out).println(noQuotasHeader);
    verifyNoMoreInteractions(out);
  }
Пример #26
0
 @Test
 public void enqueue() {
   new LogicAsserter()
       .stream(
           conj(
               Queue.O.last(42, EMPTY, A),
               Queue.O.last("1011", A, B),
               Queue.O.last(false, B, C),
               Queue.O.last('a', C, FINISH_QUEUE),
               same(null, FINISH_QUEUE.contents().hole()),
               same(D, FINISH_QUEUE.contents().head()),
               same(E, FINISH_QUEUE.size())))
       .addRequestedVar(D, E)
       .workUnits(2)
       .startSubst()
       .put(D, Cons.list(Arrays.asList(42, "1011", false, 'a')))
       .put(E, Count.of(Count.of(Count.of(Count.of(null)))))
       .test();
 }
  @Test
  public void processPathNoQuotasHuman() throws Exception {
    Path path = new Path("mockfs:/test");

    when(mockFs.getFileStatus(eq(path))).thenReturn(fileStat);
    PathData pathData = new PathData(path.toString(), conf);

    PrintStream out = mock(PrintStream.class);

    Count count = new Count();
    count.out = out;

    LinkedList<String> options = new LinkedList<String>();
    options.add("-h");
    options.add("dummy");
    count.processOptions(options);

    count.processPath(pathData);
    verify(out).println(HUMAN + NO_QUOTAS + path.toString());
  }
Пример #28
0
    public ConsumingAberrationAbility0(GameState state) {
      super(
          state,
          "Consuming Aberration's power and toughness are each equal to the number of cards in your opponents' graveyards.",
          Characteristics.Characteristic.POWER,
          Characteristics.Characteristic.TOUGHNESS);

      SetGenerator number =
          Count.instance(
              InZone.instance(GraveyardOf.instance(OpponentsOf.instance(You.instance()))));
      this.addEffectPart(setPowerAndToughness(This.instance(), number, number));
    }
Пример #29
0
 public static void processEpub(String bookPath, String dest)
     throws FileNotFoundException, IOException {
   EpubReader reader = new EpubReader();
   Book b = reader.readEpub(new FileInputStream(new File(bookPath)));
   String content = "";
   int pagecount = 1;
   int tempCounter;
   Count cnt = new Count(0, 0);
   for (Resource res : b.getContents()) {
     content = new String(res.getData());
     Document doc = Jsoup.parse(content, "UTF-8");
     // http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"");
     Element elem = new Element(Tag.valueOf("meta"), "");
     elem.attr("http-equiv", "content-type");
     elem.attr("content", "text/html; charset=utf-8");
     doc.head().after(elem);
     System.out.println(doc.head().data());
     Element ele = doc.body();
     alterElement(ele);
     Count cTemp = modify(ele, cnt);
     cnt.setCount(cTemp.getCount());
     cnt.setPgCount(cTemp.getPgCount());
     doc.body().html(ele.html());
     res.setData(doc.html().getBytes());
     if (res.getMediaType() == null) res.setMediaType(new MediaType("html", "html"));
   }
   EpubWriter wr = new EpubWriter();
   wr.write(b, new FileOutputStream(new File(dest)));
 }
  // check the correct description is returned
  @Test
  public void getDescription() {
    Count count = new Count();
    String actual = count.getDescription();
    String expected =
        "Count the number of directories, files and bytes under the paths\n"
            + "that match the specified file pattern.  The output columns are:\n"
            + "DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME\n"
            + "or, with the -q option:\n"
            + "QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA\n"
            + "      DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME\n"
            + "The -h option shows file sizes in human readable format.\n"
            + "The -v option displays a header line.\n"
            + "The -t option displays quota by storage types.\n"
            + "It must be used with -q option.\n"
            + "If a comma-separated list of storage types is given after the -t option, \n"
            + "it displays the quota and usage for the specified types. \n"
            + "Otherwise, it displays the quota and usage for all the storage \n"
            + "types that support quota";

    assertEquals("Count.getDescription", expected, actual);
  }