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() 

Source Link

Document

Creates a new random number generator.

Usage

From source file:knop.psfj.heatmap.HeatMapGenerator.java

/**
 * The main method.//w ww  .  j a  va 2  s.  co  m
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    BeadImage i = new BeadImage();
    i.setFileAddress("/home/cyril/test_img/6_small.tif");
    i.workFromMemory();

    FovDataSet dataSet = new FovDataSet();

    Random random = new Random();

    for (int j = 0; j != 3000; j++) {
        dataSet.addValue("x", random.nextDouble() * 10);
        dataSet.addValue("y", random.nextDouble() * 10);
        dataSet.addValue("deltaX", random.nextDouble() * 1.5 / 2);
    }

    // dataSet.setTheoriticalValue("deltaX_norm", 1.0);
    dataSet.setColumnsUnits(MathUtils.MICROMETERS, "x", "y", "deltaX");
    HeatMapGenerator generator = new HeatMapGenerator(dataSet);
    generator.setMinAndMax(-1, 0, 1);
    // generator.setMinAndMaxLabels("", lineLabel, maxLabel)
    generator.setUnit("");
    generator.setBeadImage(i);
    // generator.setLutMode(NORMALIZED);
    generator.setCurrentColumn("deltaX");

    // generator.show(gene);

    // generator.injectDataSet(new FovDataSet("/home/cyril/data2.txt"),
    // "fwhmZ");
    generator.show(generator.getAnnotatedHeatMap());

    // System.out.println(dataSet.getTheoriticalValue("fwhmZ"));

}

From source file:edu.berkeley.sparrow.examples.ProtoFrontendAsync.java

public static void main(String[] args) {
    try {//from   w  w  w  .j a  v a 2s.c  o m
        OptionParser parser = new OptionParser();
        parser.accepts("c", "configuration file").withRequiredArg().ofType(String.class);
        parser.accepts("help", "print help statement");
        OptionSet options = parser.parse(args);

        if (options.has("help")) {
            parser.printHelpOn(System.out);
            System.exit(-1);
        }

        // Logger configuration: log to the console
        BasicConfigurator.configure();
        LOG.setLevel(Level.DEBUG);

        Configuration conf = new PropertiesConfiguration();

        if (options.has("c")) {
            String configFile = (String) options.valueOf("c");
            conf = new PropertiesConfiguration(configFile);
        }

        Random r = new Random();
        double lambda = conf.getDouble("job_arrival_rate_s", DEFAULT_JOB_ARRIVAL_RATE_S);
        int tasksPerJob = conf.getInt("tasks_per_job", DEFAULT_TASKS_PER_JOB);
        int benchmarkIterations = conf.getInt("benchmark.iterations", DEFAULT_BENCHMARK_ITERATIONS);
        int benchmarkId = conf.getInt("benchmark.id", DEFAULT_TASK_BENCHMARK);

        int schedulerPort = conf.getInt("scheduler_port", SchedulerThrift.DEFAULT_SCHEDULER_THRIFT_PORT);

        TProtocolFactory factory = new TBinaryProtocol.Factory();
        TAsyncClientManager manager = new TAsyncClientManager();

        long lastLaunch = System.currentTimeMillis();
        // Loop and generate tasks launches
        while (true) {
            // Lambda is the arrival rate in S, so we need to multiply the result here by
            // 1000 to convert to ms.
            long delay = (long) (generateInterarrivalDelay(r, lambda) * 1000);
            long curLaunch = lastLaunch + delay;
            long toWait = Math.max(0, curLaunch - System.currentTimeMillis());
            lastLaunch = curLaunch;
            if (toWait == 0) {
                LOG.warn("Generated workload not keeping up with real time.");
            }
            List<TTaskSpec> tasks = generateJob(tasksPerJob, benchmarkId, benchmarkIterations);
            TUserGroupInfo user = new TUserGroupInfo();
            user.setUser("*");
            user.setGroup("*");
            TSchedulingRequest req = new TSchedulingRequest();
            req.setApp("testApp");
            req.setTasks(tasks);
            req.setUser(user);

            TNonblockingTransport tr = new TNonblockingSocket("localhost", schedulerPort);
            SchedulerService.AsyncClient client = new SchedulerService.AsyncClient(factory, manager, tr);
            //client.registerFrontend("testApp", new RegisterCallback());
            client.submitJob(req, new SubmitCallback(req, tr));
        }
    } catch (Exception e) {
        LOG.error("Fatal exception", e);
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.QueryGenNMSLIB.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption(CommonParams.QUERY_FILE_PARAM, null, true, CommonParams.QUERY_FILE_DESC);
    options.addOption(CommonParams.MEMINDEX_PARAM, null, true, CommonParams.MEMINDEX_DESC);
    options.addOption(CommonParams.KNN_QUERIES_PARAM, null, true, CommonParams.KNN_QUERIES_DESC);
    options.addOption(CommonParams.NMSLIB_FIELDS_PARAM, null, true, CommonParams.NMSLIB_FIELDS_DESC);
    options.addOption(CommonParams.MAX_NUM_QUERY_PARAM, null, true, CommonParams.MAX_NUM_QUERY_DESC);
    options.addOption(CommonParams.SEL_PROB_PARAM, null, true, CommonParams.SEL_PROB_DESC);

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter knnQueries = null;

    int maxNumQuery = Integer.MAX_VALUE;

    Float selProb = null;/* ww w. j a va  2 s.c om*/

    try {
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null;

        if (cmd.hasOption(CommonParams.QUERY_FILE_PARAM)) {
            queryFile = cmd.getOptionValue(CommonParams.QUERY_FILE_PARAM);
        } else {
            Usage("Specify 'query file'", options);
        }

        String knnQueriesFile = cmd.getOptionValue(CommonParams.KNN_QUERIES_PARAM);

        if (null == knnQueriesFile)
            Usage("Specify '" + CommonParams.KNN_QUERIES_DESC + "'", options);

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                Usage("Maximum number of queries isn't integer: '" + tmpn + "'", options);
            }
        }

        String tmps = cmd.getOptionValue(CommonParams.NMSLIB_FIELDS_PARAM);
        if (null == tmps)
            Usage("Specify '" + CommonParams.NMSLIB_FIELDS_DESC + "'", options);
        String nmslibFieldList[] = tmps.split(",");

        knnQueries = new BufferedWriter(new FileWriter(knnQueriesFile));
        knnQueries.write("isQueryFile=1");
        knnQueries.newLine();
        knnQueries.newLine();

        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);

        if (null == memIndexPref) {
            Usage("Specify '" + CommonParams.MEMINDEX_DESC + "'", options);
        }

        String tmpf = cmd.getOptionValue(CommonParams.SEL_PROB_PARAM);

        if (tmpf != null) {
            try {
                selProb = Float.parseFloat(tmpf);
            } catch (NumberFormatException e) {
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
            }
            if (selProb < Float.MIN_NORMAL || selProb + Float.MIN_NORMAL >= 1)
                Usage("A selection probability isn't a number in the range (0,1)'" + tmpf + "'", options);
        }

        BufferedReader inpText = new BufferedReader(
                new InputStreamReader(CompressUtils.createInputStream(queryFile)));

        String docText = XmlHelper.readNextXMLIndexEntry(inpText);

        NmslibQueryGenerator queryGen = new NmslibQueryGenerator(nmslibFieldList, memIndexPref);

        Random rnd = new Random();

        for (int docNum = 1; docNum <= maxNumQuery
                && docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) {
            if (selProb != null) {
                if (rnd.nextFloat() > selProb)
                    continue;
            }

            Map<String, String> docFields = null;

            try {
                docFields = XmlHelper.parseXMLIndexEntry(docText);

                String queryObjStr = queryGen.getStrObjForKNNService(docFields);

                knnQueries.append(queryObjStr);
                knnQueries.newLine();
            } catch (SAXException e) {
                System.err.println("Parsing error, offending DOC:" + NL + docText + " doc # " + docNum);
                throw new Exception("Parsing error.");
            }
        }

        knnQueries.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments", options);
        if (null != knnQueries)
            try {
                knnQueries.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        try {
            if (knnQueries != null)
                knnQueries.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.exit(1);
    }

    System.out.println("Terminated successfully!");
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);/*from   ww  w . ja  v  a2  s  .co m*/
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:com.yahoo.pasc.paxos.client.PaxosClient.java

public static void main(String[] args) throws Exception {

    CommandLineParser parser = new PosixParser();
    Options options;//ww  w  .ja  v  a 2 s.  c  om

    {
        Option id = new Option("i", true, "client id");
        Option clients = new Option("c", true, "number of clients");
        Option host = new Option("l", true, "leader (hostname:port)");
        Option servers = new Option("s", true, "number of servers");
        Option quorum = new Option("q", true, "necesarry quorum at the client");
        Option port = new Option("p", true, "port used by client");
        Option buffer = new Option("b", true, "number of concurrent clients");
        Option timeout = new Option("t", true, "timeout in milliseconds");
        Option udp = new Option("u", false, "use UDP");
        Option zookeeper = new Option("z", true, "zookeeper connection string");
        Option warmup = new Option("w", true, "warmup messagges");
        Option measuring = new Option("m", true, "measuring time");
        Option request = new Option("r", true, "request size");
        Option frequency = new Option("f", true, "frequency of throughput info");
        Option anm = new Option("a", false, "use protection");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option asynSize = new Option("y", true, "size of async messages queue");

        options = new Options();
        options.addOption(id).addOption(host).addOption(servers).addOption(quorum).addOption(port)
                .addOption(warmup).addOption(buffer).addOption(timeout).addOption(udp).addOption(zookeeper)
                .addOption(clients).addOption(measuring).addOption(request).addOption(frequency).addOption(anm)
                .addOption(inlineThresh).addOption(asynSize);
    }

    CommandLine line = null;
    try {
        line = parser.parse(options, args);

        String host = line.hasOption('l') ? line.getOptionValue('l')
                : "localhost:20548,localhost:20748,localhost:20778";
        String zkConnection = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int clientIds = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int servers = line.hasOption('s') ? Integer.parseInt(line.getOptionValue('s')) : 3;
        int quorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : 1;
        int buffer = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int timeout = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t')) : 5000;
        int clients = line.hasOption('c') ? Integer.parseInt(line.getOptionValue('c')) : 1;
        int requestSize = line.hasOption('r') ? Integer.parseInt(line.getOptionValue('r')) : 0;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        int asynSize = line.hasOption('y') ? Integer.parseInt(line.getOptionValue('y')) : 100;
        boolean protection = line.hasOption('a');

        int threads = Runtime.getRuntime().availableProcessors() * 2;
        final ExecutionHandler executor = new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(threads,
                1024 * 1024, 1024 * 1024 * 1024, 30, TimeUnit.SECONDS, Executors.defaultThreadFactory()));

        String[] serverHosts = host.split(",");

        ServerHelloHandler shello = new ServerHelloHandler();
        ReplyHandler reply = new ReplyHandler();
        SubmitHandler submit = new SubmitHandler();
        TimeoutHandler tout = new TimeoutHandler();
        AsyncMessageHandler asyncm = new AsyncMessageHandler();
        ByeHandler bye = new ByeHandler();
        HelloHandler hello = new HelloHandler();

        Random rnd = new Random();

        for (int i = 0; i < buffer; ++i) {
            ClientState clientState = new ClientState(servers, quorum, inlineThreshold, asynSize);
            final PascRuntime<ClientState> runtime = new PascRuntime<ClientState>(protection);
            runtime.setState(clientState);
            runtime.addHandler(ServerHello.class, shello);
            runtime.addHandler(Reply.class, reply);
            runtime.addHandler(Submit.class, submit);
            runtime.addHandler(Timeout.class, tout);
            runtime.addHandler(AsyncMessage.class, asyncm);
            runtime.addHandler(Bye.class, bye);
            runtime.addHandler(Hello.class, hello);

            final PaxosClientHandler handler = new PaxosClientHandler(runtime, new SimpleClient(requestSize),
                    serverHosts, clients, timeout, zkConnection, executor);

            if (line.hasOption('w'))
                handler.setWarmup(Integer.parseInt(line.getOptionValue('w')));
            if (line.hasOption('m'))
                handler.setMeasuringTime(Integer.parseInt(line.getOptionValue('m')));
            if (line.hasOption('f'))
                handler.setPeriod(Integer.parseInt(line.getOptionValue('f')));

            handler.start();

            Thread.sleep(rnd.nextInt(200));
        }
    } catch (Exception e) {
        System.err.println("Unexpected exception " + e);
        e.printStackTrace();

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.exit(-1);
    }
}

From source file:imp.lstm.main.Driver.java

public static void main(String[] args)
        throws FileNotFoundException, IOException, ConfigurationException, InvalidParametersException {
    FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>(
            PropertiesConfiguration.class).configure(
                    new Parameters().properties().setFileName(args[0]).setThrowExceptionOnMissing(true)
                            .setListDelimiterHandler(new DefaultListDelimiterHandler(';'))
                            .setIncludesAllowed(false));
    Configuration config = builder.getConfiguration();

    String inputSongPath = config.getString("input_song");
    String outputFolderPath = config.getString("output_folder");
    String autoEncoderParamsPath = config.getString("auto_encoder_params");
    String nameGeneratorParamsPath = config.getString("name_generator_params");
    String queueFolderPath = config.getString("queue_folder");
    String referenceQueuePath = config.getString("reference_queue", "nil");
    String inputCorpusFolder = config.getString("input_corpus_folder");
    boolean shouldWriteQueue = config.getBoolean("should_write_generated_queue");
    boolean frankensteinTest = config.getBoolean("queue_tests_frankenstein");
    boolean interpolateTest = config.getBoolean("queue_tests_interpolation");
    boolean iterateOverCorpus = config.getBoolean("iterate_over_corpus", false);
    boolean shouldGenerateSongTitle = config.getBoolean("generate_song_title");
    boolean shouldGenerateSong = config.getBoolean("generate_leadsheet");

    LogTimer.initStartTime(); //start our logging timer to keep track of our execution time
    LogTimer.log("Creating name generator...");

    //here is just silly code for generating name based on an LSTM lol $wag
    LSTM lstm = new LSTM();
    FullyConnectedLayer fullLayer = new FullyConnectedLayer(Operations.None);
    Loadable titleNetLoader = new Loadable() {
        @Override/* ww  w. java  2s .  c  o m*/
        public boolean load(INDArray array, String path) {
            String car = pathCar(path);
            String cdr = pathCdr(path);
            switch (car) {
            case "full":
                return fullLayer.load(array, cdr);
            case "lstm":
                return lstm.load(array, cdr);
            default:
                return false;
            }
        }
    };

    LogTimer.log("Packing name generator from files...");
    (new NetworkConnectomeLoader()).load(nameGeneratorParamsPath, titleNetLoader);

    String characterString = " !\"'[],-.01245679:?ABCDEFGHIJKLMNOPQRSTUVWYZabcdefghijklmnopqrstuvwxyz";

    //Initialization
    LogTimer.log("Creating autoencoder...");
    int inputSize = 34;
    int outputSize = EncodingParameters.noteEncoder.getNoteLength();
    int featureVectorSize = 100;
    ProductCompressingAutoencoder autoencoder = new ProductCompressingAutoencoder(24, 48, 84 + 1, false); //create our network

    int numInterpolationDivisions = 5;

    //"pack" the network from weights and biases file directory
    LogTimer.log("Packing autoencoder from files");
    (new NetworkConnectomeLoader()).load(autoEncoderParamsPath, autoencoder);

    File[] songFiles;
    if (iterateOverCorpus) {
        songFiles = new File(inputCorpusFolder).listFiles();
    } else {
        songFiles = new File[] { new File(inputSongPath) };
    }
    for (File inputFile : songFiles) {
        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
        String songTitle;
        if (shouldGenerateSong) {
            Random rand = new Random();
            AVector charOut = Vector.createLength(characterString.length());
            GroupedSoftMaxSampler sampler = new GroupedSoftMaxSampler(
                    new Group[] { new Group(0, characterString.length(), true) });
            songTitle = "";
            for (int i = 0; i < 50; i++) {
                charOut = fullLayer.forward(lstm.step(charOut));
                charOut = sampler.filter(charOut);
                int charIndex = 0;
                for (; charIndex < charOut.length(); charIndex++) {
                    if (charOut.get(charIndex) == 1.0) {
                        break;
                    }
                }
                songTitle += characterString.substring(charIndex, charIndex + 1);
            }
            songTitle = songTitle.trim();

            LogTimer.log("Generated song name: " + songTitle);
        } else {
            songTitle = "The Song We Never Name";
        }
        LogTimer.log("Reading file...");
        LeadSheetDataSequence inputSequence = LeadSheetIO.readLeadSheet(inputFile); //read our leadsheet to get a data vessel as retrieved in rbm-provisor
        LeadSheetDataSequence outputSequence = inputSequence.copy();

        outputSequence.clearMelody();
        if (interpolateTest) {
            LeadSheetDataSequence additionalOutput = outputSequence.copy();
            for (int i = 0; i < numInterpolationDivisions; i++) {
                outputSequence.concat(additionalOutput.copy());
            }
        }
        LeadSheetDataSequence decoderInputSequence = outputSequence.copy();

        LogTimer.startLog("Encoding data...");
        //TradingTimer.initStart(); //start our trading timer to keep track our our generation versus realtime play
        while (inputSequence.hasNext()) { //iterate through time steps in input data
            //TradingTimer.waitForNextTimedInput();
            autoencoder.encodeStep(inputSequence.retrieve()); //feed the resultant input vector into the network
            if (advanceDecoding) { //if we are using advance decoding (we start decoding as soon as we can)
                if (autoencoder.canDecode()) { //if queue has enough data to decode from
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are
                }
            }
        }
        LogTimer.endLog();

        if (shouldWriteQueue) {
            String queueFilePath = queueFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", ".q");
            FragmentedNeuralQueue currQueue = autoencoder.getQueue();
            currQueue.writeToFile(queueFilePath);
            LogTimer.log("Wrote queue " + inputFile.getName().replace(".ls", ".q") + " to file...");
        }
        if (shouldGenerateSong) {
            if (interpolateTest) {

                FragmentedNeuralQueue refQueue = new FragmentedNeuralQueue();
                refQueue.initFromFile(referenceQueuePath);

                FragmentedNeuralQueue currQueue = autoencoder.getQueue();
                //currQueue.writeToFile(queueFilePath);

                autoencoder.setQueue(currQueue.copy());
                while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                    outputSequence.pushStep(null, null,
                            autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                    //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                }

                for (int i = 1; i <= numInterpolationDivisions; i++) {
                    System.out.println("Starting interpolation " + ((1.0 / numInterpolationDivisions) * (i)));
                    (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder, "initialstate");
                    FragmentedNeuralQueue currCopy = currQueue.copy();
                    currCopy.basicInterpolate(refQueue, (1.0 / numInterpolationDivisions) * (i));
                    autoencoder.setQueue(currCopy);
                    int timeStep = 0;
                    while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                        System.out.println("interpolation " + i + " step " + ++timeStep);
                        outputSequence.pushStep(null, null,
                                autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                        //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                    }
                }

            }
            if (frankensteinTest) {
                LogTimer.startLog("Loading queues");
                File queueFolder = new File(queueFolderPath);
                int numComponents = config.getInt("frankenstein_num_components", 5);
                int numCombinations = config.getInt("frankenstein_num_combinations", 6);
                double interpolationMagnitude = config.getDouble("frankenstein_magnitude", 2.0);
                if (queueFolder.isDirectory()) {
                    File[] queueFiles = queueFolder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.contains(".q");
                        }
                    });

                    List<File> fileList = new ArrayList<>();
                    for (File file : queueFiles) {
                        fileList.add(file);
                    }
                    Collections.shuffle(fileList);
                    int numSelectedFiles = (numComponents > queueFiles.length) ? queueFiles.length
                            : numComponents;

                    for (int i = 0; i < queueFiles.length - numSelectedFiles; i++) {
                        fileList.remove(fileList.size() - 1);
                    }
                    List<FragmentedNeuralQueue> queuePopulation = new ArrayList<>(fileList.size());
                    songTitle += " - a mix of ";
                    for (File file : fileList) {
                        FragmentedNeuralQueue newQueue = new FragmentedNeuralQueue();
                        newQueue.initFromFile(file.getPath());
                        queuePopulation.add(newQueue);
                        songTitle += file.getName().replaceAll(".ls", "") + ", ";
                    }
                    LogTimer.endLog();

                    LeadSheetDataSequence additionalOutput = outputSequence.copy();
                    for (int i = 1; i < numCombinations; i++) {
                        outputSequence.concat(additionalOutput.copy());
                    }
                    decoderInputSequence = outputSequence.copy();

                    FragmentedNeuralQueue origQueue = autoencoder.getQueue();

                    for (int i = 0; i < numCombinations; i++) {

                        LogTimer.startLog("Performing queue interpolation...");
                        AVector combinationStrengths = Vector.createLength(queuePopulation.size());
                        Random vectorRand = new Random(i);
                        for (int j = 0; j < combinationStrengths.length(); j++) {
                            combinationStrengths.set(j, vectorRand.nextDouble());
                        }
                        combinationStrengths.divide(combinationStrengths.elementSum());
                        FragmentedNeuralQueue currQueue = origQueue.copy();
                        for (int k = 0; k < combinationStrengths.length(); k++) {
                            currQueue.basicInterpolate(queuePopulation.get(k),
                                    combinationStrengths.get(k) * interpolationMagnitude);
                        }
                        LogTimer.endLog();
                        autoencoder.setQueue(currQueue);
                        LogTimer.startLog("Refreshing autoencoder state...");
                        (new NetworkConnectomeLoader()).refresh(autoEncoderParamsPath, autoencoder,
                                "initialstate");
                        LogTimer.endLog();
                        LogTimer.startLog("Decoding segment...");
                        while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                            outputSequence.pushStep(null, null,
                                    autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                            //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
                        }
                        LogTimer.endLog();
                    }

                }
            }

            while (autoencoder.hasDataStepsLeft()) { //we are done encoding all time steps, so just finish decoding!{
                outputSequence.pushStep(null, null, autoencoder.decodeStep(decoderInputSequence.retrieve())); //take sampled data for a timestep from autoencoder
                //TradingTimer.logTimestep(); //log our time to TradingTimer so we can know how far ahead of realtime we are       
            }
            LogTimer.log("Writing file...");

            String outputFilename = outputFolderPath + java.io.File.separator
                    + inputFile.getName().replace(".ls", "_Output"); //we'll write our generated file with the same name plus "_Output"
            LeadSheetIO.writeLeadSheet(outputSequence, outputFilename, songTitle);
            System.out.println(outputFilename);
        } else {
            autoencoder.setQueue(new FragmentedNeuralQueue());
        }
    }
    LogTimer.log("Process finished"); //Done!

}

From source file:msi.gaml.operators.Maths.java

public static void main(final String[] args) throws ParseException {
    java.lang.System.out.println("Various format tests");
    java.lang.System.out.println("NumberFormat.parse1e1 = " + NumberFormat.getInstance(Locale.US).parse("1e1"));
    java.lang.System.out.println("Double.parse 1e1 = " + Double.parseDouble("1e1"));
    java.lang.System.out//from w  w  w  .  ja v a2 s. c om
            .println("NumberFormat.parse 1E1 = " + NumberFormat.getInstance(Locale.US).parse("1E1"));
    java.lang.System.out.println("Double.parse 1E1 = " + Double.parseDouble("1E1"));
    java.lang.System.out
            .println("NumberFormat.parse 1.0e1 = " + NumberFormat.getInstance(Locale.US).parse("1.0e1"));
    java.lang.System.out.println("Double.parse 1.0e1 = " + Double.parseDouble("1.0e1"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E+10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E+10"));
    java.lang.System.out.println("Double.parse 0.001E+10 = " + Double.parseDouble("0.001E+10"));
    java.lang.System.out.println(
            "NumberFormat.parse 0.001E-10 = " + NumberFormat.getInstance(Locale.US).parse("0.001E-10"));
    java.lang.System.out.println("Double.parse 0.001E-10 = " + Double.parseDouble("0.001E-10"));
    java.lang.System.out
            .println("NumberFormat.parse 0.001e-10 =" + NumberFormat.getInstance(Locale.US).parse("0.001e-10"));
    java.lang.System.out.println("Double.parse 0.001e-10 = " + Double.parseDouble("0.001e-10"));
    java.lang.System.out.println("Various arithmetic tests");
    java.lang.System.out.println("cos(PI) = " + Maths.cos_rad(PI));
    java.lang.System.out.println("sin_rad(0.0) = " + sin_rad(0.0));
    java.lang.System.out.println("tan_rad(0.0) = " + tan_rad(0.0));
    java.lang.System.out.println("sin(360) = " + sin(360));
    java.lang.System.out.println("sin(-720) = " + sin(-720));
    java.lang.System.out.println("sin(360.0) = " + sin(360.0));
    java.lang.System.out.println("sin(-720.0) = " + sin(-720.0));
    java.lang.System.out.println("sin(90) = " + sin(90));
    java.lang.System.out.println("sin(45) = " + sin(45));
    java.lang.System.out.println("sin(0) = " + sin(0));
    java.lang.System.out.println("sin(135) = " + sin(135));

    java.lang.System.out.println("Math.sin(360.0) = " + Math.sin(2 * Math.PI));
    // java.lang.System.out.println("3.0 = 3" + (3d == 3));
    // java.lang.System.out.println("3.0 != 3" + (3d != 3));
    java.lang.System.out.println("floor and ceil 2.7 " + floor(2.7) + " and " + ceil(2.7));
    java.lang.System.out.println("floor and ceil -2.7 " + floor(-2.7) + " and " + ceil(-2.7));
    java.lang.System.out.println("floor and ceil -2 " + floor(-2) + " and " + ceil(-2));
    java.lang.System.out.println("floor and ceil 3 " + floor(3) + " and " + ceil(3));
    double atan2diff = 0;
    double atan2diff2 = 0;
    Random rand = new Random();
    long s1 = 0;
    long t1 = 0;
    long t2 = 0;
    long t3 = 0;
    // for ( int i = 0; i < 10000000; i++ ) {
    // double x = rand.nextDouble();
    // double y = rand.nextDouble();
    // s1 = java.lang.System.currentTimeMillis();
    // double a1 = Math.atan2(x, y);
    // t1 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a2 = FastMath.atan2(x, y);
    // t2 += java.lang.System.currentTimeMillis() - s1;
    // s1 = java.lang.System.currentTimeMillis();
    // double a3 = Maths.atan2Opt2(x, y);
    // t3 += java.lang.System.currentTimeMillis() - s1;
    //
    // atan2diff += Math.abs(a1 - a2);
    // atan2diff2 += Math.abs(a1 - a3);
    // }
    // java.lang.System.out.println("atan2diff : " + atan2diff + "  atan2diff2 : " + atan2diff2 + " t1 : " + t1 +
    // " t2 : " + t2 + " t3 : " + t3);

    long t4 = 0;
    long t5 = 0;
    long t6 = 0;
    double distDiff1 = 0;
    double distDiff2 = 0;
    for (int i = 0; i < 1000000; i++) {
        double x1 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y2 = rand.nextDouble();
        Coordinate c1 = new Coordinate(x1, y1);
        Coordinate c2 = new Coordinate(x2, y2);

        s1 = java.lang.System.currentTimeMillis();
        double a1 = Math.hypot(x2 - x1, y2 - y1);
        t4 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a2 = FastMath.hypot(x2 - x1, y2 - y1);
        t5 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        double a3 = c1.distance(c2);
        t6 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
        distDiff2 += Math.abs(a1 - a3);
    }
    java.lang.System.out.println("distDiff1 : " + distDiff1 + "  distDiff2 : " + distDiff2 + " t4 : " + t4
            + " t5 : " + t5 + " t6 : " + t6);

    long t7 = 0;
    long t8 = 0;
    distDiff1 = 0;

    for (int i = 0; i < 1000000; i++) {
        double a1, a2;
        double x1 = rand.nextDouble();
        double x2 = rand.nextDouble();
        double y1 = rand.nextDouble();
        double y2 = rand.nextDouble();
        double z1 = 0.0;
        double z2 = 0.0;
        GamaPoint c2 = new GamaPoint(x2, y2, z2);

        s1 = java.lang.System.currentTimeMillis();
        if (z1 == 0d && c2.getZ() == 0d) {
            a1 = hypot(x1, x2, y1, y2);
        } else {
            a1 = hypot(x1, x2, y1, y2, z1, z2);
        }
        t7 += java.lang.System.currentTimeMillis() - s1;
        s1 = java.lang.System.currentTimeMillis();
        a2 = hypot(x1, x2, y1, y2, z1, c2.getZ());
        t8 += java.lang.System.currentTimeMillis() - s1;
        distDiff1 += Math.abs(a1 - a2);
    }
    java.lang.System.out.println(
            "with 0.0 check : " + t7 + "  with direct 3 parameters call : " + t8 + " distance : " + distDiff1);
    // java.lang.System.out.println("Infinity to int:" + (int) Double.POSITIVE_INFINITY);
    // java.lang.System.out.println("NaN to int:" + (int) Double.NaN);
    // GuiUtils.debug("(int) (1.0/0.0):" + (int) (1.0 / 0.0));
    // GuiUtils.debug("(int) (1.0/0):" + (int) (1.0 / 0));
    // GuiUtils.debug("(int) (1.0/0d):" + (int) (1 / 0d));
    // GuiUtils.debug("(int) (1/0):" + 1 / 0);
}

From source file:ca.mcgill.networkdynamics.geoinference.evaluation.CrossValidationScorer.java

public static void main(String[] args) throws Exception {

    if (args.length != 4) {
        System.out.println("java CVS predictions-dir/ " + "cv-gold-dir/ results.txt error-sample.tsv");
        return;/* ww w .  j  a  v a2  s .  c  o m*/
    }

    File predDir = new File(args[0]);
    File cvDir = new File(args[1]);

    TDoubleList errors = new TDoubleArrayList(10_000_000);
    TLongSet locatedUsers = new TLongHashSet(10_000_000);
    TLongSet allUsers = new TLongHashSet(10_000_000);
    TLongObjectMap<TDoubleList> userToErrors = new TLongObjectHashMap<TDoubleList>();

    TLongDoubleMap tweetIdToError = new TLongDoubleHashMap(10_000_000);
    TLongObjectMap<double[]> idToPredLoc = new TLongObjectHashMap<double[]>();

    int tweetsSeen = 0;
    int tweetsLocated = 0;

    BufferedReader cvBr = new BufferedReader(new FileReader(new File(cvDir, "folds.info.tsv")));
    for (String foldLine = null; (foldLine = cvBr.readLine()) != null;) {
        String[] cols = foldLine.split("\t");
        String foldName = cols[0];

        System.out.printf("Scoring results for fold %s%n", foldName);

        File foldPredictionsFile = new File(predDir, foldName + ".results.tsv.gz");

        File goldLocFile = new File(cvDir, foldName + ".gold-locations.tsv");

        if (foldPredictionsFile.exists()) {
            BufferedReader br = Files.openGz(foldPredictionsFile);
            for (String line = null; (line = br.readLine()) != null;) {
                String[] arr = line.split("\t");
                long id = Long.parseLong(arr[0]);
                idToPredLoc.put(id, new double[] { Double.parseDouble(arr[1]), Double.parseDouble(arr[2]) });
            }
            br.close();
        }

        System.out.printf("loaded predictions for %d tweets; " + "scoring predictions%n", idToPredLoc.size());

        BufferedReader br = new BufferedReader(new FileReader(goldLocFile));
        for (String line = null; (line = br.readLine()) != null;) {
            String[] arr = line.split("\t");
            long id = Long.parseLong(arr[0]);
            long userId = Long.parseLong(arr[1]);

            allUsers.add(userId);
            tweetsSeen++;

            double[] predLoc = idToPredLoc.get(id);
            if (predLoc == null)
                continue;

            tweetsLocated++;
            locatedUsers.add(userId);

            double[] goldLoc = new double[] { Double.parseDouble(arr[2]), Double.parseDouble(arr[3]) };

            double dist = Geometry.getDistance(predLoc, goldLoc);
            errors.add(dist);
            tweetIdToError.put(id, dist);

            TDoubleList userErrors = userToErrors.get(userId);
            if (userErrors == null) {
                userErrors = new TDoubleArrayList();
                userToErrors.put(userId, userErrors);
            }
            userErrors.add(dist);

        }
        br.close();
    }

    errors.sort();
    System.out.println("Num errors to score: " + errors.size());

    double auc = 0;
    double userCoverage = 0;
    double tweetCoverage = tweetsLocated / (double) tweetsSeen;
    double medianMaxUserError = Double.NaN;
    double medianMedianUserError = Double.NaN;

    if (errors.size() > 0) {
        auc = computeAuc(errors);
        userCoverage = locatedUsers.size() / ((double) allUsers.size());
        TDoubleList maxUserErrors = new TDoubleArrayList(locatedUsers.size());
        TDoubleList medianUserErrors = new TDoubleArrayList(locatedUsers.size());
        for (TDoubleList userErrors : userToErrors.valueCollection()) {
            userErrors.sort();
            maxUserErrors.add(userErrors.get(userErrors.size() - 1));
            medianUserErrors.add(userErrors.get(userErrors.size() / 2));
        }

        maxUserErrors.sort();
        medianMaxUserError = maxUserErrors.get(maxUserErrors.size() / 2);

        medianUserErrors.sort();
        medianMedianUserError = medianUserErrors.get(medianUserErrors.size() / 2);

        // Compute CDF
        int[] errorsPerKm = new int[MAX_KM];
        for (int i = 0; i < errors.size(); ++i) {
            int error = (int) (Math.round(errors.get(i)));
            errorsPerKm[error]++;
        }

        // The accumulated sum of errors per km
        int[] errorsBelowEachKm = new int[errorsPerKm.length];
        for (int i = 0; i < errorsBelowEachKm.length; ++i) {
            errorsBelowEachKm[i] = errorsPerKm[i];
            if (i > 0)
                errorsBelowEachKm[i] += errorsBelowEachKm[i - 1];
        }

        final double[] cdf = new double[errorsBelowEachKm.length];
        double dSize = errors.size(); // to avoid casting all the time
        for (int i = 0; i < cdf.length; ++i)
            cdf[i] = errorsBelowEachKm[i] / dSize;
    }

    PrintWriter pw = new PrintWriter(new File(args[2]));
    pw.println("AUC\t" + auc);
    pw.println("user coverage\t" + userCoverage);
    pw.println("tweet coverage\t" + tweetCoverage);
    pw.println("median-max error\t" + medianMaxUserError);
    pw.close();

    // Choose a random sampling of 10K tweets to pass on to the authors
    // here.        
    PrintWriter errorsPw = new PrintWriter(args[3]);
    TLongList idsWithErrors = new TLongArrayList(tweetIdToError.keySet());
    idsWithErrors.shuffle(new Random());
    // Choose the first 10K
    for (int i = 0, chosen = 0; i < idsWithErrors.size() && chosen < 10_000; ++i) {

        long id = idsWithErrors.get(i);
        double[] prediction = idToPredLoc.get(id);
        double error = tweetIdToError.get(id);
        errorsPw.println(id + "\t" + error + "\t" + prediction[0] + "\t" + prediction[1]);
        ++chosen;
    }
    errorsPw.close();
}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());/*from   w w  w.  j  ava  2s .  co m*/
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}

From source file:fsm.process.test.ProcessTest.java

public static void main(String args[]) throws Exception {
    try {/*ww w  . ja  v a 2  s .  c  om*/
        initDataBase();
        Integer auditorId1 = createOperator("wd", "13399999999");
        Integer auditorId2 = createOperator("lm", "13499999999");

        Integer orgId1 = createOrganization("", "", "100010", "10099900393");
        Integer orgId2 = createOrganization("?", "?", "100011", "10099900394");

        List<User> agents = new ArrayList<User>();

        Integer agentId1 = registerAgent("zs", "13511111111", orgId1, "001", "001001");
        agents.add(userDao.find(agentId1));
        Integer agentId2 = registerAgent("zs2", "13511111112", orgId1, "001", "001002");
        agents.add(userDao.find(agentId2));
        Integer agentId3 = registerAgent("zs3", "13511111113", orgId1, "001", "001003");
        agents.add(userDao.find(agentId3));
        Integer agentId4 = registerAgent("zs4", "13511111114", orgId1, "001", "001004");
        agents.add(userDao.find(agentId4));
        Integer agentId5 = registerAgent("zs5", "13511111115", orgId1, "002", "002001");
        agents.add(userDao.find(agentId5));
        Integer agentId6 = registerAgent("zs6", "13511111116", orgId1, "002", "002002");
        agents.add(userDao.find(agentId6));
        Integer agentId7 = registerAgent("zs7", "13511111117", orgId1, "002", "002003");
        agents.add(userDao.find(agentId7));

        Integer agentId8 = registerAgent("zs8", "13511111118", orgId2, "001", "001001");
        agents.add(userDao.find(agentId8));
        Integer agentId9 = registerAgent("zs9", "13511111119", orgId2, "001", "001002");
        agents.add(userDao.find(agentId9));
        Integer agentId10 = registerAgent("zs10", "13511111120", orgId2, "001", "001003");
        agents.add(userDao.find(agentId10));
        Integer agentId11 = registerAgent("zs11", "13511111121", orgId2, "001", "001004");
        agents.add(userDao.find(agentId11));
        Integer agentId12 = registerAgent("zs12", "13511111122", orgId2, "002", "002001");
        agents.add(userDao.find(agentId12));
        Integer agentId13 = registerAgent("zs13", "13511111123", orgId2, "002", "002002");
        agents.add(userDao.find(agentId13));
        Integer agentId14 = registerAgent("zs14", "13511111124", orgId2, "002", "002003");
        agents.add(userDao.find(agentId14));

        auditAgent(agentId1, true);
        auditAgent(agentId2, false);
        auditAgent(agentId3, true);
        auditAgent(agentId4, false);
        auditAgent(agentId5, true);
        auditAgent(agentId6, true);
        auditAgent(agentId7, true);
        auditAgent(agentId8, true);
        auditAgent(agentId9, true);
        auditAgent(agentId10, true);
        auditAgent(agentId11, true);
        auditAgent(agentId12, true);
        auditAgent(agentId13, true);
        auditAgent(agentId14, true);

        reApplyAgent(agentId2);
        reApplyAgent(agentId4);

        auditAgent(agentId2, true);
        auditAgent(agentId4, true);

        Integer proId1 = createProduct("", agentId1, "001001", orgId1, Product.TYPE_XINYONG,
                ";;",
                "?;?;?");
        addProductAction(1, proId1, "", "?", 5);
        addProductAction(2, proId1, "", "?", 7);
        addProductAction(3, proId1, "", "??", 3);
        applyAuditProduct(proId1);
        auditProduct(proId1, true);

        Integer proId2 = createProduct("", agentId2, "002001", orgId1, Product.TYPE_XIAOFEI,
                ";;",
                "?;?;?");
        addProductAction(1, proId2, "", "?", 6);
        addProductAction(2, proId2, "", "?", 4);
        addProductAction(3, proId2, "", "??", 1);
        applyAuditProduct(proId2);
        auditProduct(proId2, false);
        applyAuditProduct(proId2);
        auditProduct(proId2, true);

        String[] steps = { "?", "?", "?",
                "?", "?", "?" };
        String[] profits = { "", "???", "", "??",
                "?" };
        String[] requires = { "?", "???",
                "??", "?2000", "?",
                "?" };

        for (User agent : agents) {
            Random ran = new Random();

            String profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            String requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];

            Integer proId_fangdai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_HOUSE, profitstr, requirestr);

            int step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_fangdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_fangdai);
            auditProduct(proId_fangdai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_jingyingdai = createProduct("??", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_JINGYING, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_jingyingdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_jingyingdai);
            auditProduct(proId_jingyingdai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_chedai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_CAR, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_chedai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_chedai);
            auditProduct(proId_chedai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_diyadai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_DIYA, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_diyadai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_diyadai);
            auditProduct(proId_diyadai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_xiaofeidai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_XIAOFEI, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_xiaofeidai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_xiaofeidai);
            auditProduct(proId_xiaofeidai, true);

            profitstr = profits[ran.nextInt(100) % 5] + ";" + profits[ran.nextInt(100) % 5] + ";"
                    + profits[ran.nextInt(100) % 5];
            requirestr = requires[ran.nextInt(100) % 6] + ";" + requires[ran.nextInt(100) % 6] + ";"
                    + requires[ran.nextInt(100) % 6];
            Integer proId_xinyongdai = createProduct("", agent.getId(), agent.getCity(),
                    agent.getOrganizationId(), Product.TYPE_XINYONG, profitstr, requirestr);
            step = ran.nextInt(6);
            for (int i = 0; i < step; i++) {
                addProductAction((i + 1), proId_xinyongdai, "" + i, steps[i], ran.nextInt(10));
            }
            applyAuditProduct(proId_xinyongdai);
            auditProduct(proId_xinyongdai, true);
        }

        Integer userId1 = userRegister("wangxiaopang", "13899977889");
        Integer userId2 = userRegister("wangxiaoshuai", "13899977890");

        Integer operationId1 = applyOperation(userId1, Product.TYPE_XINYONG, 20, 24, "001", "001001");
        updateOperation(operationId1, proId1, agentId1);

        Integer operationId2 = applyOperation(userId2, Product.TYPE_XIAOFEI, 15, 120, "002", "002001");
        updateOperation(operationId2, proId2, agentId2);

        auditOperation(operationId1, true);
        auditOperation(operationId2, false);
        reApplyOperation(operationId2);
        auditOperation(operationId2, true);

        takeoverOperation(operationId1, agentId1);
        takeoverOperation(operationId2, agentId2);
        handleOperation(operationId1);
        handleOperation(operationId2);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        System.exit(0);
    }

}