Exemplo n.º 1
0
  public static void main(String[] args) {
    List<String> list = new ArrayList<String>();

    Collections.addAll(list, "A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
    System.out.println(list);
    System.out.println("list.subList(3,8): " + list.subList(3, 8));
    System.out.println("list.subList(3,8).get(2): " + list.subList(3, 8).get(2));

    System.out.println("list.subList(3,8).set(2,\"B\"):");
    list.subList(3, 8).set(2, "B");
    System.out.println(list);
    System.out.println("list.indexOf(\"B\"): " + list.indexOf("B"));
    System.out.println("list.subList(3,8).indexOf(\"B\"): " + list.subList(3, 8).indexOf("B"));
    System.out.println(list);
    System.out.println("Collections.reverse(list.subList(3,8)):");
    Collections.reverse(list.subList(3, 8));
    System.out.println(list);
    System.out.println("Collections.rotate(list.subList(3,8), 2):");
    Collections.rotate(list.subList(3, 8), 2);
    System.out.println(list);
    System.out.println("Collections.fill(list.subList(3,8), \"X\"):");
    Collections.fill(list.subList(3, 8), "X");
    System.out.println(list);
    list.subList(3, 8).clear();
    System.out.println(list);
  }
Exemplo n.º 2
0
  public static void main(String args[]) {
    String os[] = {"GNU/Linux", "Windows 7", "Solaris", "Amiga OS", "FreeBSD", "Mac OS X"};

    LinkedList<String> al_operating_systems =
        new LinkedList<>(Arrays.asList(os)); // Lista di os
    Collections.sort(al_operating_systems); // ordina la collezione
    System.out.print("Collezione ordinata: ");
    System.out.println(al_operating_systems);

    int ix =
        Collections.binarySearch(
            al_operating_systems, "Be OS", null); // ricerca se presente l'elemento Be Os
    if (ix < 0) // se non è presente aggiungilo
    al_operating_systems.add(-(ix + 1), "Be OS");

    System.out.print("Collezione con elemento Be OS aggiunto: ");
    System.out.println(al_operating_systems);

    Collections.rotate(al_operating_systems, 3); // ruota gli elementi di 3 posizioni
    System.out.print("Collezione con elementi ruotati: ");
    System.out.println(al_operating_systems);

    System.out.print("Elemento della collezione minore: ["); // elemento più piccolo
    System.out.println(Collections.min(al_operating_systems) + "]");

    System.out.print("Elemento della collezione maggiore: ["); // elemento più grande
    System.out.println(Collections.max(al_operating_systems) + "]");
  }
Exemplo n.º 3
0
 private Component getNextComponent() {
   Component component;
   synchronized (components) {
     component = components.get(0);
     Collections.rotate(components, 1);
   }
   return component;
 }
  /**
   * method to add a recent file with its associated attributes
   *
   * @param file the recent file object
   * @param attributes the string attributes array
   * @throws FileNotFoundException
   * @throws IOException
   */
  public void add(File file, String[] attributes) throws FileNotFoundException, IOException {
    // process only if the file is a valid file
    if (file != null) {
      // create a recent file object based on the input parameter
      RecentFile recentFile = new RecentFile(file, attributes);

      // now if the recent file list doesnt contian the recent file then
      if (!recentFilesList.contains(recentFile)) {

        // check if the recent file list size is less than the max record size
        if (recentFilesList.size() < maxRecords) {

          // if yes then add the recent file to the recent files list
          recentFilesList.add(recentFile);

          // rotate the list one time to make the last added (that is the current object added)
          // element to be the first element in the list
          Collections.rotate(recentFilesList, 1);
        } else {

          // else if the max record size have been reached then
          // rotate to make the last element in the list to be at the first position
          Collections.rotate(recentFilesList, 1);

          // replace the first position with the new recent file object
          recentFilesList.set(0, recentFile);
        }
      } // else if the the recent file list does contain the recent file then
      else {

        // removes the recent file with the same file object
        recentFilesList.remove(recentFile);

        // adds the recent file with new attributes
        recentFilesList.add(recentFile);
      }

      // save the recent files list to the config file
      save();

      // load the recent files menu items
      loadRecentFilesMenuItems();
    }
  }
Exemplo n.º 5
0
  private void actualizarJugadorQueDebeJugar() {

    try {
      Jugador jugador = this.manoActual.obtenerGanador();
      int posicion = this.jugadoresEnJuego.indexOf(jugador);
      Collections.rotate(jugadoresEnJuego, -posicion);
      this.jugadorQueDebeJugar = this.jugadoresEnJuego.getFirst();
      this.jugadorQueDebeCantar = this.jugadorQueDebeJugar;
    } catch (NoHayGanadorHuboEmpateException e) {
      this.actualizarTurnos();
    }
  }
 static {
   List<Boolean> addFlags = new ArrayList<Boolean>();
   for (int i = 0; i < Fragment.values().length; i++) {
     addFlags.add(RandomUtil.nextBoolean());
   }
   List<List<Boolean>> testFlags = new ArrayList<List<Boolean>>();
   for (int i = 0; i < Fragment.values().length; i++) {
     Collections.rotate(addFlags, 1);
     testFlags.add(new ArrayList<Boolean>(addFlags));
   }
   FLAGS = TestUtils.createData(testFlags.toArray());
   List<Range<?>> ranges = new ArrayList<Range<?>>();
   for (Fragment fragment : Fragment.values()) {
     switch (fragment) {
       case DOES_INVERT:
         ranges.add(Range.getInstance(false, true));
         ranges.add(Range.getInstance(false, true));
         break;
       case DELAY:
       case OSCILLATION_OFFSET:
       case OSCILLATION_PERIOD:
         ranges.add(Range.getInstance(RandomUtil.nextInteger()));
         ranges.add(Range.getInstance(RandomUtil.nextInteger()));
         break;
       default:
         ranges.add(Range.getInstance(RandomUtil.nextFloat()));
         ranges.add(Range.getInstance(RandomUtil.nextFloat()));
         break;
     }
   }
   RANGES = ranges.toArray(new Range<?>[0]);
   TEMPLATE =
       NodeConfiguration //
           .builder() //
           .setDelay(Range.getInstance(0), null) //
           .setInvertFlag(Range.<Boolean>openRange(), null) //
           .setEnergy(Range.<Float>openRange(), null) //
           .setEnergyDecay(Range.<Float>openRange(), null) //
           .setExcitatoryScale(Range.<Float>openRange(), null) //
           .setInhibitoryScale(Range.<Float>openRange(), null) //
           .setOscillationMaximum(Range.<Float>openRange(), null) //
           .setOscillationMinimum(Range.<Float>openRange(), null) //
           .setOscillationOffset(Range.<Integer>openRange(), null) //
           .setOscillationPeriod(Range.<Integer>openRange(), null) //
           .setScale(Range.<Float>openRange(), null) //
           .setShift(Range.<Float>openRange(), null) //
           .setTwitchMaximum(Range.<Float>openRange(), null) //
           .setTwitchMinimum(Range.<Float>openRange(), null) //
           .setTwitchProbability(Range.<Float>openRange(), null) //
           .newInstance();
 }
Exemplo n.º 7
0
  public Pair<FloatDataSet, FloatDataSet> splitTestAndTrain(int numHoldout) {

    if (numHoldout >= numExamples())
      throw new IllegalArgumentException("Unable to split on size larger than the number of rows");

    List<FloatDataSet> list = asList();

    Collections.rotate(list, 3);
    Collections.shuffle(list);
    List<List<FloatDataSet>> partition = new ArrayList<>();
    partition.add(list.subList(0, numHoldout));
    partition.add(list.subList(numHoldout, list.size()));
    FloatDataSet train = merge(partition.get(0));
    FloatDataSet test = merge(partition.get(1));
    return new Pair<>(train, test);
  }
Exemplo n.º 8
0
  @Test
  @RegressionTest("https://issues.jboss.org/browse/RF-9646")
  public void testFirstWeekDay() {
    DayPicker proxiedDayPicker = calendar.openPopup().getProxiedDayPicker();
    List<String> weekDays = Arrays.asList("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

    assertEquals(proxiedDayPicker.getWeekDayShortNames(), weekDays);

    // wrong input, nothing changes, RF-9646
    calendarAttributes.set(CalendarAttributes.firstWeekDay, 7);
    assertEquals(proxiedDayPicker.getWeekDayShortNames(), weekDays);

    calendarAttributes.set(CalendarAttributes.firstWeekDay, 1);
    Collections.rotate(weekDays, -1);
    assertEquals(proxiedDayPicker.getWeekDayShortNames(), weekDays);
  }
 private void assertEqual(
     final ValueProperties expected,
     final MockPropertyPreservingFunction func,
     final ValueProperties... inputs) {
   final List<ValueSpecification> specses = getSpecs(inputs);
   // Check even empty sets
   assertEqualOrdered(expected, func, specses);
   // Try and check a few permutations
   // TODO: check non rotation permutations
   for (int i = 0; i < specses.size(); i++) {
     assertEqualOrdered(expected, func, specses);
     Collections.rotate(specses, 1);
   }
   // Check repeats, since there are 2 code branches
   final List<ValueSpecification> doubled = new ArrayList<ValueSpecification>(inputs.length * 2);
   doubled.addAll(specses);
   doubled.addAll(specses);
   assertEqualOrdered(expected, func, doubled);
 }
Exemplo n.º 10
0
  public static <V, E> void assertEmbeddingEquals(PlanarGraph<V, E> graph, V vertex, String ids) {
    String[] idArray = ids.split(",");

    LinkedList<String> embeddingIds = new LinkedList<String>();
    for (E edge : graph.edgesOf(vertex)) {
      V other = Graphs.getOppositeVertex(graph, edge, vertex);
      embeddingIds.add(other.toString());
    }

    if (idArray.length > 0) {
      int firstIndex = embeddingIds.indexOf(idArray[0]);
      if (firstIndex < 0) {
        assertEquals(Arrays.deepToString(idArray), Arrays.deepToString(embeddingIds.toArray()));
      } else {
        Collections.rotate(embeddingIds, -firstIndex);
        assertEquals(Arrays.deepToString(idArray), Arrays.deepToString(embeddingIds.toArray()));
      }
    } else {
      assertEquals(Arrays.deepToString(idArray), Arrays.deepToString(embeddingIds.toArray()));
    }
  }
Exemplo n.º 11
0
 public static void main(String[] args) {
   print(list);
   print(
       "'list' disjoint (Four)?: "
           + Collections.disjoint(list, Collections.singletonList("Four")));
   print("max: " + Collections.max(list));
   print("min: " + Collections.min(list));
   print("max w/ comparator: " + Collections.max(list, String.CASE_INSENSITIVE_ORDER));
   print("min w/ comparator: " + Collections.min(list, String.CASE_INSENSITIVE_ORDER));
   List<String> sublist = Arrays.asList("Four five six".split(" "));
   print("indexOfSubList: " + Collections.indexOfSubList(list, sublist));
   print("lastIndexOfSubList: " + Collections.lastIndexOfSubList(list, sublist));
   Collections.replaceAll(list, "one", "Yo");
   print("replaceAll: " + list);
   Collections.reverse(list);
   print("reverse: " + list);
   Collections.rotate(list, 3);
   print("rotate: " + list);
   List<String> source = Arrays.asList("in the matrix".split(" "));
   Collections.copy(list, source);
   print("copy: " + list);
   Collections.swap(list, 0, list.size() - 1);
   print("swap: " + list);
   Collections.shuffle(list, new Random(47));
   print("shuffled: " + list);
   Collections.fill(list, "pop");
   print("fill: " + list);
   print("frequency of 'pop': " + Collections.frequency(list, "pop"));
   List<String> dups = Collections.nCopies(3, "snap");
   print("dups: " + dups);
   print("'list' disjoint 'dups'?: " + Collections.disjoint(list, dups));
   // Getting an old-style Enumeration:
   Enumeration<String> e = Collections.enumeration(dups);
   Vector<String> v = new Vector<String>();
   while (e.hasMoreElements()) v.addElement(e.nextElement());
   // Converting an old-style Vector
   // to a List via an Enumeration:
   ArrayList<String> arrayList = Collections.list(v.elements());
   print("arrayList: " + arrayList);
 }
Exemplo n.º 12
0
  /**
   * Sends an IQ packet to the Clearspace external component and returns the IQ packet returned by
   * CS or <tt>null</tt> if no answer was received before the specified timeout.
   *
   * @param packet IQ packet to send.
   * @param timeout milliseconds to wait before timing out.
   * @return IQ packet returned by Clearspace responsing the packet we sent.
   */
  public IQ query(final IQ packet, int timeout) {
    // Complain if FROM is empty
    if (packet.getFrom() == null) {
      throw new IllegalStateException("IQ packets with no FROM cannot be sent to Clearspace");
    }
    // If CS is not connected then return null
    if (clearspaces.isEmpty()) {
      return null;
    }
    // Set the target address to the IQ packet. Roate list so we distribute load
    String component;
    synchronized (clearspaces) {
      component = clearspaces.get(0);
      Collections.rotate(clearspaces, 1);
    }
    packet.setTo(component);
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<IQ>(8);
    final IQRouter router = XMPPServer.getInstance().getIQRouter();
    router.addIQResultListener(
        packet.getID(),
        new IQResultListener() {
          public void receivedAnswer(IQ packet) {
            answer.offer(packet);
          }

          public void answerTimeout(String packetId) {
            Log.warn("No answer from Clearspace was received for IQ stanza: " + packet);
          }
        });
    XMPPServer.getInstance().getIQRouter().route(packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
 static {
   List<Boolean> addFlags = new ArrayList<Boolean>();
   for (int i = 0; i < Fragment.values().length; i++) {
     addFlags.add(RandomUtil.nextBoolean());
   }
   List<List<Boolean>> testFlags = new ArrayList<List<Boolean>>();
   for (int i = 0; i < Fragment.values().length; i++) {
     Collections.rotate(addFlags, 1);
     testFlags.add(new ArrayList<Boolean>(addFlags));
   }
   FLAGS = TestUtils.createData(testFlags.toArray());
   List<Range<?>> ranges = new ArrayList<Range<?>>();
   for (Fragment fragment : Fragment.values()) {
     switch (fragment) {
       case IS_INHIBITORY:
         ranges.add(Range.getInstance(false, true));
         ranges.add(Range.getInstance(false, true));
         break;
       default:
         ranges.add(Range.getInstance(RandomUtils.nextFloat()));
         ranges.add(Range.getInstance(RandomUtils.nextFloat()));
         break;
     }
   }
   RANGES = ranges.toArray(new Range<?>[0]);
   TEMPLATE =
       LinkConfiguration //
           .builder() //
           .setCapacity(Range.<Float>openRange(), null) //
           .setCapacityAttack(Range.<Float>openRange(), null) //
           .setCapacityDecay(Range.<Float>openRange(), null) //
           .setStrength(Range.<Float>openRange(), null) //
           .setStrengthAttack(Range.<Float>openRange(), null) //
           .setStrengthDecay(Range.<Float>openRange(), null) //
           .setInhibitoryFlag(Range.<Boolean>openRange(), null) //
           .newInstance();
 }
 public static void main(String args[]) {
   List<Integer> list = new LinkedList<Integer>();
   for (int i = 10; i <= 50; i = i + 10) list.add(new Integer(i));
   System.out.println("洗牌前,链表中的数据");
   Iterator<Integer> iter = list.iterator();
   while (iter.hasNext()) {
     Integer n = iter.next();
     System.out.printf("%d\t", n.intValue());
   }
   Collections.shuffle(list);
   System.out.printf("\n洗牌后,链表中的数据\n");
   iter = list.iterator();
   while (iter.hasNext()) {
     Integer n = iter.next();
     System.out.printf("%d\t", n.intValue());
   }
   System.out.printf("\n再向右旋转1次后,链表中的数据\n");
   Collections.rotate(list, 1);
   iter = list.iterator();
   while (iter.hasNext()) {
     Integer n = iter.next();
     System.out.printf("%d\t", n.intValue());
   }
 }
Exemplo n.º 15
0
  public static void runGame(String filename, int port, int rounds, int time)
      throws IOException, InterruptedException, ExecutionException {
    final World world;
    int users = 0;
    try {
      WorldParser wp = new WorldParser();
      world = wp.parse(filename);
      users = world.getNumberOfSpawnpoints();
    } catch (FileNotFoundException e) {
      logger.error("Map file not found: '" + filename + "'.");
      return;
    }

    Message info = new InfoMessage(time, rounds, filename, users);

    logger.info("Starting graphics server.");
    GraphicsServer graphics = new GraphicsServer(info, port + 10);
    graphics.start();

    logger.info("Waiting for clients to connect.");
    ServerSocket socket = new ServerSocket(port);
    List<Player> players = new ArrayList<>();
    for (int i = 0; i < users; i++) {
      Socket client = socket.accept();
      Connection conn = new Connection(client);
      new Thread(conn).start();
      conn.sendMessage(info);
      players.add(new Player(conn));
    }
    logger.info("All clients connected.");

    logger.info("Setting spawnpoints.");
    Collections.shuffle(players);
    Queue<Vector2d> spawnpoints = world.getSpawnpoints();
    for (Player player : players) {
      player.setSpawn(spawnpoints.poll());
    }

    logger.info("Sending initial game state.");
    Message state0 = new GameStateMessage(0, world, players);
    players.stream().peek(p -> p.send(state0));
    graphics.sendToAll(state0);
    logger.info("Recieved loadout from all.");

    logger.info("Starting game.");
    for (int round = 1; round <= rounds; round++) {
      for (Player player : players) {
        logger.info("Starting player '" + player.getName() + "' turn.");
        logger.info("Clearing all messages from player queue.");
        player.clear();
        logger.info("Sending first round to all.");
        Message state = new GameStateMessage(round, world, players);
        players.stream().forEach(p -> p.send(state));
        graphics.sendToAll(state);

        if (player.isDead()) {
          logger.info(player.getName() + " is dead. Respawning...");
          player.respawn();
        } else {
          List<ActionMessage> actions = new ArrayList<>();
          Instant stop = Instant.now().plus(time, MILLIS);
          for (int a = 0; a < 3; a++) {
            logger.info("Waiting for action " + a + ".");
            long timeout = Math.max(0, MILLIS.between(Instant.now(), stop));
            ActionMessage action = player.next(timeout, MILLISECONDS);
            if (action == null) {
              logger.debug(
                  "==> Player '" + player.getName() + "' timed out in round " + round + ".");
              break;
            }

            try {
              logger.info("Performing action.");
              action.performAction(player, world);
              actions.add(action);
              logger.info("Successful message: " + action.toString());
              players.stream().forEach(p -> p.send(action));
            } catch (ProtocolException e) {
              logger.debug(e.getMessage());
              player.send(new ErrorMessage(e));
            }
          }
          logger.info("Waiting to complete round.");
          Thread.sleep(Math.max(0, MILLIS.between(Instant.now(), stop)));
          player.send(new EndTurnMessage());

          logger.info("Sending actions to graphics.");
          for (Message m : actions) {
            graphics.sendToAll(m);
          }
        }
      }

      Collections.rotate(players, 1);
    }

    players.sort(comparing(Player::score));
    Collections.reverse(players);
    players.removeIf(p -> p.score() < players.get(0).score());
    String winner;
    if (players.size() > 1) {
      winner =
          String.format(
              "A %d-way tie between: %s",
              players.size(), String.join(", ", players.toArray(new String[players.size()])));
    } else {
      winner = String.format("The winner is ", players.get(0));
    }

    logger.info("Winner: " + winner);
    Message message = new GameFinishedMessage(winner);
    players.stream().forEach(p -> p.send(message));
    graphics.sendToAll(message);
    socket.close();
  }
Exemplo n.º 16
0
  public static void main(String[] args) {

    List<MyClass> list = new ArrayList<MyClass>();

    list.add(new MyClass("Василий"));
    list.add(new MyClass("Павел"));
    list.add(new MyClass("Андрей"));
    list.add(new MyClass("Андрей"));
    list.add(new MyClass("Петр"));
    list.add(new MyClass("Анжелика"));

    System.out.println("Оригинал");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Смешивание
    Collections.shuffle(list);
    System.out.println("Смешивание");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Обратный порядок
    Collections.reverse(list);
    System.out.println("Обратный порядок");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // "Проворачивание" на определенное количество
    Collections.rotate(list, 2); // Число может быть отрицательным - тогда порядок будет обратный
    System.out.println("Проворачивание");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Обмен элементов
    Collections.swap(list, 0, list.size() - 1);
    System.out.println("Обмен элементов");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Замена
    Collections.replaceAll(list, new MyClass("Андрей"), new MyClass("Алексей"));
    System.out.println("Замена");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Сортировка
    // Collections.sort(list);   // Этот запрос не пройдет т.к. класс MyClass
    // не реализует интерфейс Comparable
    System.out.println("Сортировка Comparable класса");
    List<MyClassCompare> listSort = new ArrayList<MyClassCompare>();
    System.out.println("Без сортировки");
    for (MyClass mc : list) {
      listSort.add(new MyClassCompare(mc.toString()));
      System.out.println("Item sort:" + mc);
    }
    Collections.sort(listSort);
    System.out.println("После сортировки");
    for (MyClassCompare mc : listSort) {
      System.out.println("Item sort:" + mc);
    }
    System.out.println();

    // Сортировка с классом Comparator
    System.out.println("Сортировка с Comparator");
    System.out.println("Без сортировки");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    Collections.sort(list, new MyClassComparator());
    System.out.println("После сортировки");
    for (MyClass mc : list) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Копирование - здесь обязательно надо иметь нужные размеры
    List<MyClass> list2 = new ArrayList<MyClass>();
    // Поэтому заполняем список. Хоть чем-нибудь.
    for (MyClass mc : list) {
      list2.add(null);
    }
    // Компируем из правого аргумента в левый
    Collections.copy(list2, list);
    System.out.println("Копирование");
    for (MyClass mc : list2) {
      System.out.println("Item:" + mc);
    }
    System.out.println();

    // Полная замена
    Collections.fill(list2, new MyClass("Антон"));
    System.out.println("Полная замена");
    for (MyClass mc : list2) {
      System.out.println("Item:" + mc);
    }
    System.out.println();
  }
Exemplo n.º 17
0
  private void actualizarTurnos() {

    Collections.rotate(this.jugadoresEnJuego, -1);
    this.jugadorQueDebeJugar = this.jugadoresEnJuego.getFirst();
    this.jugadorQueDebeCantar = this.jugadorQueDebeJugar;
  }
Exemplo n.º 18
0
 /** shift the workable list forward one e.g. [1,2,3] becomes [2,3,1] */
 public void nextExercise() {
   Collections.rotate(workable, -1);
 }
  /**
   * Create a file with three stripes, corrupt a block each in two stripes, and wait for the the
   * file to be fixed.
   */
  private void implDirBlockFix(boolean local, boolean hasStripeInfo, boolean corruptStripe)
      throws Exception {
    LOG.info(
        "Test testDirBlockFix started. local:"
            + local
            + " hasStripeInfo:"
            + hasStripeInfo
            + " corruptStripe:"
            + corruptStripe);
    int stripeLength = 3;
    mySetup(stripeLength);
    long[] crcs = new long[3];
    int[] seeds = new int[3];
    Path dirPath = new Path("/user/dhruba/raidtestrs");
    Path[] files =
        TestRaidDfs.createTestFiles(
            dirPath, fileSizes, blockSizes, crcs, seeds, fileSys, (short) 1);
    Path destPath = new Path("/destraidrs/user/dhruba");
    LOG.info("Test testDirBlockFix created test files");
    Configuration localConf = this.getRaidNodeConfig(conf, local);
    // Not allow multiple running jobs
    localConf.setLong("raid.blockfix.maxpendingjobs", 1L);

    try {
      cnode = RaidNode.createRaidNode(null, localConf);
      TestRaidDfs.waitForDirRaided(LOG, fileSys, dirPath, destPath);
      cnode.stop();
      cnode.join();

      DistributedFileSystem dfs = (DistributedFileSystem) fileSys;
      String[] corruptFiles = DFSUtil.getCorruptFiles(dfs);
      assertEquals("no corrupt files expected", 0, corruptFiles.length);
      assertEquals(
          "filesFixed() should return 0 before fixing files",
          0,
          cnode.blockIntegrityMonitor.getNumFilesFixed());
      if (!hasStripeInfo) {
        // clear out all stripes
        LocalStripeStore lss = new LocalStripeStore();
        lss.initialize(localConf, false, dfs);
        lss.clear();
      }
      if (corruptStripe) {
        LocalStripeStore lss = new LocalStripeStore();
        lss.initialize(localConf, false, dfs);
        Set<List<Block>> corruptCandidates = new HashSet<List<Block>>(lss.stripeSet.keySet());
        for (List<Block> lb : corruptCandidates) {
          for (Codec codec : Codec.getCodecs()) {
            StripeInfo si = lss.getStripe(codec, lb.get(0));
            if (si == null) {
              continue;
            }
            String oldSi = si.toString();
            Collections.rotate(si.parityBlocks, 1);
            Collections.rotate(si.srcBlocks, 1);
            lss.putStripe(codec, si.parityBlocks, si.srcBlocks);
            String newSi = lss.getStripe(codec, lb.get(0)).toString();
            LOG.info("Corrupt the stripe info old : " + oldSi + " new : " + newSi);
          }
        }
      }

      this.corruptFiles(dirPath, crcs, rsCorruptFileIdx1, dfs, files, rsNumCorruptBlocksInFiles1);
      cnode = RaidNode.createRaidNode(null, localConf);
      long start = System.currentTimeMillis();
      while (cnode.blockIntegrityMonitor.getNumFilesFixed() < 3
          && cnode.blockIntegrityMonitor.getNumFileFixFailures() < 3
          && System.currentTimeMillis() - start < 120000) {
        LOG.info("Test testDirBlockFix waiting for files to be fixed.");
        Thread.sleep(1000);
      }
      long totalCorruptBlocks = getTotal(rsNumCorruptBlocksInFiles1);
      if (hasStripeInfo) {
        if (!corruptStripe) {
          TestBlockFixer.verifyMetrics(fileSys, cnode, local, 3L, totalCorruptBlocks);

          dfs = getDFS(conf, dfs);
          for (int i = 0; i < fileSizes.length; i++) {
            assertTrue(
                "file " + files[i] + " not fixed",
                TestRaidDfs.validateFile(dfs, files[i], fileSizes[i], crcs[i]));
          }
        } else {
          TestBlockFixer.verifyMetrics(fileSys, cnode, local, 0L, 0L);
          assertTrue(
              "should fail to fix more than 3 files",
              cnode.blockIntegrityMonitor.getNumFileFixFailures() >= 3L);
          TestBlockFixer.verifyMetrics(
              fileSys, cnode, LOGTYPES.OFFLINE_RECONSTRUCTION_FILE, LOGRESULTS.FAILURE, 3L, true);
          // Will throw stripe mismatch exception for the first blocks of 3 files
          TestBlockFixer.verifyMetrics(
              fileSys,
              cnode,
              LOGTYPES.OFFLINE_RECONSTRUCTION_STRIPE_VERIFICATION,
              LOGRESULTS.FAILURE,
              3L,
              true);
        }
      } else {
        TestBlockFixer.verifyMetrics(fileSys, cnode, local, 0L, 0L);
        assertTrue(
            "should fail to fix more than 3 files",
            cnode.blockIntegrityMonitor.getNumFileFixFailures() >= 3L);
        TestBlockFixer.verifyMetrics(
            fileSys,
            cnode,
            LOGTYPES.OFFLINE_RECONSTRUCTION_GET_STRIPE,
            LOGRESULTS.FAILURE,
            totalCorruptBlocks,
            true);
        TestBlockFixer.verifyMetrics(
            fileSys, cnode, LOGTYPES.OFFLINE_RECONSTRUCTION_FILE, LOGRESULTS.FAILURE, 3L, true);
      }
    } catch (Exception e) {
      LOG.info("Test testDirBlockFix Exception " + e, e);
      throw e;
    } finally {
      myTearDown();
    }
    LOG.info("Test testDirBlockFix completed.");
  }
Exemplo n.º 20
0
 /** shift the workable list backwards one e.g. [1,2,3] becomes [3,1,2] */
 public void previousExercise() {
   Collections.rotate(workable, 1);
 }
Exemplo n.º 21
0
 /**
  * Re-orders the cards in a hand so that the most significant cards(s) are first. For example, the
  * highest ranked card is the most significant in a straight or flush whereas the two matching
  * cards are the most significant in a hand that has one pair.
  *
  * <p>Once the hand is correctly ordered, two hands with the same ranking can easily be compared
  * to see which is better by comparing the most significant card (if these are equivalent then the
  * second most significant cards can be compared and so on).
  */
 private void orderCards(List<PlayingCard> cards, HandRanking ranking) {
   // Assumes that the cards are already sorted by rank, so for flushes, high
   // cards and most straights, there is nothing to do.
   switch (ranking) {
     case STRAIGHT_FLUSH:
     case STRAIGHT:
       {
         // If this hand is A, 2, 3, 4, 5, make sure ace is low.
         if (cards.get(0).getValue() == FaceValue.ACE
             && cards.get(1).getValue() == FaceValue.FIVE) {
           Collections.rotate(cards, -1);
         }
         break;
       }
     case FOUR_OF_A_KIND:
       {
         // The matching four cards will all be next to each other, so the kicker
         // is either at the beginning or the end.  If it's at the beginning, it
         // needs to be moved to the end.
         if (cards.get(0).getValue() != cards.get(1).getValue()) {
           Collections.rotate(cards, -1);
         }
         break;
       }
     case FULL_HOUSE:
       {
         // The three-of-a-kind is more important than the pair, so if the pair
         // is first, it needs to be moved to the end.
         if (cards.get(2).getValue()
             != cards.get(0).getValue()) // 3rd card is not the same as 1st.
         {
           Collections.rotate(cards, -2);
         }
         break;
       }
     case THREE_OF_A_KIND:
       {
         int start = findPair(cards);
         ListUtils.shiftLeft(cards, start, 3, start);
         break;
       }
     case TWO_PAIR:
       {
         // The kicker will either be the first, third or fifth card.  If it is the first or third,
         // it needs to be moved.
         if (cards.get(0).getValue() != cards.get(1).getValue()) // Kicker is first card.
         {
           Collections.rotate(cards, -1);
         } else if (cards.get(2).getValue() != cards.get(3).getValue()) // Kicker is third card.
         {
           cards.add(cards.remove(2));
         }
         break;
       }
     case PAIR:
       {
         int start = findPair(cards);
         ListUtils.shiftLeft(cards, start, 2, start);
         break;
       }
   }
 }