List of usage examples for java.util Collections shuffle
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void shuffle(List<?> list, Random rnd)
From source file:mx.ecosur.multigame.gente.entity.GenteStrategyAgent.java
public List<Move> determineMoves(Game impl) { List<Move> ret = new ArrayList<Move>(); GenteGame game = (GenteGame) impl;/* w w w .j av a2s.c o m*/ GameGrid grid = game.getGrid(); if (isTurn()) { if (kBase == null) initialize(); StatefulKnowledgeSession session = kBase.newStatefulKnowledgeSession(); session.setGlobal("dim", game.getSize()); session.insert(this); session.insert(ret); session.insert(grid); /* Insert any unbound adjacent cells if grid is not empty */ if (!grid.isEmpty()) { Set<Color> colors = new HashSet<Color>(); for (Color c : Color.values()) { colors.add(c); } for (GridCell cell : findUnboundAdjacentCells(game, colors)) { session.insert(cell); } session.setGlobal("unbound", new ArrayList<Move>()); } else { session.setGlobal("unbound", Collections.EMPTY_LIST); } session.fireAllRules(); session.dispose(); } Collections.shuffle(ret, new Random()); return ret; }
From source file:cc.kave.commons.pointsto.evaluation.cv.StratifiedProjectsCVFoldBuilder.java
@Override public List<List<Usage>> createFolds(Map<ProjectIdentifier, List<Usage>> projectUsages) { EnumeratedDistribution<ProjectIdentifier> projectDistribution; List<Pair<ProjectIdentifier, Double>> projectProbabilities = new ArrayList<>(projectUsages.size()); // initialize distributions long totalUsages = 0; for (Map.Entry<ProjectIdentifier, List<Usage>> project : projectUsages.entrySet()) { projectProbabilities// w w w. ja v a 2s . c om .add(new Pair<ProjectIdentifier, Double>(project.getKey(), (double) project.getValue().size())); totalUsages += project.getValue().size(); } // normalization of the probability mass is done by the constructor projectDistribution = new EnumeratedDistribution<>(rndGenerator, projectProbabilities); shuffleUsages(projectUsages.values()); List<List<Usage>> folds = new ArrayList<>(numFolds); int avgFoldSize = (int) (totalUsages / numFolds); for (int f = 0; f < numFolds - 1; ++f) { List<Usage> fold = new ArrayList<>(avgFoldSize); folds.add(fold); for (int i = 0; i < avgFoldSize; ++i) { ProjectIdentifier project; List<Usage> usages; do { project = projectDistribution.sample(); usages = projectUsages.get(project); } while (usages.isEmpty()); int lastIndex = usages.size() - 1; Usage usage = usages.remove(lastIndex); fold.add(usage); } } // add remaining usages to the last fold List<Usage> lastFold = new ArrayList<>(avgFoldSize); folds.add(lastFold); for (List<Usage> usages : projectUsages.values()) { lastFold.addAll(usages); usages.clear(); } Collections.shuffle(lastFold, new Random(rndGenerator.nextLong())); return folds; }
From source file:de.langerhans.wallet.ui.send.RequestWalletBalanceTask.java
public void requestWalletBalance(final Address address) { backgroundHandler.post(new Runnable() { @Override//ww w. java 2s . co m public void run() { // Use either dogechain or chain.so List<String> urls = new ArrayList<String>(2); urls.add(Constants.DOGECHAIN_API_URL); urls.add(Constants.CHAINSO_API_URL); Collections.shuffle(urls, new Random(System.nanoTime())); final StringBuilder url = new StringBuilder(urls.get(0)); url.append(address.toString()); log.debug("trying to request wallet balance from {}", url); HttpURLConnection connection = null; Reader reader = null; try { connection = (HttpURLConnection) new URL(url.toString()).openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(false); connection.setRequestMethod("GET"); if (userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Charsets.UTF_8); final StringBuilder content = new StringBuilder(); Io.copy(reader, content); final JSONObject json = new JSONObject(content.toString()); final int success = json.getInt("success"); if (success != 1) throw new IOException("api status " + success + " when fetching unspent outputs"); final JSONArray jsonOutputs = json.getJSONArray("unspent_outputs"); final Map<Sha256Hash, Transaction> transactions = new HashMap<Sha256Hash, Transaction>( jsonOutputs.length()); for (int i = 0; i < jsonOutputs.length(); i++) { final JSONObject jsonOutput = jsonOutputs.getJSONObject(i); final Sha256Hash uxtoHash = new Sha256Hash(jsonOutput.getString("tx_hash")); final int uxtoIndex = jsonOutput.getInt("tx_output_n"); final byte[] uxtoScriptBytes = HEX.decode(jsonOutput.getString("script")); final Coin uxtoValue = Coin.valueOf(Long.parseLong(jsonOutput.getString("value"))); Transaction tx = transactions.get(uxtoHash); if (tx == null) { tx = new FakeTransaction(Constants.NETWORK_PARAMETERS, uxtoHash); tx.getConfidence().setConfidenceType(ConfidenceType.BUILDING); transactions.put(uxtoHash, tx); } if (tx.getOutputs().size() > uxtoIndex) throw new IllegalStateException("cannot reach index " + uxtoIndex + ", tx already has " + tx.getOutputs().size() + " outputs"); // fill with dummies while (tx.getOutputs().size() < uxtoIndex) tx.addOutput(new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, Coin.NEGATIVE_SATOSHI, new byte[] {})); // add the real output final TransactionOutput output = new TransactionOutput(Constants.NETWORK_PARAMETERS, tx, uxtoValue, uxtoScriptBytes); tx.addOutput(output); } log.info("fetched unspent outputs from {}", url); onResult(transactions.values()); } else { final String responseMessage = connection.getResponseMessage(); log.info("got http error '{}: {}' from {}", responseCode, responseMessage, url); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final JSONException x) { log.info("problem parsing json from " + url, x); onFail(R.string.error_parse, x.getMessage()); } catch (final IOException x) { log.info("problem querying unspent outputs from " + url, x); onFail(R.string.error_io, x.getMessage()); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } } }); }
From source file:com.bt.aloha.batchtest.v2.TestRunner.java
@SuppressWarnings("unchecked") public ResultTotals run() { log.info("= Summary ============================================================="); log.info("Number of scenario runs: " + testRunnerConfig.getNumberOfRuns()); log.info("Number of scenario types: " + scenarioBeanNameAndWeightMap.size()); log.info("Size of executor pool (core): " + taskExecutor.getCorePoolSize()); log.info("Size of executor pool (max): " + taskExecutor.getMaxPoolSize()); Vector v = (Vector) applicationContext.getBean("allScenarioLifecycleListeners"); if (v != null && v.get(0) != null) log.info("Using Stack Manager of type " + v.get(0).getClass()); log.info("======================================================================="); normalizeWeightsToNumberOfConcurrentStarts(); CountDownLatch latch = new CountDownLatch(testRunnerConfig.getNumberOfRuns()); Vector<String> sNames = new Vector<String>(); for (String s : scenarioBeanNameAndWeightMap.keySet()) { Integer weight = scenarioBeanNameAndWeightMap.get(s); for (int run = 0; run < weight; run++) { sNames.add(s);/* w w w.j a va 2 s . c o m*/ } } // shuffle names so that they can be executed randomly and not in a prefixed order Collections.shuffle(sNames, new Random(System.currentTimeMillis())); for (String s : sNames) { Scenario scenario = (Scenario) applicationContext.getBean(s); // it's a prototype - so has to be extracted from the app ctx every time ScenarioRunner sRunner = (ScenarioRunner) applicationContext.getBean("scenarioRunner"); sRunner.setCountdownLatch(latch); sRunner.setScenario(scenario); // note that scenario lifecycle listeners (needed for start/stop stack) are set in the app context taskExecutor.execute(sRunner); } taskExecutor.shutdown(); try { // waits for all runners to finish latch.await(); } catch (InterruptedException e) { log.warn("Unable to wait for latch to get to 0", e); } resultLogger.logResultEntries(); return resultLogger.logResultsSummary(); }
From source file:net.acesinc.data.json.generator.EventGenerator.java
protected void runRandom() { List<WorkflowStep> stepsCopy = new ArrayList<>(workflow.getSteps()); Collections.shuffle(stepsCopy, new Random(System.currentTimeMillis())); Iterator<WorkflowStep> it = stepsCopy.iterator(); while (running && it.hasNext()) { WorkflowStep step = it.next();//from w w w . j av a 2 s .c o m executeStep(step); if (!it.hasNext() && workflow.isRepeatWorkflow()) { Collections.shuffle(stepsCopy, new Random(System.currentTimeMillis())); it = stepsCopy.iterator(); try { performWorkflowSleep(workflow); } catch (InterruptedException ie) { //wake up! running = false; break; } } } }
From source file:com.github.rinde.rinsim.central.RandomSolver.java
@Override public ImmutableList<ImmutableList<Parcel>> solve(GlobalStateObject state) { checkArgument(!state.getVehicles().isEmpty(), "Need at least one vehicle."); final LinkedListMultimap<VehicleStateObject, Parcel> map = LinkedListMultimap.create(); final Set<Parcel> available = newLinkedHashSet(state.getAvailableParcels()); final Set<Parcel> destinations = newLinkedHashSet(); for (final VehicleStateObject vso : state.getVehicles()) { destinations.addAll(vso.getDestination().asSet()); }//from ww w . ja va 2 s . c o m available.removeAll(destinations); // do random assignment of available parcels for (final Parcel p : available) { final int index = randomGenerator.nextInt(state.getVehicles().size()); map.put(state.getVehicles().get(index), p); map.put(state.getVehicles().get(index), p); } final ImmutableList.Builder<ImmutableList<Parcel>> builder = ImmutableList.builder(); // insert contents, shuffle ordering, insert destination if applicable for (final VehicleStateObject vso : state.getVehicles()) { final List<Parcel> assigned = newArrayList(map.get(vso)); final List<Parcel> conts = newArrayList(vso.getContents()); conts.removeAll(vso.getDestination().asSet()); assigned.addAll(conts); if (vso.getDestination().isPresent() && state.getAvailableParcels().contains(vso.getDestination().get())) { assigned.add(vso.getDestination().get()); } Collections.shuffle(assigned, new RandomAdaptor(randomGenerator)); if (vso.getDestination().isPresent()) { assigned.add(0, vso.getDestination().get()); } builder.add(ImmutableList.copyOf(assigned)); } return builder.build(); }
From source file:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java
public void testThatUnconfiguredCiphersAreRejected() throws Exception { Set<String> supportedCiphers = Sets .newHashSet(SSLContext.getDefault().getSupportedSSLParameters().getCipherSuites()); Set<String> defaultXPackCiphers = Sets.newHashSet(XPackSettings.DEFAULT_CIPHERS); final List<String> unconfiguredCiphers = new ArrayList<>( Sets.difference(supportedCiphers, defaultXPackCiphers)); Collections.shuffle(unconfiguredCiphers, random()); assumeFalse("the unconfigured ciphers list is empty", unconfiguredCiphers.isEmpty()); try (TransportClient transportClient = new TestXPackTransportClient( Settings.builder().put(transportClientSettings()).put("node.name", "programmatic_transport_client") .put("cluster.name", internalCluster().getClusterName()) .putList("xpack.ssl.cipher_suites", unconfiguredCiphers).build(), LocalStateSecurity.class)) { TransportAddress transportAddress = randomFrom( internalCluster().getInstance(Transport.class).boundAddress().boundAddresses()); transportClient.addTransportAddress(transportAddress); transportClient.admin().cluster().prepareHealth().get(); fail("Expected NoNodeAvailableException"); } catch (NoNodeAvailableException e) { assertThat(e.getMessage(), containsString("None of the configured nodes are available: [{#transport#")); }//w ww . ja v a 2 s.com }
From source file:edu.byu.nlp.util.Iterables2.java
public static <E> Iterable<E> shuffled(final Iterable<E> iterable, RandomGenerator rnd) { ArrayList<E> retval = Lists.newArrayList(iterable); Collections.shuffle(retval, new RandomAdaptor(rnd)); return retval; }
From source file:game.plugins.algorithms.RealFeaturesTree.java
protected Criterion bestCriterion(Dataset dataset) { CriterionWithGain ret = new CriterionWithGain(null, 0); List<Integer> featurePositions = Utils.range(0, block.datasetTemplate.sourceTemplate.size()); int totalAttempts = featuresPerNode == 0 ? featurePositions.size() : featuresPerNode; if (featuresPerNode > 0) Collections.shuffle(featurePositions, Experiment.getRandom()); for (int i = 0; i < totalAttempts; i++) { CriterionWithGain current = bestCriterionFor(featurePositions.get(i), dataset); if (current.gain > ret.gain) ret = current;/*from w w w .j a va 2s. c om*/ } return ret.criterion; }
From source file:org.apache.solr.client.solrj.impl.HttpSolrClientConPoolTest.java
public void testPoolSize() throws SolrServerException, IOException { PoolingHttpClientConnectionManager pool = HttpClientUtil.createPoolingConnectionManager(); final HttpSolrClient client1; final String fooUrl; {/* w w w . ja v a 2s . c o m*/ fooUrl = jetty.getBaseUrl().toString() + "/" + "collection1"; CloseableHttpClient httpClient = HttpClientUtil.createClient(new ModifiableSolrParams(), pool, false /* let client shutdown it*/); client1 = getHttpSolrClient(fooUrl, httpClient); client1.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT); } final String barUrl = yetty.getBaseUrl().toString() + "/" + "collection1"; { client1.setBaseURL(fooUrl); client1.deleteByQuery("*:*"); client1.setBaseURL(barUrl); client1.deleteByQuery("*:*"); } List<String> urls = new ArrayList<>(); for (int i = 0; i < 17; i++) { urls.add(fooUrl); } for (int i = 0; i < 31; i++) { urls.add(barUrl); } Collections.shuffle(urls, random()); try { int i = 0; for (String url : urls) { if (!client1.getBaseURL().equals(url)) { client1.setBaseURL(url); } client1.add(new SolrInputDocument("id", "" + (i++))); } client1.setBaseURL(fooUrl); client1.commit(); assertEquals(17, client1.query(new SolrQuery("*:*")).getResults().getNumFound()); client1.setBaseURL(barUrl); client1.commit(); assertEquals(31, client1.query(new SolrQuery("*:*")).getResults().getNumFound()); PoolStats stats = pool.getTotalStats(); assertEquals("oh " + stats, 2, stats.getAvailable()); } finally { for (HttpSolrClient c : new HttpSolrClient[] { client1 }) { HttpClientUtil.close(c.getHttpClient()); c.close(); } } }