Example usage for java.util Random Random

List of usage examples for java.util Random Random

Introduction

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

Prototype

public Random(long seed) 

Source Link

Document

Creates a new random number generator using a single long seed.

Usage

From source file:cz.cuni.mff.d3s.spl.example.newton.app.Main.java

public static void main(String[] args) {
    try {/*from w  ww  . j  a va 2  s  .  co  m*/
        System.out.printf("Letting things settle down before actual computation.\n");
        Thread.sleep(1000 * 1);
    } catch (InterruptedException ignored) {
    }

    /* This seed gives reasonable data, keep it at that ;-). */
    Random random = new Random(2);
    double[] coefficients = generateCoefficients(random);

    PolynomialFunction function = new PolynomialFunction(coefficients);
    NewtonSolver solver = new NewtonSolver();

    System.out.printf("Will solve polynomial function of degree %d.\n", function.degree());

    inspectClass(solver);

    try {
        for (int i = 0; i < WARM_UP_LOOPS; i++) {
            double result = solver.solve(10000, function, -1000, 1000);
        }

        long startTimeNanos = System.nanoTime();
        for (int i = 0; i < MEASURED_LOOPS; i++) {
            double result = solver.solve(10000, function, -1000, 1000);
        }
        long endTimeNanos = System.nanoTime();

        long runTimeNanos = endTimeNanos - startTimeNanos;
        long runTimeMillis = runTimeNanos / (1000 * 1000);

        System.out.printf("%d loops of solving took %dns (%dms).\n", MEASURED_LOOPS, runTimeNanos,
                runTimeMillis);
    } catch (MaxIterationsExceededException e) {
        e.printStackTrace();
    } catch (FunctionEvaluationException e) {
        e.printStackTrace();
    }

    inspectClass(solver);
}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step2ArgumentPairsSampling.java

public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*w w  w .  j a v a 2 s  .  co  m*/

    // /tmp
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // pseudo-random
    final Random random = new Random(1);

    int totalPairsCount = 0;

    // read all debates
    for (File file : IOHelper.listXmlFiles(new File(inputDir))) {
        Debate debate = DebateSerializer.deserializeFromXML(FileUtils.readFileToString(file, "utf-8"));

        // get two stances
        SortedSet<String> originalStances = debate.getStances();

        // cleaning: some debate has three or more stances (data are inconsistent)
        // remove those with only one argument
        SortedSet<String> stances = new TreeSet<>();
        for (String stance : originalStances) {
            if (debate.getArgumentsForStance(stance).size() > 1) {
                stances.add(stance);
            }
        }

        if (stances.size() != 2) {
            throw new IllegalStateException(
                    "2 stances per debate expected, was " + stances.size() + ", " + stances);
        }

        // for each stance, get pseudo-random N arguments
        for (String stance : stances) {
            List<Argument> argumentsForStance = debate.getArgumentsForStance(stance);

            // shuffle
            Collections.shuffle(argumentsForStance, random);

            // and get max first N arguments
            List<Argument> selectedArguments = argumentsForStance.subList(0,
                    argumentsForStance.size() < MAX_SELECTED_ARGUMENTS_PRO_SIDE ? argumentsForStance.size()
                            : MAX_SELECTED_ARGUMENTS_PRO_SIDE);

            List<ArgumentPair> argumentPairs = new ArrayList<>();

            // now create pairs
            for (int i = 0; i < selectedArguments.size(); i++) {
                for (int j = (i + 1); j < selectedArguments.size(); j++) {
                    Argument arg1 = selectedArguments.get(i);
                    Argument arg2 = selectedArguments.get(j);

                    ArgumentPair argumentPair = new ArgumentPair();
                    argumentPair.setDebateMetaData(debate.getDebateMetaData());

                    // assign arg1 and arg2 pseudo-randomly
                    // (not to have the same argument as arg1 all the time)
                    if (random.nextBoolean()) {
                        argumentPair.setArg1(arg1);
                        argumentPair.setArg2(arg2);
                    } else {
                        argumentPair.setArg1(arg2);
                        argumentPair.setArg2(arg1);
                    }

                    // set unique id
                    argumentPair.setId(argumentPair.getArg1().getId() + "_" + argumentPair.getArg2().getId());

                    argumentPairs.add(argumentPair);
                }
            }

            String fileName = IOHelper.createFileName(debate.getDebateMetaData(), stance);

            File outputFile = new File(outputDir, fileName);

            // and save all sampled pairs into a XML file
            XStreamTools.toXML(argumentPairs, outputFile);

            System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);

            totalPairsCount += argumentPairs.size();
        }

    }

    System.out.println("Total pairs generated: " + totalPairsCount);
}

From source file:com.palmercox.rustcryptotester.App.java

public static void main(String[] args) throws Exception {
    final CommandLineParser clp = new GnuParser();
    final CommandLine cl = clp.parse(getOptions(), args);

    if (cl.hasOption("help")) {
        help();/*from   w  w  w .  j  a  va 2  s  . co m*/
        return;
    }

    final String rustExec;
    if (cl.hasOption("rustexec")) {
        rustExec = cl.getOptionValue("rustexec");
    } else {
        help();
        return;
    }

    System.out.println("Starting Rust Crypto Tests:");

    boolean ok = true;

    final RustCryptRunner runner = new RustCryptRunner(new File(rustExec));
    try {
        for (final Tester t : getTesters()) {
            final Random rand = new Random(0);
            final boolean result = t.test(runner, rand);
            System.out.println("Test passed: " + result);
            ok = ok && result;
        }
    } finally {
        runner.close();
    }

    System.out.println("Done");

    if (!ok) {
        System.exit(1);
    }
}

From source file:de.termininistic.serein.examples.benchmarks.Benchmark.java

/**
 * @param args/*from ww  w.  j  a  v  a2  s  . com*/
 */
public static void main(String[] args) {

    // Benchmark parameters
    BenchmarkFunction function = new RastriginFunction();
    int dimension = 10;
    double optimum = function.map(function.getOptimum(dimension));
    double absoluteError = 1.0e-2;

    // Metaheuristic Parameters
    Random random = new Random(1233);
    int populationSize = 100;
    Recombination<DoubleGenome> recombination = new UniformCrossover<>();
    Mutation<DoubleGenome> mutation = new SinglePointMutation<>();
    double recombinationProbability = 1.0;
    BenchmarkFunctionFitness fitness = new BenchmarkFunctionFitness(function);
    TerminationCondition<RealVector> termination = new TerminationConditionFitness<>(fitness,
            optimum + absoluteError);

    // Translator doubleGenome --> function domain
    LinearTranslator translator = new LinearTranslator(function.getDomain().getMinVector(dimension),
            function.getDomain().getMaxVector(dimension));

    // Initial individual 
    DoubleGenome initialGenome = DoubleGenome.createRandomDoubleGenome(dimension, random);
    BasicIndividual<RealVector, DoubleGenome> initialIndividual = new BasicIndividual<RealVector, DoubleGenome>(
            initialGenome, translator);
    initialIndividual.setRecombination(recombination);
    initialIndividual.<Double>setProperty("ProbabilityOfRecombination", recombinationProbability, true);
    initialIndividual.setMutation(mutation);
    initialIndividual.setMateSelection(new TournamentSelection<>(fitness, 3));

    // Start population
    Population<RealVector> startPop = Populations.generatePopulation(initialIndividual, populationSize, random);

    // Assemble Metaheuristic 
    AlgorithmFactory<RealVector> factory = new AlgorithmFactory<>();
    factory.termination = termination;
    EvolutionEnvironment<RealVector> algo = factory.createReferenceEvolutionaryAlgorithm(fitness, startPop,
            random);

    // Add a simple listener (output to console)
    StatsListener<RealVector> listener = new StatsListener<RealVector>(fitness, 50);
    algo.addListener(listener);

    // Start optimization
    algo.evolve();

}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/*from   w ww.j  a v a  2s.  c om*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:DruidThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override/*from w w w  . j a v a 2  s  .  c om*/
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:jmbench.plots.SummaryWhiskerPlot.java

public static void main(String args[]) {
    Random rand = new Random(2344);

    SummaryWhiskerPlot plot = new SummaryWhiskerPlot("Test Summary", "Weighted by Operation Time");

    for (int i = 0; i < 3; i++) {
        List<Double> overall = new ArrayList<Double>();
        List<Double> large = new ArrayList<Double>();
        List<Double> small = new ArrayList<Double>();

        for (int j = 0; j < 50; j++) {
            overall.add(rand.nextDouble());
            large.add(rand.nextDouble());
            small.add(rand.nextDouble());
        }/*from  w w w .j a  v a2s . c o  m*/

        plot.addLibrary("Lib " + i, overall, large, small);
    }

    plot.displayWindow(600, 350);
}

From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerRandomUnitTest.java

public static void main(String args[]) throws ACIDException, AsterixException, IOException {
    int i;//from   ww w. ja v a2  s  . co  m
    //prepare configuration file
    File cwd = new File(System.getProperty("user.dir"));
    File asterixdbDir = cwd.getParentFile();
    File srcFile = new File(asterixdbDir.getAbsoluteFile(),
            "asterix-app/src/main/resources/asterix-build-configuration.xml");
    File destFile = new File(cwd, "target/classes/asterix-configuration.xml");
    FileUtils.copyFile(srcFile, destFile);

    TransactionSubsystem txnProvider = new TransactionSubsystem("nc1", null,
            new AsterixTransactionProperties(new AsterixPropertiesAccessor()));
    rand = new Random(System.currentTimeMillis());
    for (i = 0; i < MAX_NUM_OF_ENTITY_LOCK_JOB; i++) {
        System.out.println("Creating " + i + "th EntityLockJob..");
        generateEntityLockThread(txnProvider);
    }

    for (i = 0; i < MAX_NUM_OF_DATASET_LOCK_JOB; i++) {
        System.out.println("Creating " + i + "th DatasetLockJob..");
        generateDatasetLockThread(txnProvider);
    }

    for (i = 0; i < MAX_NUM_OF_UPGRADE_JOB; i++) {
        System.out.println("Creating " + i + "th EntityLockUpgradeJob..");
        generateEntityLockUpgradeThread(txnProvider);
    }
    ((LogManager) txnProvider.getLogManager()).stop(false, null);
}

From source file:dhtaccess.benchmark.LatencyMeasure.java

public static void main(String[] args) {
    boolean details = false;
    int repeats = DEFAULT_REPEATS;
    boolean doPut = true;

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("d", "details", false, "requests secret hash and TTL");
    options.addOption("r", "repeats", true, "number of requests");
    options.addOption("n", "no-put", false, "does not put");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*  w  w w  . j av a 2s .  c  o m*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    if (cmd.hasOption('d')) {
        details = true;
    }
    optVal = cmd.getOptionValue('r');
    if (optVal != null) {
        repeats = Integer.parseInt(optVal);
    }
    if (cmd.hasOption('n')) {
        doPut = false;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    int numAccessor = args.length;
    DHTAccessor[] accessorArray = new DHTAccessor[numAccessor];
    try {
        for (int i = 0; i < numAccessor; i++) {
            accessorArray[i] = new DHTAccessor(args[i]);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // generate key prefix
    Random rnd = new Random(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < KEY_PREFIX_LENGTH; i++) {
        sb.append((char) ('a' + rnd.nextInt(26)));
    }
    String keyPrefix = sb.toString();
    String valuePrefix = VALUE_PREFIX;

    // benchmarking
    System.out.println("Repeats " + repeats + " times.");

    if (doPut) {
        System.out.println("Putting: " + keyPrefix + "<number>");

        for (int i = 0; i < repeats; i++) {
            byte[] key = null, value = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
                value = (valuePrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            acc.put(key, value, TTL);
        }
    }

    System.out.println("Benchmarking by getting.");

    int count = 0;
    long startTime = System.currentTimeMillis();

    if (details) {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<DetailedGetResult> valueSet = acc.getDetails(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    } else {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<byte[]> valueSet = acc.get(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    }

    System.out.println(System.currentTimeMillis() - startTime + " msec.");
    System.out.println("Rate of successful gets: " + count + " / " + repeats);
}

From source file:gpframework.RunExperiment.java

/**
 * Application's entry point./*from www  . j a  va 2 s .  co  m*/
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}