List of usage examples for java.util Collections shuffle
public static void shuffle(List<?> list)
From source file:com.twitter.distributedlog.service.balancer.ClusterBalancer.java
void moveRemainingStreamsFromSource(Host source, List<Host> hosts, Optional<RateLimiter> rateLimiter) { LinkedList<String> streamsToMove = new LinkedList<String>(source.streams); Collections.shuffle(streamsToMove); if (logger.isDebugEnabled()) { logger.debug("Try to move remaining streams from {} : {}", source, streamsToMove); }//from w w w . j a v a2 s . co m int hostIdx = hosts.size() - 1; while (!streamsToMove.isEmpty()) { if (rateLimiter.isPresent()) { rateLimiter.get().acquire(); } Host target = hosts.get(hostIdx); if (!target.address.equals(source.address)) { String stream = streamsToMove.remove(); // move the stream if (moveStream(stream, source, target)) { source.streams.remove(stream); target.streams.add(stream); } } --hostIdx; if (hostIdx < 0) { hostIdx = hosts.size() - 1; } } }
From source file:com.twitter.aurora.scheduler.configuration.Resources.java
/** * Attempts to grab {@code numPorts} from the given resource {@code offer}. * * @param offer The offer to grab ports from. * @param numPorts The number of ports to grab. * @return The set of ports grabbed.//from ww w .ja v a2s. c o m * @throws InsufficientResourcesException if not enough ports were available. */ public static Set<Integer> getPorts(Offer offer, int numPorts) throws InsufficientResourcesException { checkNotNull(offer); if (numPorts == 0) { return ImmutableSet.of(); } List<Integer> availablePorts = Lists.newArrayList(Sets.newHashSet( Iterables.concat(Iterables.transform(getPortRanges(offer.getResourcesList()), RANGE_TO_MEMBERS)))); if (availablePorts.size() < numPorts) { throw new InsufficientResourcesException( String.format("Could not get %d ports from %s", numPorts, offer)); } Collections.shuffle(availablePorts); return ImmutableSet.copyOf(availablePorts.subList(0, numPorts)); }
From source file:net.daboross.bukkitdev.skywars.config.RandomChestConfiguration.java
@Override public ItemStack[] getItems(final int size, final int chestLevel, final int minValue, final int maxValue) { SkyStatic.debug("[RandomChests] Filling with size: %s, level: %s, min: %s, max: %s", size, chestLevel, minValue, maxValue);/* ww w.java 2 s.co m*/ int totalChance = 0; List<ChestLevel> acceptableLevels = new ArrayList<>(); for (ChestLevel level : levels) { if (level.itemValue >= minValue && level.itemValue <= maxValue) { acceptableLevels.add(level); totalChance += level.chance; } } if (acceptableLevels.isEmpty()) { SkyStatic.log(Level.SEVERE, "Warning: No acceptable chest levels found when filling chest with minValue={0}, maxValue={1}! Chest will be completely empty.", minValue, maxValue); return new ItemStack[size]; } SkyStatic.debug("[RandomChests] Found acceptable levels: %s", acceptableLevels); int totalValue = 0; List<ItemStack> inventory = new ArrayList<>(); while (totalValue <= chestLevel) { ChestLevel level = null; int chanceIndex = random.nextInt(totalChance); int accumulatedChance = 0; // This is a somewhat convoluted way to give each level the right probability of being picked. for (ChestLevel testLevel : acceptableLevels) { accumulatedChance += testLevel.chance; if (accumulatedChance > chanceIndex) { level = testLevel; break; } } Validate.notNull(level, "Never null"); // should never be null SkyStatic.debug("[RandomChests] Choosing level %s", level); SkyKitItem item = level.items.get(random.nextInt(level.items.size())); inventory.add(item.toItem()); totalValue += level.itemValue; } ItemStack[] result; if (inventory.size() > size) { result = inventory.subList(0, size).toArray(new ItemStack[size]); } else { result = inventory.toArray(new ItemStack[size]); } Collections.shuffle(Arrays.asList(result)); return result; }
From source file:imitationNLG.SFX.java
public void runTestWithJAROW(boolean useDAggerArg, boolean useDAggerWord) { File dataFile = new File("sfx_data/sfx" + dataset + "/train+valid+test.json"); String wenFile = "results/wenResults/sfxhotel.log"; if (dataset.equals("restaurant")) { wenFile = "results/wenResults/sfxrest.log"; }//from ww w . java 2 s.c o m boolean useValidation = true; boolean useRandomAlignments = false; createLists(dataFile); //RANDOM DATA SPLIT /*int to = (int) Math.round(datasetInstances.size() * 0.1); if (to > datasetInstances.size()) { to = datasetInstances.size(); } ArrayList<DatasetInstance> trainingData = new ArrayList<>(); ArrayList<DatasetInstance> validationData = new ArrayList<>(); ArrayList<DatasetInstance> testingData = new ArrayList<>(); for (String predicate : predicates) { trainingData.addAll(datasetInstances.get(predicate).subList(0, ((int) Math.round(datasetInstances.get(predicate).size() * 0.3)))); validationData.addAll(datasetInstances.get(predicate).subList(((int) Math.round(datasetInstances.get(predicate).size() * 0.3)), ((int) Math.round(datasetInstances.get(predicate).size() * 0.4)))); testingData.addAll(datasetInstances.get(predicate).subList(((int) Math.round(datasetInstances.get(predicate).size() * 0.4)), datasetInstances.get(predicate).size())); }*/ //WEN DATA SPLIT //PRINT RESULTS ArrayList<String> mrs = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(wenFile))) { String s; while ((s = br.readLine()) != null) { if (!s.trim().isEmpty()) { mrs.add(s.trim()); } } } catch (FileNotFoundException ex) { Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<String> testWenMRs = new ArrayList<>(); wenDaToGen = new HashMap<>(); try (BufferedReader br = new BufferedReader(new FileReader(wenFile))) { String s; boolean inGen = false; boolean inRef = false; String da = ""; while ((s = br.readLine()) != null) { if (s.startsWith("DA")) { inGen = false; inRef = false; da = s.substring(s.indexOf(":") + 1).replaceAll(",", ";").replaceAll("no or yes", "yes or no") .replaceAll("ave ; presidio", "ave and presidio") .replaceAll("point ; ste", "point and ste").trim(); testWenMRs.add(da); } else if (s.startsWith("Gen")) { inGen = true; } else if (s.startsWith("Ref")) { inRef = true; } else if (inGen) { inGen = false; if (!wenDaToGen.containsKey(da)) { wenDaToGen.put(da.toLowerCase(), s.trim()); } da = ""; } else if (inRef) { if (s.trim().isEmpty()) { inRef = false; da = ""; } } } } catch (FileNotFoundException ex) { Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Bagel.class.getName()).log(Level.SEVERE, null, ex); } ArrayList<DatasetInstance> trainingData = new ArrayList<>(); ArrayList<DatasetInstance> validationData = new ArrayList<>(); ArrayList<DatasetInstance> testingData = new ArrayList<>(); System.out.println(testWenMRs.size()); ArrayList<DatasetInstance> restData = new ArrayList<>(); for (String predicate : predicates) { for (DatasetInstance in : datasetInstances.get(predicate)) { if (testWenMRs.contains(in.getMeaningRepresentation().getMRstr())) { testingData.add(in); testWenMRs.remove(in.getMeaningRepresentation().getMRstr()); } else { restData.add(in); } } } Collections.shuffle(restData); for (int i = 0; i < restData.size(); i++) { if (i < testingData.size()) { validationData.add(restData.get(i)); } else { trainingData.add(restData.get(i)); } } System.out.println(trainingData.size()); System.out.println(validationData.size()); System.out.println(testingData.size()); System.out.println(testWenMRs); r = new Random(seed); HashMap<String, JAROW> classifiersAttrs = new HashMap<>(); HashMap<String, HashMap<String, JAROW>> classifiersWords = new HashMap<>(); HashMap<Integer, HashSet<String>> nGrams; if (!useRandomAlignments) { nGrams = createNaiveAlignments(trainingData); } else { nGrams = createRandomAlignments(trainingData); } HashMap<String, HashSet<String>> availableAttributeActions = new HashMap<>(); HashMap<String, HashMap<String, HashSet<Action>>> availableWordActions = new HashMap<>(); for (DatasetInstance DI : trainingData) { String predicate = DI.getMeaningRepresentation().getPredicate(); if (!availableAttributeActions.containsKey(predicate)) { availableAttributeActions.put(predicate, new HashSet<String>()); } if (!availableWordActions.containsKey(predicate)) { availableWordActions.put(predicate, new HashMap<String, HashSet<Action>>()); } ArrayList<Action> realization = DI.getTrainRealization(); for (Action a : realization) { if (!a.getAttribute().equals(SFX.TOKEN_END)) { String attr = ""; if (a.getAttribute().contains("=")) { attr = a.getAttribute().substring(0, a.getAttribute().indexOf('=')); } else { attr = a.getAttribute(); } availableAttributeActions.get(predicate).add(attr); if (!availableWordActions.get(predicate).containsKey(attr)) { availableWordActions.get(predicate).put(attr, new HashSet<Action>()); availableWordActions.get(predicate).get(attr).add(new Action(SFX.TOKEN_END, attr)); } if (!a.getWord().equals(SFX.TOKEN_START) && !a.getWord().equals(SFX.TOKEN_END) && !a.getWord().matches("([,.?!;:'])")) { if (a.getWord().startsWith(SFX.TOKEN_X)) { if (a.getWord().substring(3, a.getWord().lastIndexOf('_')).toLowerCase().trim() .equals(attr)) { availableWordActions.get(predicate).get(attr).add(new Action(a.getWord(), attr)); } } else { availableWordActions.get(predicate).get(attr).add(new Action(a.getWord(), attr)); } } if (attr.equals("[]")) { System.out.println("RR " + realization); System.out.println("RR " + a); } } } } //ONLY WHEN RANDOM ALIGNMENTS if (useRandomAlignments) { valueAlignments = new HashMap<>(); } Object[] results = createTrainingDatasets(trainingData, availableAttributeActions, availableWordActions, nGrams); HashMap<String, ArrayList<Instance>> predicateAttrTrainingData = (HashMap<String, ArrayList<Instance>>) results[0]; HashMap<String, HashMap<String, ArrayList<Instance>>> predicateWordTrainingData = (HashMap<String, HashMap<String, ArrayList<Instance>>>) results[1]; boolean setToGo = true; if (predicateWordTrainingData.isEmpty() || predicateAttrTrainingData.isEmpty()) { setToGo = false; } if (setToGo) { JDAggerForSFX JDWords = new JDAggerForSFX(this); Object[] LOLSResults = null; if (useValidation) { LOLSResults = JDWords.runLOLS(availableAttributeActions, trainingData, predicateAttrTrainingData, predicateWordTrainingData, availableWordActions, valueAlignments, wordRefRolloutChance, validationData, nGrams); } else { LOLSResults = JDWords.runLOLS(availableAttributeActions, trainingData, predicateAttrTrainingData, predicateWordTrainingData, availableWordActions, valueAlignments, wordRefRolloutChance, testingData, nGrams); } classifiersAttrs = (HashMap<String, JAROW>) LOLSResults[0]; classifiersWords = (HashMap<String, HashMap<String, JAROW>>) LOLSResults[1]; if (useValidation) { evaluateGeneration(classifiersAttrs, classifiersWords, trainingData, validationData, availableAttributeActions, availableWordActions, nGrams, true, 100000); } else { evaluateGeneration(classifiersAttrs, classifiersWords, trainingData, testingData, availableAttributeActions, availableWordActions, nGrams, true, 100000); } } double finalAvgArgDistance = 0.0; for (Double avg : crossAvgArgDistances) { finalAvgArgDistance += avg; } finalAvgArgDistance /= crossAvgArgDistances.size(); System.out.println("=========================="); System.out.println("=========================="); System.out.println("Final avg arg distance: \t" + finalAvgArgDistance); double finalNISTDistance = 0.0; for (Double avg : crossNIST) { finalNISTDistance += avg; } finalNISTDistance /= crossNIST.size(); System.out.println("Final NIST: \t" + finalNISTDistance); double finalBLEUDistance = 0.0; for (Double avg : crossBLEU) { finalBLEUDistance += avg; } finalBLEUDistance /= crossBLEU.size(); System.out.println("Final BLEU: \t" + finalBLEUDistance); double finalBLEUSmoothDistance = 0.0; for (Double avg : crossBLEUSmooth) { finalBLEUSmoothDistance += avg; } finalBLEUSmoothDistance /= crossBLEUSmooth.size(); System.out.println("Final BLEUSmooth: \t" + finalBLEUSmoothDistance); System.out.println("=========================="); System.out.println("=========================="); }
From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java
/** * Runs the tests without applying any changes.And executes each test * multiple times and in a different order. This method is used to check if * the driver works correctly.// w ww . j ava2s .co m */ private void runPermutedTests() { logger.info("Running permuted tests for project " + configuration.getProjectPrefix()); addListenersFromProperty(); List<String> allTests = new ArrayList<String>(getAllTests()); timeout = Integer.MAX_VALUE; List<SingleTestResult> allFailingTests = new ArrayList<SingleTestResult>(); coldRun(allTests); testsStart(); int permutations = configuration.getTestPermutations(); for (int i = 0; i < permutations; i++) { logger.info("Shuffling tests. Round " + (i + 1)); Collections.shuffle(allTests); List<SingleTestResult> failingTests = runNormalTests(allTests); allFailingTests.addAll(failingTests); } testsEnd(); if (allFailingTests.size() == 0) { String message = "All " + allTests.size() + " tests passed for " + permutations + " permutations."; System.out.println(message); logger.info(message); } else { logger.warn("Not all tests passed"); Set<String> failingTests = new HashSet<String>(); for (SingleTestResult str : allFailingTests) { String testCaseName = str.getTestMessage().getTestCaseName(); logger.warn("Test Failed: " + testCaseName + ": " + str.getTestMessage()); failingTests.add(testCaseName); } try { FileUtils.writeLines(new File(configuration.getOutputDir(), "/failing-tests-permuted.txt"), failingTests); } catch (IOException e) { throw new RuntimeException(e); } } }
From source file:com.devicehive.service.NetworkServiceTest.java
@Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD) public void should_sort_networks() throws Exception { List<String> descriptions = asList("a", "b", "c", "d", "e"); Collections.shuffle(descriptions); descriptions.forEach(descr -> {//ww w . jav a 2 s . c om NetworkVO network = new NetworkVO(); network.setName(namePrefix + randomUUID()); network.setDescription(descr); NetworkVO created = networkService.create(network); assertThat(created.getId(), notNullValue()); }); handleListNetworkRequest(); networkService.list(null, namePrefix + "%", "description", true, 100, 0, null).thenAccept(networks -> { assertThat(networks, hasSize(descriptions.size())); assertThat(networks.get(0).getDescription(), equalTo("a")); assertThat(networks.get(1).getDescription(), equalTo("b")); assertThat(networks.get(2).getDescription(), equalTo("c")); assertThat(networks.get(3).getDescription(), equalTo("d")); assertThat(networks.get(4).getDescription(), equalTo("e")); }).get(5, TimeUnit.SECONDS); networkService.list(null, namePrefix + "%", "description", false, 100, 0, null).thenAccept(networks -> { assertThat(networks, hasSize(descriptions.size())); assertThat(networks.get(0).getDescription(), equalTo("e")); assertThat(networks.get(1).getDescription(), equalTo("d")); assertThat(networks.get(2).getDescription(), equalTo("c")); assertThat(networks.get(3).getDescription(), equalTo("b")); assertThat(networks.get(4).getDescription(), equalTo("a")); }).get(5, TimeUnit.SECONDS); verify(requestHandler, times(2)).handle(argument.capture()); }
From source file:clummy.classes.DataHandlingClass.java
/** * get shuffle list of occupation/*from ww w . jav a 2s . co m*/ * @param age * @return */ public String getShuffledOccupation(int age) { List<String> listOccupation = readFile(AllFileList.OCCUPATIONLIST); Collections.shuffle(listOccupation); Collections.shuffle(listOccupation); if (age < 6) return "Unemployed"; else if (age >= 7 && age <= 17) { return "Student"; } else return listOccupation.get(randBetween(0, listOccupation.size() - 1)); }
From source file:com.serphacker.serposcope.task.google.GoogleTask.java
protected void initializeSearches() { List<GoogleSearch> searchList; if (updateRun) { searchList = googleDB.search.listUnchecked(run.getId()); } else if (run.getGroup() != null) { Collection<Integer> groups = new ArrayList<Integer>(); groups.add(run.getGroup().getId()); searchList = googleDB.search.listByGroup(groups); } else {// w w w.j a v a2 s .c o m searchList = googleDB.search.list(); } if (shuffle) { Collections.shuffle(searchList); } searches = new LinkedBlockingQueue<>(searchList); LOG.info("{} searches to do", searches.size()); }
From source file:net.sourceforge.subsonic.ajax.PlaylistService.java
private List<MediaFile> getRandomChildren(MediaFile file, int count) throws IOException { List<MediaFile> children = mediaFileService.getDescendantsOf(file, false); removeVideoFiles(children);/*from w w w. ja v a2 s. co m*/ if (children.isEmpty()) { return children; } Collections.shuffle(children); return children.subList(0, Math.min(count, children.size())); }
From source file:clummy.classes.DataHandlingClass.java
/** * get shuffle list file 1/*from w w w .j a v a2s .c o m*/ * @param fileName * @return */ public String getShuffleListFile(String fileName) { List<String> listShuffle1 = readFile(fileName); if (!listShuffle1.isEmpty()) { Collections.shuffle(listShuffle1); Collections.shuffle(listShuffle1); return listShuffle1.get(randBetween(0, listShuffle1.size() - 1)); } else return null; }