Example usage for java.lang Math random

List of usage examples for java.lang Math random

Introduction

In this page you can find the example usage for java.lang Math random.

Prototype

public static double random() 

Source Link

Document

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0 .

Usage

From source file:BufferedImageThread.java

public void step(int w, int h) {
    x += xi;/*from  www . jav a2 s  .com*/
    y += yi;

    if (x > w) {
        x = w - 1;
        xi = Math.random() * -w / 32;
    }
    if (x < 0) {
        x = 2;
        xi = Math.random() * w / 32;
    }
    if (y > h) {
        y = h - 2;
        yi = Math.random() * -h / 32;
    }
    if (y < 0) {
        y = 2;
        yi = Math.random() * h / 32;
    }

    if ((rotate += 5) == 360) {
        rotate = 0;
    }
    if (scaleDirection == UP) {
        if ((scale += 0.5) > 1.5) {
            scaleDirection = DOWN;
        }
    } else if (scaleDirection == DOWN) {
        if ((scale -= .05) < 0.5) {
            scaleDirection = UP;
        }
    }
}

From source file:com.stableapps.anglewraparounddemo.AngleWrapDemoMain.java

/**
 * Creates a sample dataset.//  w  w w  .ja  v a2 s .c  o  m
 *
 * @param count the item count.
 *
 * @return the dataset.
 */
private XYDataset createAngleDataset(final int count) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    final TimeSeries s1 = new TimeSeries("Angle (In Degrees)");
    RegularTimePeriod start = new Minute();
    double direction = 180.0;
    for (int i = 0; i < count; i++) {
        s1.add(start, direction);
        start = start.next();
        direction = direction + (Math.random() - 0.45) * 15.0;
        if (direction < 0.0) {
            direction = direction + 360.0;
        } else if (direction > 360.0) {
            direction = direction - 360.0;
        }
    }
    dataset.addSeries(s1);
    return dataset;
}

From source file:com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector.java

private String selectOneInstance(InstanceGroup group, double probability) {
    Validate.isTrue(probability < 1);
    if (probability <= 0) {
        logger().info("Group {} [type {}] has disabled probability: {}",
                new Object[] { group.name(), group.type(), probability });
        return null;
    }/*w w  w. j av  a2s  .  c  om*/
    double rand = Math.random();
    if (rand > probability || group.instances().isEmpty()) {
        logger().info("Group {} [type {}] got lucky: {} > {}",
                new Object[] { group.name(), group.type(), rand, probability });
        return null;
    }
    return group.instances().get(RANDOM.nextInt(group.instances().size()));
}

From source file:de.tor.tribes.ui.wiz.dep.DefensePlanerWizard.java

private static List<SOSRequest> createSampleRequests() {
    int wallLevel = 20;
    int supportCount = 100;
    int maxAttackCount = 50;
    int maxFakeCount = 0;

    List<SOSRequest> result = new LinkedList<>();
    Village[] villages = GlobalOptions.getSelectedProfile().getTribe().getVillageList();
    Village[] attackerVillages = DataHolder.getSingleton().getTribeByName("Alexander25").getVillageList();

    for (int i = 0; i < supportCount; i++) {
        int id = (int) Math.rint(Math.random() * (villages.length - 1));
        Village target = villages[id];// w  ww .  j  a  va  2s .  c  o  m
        SOSRequest r = new SOSRequest(target.getTribe());
        r.addTarget(target);
        TargetInformation info = r.getTargetInformation(target);
        info.setWallLevel(wallLevel);

        TroopAmountFixed troops = new TroopAmountFixed();
        troops.setAmountForUnit("spear", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("sword", (int) Math.rint(Math.random() * 14000));
        troops.setAmountForUnit("heavy", (int) Math.rint(Math.random() * 5000));
        info.setTroops(troops);

        int cnt = (int) Math.rint(maxAttackCount * Math.random());
        for (int j = 0; j < cnt; j++) {
            int idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
            Village v = attackerVillages[idx];
            info.addAttack(v, new Date(
                    System.currentTimeMillis() + Math.round(DateUtils.MILLIS_PER_DAY * 7 * Math.random())));
            for (int k = 0; k < (int) Math.rint(maxFakeCount * Math.random()); k++) {
                idx = (int) Math.rint(Math.random() * (attackerVillages.length - 2));
                v = attackerVillages[idx];
                info.addAttack(v, new Date(System.currentTimeMillis() + Math.round(3600 * Math.random())));
            }
        }
        result.add(r);
    }

    return result;
}

From source file:com.btobits.automator.ant.utils.task.RandomTask.java

protected int calculateRandom(int minInt, int maxInt) {
    return minInt + (int) (Math.random() * (maxInt - minInt + 1));
}

From source file:com.netflix.simianarmy.basic.sniper.BasicSniperInstanceSelector.java

private String selectOneInstance(InstanceGroup group, double probability) {
    Validate.isTrue(probability <= 1.0);
    if (probability <= 0) {
        logger().info("Group {} [type {}] has disabled probability: {}",
                new Object[] { group.name(), group.type(), probability });
        return null;
    }/*from w  w w . ja  va  2 s  . c  o m*/
    double rand = Math.random();
    if (rand > probability || group.instances().isEmpty()) {
        logger().info("Group {} [type {}] got lucky: {} > {}",
                new Object[] { group.name(), group.type(), rand, probability });
        return null;
    }
    return group.instances().get(RANDOM.nextInt(group.instances().size()));
}

From source file:org.openbaton.vnfm.dummy.DummyAMQPVNFManager.java

@Override
public VirtualNetworkFunctionRecord scale(Action scaleInOrOut,
        VirtualNetworkFunctionRecord virtualNetworkFunctionRecord, VNFCInstance component, Object scripts,
        VNFRecordDependency dependency) throws Exception {
    Thread.sleep((int) (Math.random() * 500) + 1000);
    return virtualNetworkFunctionRecord;
}

From source file:org.openmrs.contrib.metadatarepository.service.MailEngineTest.java

@Test
public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);// www.ja v a 2s  .co m
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    // a null from should work
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, null, cpResource, emailBody, emailSubject,
            ATTACHMENT_NAME);

    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    // one without and one with from
    assertTrue(wiser.getMessages().size() == 2);

    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}

From source file:com.shyslav.controller.UploadController.java

@RequestMapping(value = "/uploadAction")
private String uploadAction(ModelMap mv, RedirectAttributes redirectAttributes, HttpSession ses,
        HttpServletRequest request) throws URISyntaxException {
    String name = null;/*from   w  w  w .j  a v  a 2  s  . c  o  m*/
    String genre = null;
    String author = null;
    String smallText = null;
    String fullText = null;
    String vision = null;
    String serverPath = null;
    Properties props = new Properties();
    try (InputStream in = UploadController.class.getResourceAsStream("application.properties")) {
        props.load(in);
    } catch (IOException ex) {
        System.out.println(ex);
    }
    DiskFileItemFactory d = new DiskFileItemFactory();
    ServletFileUpload uploadre = new ServletFileUpload(d);
    System.out.println(props.getProperty("downloadDirectory"));
    try {
        List<FileItem> list = uploadre.parseRequest(request);
        for (FileItem f : list) {
            if (f.isFormField() == false) {
                //write file to upload folder;

                if (!FilenameUtils.getExtension(f.getName()).equals("pdf")) {
                    String ext = FilenameUtils.getExtension(f.getName());
                    System.out.println(ext);
                    System.out.println("comed");
                    redirectAttributes.addFlashAttribute("error",
                            "?   ? , ?  pdf");
                    return "redirect:add.htm";
                }
                serverPath = "/" + author + "_" + name + "_" + genre + "_" + Math.random() * 100 + "."
                        + FilenameUtils.getExtension(f.getName());
                f.write(new File(props.getProperty("downloadDirectory") + serverPath));
                System.out.println(f.getName());
            } else if (f.isFormField()) {
                String fieldname = f.getFieldName();
                if (fieldname.equals("name")) {
                    name = f.getString("UTF-8");
                } else if (fieldname.equals("genre")) {
                    genre = f.getString("UTF-8");
                } else if (fieldname.equals("author")) {
                    author = f.getString("UTF-8");
                } else if (fieldname.equals("smallText")) {
                    smallText = f.getString("UTF-8");
                } else if (fieldname.equals("fullText")) {
                    fullText = f.getString("UTF-8");
                } else if (fieldname.equals("vision")) {
                    vision = f.getString("UTF-8");
                }
                System.out.println(f.getFieldName().toString());
            }
        }
    } catch (Exception ex) {
        System.out.println(ex);
    }
    if (name == null || genre == null || author == null || smallText == null || fullText == null
            || vision == null || smallText.length() < 30 || fullText.length() < 50 || name.length() < 3) {
        redirectAttributes.addFlashAttribute("error",
                "? ? ?  ");
        return "redirect:add.htm";
    }
    try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query query = session.createSQLQuery("INSERT INTO books\n"
                + "(name, author, genre, small_text, full_text, date_create, vision, server_Path)\n"
                + "VALUES('" + name + "', '" + author + "', " + genre + ", '" + smallText + "', '" + fullText
                + "', NOW(), '" + vision + "','" + serverPath + "')");
        System.out.println(query.toString());
        int result = query.executeUpdate();
        session.getTransaction().commit();
    } catch (Exception ex) {
        System.out.println(ex);
    }
    redirectAttributes.addFlashAttribute("sucses", " ? ");
    return "redirect:index.htm";
}

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private File createTempDir(File dataDir) throws IOException {
    nextStep("Creating temporary directory.");
    File tempDir = new File(new File("."), "/.psxperia." + (int) (Math.random() * 1000));
    if (tempDir.exists())
        FileUtils.deleteDirectory(tempDir);
    if (!tempDir.mkdirs())
        throw new IOException("Cannot create temporary directory!");
    FileUtils.copyDirectory(dataDir, tempDir);
    Logger.debug("Created temporary directory at, %s", tempDir.getPath());
    return tempDir;
}