Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

In this page you can find the example usage for java.util Collections shuffle.

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:com.graphaware.neo4j.webexpo.database.DataGenerator.java

private String[] randomNumberOfRandomTopics(List<String> allTopics) {
    if (allTopics.size() < MAX_NUMBER_OF_INTERESTS) {
        throw new IllegalStateException("There must be at least " + MAX_NUMBER_OF_INTERESTS + " topics");
    }/*from   w ww .ja va2s .  co m*/

    Collections.shuffle(allTopics);

    int numberOfTopics = random.nextInt(MAX_NUMBER_OF_INTERESTS) + 1; //at least 1 topic, maximum MAX_NUMBER_OF_INTERESTS
    String[] randomTopics = new String[numberOfTopics];
    for (int i = 0; i < numberOfTopics; i++) {
        randomTopics[i] = allTopics.get(i);
    }

    return randomTopics;
}

From source file:edu.berkeley.sparrow.daemon.scheduler.Scheduler.java

/** Adds constraints such that tasks in the job will be spread evenly across the cluster.
 *
 *  We expect three of these special jobs to be submitted; 3 sequential calls to this
 *  method will result in spreading the tasks for the 3 jobs across the cluster such that no
 *  more than 1 task is assigned to each machine.
 *///from  w w  w.ja  v a2s .  co  m
private TSchedulingRequest addConstraintsToSpreadTasks(TSchedulingRequest req) throws TException {
    LOG.info("Handling spread tasks request: " + req);
    int specialCaseIndex = specialCaseCounter.incrementAndGet();
    if (specialCaseIndex < 1 || specialCaseIndex > 3) {
        LOG.error("Invalid special case index: " + specialCaseIndex);
    }

    // No tasks have preferences and we have the magic number of tasks
    TSchedulingRequest newReq = new TSchedulingRequest();
    newReq.user = req.user;
    newReq.app = req.app;
    newReq.probeRatio = req.probeRatio;

    List<InetSocketAddress> allBackends = Lists.newArrayList();
    List<InetSocketAddress> backends = Lists.newArrayList();
    // We assume the below always returns the same order (invalid assumption?)
    for (InetSocketAddress backend : state.getBackends(req.app)) {
        allBackends.add(backend);
    }

    // Each time this is called, we restrict to 1/3 of the nodes in the cluster
    for (int i = 0; i < allBackends.size(); i++) {
        if (i % 3 == specialCaseIndex - 1) {
            backends.add(allBackends.get(i));
        }
    }
    Collections.shuffle(backends);

    if (!(allBackends.size() >= (req.getTasks().size() * 3))) {
        LOG.error("Special case expects at least three times as many machines as tasks.");
        return null;
    }
    LOG.info(backends);
    for (int i = 0; i < req.getTasksSize(); i++) {
        TTaskSpec task = req.getTasks().get(i);
        TTaskSpec newTask = new TTaskSpec();
        newTask.message = task.message;
        newTask.taskId = task.taskId;
        newTask.preference = new TPlacementPreference();
        newTask.preference.addToNodes(backends.get(i).getHostName());
        newReq.addToTasks(newTask);
    }
    LOG.info("New request: " + newReq);
    return newReq;
}

From source file:ch.epfl.eagle.daemon.nodemonitor.NodeMonitor.java

public void requestTaskReservations() {
    LOG.info(Logging.functionCall());/* w w  w  .j  a v  a  2 s  .  co  m*/
    // 1. call sendTaskReservations to n workers
    List<InetSocketAddress> listBackends = getCleanWorkersList();
    // Get the big partition
    LOG.debug("STEALING: Initial node list size: " + listBackends.size());
    int last_nodeID = (int) (listBackends.size() * bigPartition / 100);
    listBackends = listBackends.subList(0, last_nodeID);
    LOG.debug("STEALING: Using nodes from 0 to " + last_nodeID + ". List consists of : " + listBackends);

    LOG.debug("STEALING: New list of backends " + listBackends.toString());
    Collections.shuffle(listBackends);
    InetSocketAddress chosenBackend = listBackends.get(0);

    try {
        InternalService.AsyncClient client = nodeMonitorClientPool.borrowClient(chosenBackend);
        stealingAttempts++;
        LOG.debug("STEALING: Launching sendTasksReservations on node: " + chosenBackend + " stealing attempts"
                + stealingAttempts);
        client.sendTasksReservations(new SendTaskReservationsCallback(chosenBackend, client));
        LOG.debug("STEALING: Finished launching sendTasksReservations on node: " + chosenBackend);
    } catch (Exception e) {
        LOG.error("Error enqueuing task on node " + chosenBackend.toString() + ":" + e);
    }

}

From source file:cm.aptoide.pt.MainActivity.java

private void loadUIEditorsApps() {

    final int[] res_ids = { R.id.central, R.id.topleft, R.id.topright, R.id.bottomleft, R.id.bottomcenter,
            R.id.bottomright };//from ww  w.  jav a2 s .  c  o  m
    final ArrayList<HashMap<String, String>> image_urls = db.getFeaturedGraphics();
    final HashMap<String, String> image_url_highlight = db.getHighLightFeature();

    //        System.out.println(image_url_highlight + "ASDASDASDASD");
    //        System.out.println(image_urls + "ASDASDASDASD");

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (image_url_highlight.size() > 0) {
                a = 1;
                ImageView v = (ImageView) featuredView.findViewById(res_ids[0]);
                // imageLoader.DisplayImage(-1, image_url_highlight.get("url"), v,
                // mContext);
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .displayer(new FadeInBitmapDisplayer(1000)).cacheOnDisc().cacheInMemory().build();
                cm.aptoide.com.nostra13.universalimageloader.core.ImageLoader.getInstance()
                        .displayImage(image_url_highlight.get("url"), v, options);
                v.setTag(image_url_highlight.get("id"));
                v.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {

                        Intent i = new Intent(MainActivity.this, ApkInfo.class);
                        i.putExtra("_id", Long.parseLong((String) arg0.getTag()));
                        i.putExtra("top", false);
                        i.putExtra("category", Category.EDITORSCHOICE.ordinal());
                        startActivity(i);

                    }
                });
                // v.setOnClickListener(featuredListener);
            }
        }
    });

    Collections.shuffle(image_urls);
    runOnUiThread(new Runnable() {

        public void run() {

            for (int i = a; i != res_ids.length; i++) {
                try {
                    ImageView v = (ImageView) featuredView.findViewById(res_ids[i]);

                    // imageLoader.DisplayImage(-1,
                    // image_urls.get(i).get("url"), v, mContext);
                    DisplayImageOptions options = new DisplayImageOptions.Builder()
                            .displayer(new FadeInBitmapDisplayer(1000)).cacheOnDisc().cacheInMemory().build();
                    cm.aptoide.com.nostra13.universalimageloader.core.ImageLoader.getInstance()
                            .displayImage(image_urls.get(i - a).get("url"), v, options);

                    v.setTag(image_urls.get(i - a).get("id"));
                    v.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            Intent i = new Intent(MainActivity.this, ApkInfo.class);
                            i.putExtra("_id", Long.parseLong((String) arg0.getTag()));
                            i.putExtra("top", false);
                            i.putExtra("category", Category.EDITORSCHOICE.ordinal());
                            startActivity(i);
                        }
                    });
                    // v.setOnClickListener(featuredListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    });
}

From source file:com.twitter.distributedlog.service.balancer.ClusterBalancer.java

void moveStreams(List<Host> hosts, AtomicInteger hostIdxMoveFrom, int moveFromLowWaterMark,
        AtomicInteger hostIdxMoveTo, int moveToHighWaterMark, Optional<RateLimiter> rateLimiter) {
    if (hostIdxMoveFrom.get() < 0 || hostIdxMoveFrom.get() >= hosts.size() || hostIdxMoveTo.get() < 0
            || hostIdxMoveTo.get() >= hosts.size() || hostIdxMoveFrom.get() >= hostIdxMoveTo.get()) {
        return;/* w  w w . j a va 2 s . c  o  m*/
    }

    if (logger.isDebugEnabled()) {
        logger.debug(
                "Moving streams : hosts = {}, from = {}, to = {} : from_low_water_mark = {}, to_high_water_mark = {}",
                new Object[] { hosts, hostIdxMoveFrom.get(), hostIdxMoveTo.get(), moveFromLowWaterMark,
                        moveToHighWaterMark });
    }

    Host hostMoveFrom = hosts.get(hostIdxMoveFrom.get());
    int numStreamsOnFromHost = hostMoveFrom.streams.size();
    if (numStreamsOnFromHost <= moveFromLowWaterMark) {
        // do nothing
        return;
    }

    int numStreamsToMove = numStreamsOnFromHost - moveFromLowWaterMark;
    LinkedList<String> streamsToMove = new LinkedList<String>(hostMoveFrom.streams);
    Collections.shuffle(streamsToMove);

    if (logger.isDebugEnabled()) {
        logger.debug("Try to move {} streams from host {} : streams = {}",
                new Object[] { numStreamsToMove, hostMoveFrom.address, streamsToMove });
    }

    while (numStreamsToMove-- > 0 && !streamsToMove.isEmpty()) {
        if (rateLimiter.isPresent()) {
            rateLimiter.get().acquire();
        }

        // pick a host to move
        Host hostMoveTo = hosts.get(hostIdxMoveTo.get());
        while (hostMoveTo.streams.size() >= moveToHighWaterMark) {
            int hostIdx = hostIdxMoveTo.decrementAndGet();
            logger.info("move to host : {}, from {}", hostIdx, hostIdxMoveFrom.get());
            if (hostIdx <= hostIdxMoveFrom.get()) {
                return;
            } else {
                hostMoveTo = hosts.get(hostIdx);
                if (logger.isDebugEnabled()) {
                    logger.debug("Target host to move moved to host {} @ {}", hostIdx, hostMoveTo);
                }
            }
        }

        // pick a stream
        String stream = streamsToMove.remove();

        // move the stream
        if (moveStream(stream, hostMoveFrom, hostMoveTo)) {
            hostMoveFrom.streams.remove(stream);
            hostMoveTo.streams.add(stream);
        }
    }

}

From source file:clummy.classes.DataHandlingClass.java

/**
 * to permutate the list into unique combination of list
 * @param filesToRead/* w w w . j av  a  2  s  .  com*/
 * @return 
 */
public List<String> getPermutationOfNames(String filesToRead) {
    List<String> listNames = new ArrayList<>();
    ICombinatoricsVector<String> initialVector = Factory.createVector(readFile(filesToRead));
    // Create a simple combination generator to generate 3-combinations of the initial vector
    Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 2);

    // Print all possible combinations in vector
    for (ICombinatoricsVector<String> combination : gen) {
        //transfer vector to list and trim unessacry characters
        listNames.add(
                combination.getVector().toString().replace(",", "").replace("[", "").replace("]", "").trim());

    }
    //shuffle the list
    Collections.shuffle(listNames);
    Collections.shuffle(listNames);
    totalListFromName = listNames.size();
    System.out.println(listNames);
    return listNames;
}

From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.Test.java

private static ArrayList<HashSet<String>> extractEntities(File csvData, int nOfAttributes) throws IOException {
    CSVParser parser = CSVParser.parse(csvData, Charset.defaultCharset(), CSVFormat.RFC4180);
    int r = 0;//w  w w  .jav  a  2 s .  com
    ArrayList<Integer> attributePositions = new ArrayList<>();
    ArrayList<String> attributeNames = new ArrayList<>();
    ArrayList<HashSet<String>> res = new ArrayList<>();
    for (CSVRecord csvRecord : parser) {
        if (r == 0) {
            Iterator<String> it = csvRecord.iterator();
            it.next(); //skip URI
            if (!it.hasNext()) { //it is an empty file
                return res;
            }
            it.next(); //skip rdf-schema#label
            it.next(); //skip rdf-schema#comment
            int c = 2;
            for (; it.hasNext();) {
                c++;
                String attr = it.next();
                if (!attr.endsWith("_label")) {
                    attributePositions.add(c);
                }
            }
        } else if (r == 1) {
            Iterator<String> it = csvRecord.iterator();
            it.next(); //skip uri
            it.next(); //skip rdf-schema#label
            it.next(); //skip rdf-schema#comment
            int c = 2;
            int i = 0;
            while (i < attributePositions.size()) {
                c++;
                String attr = it.next();
                if (attributePositions.get(i) == c) {
                    if (!stopAttributes.contains(attr)) {
                        attributes.add(attr);
                    }
                    attributeNames.add(attr);
                    i++;
                }
            }
        } else if (r > 3) {
            ArrayList<String> attributesOfThisEntity = new ArrayList<>();
            Iterator<String> it = csvRecord.iterator();
            String uri = it.next();
            it.next(); //skip rdf-schema#label
            it.next(); //skip rdf-schema#comment
            int c = 2;
            int i = 0;
            while (i < attributePositions.size()) {
                c++;
                String val = it.next();
                if (attributePositions.get(i) == c) {
                    if (!val.equalsIgnoreCase("null")) {
                        String attribute = attributeNames.get(i);
                        if (!stopAttributes.contains(attribute)) {
                            attributesOfThisEntity.add(attribute);
                        }
                    }
                    i++;
                }
            }
            Collections.shuffle(attributesOfThisEntity);
            HashSet<String> s = new HashSet<>();
            for (int k = 0; k < Math.min(nOfAttributes, attributesOfThisEntity.size()); k++) {
                s.add(attributesOfThisEntity.get(k));
            }
            res.add(s);
        }
        r++;
    }
    return res;
}

From source file:com.caved_in.commons.utilities.StringUtil.java

/**
 * Scramble text; What else is there?// w w w.ja  v a2 s.  c  o  m
 *
 * @param text
 * @return
 */
public static String scrambleText(String text) {
    StringBuilder Scrambled = new StringBuilder();
    if (text.contains(" ")) {
        String[] Words = text.split(" ");
        for (String word : Words) {
            ArrayList<Character> chars = new ArrayList<>(word.length());
            for (char c : word.toCharArray()) {
                chars.add(c);
            }
            Collections.shuffle(chars);
            char[] shuffled = new char[chars.size()];
            for (int i = 0; i < shuffled.length; i++) {
                shuffled[i] = chars.get(i);
            }
            Scrambled.append(" ").append(shuffled);
        }
        return Scrambled.toString();
    } else {
        ArrayList<Character> chars = new ArrayList<>(text.length());
        for (char c : text.toCharArray()) {
            chars.add(c);
        }
        Collections.shuffle(chars);
        char[] shuffled = new char[chars.size()];
        for (int i = 0; i < shuffled.length; i++) {
            shuffled[i] = chars.get(i);
        }
        return new String(shuffled);
    }
}

From source file:br.com.autonomiccs.autonomic.plugin.common.services.AutonomiccsSystemVmDeploymentService.java

/**
 * This method tries to find a suitable host to deploy an Autonomiccs system VM.
 * The process is the following:/*w ww. j av a2  s  .  co m*/
 * <ul>
 *   <li>We load all hosts of the given cluster, we also shuffle the host list;
 *   <li>after that, we go over the host list and check if it can host the system VM {@link #canHostSupportVm(ServiceOfferingVO, HostResources)}
 *   <li>if the host has resources to support the system VM, we check if its hypervisor type has a system VM template registered for it, if so we use it as the host to deploy the system VM
 * </ul>
 * @param c cluster to look for a host to deploy a system VM
 * @param excludeHosts hosts to exclude from the search
 * @return {@link HostVO} to deploy a system VM, it may return null if no suitable hosts have been found
 */
private HostVO searchForAnotherRandomHostInTheClusterToStartSystemVmExcludingHosts(ClusterVO c,
        List<HostVO> excludeHosts) {
    List<HostVO> allHostsInCluster = hostService.listAllHostsInCluster(c);
    allHostsInCluster.removeAll(excludeHosts);
    Collections.shuffle(allHostsInCluster);
    for (HostVO h : allHostsInCluster) {
        if (canDeployAutonomiccsSystemVmOnHost(h)) {
            return h;
        }
    }
    logger.info(String.format(
            "Could not find any suitable hosts to deploy the system VM into cluster [clusterId=%d, clusterName=%s]",
            c.getId(), c.getName()));
    return null;
}

From source file:de.Keyle.MyPet.entity.MyPet.java

public boolean autoAssignSkilltree() {
    if (skillTree == null && this.petOwner.isOnline()) {
        if (Configuration.Skilltree.AUTOMATIC_SKILLTREE_ASSIGNMENT) {
            if (SkillTreeMobType.getSkillTreeNames(this.getPetType()).size() > 0) {
                List<SkillTree> skilltrees = SkillTreeMobType.getSkillTrees(this.getPetType());
                if (Configuration.Skilltree.RANDOM_SKILLTREE_ASSIGNMENT) {
                    Collections.shuffle(skilltrees);
                }/*from  w w w  .j a  v a2 s. com*/
                for (SkillTree skillTree : skilltrees) {
                    if (Permissions.hasLegacy(this.petOwner.getPlayer(), "MyPet.skilltree.",
                            skillTree.getPermission())) {
                        return setSkilltree(skillTree);
                    }
                }
            }
        } else {
            for (SkillTree skillTree : SkillTreeMobType.getSkillTrees(this.getPetType())) {
                if (Permissions.hasLegacy(this.petOwner.getPlayer(), "MyPet.skilltree.",
                        skillTree.getPermission())) {
                    getOwner().sendMessage(Util.formatText(
                            Translation.getString("Message.Skilltree.SelectionPrompt", getOwner()),
                            getPetName()));
                    break;
                }
            }
            return false;
        }
    }
    return true;
}