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:fr.ritaly.dungeonmaster.item.ItemManager.java

@Override
public synchronized Item removeItem() {
    if (items == null) {
        return null;
    }/* w w  w .  j  a v a 2s  .  c om*/

    final List<Sector> sectors = new ArrayList<Sector>(items.keySet());

    if (sectors.isEmpty()) {
        // Not supposed to happen
        return null;
    }

    Collections.shuffle(sectors);

    return removeItem(sectors.iterator().next());
}

From source file:com.example.examplersqr.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //////////////////////
    //  Setup QR Bar    //
    //////////////////////
    inAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_in_top);
    outAnim = AnimationUtils.loadAnimation(this, R.anim.abc_slide_out_top);
    qrBar = (LinearLayout) findViewById(R.id.myQRBar);

    // In production, better to get this from a "values.xml" resource
    // in a res folder appropriate to screen size / orientation
    columnCount = 2;/*from  ww w  . j av a 2 s. c  o  m*/

    // Set the QRBar Height to that of the ActionBar
    TypedValue tv = new TypedValue();
    if (getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
        qrBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
    }

    tvQRBarTitle = (TextView) findViewById(R.id.tvQRBarTitle);
    tvQRBarTitle.setText("Tap to add item at top...");
    tvQRBarTitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addItemAtPosition(0, "NEW CARD ADDED ON: " + new Date().toString());
        }
    });

    //////////////////////////////
    //  Setup Swipe To Refresh  //
    //////////////////////////////
    swiper = (TargetedSwipeRefreshLayout) findViewById(R.id.swipe_container);
    swiper.setSize(SwipeRefreshLayout.LARGE);
    swiper.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
            android.R.color.holo_green_light, android.R.color.holo_red_light);

    swiper.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            // This is where you should kickoff the
            // refreshing task.

            // For now, just wait a few seconds and turn off refreshing.
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (myDataset != null && mAdapter != null) {
                        Collections.shuffle(myDataset);
                        mAdapter.notifyDataSetChanged();
                    }
                    swiper.setRefreshing(false);
                }
            }, 5000);
        }
    });

    //////////////////////////////////////////////
    //  Grab the StaggeredGrid & Layout Manager //
    //////////////////////////////////////////////
    mRecycler = (RecyclerView) findViewById(R.id.rvExampleGrid);
    mRecycler.addItemDecoration(new QRBarDecoration(columnCount, qrBarHeight));
    // mRecycler.addItemDecoration(new OverlapDecoration());

    mSGLM = new StaggeredGridLayoutManager(columnCount, StaggeredGridLayoutManager.VERTICAL);

    mRecycler.setLayoutManager(mSGLM);

    //////////////////////////////
    //  Setup Adapter & DataSet //
    //////////////////////////////
    myDataset = new ArrayList<String>();

    // Load up the dataset with random titles
    for (int x = 0; x < 50; x++) {
        myDataset.add(someTitles[randy.nextInt(someTitles.length)]);
    }

    mAdapter = new RVAdapter(this, myDataset);

    /////////////////////////////////////////////
    //  Setup the RecyclerView Scroll Listener //
    /////////////////////////////////////////////
    mRecycler.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

            // Simple check if moved vertically.
            // React to scrolls of a minimum amount (3, in this case)
            if (dy > 3) {

                if (qrBar.getVisibility() == View.VISIBLE)
                    hideQRBar();

            } else if (dy < -3) {

                if (qrBar.getVisibility() == View.GONE)
                    showQRBar();
            }
        }
    });

    // Set the RecyclerView's Adapter
    mRecycler.setAdapter(mAdapter);

    // Set the Recyclerview to be the target scrollable view
    // for the TargetedSwipeRefreshAdapter.
    swiper.setTargetScrollableView(mRecycler);

}

From source file:ltsa.jung.TreeLikeGraphLayout.java

/**
 * Set locations of nodes for subtree from {v} within rectangle such that
 * top-left corner is ({x}, {y}).  Ignore nodes in {alreadyDone}.
 *//*from  w  w w .  ja  va 2  s .  com*/
protected void buildTree(V v, int x, int y) {
    assert !alreadyDone.contains(v);
    int depth = depths.get(v);
    {
        alreadyDone.add(v);
        int currentwidth = treeWidth.get(v);
        Point p = new Point(x + currentwidth * distX / 2, y);
        locations.get(v).setLocation(p);

        int lastX = x;

        List<V> successors = new ArrayList<V>(graph.getSuccessors(v));
        Collections.shuffle(successors); // for diversity
        for (V element : successors) {
            if (depths.get(element) == depth + 1 && !alreadyDone.contains(element)) {
                // this is a successor in the tree
                buildTree(element, lastX, y + distY);
                lastX = lastX + (treeWidth.get(element) + 1) * distX;
            }
        }
    }
}

From source file:com.sankalp.characterreader.neuralnetwork.TrainingData.java

public void shuffle() {
    Collections.shuffle(sampleList);
}

From source file:forge.quest.BoosterUtils.java

private static List<Predicate<CardRules>> getColorFilters(final StartingPoolPreferences userPrefs,
        final List<PaperCard> cardPool) {

    final List<Predicate<CardRules>> colorFilters = new ArrayList<>();

    if (userPrefs != null) {

        boolean includeArtifacts = userPrefs.includeArtifacts();

        final List<Byte> preferredColors = userPrefs.getPreferredColors();

        switch (userPrefs.getPoolType()) {

        case RANDOM_BALANCED:
            preferredColors.clear();/*from  w ww . jav  a 2s.  c om*/
            int numberOfColors = COLOR_COUNT_PROBABILITIES[(int) (Math.random()
                    * COLOR_COUNT_PROBABILITIES.length)];
            if (numberOfColors < 6) {
                Collections.shuffle(possibleColors);
                for (int i = 0; i < numberOfColors; i++) {
                    preferredColors.add(possibleColors.get(i));
                }
            } else {
                preferredColors.addAll(possibleColors);
            }
            includeArtifacts = Math.random() < 0.5;
        case BALANCED:
            populateBalancedFilters(colorFilters, preferredColors, cardPool, includeArtifacts);
            break;
        case RANDOM:
            populateRandomFilters(colorFilters);
            break;

        }

    }

    return colorFilters;

}

From source file:com.wso2telco.dep.mediator.impl.smsmessaging.RetrieveSMSHandler.java

@Override
public boolean handle(MessageContext context) throws CustomException, AxisFault, Exception {

    SOAPBody body = context.getEnvelope().getBody();
    Gson gson = new GsonBuilder().serializeNulls().create();

    String reqType = "retrive_sms";
    String requestid = UID.getUniqueID(Type.SMSRETRIVE.getCode(), context, executor.getApplicationid());
    // String appID = apiUtil.getAppID(context, reqType);

    int batchSize = 100;

    URL retrieveURL = new URL("http://example.com/smsmessaging/v1" + executor.getSubResourcePath());
    String urlQuery = retrieveURL.getQuery();

    if (urlQuery != null) {
        if (urlQuery.contains("maxBatchSize")) {
            String queryParts[] = urlQuery.split("=");
            if (queryParts.length > 1) {
                if (Integer.parseInt(queryParts[1]) < 100) {
                    batchSize = Integer.parseInt(queryParts[1]);
                }/*from  w  w  w .  jav a2 s  . co  m*/
            }
        }

        List<OperatorEndpoint> endpoints = occi.getAPIEndpointsByApp(API_TYPE, executor.getSubResourcePath(),
                executor.getValidoperators());

        log.info("Endpoints size: " + endpoints.size());

        Collections.shuffle(endpoints);

        int perOpCoLimit = batchSize / (endpoints.size());

        log.info("Per OpCo limit :" + perOpCoLimit);

        JSONArray results = new JSONArray();

        int execCount = 0;
        int forLoopCount = 0;
        boolean retryFlag = true;
        FileReader fileReader = new FileReader();
        String file = CarbonUtils.getCarbonConfigDirPath() + File.separator
                + FileNames.MEDIATOR_CONF_FILE.getFileName();
        Map<String, String> mediatorConfMap = fileReader.readPropertyFile(file);
        Boolean retry = false;
        retry = Boolean.valueOf(mediatorConfMap.get("retry_on_fail"));
        Integer retryCount = Integer.valueOf(mediatorConfMap.get("retry_count"));

        ArrayList<String> responses = new ArrayList<String>();
        while ((results.length() < batchSize) && (retryFlag == true)) {
            execCount++;
            log.info("Default aEndpoint : " + endpoints.size());
            for (int i = 0; i < endpoints.size(); i++) {
                forLoopCount++;
                log.info("Default forLoopCount : " + forLoopCount);
                OperatorEndpoint aEndpoint = endpoints.remove(0);
                log.info("Default aEndpoint : " + aEndpoint.getEndpointref().getAddress());
                endpoints.add(aEndpoint);
                String url = aEndpoint.getEndpointref().getAddress();
                APICall ac = apiUtil.setBatchSize(url, body.toString(), reqType, perOpCoLimit);

                JSONObject obj = ac.getBody();
                String retStr = null;
                log.info("Retrieving messages of operator: " + aEndpoint.getOperator());

                if (context.isDoingGET()) {
                    log.info("Doing makeGetRequest");
                    retStr = executor.makeRetrieveSMSGetRequest(aEndpoint, ac.getUri(), null, true, context,
                            false);
                } else {
                    log.info("Doing makeRequest");
                    retStr = executor.makeRequest(aEndpoint, ac.getUri(), obj.toString(), true, context, false);
                }
                log.info("Retrieved messages of " + aEndpoint.getOperator() + " operator: " + retStr);

                if (retStr != null) {

                    JSONArray resList = apiUtil.getResults(reqType, retStr);
                    if (resList != null) {
                        for (int t = 0; t < resList.length(); t++) {
                            results.put(resList.get(t));
                        }
                        responses.add(retStr);
                    }

                }

                if (results.length() >= batchSize) {
                    break;
                }
            }

            if (retry == false) {
                retryFlag = false;
                log.info("11 Final value of retryFlag :" + retryFlag);
            }

            if (execCount >= retryCount) {
                retryFlag = false;
                log.info("22 Final value of retryFlag :" + retryFlag);
            }

            log.info("Final value of count :" + execCount);
            log.info("Results length of retrieve messages: " + results.length());

        }

        JSONObject paylodObject = apiUtil.generateResponse(context, reqType, results, responses, requestid);
        String strjsonBody = paylodObject.toString();

        /*add resourceURL to the southbound response*/
        SouthboundRetrieveResponse sbRetrieveResponse = gson.fromJson(strjsonBody,
                SouthboundRetrieveResponse.class);
        if (sbRetrieveResponse != null && sbRetrieveResponse.getInboundSMSMessageList() != null) {
            String resourceURL = sbRetrieveResponse.getInboundSMSMessageList().getResourceURL();
            InboundSMSMessage[] inboundSMSMessageResponses = sbRetrieveResponse.getInboundSMSMessageList()
                    .getInboundSMSMessage();

            for (int i = 0; i < inboundSMSMessageResponses.length; i++) {
                String messageId = inboundSMSMessageResponses[i].getMessageId();
                inboundSMSMessageResponses[i].setResourceURL(resourceURL + "/" + messageId);
            }
            sbRetrieveResponse.getInboundSMSMessageList().setInboundSMSMessage(inboundSMSMessageResponses);
        }

        executor.removeHeaders(context);
        executor.setResponse(context, gson.toJson(sbRetrieveResponse));
        // routeToEndPoint(context, sendResponse, "", "", strjsonBody);

        ((Axis2MessageContext) context).getAxis2MessageContext().setProperty("messageType", "application/json");

    }
    return true;
}

From source file:io.spring.springoverflow.controller.PostController.java

@RequestMapping(value = "/post/save", method = RequestMethod.POST)
public String save(@RequestParam(value = "postId", required = true) long parentPostId,
        @RequestParam(value = "body", required = true) String body, Model model) throws Exception {
    String username = SecurityContextHolder.getContext().getAuthentication().getName();

    User currentUser = userRepository.findByDisplayName(username);
    long userId = currentUser.getId();

    Post post = new Post();
    post.setBody(body);/*from   w  w  w.  j a v  a 2s  .com*/
    post.setCreationDate(new Date());
    post.setOwnerUser(currentUser);
    post.setPostTypeId(2);

    Post parentPost = postRepository.findOne(parentPostId);
    parentPost.getAnswers().add(post);
    parentPost.setAnswerCount(parentPost.getAnswerCount() + 1);

    postRepository.save(parentPost);

    List<RecommendedItem> items;
    List<Post> matchingPosts = new ArrayList<>();

    // Recommendations by Question's Tags
    matchingPosts.addAll(recommendPostsByItemsTags(parentPost));

    // Recommendations by User's History
    //      matchingPosts.addAll(recommendPostsByUsers(currentUser));

    // Recommendations By Both
    //      matchingPosts.addAll(recommendPostsByUsers(currentUser));
    //      matchingPosts.addAll(recommendPostsByItemsTags(parentPost));

    if (matchingPosts.size() < 3) {
        items = recommendItems(parentPost.getTags());

        for (RecommendedItem item : items) {
            List<Post> posts = postRepository.findByTagId(item.getItemID(), new PageRequest(0, 3));

            matchingPosts.addAll(posts);
        }
    }

    Set<Post> recommendedPosts = new HashSet<>(3);

    if (matchingPosts.size() > 3) {
        Collections.shuffle(matchingPosts);
        recommendedPosts.addAll(matchingPosts.subList(0, 3));
    } else {
        recommendedPosts.addAll(matchingPosts);
    }

    model.addAttribute("post", parentPost);
    model.addAttribute("recommendations", recommendedPosts);

    return "post/show";
}

From source file:com.rk.grid.server.TaskExecutorsTest.java

/**
 * Test method for {@link com.rk.grid.server.TaskExecutors#newFixedCluster(java.lang.String, int, int, java.lang.String[])}.
 * @throws Exception /*from   www . j a va  2 s . c o  m*/
 */
@Test
public void testErrorReporting() throws Exception {
    ITaskExecutor executor = TaskExecutors.newFixedCluster(3, 1, "-Xms20m");
    executor.unPause();
    int taskCount = 30;
    List<ITask<String>> tasks = FibonacciTask.generateTasks(taskCount);

    tasks.add(new ErrorTask());

    Collections.shuffle(tasks);

    TestHandler resultHandler = new TestHandler("TestHelloWorld");

    executor.execute(tasks, resultHandler);

    resultHandler.await();
    executor.shutdown();

    assertEquals(taskCount, resultHandler.getResultCount());
    assertEquals(0, resultHandler.getRejectedCount());
    assertEquals(1, resultHandler.getErrorCount());
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.TestEditorService.java

@Test
public void testModifyOrder() throws Exception {
    insertSampleEntries();/*from  w  w w.j a va 2 s  .  c  om*/
    QueryResult result = index.queryExact("Haus", true, true);
    List<LemmaVersion> old = result.getEntries();
    for (int i = 0; i < old.size(); i++) {
        logger.info("Old Order: " + i + " is " + old.get(i));
    }
    List<LemmaVersion> modified = new ArrayList<LemmaVersion>();
    Assert.assertTrue(old.size() > 1);
    modified.addAll(old);
    do {
        Collections.shuffle(modified);
    } while (modified.equals(old));
    for (int i = 0; i < modified.size(); i++) {
        logger.info("New Order: " + i + " is " + modified.get(i));
    }
    List<LexEntry> updated = backend.updateOrder(true, modified);
    for (int i = 0; i < updated.size(); i++) {
        Assert.assertEquals(modified.get(i), updated.get(i).getCurrent());
        logger.info("Upd Order: " + i + " is " + updated.get(i).getCurrent());
    }
}

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

/**
 * Returns the next shuffled item from the named collection.
 * /*from ww w  .  ja  va 2  s.c  o m*/
 * @param name
 * @return 
 */
private String getNextShuffledItemFor(final String name) {
    if (stringIters.containsKey(name)) {
        final Iterator<String> iter = stringIters.get(name);
        if (iter.hasNext()) {
            return iter.next();
        }
    }

    final List<String> list = stringLists.get(name);
    Collections.shuffle(list);

    final Iterator<String> iter = list.iterator();
    stringIters.put(name, iter);
    return iter.next();
}