/** @throws Exception If failed. */
  public void testClientAffinity() throws Exception {
    GridClientData partitioned = client.data(PARTITIONED_CACHE_NAME);

    Collection<Object> keys = new ArrayList<>();

    keys.addAll(Arrays.asList(Boolean.TRUE, Boolean.FALSE, 1, Integer.MAX_VALUE));

    Random rnd = new Random();
    StringBuilder sb = new StringBuilder();

    // Generate some random strings.
    for (int i = 0; i < 100; i++) {
      sb.setLength(0);

      for (int j = 0; j < 255; j++)
        // Only printable ASCII symbols for test.
        sb.append((char) (rnd.nextInt(0x7f - 0x20) + 0x20));

      keys.add(sb.toString());
    }

    // Generate some more keys to achieve better coverage.
    for (int i = 0; i < 100; i++) keys.add(UUID.randomUUID());

    for (Object key : keys) {
      UUID nodeId = grid(0).mapKeyToNode(PARTITIONED_CACHE_NAME, key).id();

      UUID clientNodeId = partitioned.affinity(key);

      assertEquals(
          "Invalid affinity mapping for REST response for key: " + key, nodeId, clientNodeId);
    }
  }
 public static void main(String[] args) throws Exception {
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < N_ELEMENTS; i++)
     for (int j = 0; j < N_GENES; j++) GRID[i][j] = new AtomicInteger(rand.nextInt(1000));
   for (int i = 0; i < N_EVOLVERS; i++) exec.execute(new Evolver());
   TimeUnit.SECONDS.sleep(5);
   exec.shutdownNow();
 }
 @Override
 @EventHandler
 public void onChatReceived(ChatReceivedEvent event) {
   super.onChatReceived(event);
   String message = Util.stripColors(event.getMessage());
   if (message.startsWith("Please register with \"/register")) {
     String password = Util.generateRandomString(10 + random.nextInt(6));
     bot.say("/register " + password + " " + password);
   } else if (message.contains("You are not member of any faction.")
       && spamMessage != null
       && createFaction) {
     String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4));
     bot.say(msg);
   }
   for (String s : captchaList) {
     Matcher captchaMatcher = Pattern.compile(s).matcher(message);
     if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1));
   }
 }
  @BeforeMethod
  public void beforeMethod() throws IOException {
    if (buffer != null) {
      buffer.close();

      deleteUsedFiles(FILE_COUNT);
    }

    initBuffer();

    Random random = new Random();
    seed = (byte) (random.nextInt() & 0xFF);
  }
  @EventHandler
  public void onTick(TickEvent event) {
    if (!bot.hasSpawned() || !bot.isConnected()) return;
    if (tickDelay > 0) {
      tickDelay--;
      return;
    }

    MainPlayerEntity player = bot.getPlayer();
    if (player == null || !bot.hasSpawned() || spamMessage == null) return;
    if (nextMessage > 0) {
      nextMessage--;
      return;
    }
    try {
      String message = spamMessage;
      MessageFormatter formatter = new MessageFormatter();
      synchronized (bots) {
        if (bots.size() > 0) {
          DarkBotMCSpambot bot = bots.get(++nextBot >= bots.size() ? nextBot = 0 : nextBot);
          if (bot != null && bot.bot != null && bot.bot.getSession() != null)
            formatter.setVariable("bot", bot.bot.getSession().getUsername());
        }
      }
      if (spamList.length > 0) {
        formatter.setVariable(
            "spamlist",
            spamList[++nextSpamList >= spamList.length ? nextSpamList = 0 : nextSpamList]);
      }
      formatter.setVariable("rnd", Util.generateRandomString(15 + random.nextInt(6)));
      formatter.setVariable(
          "msg",
          Character.toString(
              msgChars[++nextMsgChar >= msgChars.length ? nextMsgChar = 0 : nextMsgChar]));
      message = formatter.format(message);
      bot.say(message);
    } catch (Exception e) {
      e.printStackTrace();
    }
    nextMessage = messageDelay;
  }
    public void run() {
      while (!Thread.interrupted()) {
        // Randomly select an element to work on:
        int element = rand.nextInt(N_ELEMENTS);
        for (int i = 0; i < N_GENES; i++) {
          int previous = element - 1;
          if (previous < 0) previous = N_ELEMENTS - 1;
          int next = element + 1;
          if (next >= N_ELEMENTS) next = 0;
          int oldvalue = GRID[element][i].get();

          // Perform some kind of modeling calculation:
          int newvalue = oldvalue + GRID[previous][i].get() + GRID[next][i].get();
          newvalue /= 3; // Average the three values
          if (!GRID[element][i].compareAndSet(oldvalue, newvalue)) {
            // Policy here to deal with failure. Here, we
            // just report it and ignore it; our model
            // will eventually deal with it.
            System.out.println("Old value changed from " + oldvalue);
          }
        }
      }
    }
 @EventHandler
 public void onPacketProcess(PacketProcessEvent event) {
   // System.out.println("Packet received: " + event.getPacket().getId()
   // + " (" + event.getPacket() + ")");
   Packet packet = event.getPacket();
   switch (packet.getId()) {
     case 0:
       connectionHandler.sendPacket(new Packet0KeepAlive(new Random().nextInt()));
       break;
     case 3:
       String message = ((Packet3Chat) packet).message;
       message = removeColors(message);
       System.out.println("[" + bot.getSession().getUsername() + "] " + message);
       String testMessage = "[MineCaptcha] To be unmuted answer this question: What is ";
       String testMessage2 = "Please type '";
       String testMessage3 = "' to continue sending messages/commands";
       if (message.contains(testMessage)) {
         try {
           String captcha = message.split(Pattern.quote(testMessage))[1].split("[ \\?]")[0];
           ScriptEngineManager mgr = new ScriptEngineManager();
           ScriptEngine engine = mgr.getEngineByName("JavaScript");
           String solved = engine.eval(captcha).toString();
           solved = solved.split("\\.")[0];
           connectionHandler.sendPacket(new Packet3Chat(solved));
         } catch (Exception exception) {
           exception.printStackTrace();
         }
       } else if (message.contains(testMessage2) && message.contains(testMessage3)) {
         try {
           String captcha =
               message.split(Pattern.quote(testMessage2))[1].split(Pattern.quote(testMessage3))[0];
           connectionHandler.sendPacket(new Packet3Chat(captcha));
         } catch (Exception exception) {
           exception.printStackTrace();
         }
       } else if (message.startsWith("Please register with \"/register")) {
         String password = "";
         for (int i = 0; i < 10 + random.nextInt(6); i++)
           password += alphas[random.nextInt(alphas.length)];
         bot.say("/register " + password + " " + password);
       } else if (message.startsWith("/uc ")) {
         connectionHandler.sendPacket(new Packet3Chat(message));
       } else if ((message.contains("do the crime") && message.contains("do the time"))
           || message.contains("You have been muted")) {
         connectionHandler.sendPacket(new Packet3Chat("\247Leaving!"));
       } else if (message.contains(owner + " has requested to teleport to you.")) {
         connectionHandler.sendPacket(new Packet3Chat("/tpaccept"));
       } else if (message.contains(owner)) {
         if (message.contains("Go ")) {
           spamMessage = message.substring(message.indexOf("Go ") + "Go ".length());
         } else if (message.contains("Stop")) {
           spamMessage = null;
           bot.getTaskManager().stopAll();
         } else if (message.contains("Die")) {
           die = true;
         } else if (message.contains("Say ")) {
           connectionHandler.sendPacket(
               new Packet3Chat(message.substring(message.indexOf("Say ") + "Say ".length())));
         } else if (message.contains("Leave")) {
           connectionHandler.sendPacket(new Packet255KickDisconnect("Quit"));
         } else if (message.contains("Tool")) {
           MainPlayerEntity player = bot.getPlayer();
           if (player == null) return;
           PlayerInventory inventory = player.getInventory();
           inventory.setCurrentHeldSlot(
               Integer.parseInt(
                   message.substring(message.indexOf("Tool ") + "Tool ".length()).split(" ")[0]));
         } else if (message.contains("DropId ")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           String substring =
               message.substring(message.indexOf("DropId ") + "DropId ".length()).split(" ")[0];
           int id = Integer.parseInt(substring);
           for (int slot = 0; slot < 40; slot++) {
             ItemStack item = inventory.getItemAt(slot);
             if (item != null && item.getId() == id) {
               inventory.selectItemAt(slot, true);
               inventory.dropSelectedItem();
             }
           }
           inventory.close();
         } else if (message.contains("Drop")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           if (message.contains("Drop ")) {
             String substring =
                 message.substring(message.indexOf("Drop ") + "Drop ".length()).split(" ")[0];
             try {
               int slot = Integer.parseInt(substring);
               if (slot < 0 || slot >= 40) return;
               if (inventory.getItemAt(slot) != null) {
                 inventory.selectItemAt(slot, true);
                 inventory.dropSelectedItem();
               }
               return;
             } catch (NumberFormatException e) {
             }
           }
           for (int slot = 0; slot < 40; slot++) {
             if (inventory.getItemAt(slot) != null) {
               inventory.selectItemAt(slot, true);
               inventory.dropSelectedItem();
             }
           }
           inventory.close();
         } else if (message.contains("Switch ")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           String substring = message.substring(message.indexOf("Switch ") + "Switch ".length());
           try {
             int slot1 = Integer.parseInt(substring.split(" ")[0]);
             int slot2 = Integer.parseInt(substring.split(" ")[1]);
             if (slot1 < 0 || slot1 >= 45 || slot2 < 0 || slot2 >= 45) return;
             inventory.selectItemAt(slot1);
             inventory.selectItemAt(slot2);
             inventory.selectItemAt(slot1);
           } catch (NumberFormatException e) {
           }
           // inventory.close();
         } else if (message.contains("Equip")) {
           MainPlayerEntity player = bot.getPlayer();
           PlayerInventory inventory = player.getInventory();
           boolean helmet = inventory.getArmorAt(0) != null;
           boolean chestplate = inventory.getArmorAt(1) != null;
           boolean leggings = inventory.getArmorAt(2) != null;
           boolean boots = inventory.getArmorAt(3) != null;
           boolean changed = false;
           for (int i = 0; i < 36; i++) {
             ItemStack item = inventory.getItemAt(i);
             if (item == null) continue;
             int armorSlot;
             int id = item.getId();
             if (!helmet
                 && (id == 86 || id == 298 || id == 302 || id == 306 || id == 310 || id == 314)) {
               armorSlot = 0;
               helmet = true;
             } else if (!chestplate
                 && (id == 299 || id == 303 || id == 307 || id == 311 || id == 315)) {
               armorSlot = 1;
               chestplate = true;
             } else if (!leggings
                 && (id == 300 || id == 304 || id == 308 || id == 312 || id == 316)) {
               armorSlot = 2;
               leggings = true;
             } else if (!boots
                 && (id == 301 || id == 305 || id == 309 || id == 313 || id == 317)) {
               armorSlot = 3;
               boots = true;
             } else if (helmet && chestplate && leggings && boots) break;
             else continue;
             inventory.selectItemAt(i);
             inventory.selectArmorAt(armorSlot);
             changed = true;
           }
           if (!changed) {
             for (int i = 0; i < 36; i++) {
               ItemStack item = inventory.getItemAt(i);
               if (item != null) continue;
               int armorSlot;
               if (helmet) {
                 armorSlot = 0;
                 helmet = false;
               } else if (chestplate) {
                 armorSlot = 1;
                 chestplate = false;
               } else if (leggings) {
                 armorSlot = 2;
                 leggings = false;
               } else if (boots) {
                 armorSlot = 3;
                 boots = false;
               } else if (!helmet && !chestplate && !leggings && !boots) break;
               else continue;
               inventory.selectArmorAt(armorSlot);
               inventory.selectItemAt(i);
             }
           }
           inventory.close();
           bot.say("Equipped armor.");
         } else if (message.contains("Owner ")) {
           String name =
               message.substring(message.indexOf("Owner ") + "Owner ".length()).split(" ")[0];
           owner = name;
           bot.say("Set owner to " + name);
         }
       } else if (message.contains("You are not member of any faction.")
           && spamMessage != null
           && createFaction) {
         String msg = "/f create ";
         for (int i = 0; i < 7 + random.nextInt(3); i++)
           msg += alphas[random.nextInt(alphas.length)];
         bot.say(msg);
       }
       if (message.matches("[\\*]*SPQR [\\w]{1,16} invited you to SPQR")) {
         bot.say("/f join SPQR");
         bot.say("\247asdf");
       }
       break;
     case 8:
       Packet8UpdateHealth updateHealth = (Packet8UpdateHealth) packet;
       if (updateHealth.healthMP <= 0) connectionHandler.sendPacket(new Packet205ClientCommand(1));
       break;
     case 9:
       TaskManager taskManager = bot.getTaskManager();
       taskManager.stopAll();
       break;
   }
 }
  private DarkBotMCSpambot(
      DarkBot darkBot,
      String server,
      String username,
      String password,
      String sessionId,
      String loginProxy,
      String proxy,
      String owner) {
    synchronized (bots) {
      bots.add(this);
      // slotsTaken.incrementAndGet();
      synchronized (slotsTaken) {
        slotsTaken.notifyAll();
      }
    }
    MinecraftBotData.Builder builder = MinecraftBotData.builder();
    // botData.nickname = "";
    // for(int i = 0; i < 10; i++)
    // botData.nickname += alphas[random.nextInt(alphas.length)];
    if (proxy != null && !proxy.isEmpty()) {
      int port = 80;
      ProxyType type = ProxyType.SOCKS;
      if (proxy.contains(":")) {
        String[] parts = proxy.split(":");
        proxy = parts[0];
        port = Integer.parseInt(parts[1]);
        if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1];
      }
      builder.withSocksProxy(new ProxyData(proxy, port, type));
      this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port));
    }
    if (loginProxy != null && !loginProxy.isEmpty()) {
      int port = 80;
      if (loginProxy.contains(":")) {
        String[] parts = loginProxy.split(":");
        loginProxy = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP));
      this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port));
    }
    builder.withUsername(username);
    if (sessionId != null) builder.withSessionId(sessionId);
    else builder.withPassword(password);
    if (server != null && !server.isEmpty()) {
      int port = 25565;
      if (server.contains(":")) {
        String[] parts = server.split(":");
        server = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withServer(server).withPort(port);
    } else throw new IllegalArgumentException("Unknown server!");

    this.owner = owner;
    MinecraftBotData botData = builder.build();
    System.setProperty("socksProxyHost", "");
    System.setProperty("socksProxyPort", "");
    System.out.println("[" + username + "] Connecting...");
    bot = new MinecraftBot(darkBot, botData);
    bot.setMovementDisabled(true);
    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    // System.gc();
    System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")");
    bot.getEventManager().registerListener(this);
    bot.getGameHandler().registerListener(this);

    long lastShoutTime = System.currentTimeMillis();
    while (bot.isConnected()) {
      if (die) {
        connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye"));
        return;
      }
      try {
        Thread.sleep(3000 + random.nextInt(1000));
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
      if (!bot.hasSpawned()) continue;
      connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt()));
      if (spamMessage == null || !canSpam) continue;
      String message = spamMessage;
      if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]);
      if (nextSkill >= skills.length) nextSkill = 0;
      if (message.contains("%bot")) {
        synchronized (bots) {
          message =
              message.replace(
                  "%bot",
                  bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++)
                      .bot
                      .getSession()
                      .getUsername());
        }
      }
      if (message.contains("%spamlist"))
        message = message.replace("%spamlist", spamList[nextSpamList++]);
      if (nextSpamList >= spamList.length) nextSpamList = 0;
      if (message.contains("%rnd")) {
        int length = 1;
        int index = message.indexOf("%rnd") + "%rnd".length();
        int lastIndex;
        for (lastIndex = index; lastIndex < message.length(); lastIndex++)
          if (Character.isDigit(message.charAt(lastIndex))) lastIndex++;
          else break;
        if (lastIndex > message.length()) lastIndex--;
        try {
          System.out.println(index + "," + lastIndex + "," + message.length());
          length = Integer.parseInt(message.substring(index, lastIndex));
        } catch (Exception exception) {
        }

        String randomChars = "";
        for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)];
        message = message.replace("%rnd", randomChars);
      }
      if (message.contains("%msg"))
        message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", "");
      if (message.contains("%ernd")) {
        message = message.replace("%ernd", "");
        int extraMessageLength = 15 + random.nextInt(6);
        message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " [";
        extraMessageLength -= 3;
        for (int i = 0; i < extraMessageLength; i++)
          message += alphas[random.nextInt(alphas.length)];
        message += "]";
      } else message = message.substring(0, Math.min(100, message.length()));
      connectionHandler.sendPacket(new Packet3Chat(message));
    }
    synchronized (bots) {
      bots.remove(this);
    }
    amountJoined.decrementAndGet();
    slotsTaken.decrementAndGet();
    synchronized (slotsTaken) {
      slotsTaken.notifyAll();
    }
  }
  static void parTest() {
    final int N = 100000;
    final ConcurrentDoubleOrderedListMap<String> map = new ConcurrentDoubleOrderedListMap<String>();
    final double[] keys = new double[N];

    final Random r = new Random();
    for (int i = 0; i < N; i++) {
      int x = r.nextInt();
      keys[i] = x;
      map.put(x, "" + x);
    }
    map.doSanityCheck();
    System.out.println("Start parallel...");

    long s = System.currentTimeMillis();
    for (int i = 0; i < N; i++) {
      map.get(keys[i]);
    }
    long e = System.currentTimeMillis();
    System.out.println("Exec time:" + (e - s) + "ms");

    final int nReader = 8;
    final int nReplacer = 4;
    final int nWriter = 4;
    final int nThread = nReader + nReplacer + nWriter;
    for (int i = 0; i < 5; i++) {
      ParUtil.parallel(
          nThread,
          new ParUtil.CallableBlock() {
            @Override
            public void call(int index) {
              if (index < nReader) {
                for (int j = 0; j < 35; j++) {
                  for (int i = index; i < N; i += nReader) {
                    String val = map.get(keys[i]);
                    assert val != null && val.equals("" + keys[i])
                        : "key:" + keys[i] + ", val:" + val;
                  }
                }
                // System.out.println("Finished reader thread:" + index);
              } else if (index < nReader + nReplacer) {
                for (int j = 0; j < 5; j++) {
                  for (int i = index; i < N; i += nReplacer) {
                    boolean replaced = map.replace(keys[i], "" + keys[i], "" + keys[i]);
                    assert replaced;
                  }
                }
                // System.out.println("Finished writer(replace) thread:" + index);
              } else {
                for (int i = 0; i < 2 * N; i++) {
                  int x = r.nextInt();
                  map.putAtomic(x, "" + x);
                }
                // System.out.println("Finished writer thread:" + index);
              }
            }
          });
      System.out.println("Finished all parallel... i:" + i);
      map.doSanityCheck();
    }
    /*
    System.out.println("Node.pool size:"+Node.pool.size());
    while(true) {
        Node n = Node.pool.poll();
        if (n==null) break;
        System.out.println("n.refcnt:"+n.refcnt);
    }
    System.out.println("fill ratio:"+map._fillRatio());
    */
  }