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:org.jtalks.poulpe.model.dao.hibernate.SectionHibernateDaoTest.java

@Test
public void testBranchPositions() {
    for (int i = 0; i < 5; i++) {
        List<PoulpeBranch> expected = section.getPoulpeBranches();
        Collections.shuffle(expected);

        dao.saveOrUpdate(section);/*from w  ww . ja v a  2s  .  co m*/

        section = ObjectRetriever.retrieveUpdated(section, session);
        List<PoulpeBranch> actual = section.getPoulpeBranches();

        assertEquals(actual, expected);
    }
}

From source file:com.alibaba.otter.manager.biz.remote.impl.ConfigRemoteServiceImpl.java

public boolean notifyChannel(final Channel channel) {
    Assert.notNull(channel);/*from w w  w. j  av a 2s .c o  m*/
    // ?Node
    NotifyChannelEvent event = new NotifyChannelEvent();
    event.setChannel(channel);

    Set<String> addrsSet = new HashSet<String>();

    // ?otternode
    // List<Node> nodes = nodeService.listAll();
    // for (Node node : nodes) {
    // if (node.getStatus().isStart() &&
    // StringUtils.isNotEmpty(node.getIp()) && node.getPort() != 0) {
    // final String addr = node.getIp() + ":" + node.getPort();
    // addrsList.add(addr);
    // }
    // }

    // ?pipelinenode
    for (Pipeline pipeline : channel.getPipelines()) {
        List<Node> nodes = new ArrayList<Node>();
        nodes.addAll(pipeline.getSelectNodes());
        nodes.addAll(pipeline.getExtractNodes());
        nodes.addAll(pipeline.getLoadNodes());
        for (Node node : nodes) {
            if (node.getStatus().isStart() && StringUtils.isNotEmpty(node.getIp()) && node.getPort() != 0) {
                String addr = node.getIp() + ":" + node.getPort();
                if (node.getParameters().getUseExternalIp()) {
                    addr = node.getParameters().getExternalIp() + ":" + node.getPort();
                }
                addrsSet.add(addr);
            }
        }
    }

    List<String> addrsList = new ArrayList<String>(addrsSet);
    if (CollectionUtils.isEmpty(addrsList) && channel.getStatus().isStart()) {
        throw new ManagerException("no live node for notifyChannel");
    } else if (CollectionUtils.isEmpty(addrsList)) {
        // ???
        return true;
    } else {
        Collections.shuffle(addrsList);// ???????
        try {
            String[] addrs = addrsList.toArray(new String[addrsList.size()]);
            List<Boolean> result = (List<Boolean>) communicationClient.call(addrs, event); // ??
            logger.info("## notifyChannel to [{}] channel[{}] result[{}]",
                    new Object[] { ArrayUtils.toString(addrs), channel.toString(), result });

            boolean flag = true;
            for (Boolean f : result) {
                flag &= f;
            }

            return flag;
        } catch (Exception e) {
            logger.error("## notifyChannel error!", e);
            throw new ManagerException(e);
        }
    }
}

From source file:com.benfante.minimark.blo.AssessmentFillingBo.java

private QuestionFilling buildQuestionFilling(ClosedQuestion question) {
    ClosedQuestionFilling result = new ClosedQuestionFilling();
    result.setContent(question.getContent());
    result.setContentFilter(question.getContentFilter());
    result.setOriginalQuestion(question);
    result.setTitle(question.getTitle());
    result.setVisualization(question.getVisualization());
    result.setWeight(question.getWeight());
    int i = 0;/*from  w  ww . j a v a2s . c o  m*/
    for (FixedAnswer fixedAnswer : question.getFixedAnswers()) {
        FixedAnswerFilling fixedAnswerFilling = new FixedAnswerFilling();
        fixedAnswerFilling.setContent(fixedAnswer.getContent());
        fixedAnswerFilling.setContentFilter(fixedAnswer.getContentFilter());
        fixedAnswerFilling.setCorrect(fixedAnswer.getCorrect());
        fixedAnswerFilling.setOrdering(Long.valueOf(i++));
        fixedAnswerFilling.setQuestion(result);
        result.getFixedAnswers().add(fixedAnswerFilling);
        fixedAnswerFilling.setWeight(fixedAnswer.getWeight());
    }
    Collections.shuffle(result.getFixedAnswers());
    i = 0;
    for (FixedAnswerFilling fixedAnswerFilling : result.getFixedAnswers()) {
        fixedAnswerFilling.setOrdering(Long.valueOf(i++));
    }
    return result;
}

From source file:com.nextep.designer.dbgm.ui.layout.DiagramLayoutService.java

/**
 * Layout the diagram/*w  ww . j  av a2  s .c o  m*/
 * @param diagram
 */
public static void autoLayout(IDiagram diagram) {
    int x = 1;
    int y = 1;
    // Getting diagram items
    List<IDiagramItem> items = new ArrayList<IDiagramItem>(diagram.getItems());
    // Computing reverse dependencies map (one shot, multiple uses)
    final MultiValueMap invRefMap = CorePlugin.getService(IReferenceManager.class)
            .getReverseDependenciesMap(IElementType.getInstance(IBasicTable.TYPE_ID));
    // Shuffling first, since our comparator is not deterministic, we mix our
    // items to provide multiple layout suggestions
    Collections.shuffle(items);
    // Sorting items
    Collections.sort(items, new TableDependencyComparator(invRefMap));

    // Hashing diagram items
    Map<IReference, IDiagramItem> refMap = new HashMap<IReference, IDiagramItem>();
    for (IDiagramItem i : items) {
        if (!(i.getItemModel() instanceof IBasicTable)) {
            continue;
        }
        refMap.put(((IBasicTable) i.getItemModel()).getReference(), i);
    }
    // Building tree
    DependencyTree<IDiagramItem> rootTree = new DependencyTree<IDiagramItem>(null);
    List<IDiagramItem> processed = new ArrayList<IDiagramItem>();
    for (IDiagramItem i : items) {
        if (!processed.contains(i)) {
            rootTree.addChild(buildTree(i, items, processed, refMap, invRefMap));
        }
    }
    // Sorting tree
    //        DependencyTreeComparator comparator = new DependencyTreeComparator(rootTree);
    ////        Collections.sort(rootTree.getChildren(),comparator);
    //        DependencyTree next = comparator.getNextTreeToDisplay();
    //        while(next!=null) {
    //           y = position(next,x,y) + V_SPACING;
    //           next = comparator.getNextTreeToDisplay();
    //        }
    for (DependencyTree<IDiagramItem> treeItem : rootTree.getChildren()) {
        y = position(treeItem, x, y) + V_SPACING;
    }
    //        // Parent tables referenced via foreign keys
    //      for(IKeyConstraint k : table.getConstraints()) {
    //         switch(k.getConstraintType()) {
    //         case FOREIGN:
    //            ForeignKeyConstraint fk = (ForeignKeyConstraint)k;
    //            if(fk.getRemoteConstraint()!=null) {
    //               IBasicTable t = fk.getRemoteConstraint().getConstrainedTable();
    //               if(t!=null) {
    //                  final IDiagramItem fkItem = createTableItem(fk.getRemoteConstraint().getConstrainedTable(),x,y);
    //                  parentItems.add(fkItem);
    //                  // Adjusting position variables
    //                  y+=fkItem.getHeight()+V_SPACING;
    //                  // MAnaging max height / width
    //                  if(y>maxHeight) maxHeight = y;
    //                  if(fkItem.getWidth()> maxWidth) {
    //                     maxWidth = fkItem.getWidth();
    //                  }
    //                  // Registering item to diagrm
    //                  d.addItem(fkItem);
    //               }
    //            }
    //            break;
    //         }
    //      }
    //      leftHeight = maxHeight;
    //      // Central table (current)
    //        x+=maxWidth + H_SPACING;
    //        y=1;
    //        
    //        IDiagramItem tabItem = new DiagramItem(VersionHelper.getVersionable(table),x,y);
    //        tabItem.setHeight(40 + 21 * table.getColumns().size());
    //        d.addItem(tabItem);
    //        
    //        // Child tables
    //        x+=tabItem.getWidth() + H_SPACING;
    //        y=1;
    //        
    //        Collection<IReferencer> children = CorePlugin.getService(IReferenceManager.class).getReverseDependencies(table);
    //        for(IReferencer r : children) {
    //           if(r instanceof IBasicTable) {
    //              final IDiagramItem i = createTableItem((IBasicTable)r,x,y);
    //              childItems.add(i);
    //              y+=i.getHeight()+V_SPACING;
    //              if(y>maxHeight) maxHeight = y;
    //              d.addItem(i);
    //           }
    //        }
    //        
    //        // Repositioning central table Y
    //        tabItem.setYStart(maxHeight/2 - tabItem.getHeight()/2);
    //        
    //        // Repositioning minimum height elements
    //        if(leftHeight<maxHeight) {
    //           repositionItem(parentItems, leftHeight, maxHeight);
    //        } else {
    //           repositionItem(childItems, y, maxHeight);
    //        }

}

From source file:com.cloudera.oryx.ml.param.HyperParams.java

/**
 * @param ranges ranges of hyperparameters to try, one per hyperparameters
 * @param howMany how many combinations of hyperparameters to return
 * @param perParam how many different hyperparameter values to try per hyperparameter
 * @return combinations of concrete hyperparameter values. For example, for 5 parameters each
 *  with 3 values to try, the total number of combinations returned could be up to pow(3,5)
 *  or 243. The number could be less if the ranges do not actually have that many distinct
 *  values. If {@code howMany} is smaller than the total number of combinations, a random
 *  subset of all combinations are returned. The order is shuffled randomly. If no parameters
 *  are specified or {@code perParam} is 0, a single empty combination is returned.
 *//*from w w  w.  j  a v  a 2s  .com*/
public static List<List<?>> chooseHyperParameterCombos(Collection<HyperParamValues<?>> ranges, int howMany,
        int perParam) {
    Preconditions.checkArgument(howMany > 0);
    Preconditions.checkArgument(perParam >= 0);

    int numParams = ranges.size();
    if (numParams == 0 || perParam == 0) {
        return Collections.<List<?>>singletonList(Collections.emptyList());
    }

    // Put some reasonable upper limit on the number of combos
    Preconditions.checkArgument(Math.pow(perParam, numParams) <= MAX_COMBOS);

    int howManyCombos = 1;
    List<List<?>> paramRanges = new ArrayList<>(numParams);
    for (HyperParamValues<?> range : ranges) {
        List<?> values = range.getTrialValues(perParam);
        paramRanges.add(values);
        howManyCombos *= values.size();
    }

    List<List<?>> allCombinations = new ArrayList<>(howManyCombos);
    for (int combo = 0; combo < howManyCombos; combo++) {
        List<Object> combination = new ArrayList<>(numParams);
        for (int param = 0; param < numParams; param++) {
            int whichValueToTry = combo;
            for (int i = 0; i < param; i++) {
                whichValueToTry /= paramRanges.get(i).size();
            }
            whichValueToTry %= paramRanges.get(param).size();
            combination.add(paramRanges.get(param).get(whichValueToTry));
        }
        allCombinations.add(combination);
    }

    if (howMany >= howManyCombos) {
        Collections.shuffle(allCombinations);
        return allCombinations;
    }
    RandomDataGenerator rdg = new RandomDataGenerator(RandomManager.getRandom());
    int[] indices = rdg.nextPermutation(howManyCombos, howMany);
    List<List<?>> result = new ArrayList<>(indices.length);
    for (int i = 0; i < indices.length; i++) {
        result.add(allCombinations.get(i));
    }
    Collections.shuffle(result);
    return result;
}

From source file:com.pinterest.teletraan.worker.GroupInfoCollector.java

private void processNewGroups() {
    try {/*from   w  ww  .  j a  v a 2s  .c  o m*/
        List<String> groups = groupInfoDAO.getNewGroupNames();
        if (groups.isEmpty()) {
            LOG.info("GroupInfoCollector did not find any new groups, exiting.");
            return;
        }
        Collections.shuffle(groups);
        for (String group : groups) {
            processSingleGroup(group);
        }
    } catch (Exception ex) {
        LOG.error("Failed to process new groups", ex);
    }
}

From source file:se.gothiaforum.controller.tagcloud.TagCloudController.java

/**
 * Renders the view for the tag cloud.//from ww w.  j av  a 2s . co  m
 * 
 * @param request
 *            the request
 * @param model
 *            the model
 * @return a view
 */
@RenderMapping
public String renderView(RenderRequest request, Model model) {

    try {

        List<JournalArticle> articles = JournalArticleLocalServiceUtil.getJournalArticles(0,
                JournalArticleLocalServiceUtil.getJournalArticlesCount());

        Set<AssetEntry> entrys = new HashSet<AssetEntry>();

        for (JournalArticle ja : articles) {
            if (ja.getType().equals(ActorsConstants.TYPE_ACTOR)) {
                entrys.add(AssetEntryLocalServiceUtil.getEntry(JournalArticle.class.getName(),
                        ja.getResourcePrimKey()));
            }
        }

        Multiset<AssetTag> tagMultiSet = HashMultiset.create();

        for (AssetEntry entry : entrys) {

            List<AssetTag> tags = AssetTagLocalServiceUtil.getEntryTags(entry.getEntryId());

            for (AssetTag tag : tags) {
                tagMultiSet.add(tag);
            }
        }

        List<TagVO> tagVOList = new ArrayList<TagVO>();

        for (Entry<AssetTag> entry : tagMultiSet.entrySet()) {

            String cssClass;

            final int number8 = 8;
            final int number7 = 7;
            final int number6 = 6;
            final int number5 = 5;
            final int number4 = 4;
            final int number3 = 3;
            final int number2 = 2;

            if (entry.getCount() > number8) {
                cssClass = "tag-weight-10";
            } else if (entry.getCount() > number7) {
                cssClass = "tag-weight-9";
            } else if (entry.getCount() > number6) {
                cssClass = "tag-weight-8";
            } else if (entry.getCount() > number5) {
                cssClass = "tag-weight-7";
            } else if (entry.getCount() > number4) {
                cssClass = "tag-weight-6";
            } else if (entry.getCount() > number3) {
                cssClass = "tag-weight-5";
            } else if (entry.getCount() > number2) {
                cssClass = "tag-weight-4";
            } else {
                cssClass = "tag-weight-2";
            }

            TagVO tagVO = new TagVO(cssClass, entry.getElement().getName(),
                    ActorsConstants.SEARCH_REDIRECT_URL + entry.getElement().getName(),
                    entry.getElement().getTagId());

            tagVO.setCount(entry.getCount());

            tagVOList.add(tagVO);

        }

        final int size = 20;

        if (tagVOList.size() > size) {

            for (int i = 1; tagVOList.size() > size; i++) {

                List<TagVO> removeList = new ArrayList<TagVO>();

                for (TagVO tagVO : tagVOList) {

                    if (tagVO.getCount() == i) {
                        removeList.add(tagVO);
                    }
                }
                tagVOList.removeAll(removeList);
            }
        }

        Collections.shuffle(tagVOList);

        model.addAttribute("tagVOList", tagVOList);

    } catch (SystemException e) {
        e.printStackTrace();
    } catch (PortalException e) {
        e.printStackTrace();
    }

    return "tagCloudView";
}

From source file:blue.soundObject.jmask.ItemList.java

public double getValue(double time) {
    double retVal = 0.0;

    if (listItems.size() <= 1) {
        retVal = ((Double) listItems.get(index)).doubleValue();
    } else {/*  w  ww  . j  a  v a 2 s .c o m*/

        switch (this.getListType()) {
        case CYCLE:
            retVal = ((Double) listItems.get(index)).doubleValue();
            index++;

            if (index >= listItems.size()) {
                index = 0;
            }

            break;
        case SWING:
            retVal = ((Double) listItems.get(index)).doubleValue();

            if (direction == 0) {
                index++;

                if (index >= listItems.size()) {
                    index -= 2;
                    direction = 1;
                }
            } else {
                index--;

                if (index < 0) {
                    index = 1;
                    direction = 0;
                }
            }

            break;
        case RANDOM:
            index = (int) (Math.random() * listItems.size());
            retVal = ((Double) listItems.get(index)).doubleValue();

            break;
        case HEAP:
            if (index == 0) {
                Collections.shuffle(listItems);
            }
            retVal = ((Double) listItems.get(index)).doubleValue();
            index++;

            if (index >= listItems.size()) {
                index = 0;
            }

            break;
        default:
            break;
        }
    }

    return retVal;
}

From source file:com.Anderson.example.games.tanc.GameplayFragment.java

void AssignToQuestionary(JsonNode jNode) {
    ArrayNode slaidsNode = (ArrayNode) jNode.get("questions");
    Iterator<JsonNode> questionsIterator = slaidsNode.elements();

    int temp = 0;
    while (questionsIterator.hasNext()) {
        JsonNode questions = questionsIterator.next();
        mQuestionary.mQuestions[temp] = new Question();
        mQuestionary.mQuestions[temp].setCorrectAnswer(questions.get("answer").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(mQuestionary.mQuestions[temp].CorrectAnswer);
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice1").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice2").asText());
        mQuestionary.mQuestions[temp].mAnswers.add(questions.get("choice3").asText());
        Collections.shuffle(mQuestionary.mQuestions[temp].mAnswers);
        mQuestionary.mQuestions[temp].setDescription(questions.get("description").asText());
        temp++;//from ww w .j  av  a2s  . c o m
    }
}

From source file:com.strider.datadefender.functions.CoreFunctions.java

/**
 * Sets up a map, mapping a list of values to a list of shuffled values.
 * /* w ww . j  a v  a  2  s . c om*/
 * If the value is not mapped, the function guarantees returning the same
 * randomized value for a given column value - however it does not guarantee
 * that more than one column value do not have the same randomized value.
 * 
 * @param params
 * @return 
 */
private String getPredictableShuffledValueFor(final String name, final String value) {
    if (!predictableShuffle.containsKey(name)) {
        final List<String> list = stringLists.get(name);
        final List<String> shuffled = new ArrayList<>(list);
        Collections.shuffle(shuffled);

        final Map<String, String> smap = new HashMap<>();
        final Iterator<String> lit = list.iterator();
        final Iterator<String> sit = shuffled.iterator();
        while (lit.hasNext()) {
            smap.put(lit.next(), sit.next());
        }
        predictableShuffle.put(name, smap);
    }

    final Map<String, String> map = predictableShuffle.get(name);
    if (!map.containsKey(value)) {
        final String[] vals = map.values().toArray(new String[map.size()]);
        final int index = (int) Math.abs((long) value.hashCode()) % vals.length;
        return vals[index];
    }
    return map.get(value);
}