Example usage for java.lang Double parseDouble

List of usage examples for java.lang Double parseDouble

Introduction

In this page you can find the example usage for java.lang Double parseDouble.

Prototype

public static double parseDouble(String s) throws NumberFormatException 

Source Link

Document

Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .

Usage

From source file:edu.cmu.lti.oaqa.apps.Client.java

public static void main(String args[]) {
    BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));

    Options opt = new Options();

    Option o = new Option(PORT_SHORT_PARAM, PORT_LONG_PARAM, true, PORT_DESC);
    o.setRequired(true);/*from w  ww  .  j  a v a  2 s .  co m*/
    opt.addOption(o);
    o = new Option(HOST_SHORT_PARAM, HOST_LONG_PARAM, true, HOST_DESC);
    o.setRequired(true);
    opt.addOption(o);
    opt.addOption(K_SHORT_PARAM, K_LONG_PARAM, true, K_DESC);
    opt.addOption(R_SHORT_PARAM, R_LONG_PARAM, true, R_DESC);
    opt.addOption(QUERY_TIME_SHORT_PARAM, QUERY_TIME_LONG_PARAM, true, QUERY_TIME_DESC);
    opt.addOption(RET_OBJ_SHORT_PARAM, RET_OBJ_LONG_PARAM, false, RET_OBJ_DESC);
    opt.addOption(RET_EXTERN_ID_SHORT_PARAM, RET_EXTERN_ID_LONG_PARAM, false, RET_EXTERN_ID_DESC);

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

    try {
        CommandLine cmd = parser.parse(opt, args);

        String host = cmd.getOptionValue(HOST_SHORT_PARAM);

        String tmp = null;

        tmp = cmd.getOptionValue(PORT_SHORT_PARAM);

        int port = -1;

        try {
            port = Integer.parseInt(tmp);
        } catch (NumberFormatException e) {
            Usage("Port should be integer!");
        }

        boolean retObj = cmd.hasOption(RET_OBJ_SHORT_PARAM);
        boolean retExternId = cmd.hasOption(RET_EXTERN_ID_SHORT_PARAM);

        String queryTimeParams = cmd.getOptionValue(QUERY_TIME_SHORT_PARAM);
        if (null == queryTimeParams)
            queryTimeParams = "";

        SearchType searchType = SearchType.kKNNSearch;
        int k = 0;
        double r = 0;

        if (cmd.hasOption(K_SHORT_PARAM)) {
            if (cmd.hasOption(R_SHORT_PARAM)) {
                Usage("Range search is not allowed if the KNN search is specified!");
            }
            tmp = cmd.getOptionValue(K_SHORT_PARAM);
            try {
                k = Integer.parseInt(tmp);
            } catch (NumberFormatException e) {
                Usage("K should be integer!");
            }
            searchType = SearchType.kKNNSearch;
        } else if (cmd.hasOption(R_SHORT_PARAM)) {
            if (cmd.hasOption(K_SHORT_PARAM)) {
                Usage("KNN search is not allowed if the range search is specified!");
            }
            searchType = SearchType.kRangeSearch;
            tmp = cmd.getOptionValue(R_SHORT_PARAM);
            try {
                r = Double.parseDouble(tmp);
            } catch (NumberFormatException e) {
                Usage("The range value should be numeric!");
            }
        } else {
            Usage("One has to specify either range or KNN-search parameter");
        }

        String separator = System.getProperty("line.separator");

        StringBuffer sb = new StringBuffer();
        String s;

        while ((s = inp.readLine()) != null) {
            sb.append(s);
            sb.append(separator);
        }

        String queryObj = sb.toString();

        try {
            TTransport transport = new TSocket(host, port);
            transport.open();

            TProtocol protocol = new TBinaryProtocol(transport);
            QueryService.Client client = new QueryService.Client(protocol);

            if (!queryTimeParams.isEmpty())
                client.setQueryTimeParams(queryTimeParams);

            List<ReplyEntry> res = null;

            long t1 = System.nanoTime();

            if (searchType == SearchType.kKNNSearch) {
                System.out.println(String.format("Running a %d-NN search", k));
                res = client.knnQuery(k, queryObj, retExternId, retObj);
            } else {
                System.out.println(String.format("Running a range search (r=%g)", r));
                res = client.rangeQuery(r, queryObj, retExternId, retObj);
            }

            long t2 = System.nanoTime();

            System.out.println(String.format("Finished in %g ms", (t2 - t1) / 1e6));

            for (ReplyEntry e : res) {
                System.out.println(String.format("id=%d dist=%g %s", e.getId(), e.getDist(),
                        retExternId ? "externId=" + e.getExternId() : ""));
                if (retObj)
                    System.out.println(e.getObj());
            }

            transport.close(); // Close transport/socket !
        } catch (TException te) {
            System.err.println("Apache Thrift exception: " + te);
            te.printStackTrace();
        }

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:mlbench.pagerank.PagerankMerge.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, InterruptedException {
    try {//from   www .j a va  2  s  . co  m
        parseArgs(args);
        HashMap<String, String> conf = new HashMap<String, String>();
        initConf(conf);
        MPI_D.Init(args, MPI_D.Mode.Common, conf);

        JobConf jobConf = new JobConf(confPath);
        if (MPI_D.COMM_BIPARTITE_O != null) {
            // O communicator
            int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_O);
            int size = MPI_D.Comm_size(MPI_D.COMM_BIPARTITE_O);
            if (rank == 0) {
                LOG.info(PagerankMerge.class.getSimpleName() + " O start.");
            }
            FileSplit[] inputs = DataMPIUtil.HDFSDataLocalLocator.getTaskInputs(MPI_D.COMM_BIPARTITE_O, jobConf,
                    inDir, rank);
            for (int i = 0; i < inputs.length; i++) {
                FileSplit fsplit = inputs[i];
                LineRecordReader kvrr = new LineRecordReader(jobConf, fsplit);

                LongWritable key = kvrr.createKey();
                Text value = kvrr.createValue();
                {
                    while (kvrr.next(key, value)) {
                        String line_text = value.toString();
                        final String[] line = line_text.split("\t");
                        if (line.length >= 2) {
                            MPI_D.Send(new IntWritable(Integer.parseInt(line[0])), new Text(line[1]));
                        }
                    }
                }
            }

        } else if (MPI_D.COMM_BIPARTITE_A != null) {
            // A communicator
            int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_A);
            if (rank == 0) {
                LOG.info(PagerankMerge.class.getSimpleName() + " A start.");
            }
            HadoopWriter<IntWritable, Text> outrw = HadoopIOUtil.getNewWriter(jobConf, outDir,
                    IntWritable.class, Text.class, TextOutputFormat.class, null, rank, MPI_D.COMM_BIPARTITE_A);

            IntWritable oldKey = null;
            double next_rank = 0;
            double previous_rank = 0;
            double diff = 0;
            int local_diffs = 0;
            random_coeff = (1 - mixing_c) / (double) number_nodes;
            converge_threshold = ((double) 1.0 / (double) number_nodes) / 10;
            Object[] keyValue = MPI_D.Recv();
            while (keyValue != null) {
                IntWritable key = (IntWritable) keyValue[0];
                Text value = (Text) keyValue[1];
                if (oldKey == null) {
                    oldKey = key;
                }
                if (!key.equals(oldKey)) {
                    next_rank = next_rank * mixing_c + random_coeff;
                    outrw.write(oldKey, new Text("v" + next_rank));
                    diff = Math.abs(previous_rank - next_rank);
                    if (diff > converge_threshold) {
                        local_diffs += 1;
                    }
                    oldKey = key;
                    next_rank = 0;
                    previous_rank = 0;
                }

                String cur_value_str = value.toString();
                if (cur_value_str.charAt(0) == 's') {
                    previous_rank = Double.parseDouble(cur_value_str.substring(1));
                } else {
                    next_rank += Double.parseDouble(cur_value_str.substring(1));
                }

                keyValue = MPI_D.Recv();
            }
            if (previous_rank != 0) {
                next_rank = next_rank * mixing_c + random_coeff;
                outrw.write(oldKey, new Text("v" + next_rank));
                diff = Math.abs(previous_rank - next_rank);
                if (diff > converge_threshold)
                    local_diffs += 1;
            }
            outrw.close();
            reduceDiffs(local_diffs, rank);
        }

        MPI_D.Finalize();
    } catch (MPI_D_Exception e) {
        e.printStackTrace();
    }
}

From source file:com.oculusinfo.ml.spark.unsupervised.TestKMeans.java

/**
 * @param args//from w w  w. j  a v a2  s  . co m
 */
public static void main(String[] args) {
    int k = 5;

    try {
        FileUtils.deleteDirectory(new File("output/clusters"));
        FileUtils.deleteDirectory(new File("output/centroids"));
    } catch (IOException e1) {
        /* ignore (*/ }

    genTestData(k);

    JavaSparkContext sc = new JavaSparkContext("local", "OculusML");
    SparkDataSet ds = new SparkDataSet(sc);
    ds.load("test.txt", new SparkInstanceParser() {
        private static final long serialVersionUID = 1L;

        @Override
        public Tuple2<String, Instance> call(String line) throws Exception {
            Instance inst = new Instance();

            String tokens[] = line.split(",");

            NumericVectorFeature v = new NumericVectorFeature("point");

            double x = Double.parseDouble(tokens[0]);
            double y = Double.parseDouble(tokens[1]);
            v.setValue(new double[] { x, y });

            inst.addFeature(v);

            return new Tuple2<String, Instance>(inst.getId(), inst);
        }
    });

    KMeansClusterer clusterer = new KMeansClusterer(k, 10, 0.001, "output/centroids", "output/clusters");

    clusterer.registerFeatureType("point", MeanNumericVectorCentroid.class, new EuclideanDistance(1.0));

    clusterer.doCluster(ds);

    try {
        final List<double[]> instances = readInstances();

        final Color[] colors = { Color.red, Color.blue, Color.green, Color.magenta, Color.yellow, Color.black,
                Color.orange, Color.cyan, Color.darkGray, Color.white };

        TestKMeans t = new TestKMeans();
        t.add(new JComponent() {
            private static final long serialVersionUID = 2059497051387104848L;

            public void paintComponent(Graphics g) {
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                for (double[] inst : instances) {
                    int color = (int) inst[0];
                    g.setColor(colors[color]);

                    Ellipse2D l = new Ellipse2D.Double(inst[1], inst[2], 5, 5);
                    g2.draw(l);
                }
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 400);
        t.setVisible(true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.act.lcms.CompareTwoNetCDFAroundMass.java

public static void main(String[] args) throws Exception {
    if (args.length < 5 || !areNCFiles(Arrays.copyOfRange(args, 3, args.length))) {
        throw new RuntimeException("Needs: \n" + "(1) mass value, e.g., 132.0772 for debugging, \n"
                + "(2) how many timepoints to process (-1 for all), \n"
                + "(3) prefix for .data and rendered .pdf \n" + "(4,5..) 2 or more NetCDF .nc files");
    }//from ww w  .j  a  va  2s.  c o m

    String fmt = "pdf";
    Double mz = Double.parseDouble(args[0]);
    Integer numSpectraToProcess = Integer.parseInt(args[1]);
    String outPrefix = args[2];
    String outImg = outPrefix.equals("-") ? null : outPrefix + "." + fmt;
    String outData = outPrefix.equals("-") ? null : outPrefix + ".data";

    CompareTwoNetCDFAroundMass c = new CompareTwoNetCDFAroundMass();
    String[] netCDF_fnames = Arrays.copyOfRange(args, 3, args.length);
    List<List<Pair<Double, Double>>> spectra = c.getSpectraForMass(mz, netCDF_fnames, numSpectraToProcess);

    // Write data output to outfile
    PrintStream out = outData == null ? System.out : new PrintStream(new FileOutputStream(outData));

    // print out the spectra to outData
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        for (Pair<Double, Double> xy : spectraInFile) {
            out.format("%.4f\t%.4f\n", xy.getLeft(), xy.getRight());
            out.flush();
        }
        // delimit this dataset from the rest
        out.print("\n\n");
    }
    // find the ymax across all spectra, so that we can have a uniform y scale
    Double yrange = 0.0;
    for (List<Pair<Double, Double>> spectraInFile : spectra) {
        Double ymax = 0.0;
        for (Pair<Double, Double> xy : spectraInFile) {
            Double intensity = xy.getRight();
            if (ymax < intensity)
                ymax = intensity;
        }
        if (yrange < ymax)
            yrange = ymax;
    }

    if (outData != null) {
        // if outData is != null, then we have written to .data file
        // now render the .data to the corresponding .pdf file

        // first close the .data
        out.close();

        // render outData to outFILE using gnuplo
        Gnuplotter plotter = new Gnuplotter();
        plotter.plot2D(outData, outImg, netCDF_fnames, "time in seconds", yrange, "intensity", fmt);
    }
}

From source file:SDRecord.java

public static void main(String[] args) {

    boolean recordToInf = false;
    long recordTo = 0, txsize = 0, wr = 0, max = 0;
    int sourcePort = 0, destPort = 0;
    String val;
    OutputStream writer = null;/*  w  w w .j  a  va 2s. co  m*/
    InetAddress rhost = null, lhost = null;
    DatagramSocket socket = null;

    //Default values
    int buffSize = 1500;
    try {
        lhost = InetAddress.getByName("0.0.0.0");
    } catch (UnknownHostException e1) {
        System.err.println("ERROR!: Host not reconized");
        System.exit(3);
    }
    recordToInf = true;
    sourcePort = 7355;

    Options options = new Options();

    options.addOption("m", true, "Minutes to record, default is no limit");
    options.addOption("l", true, "Bind to a specific local address, default is 0.0.0.0");
    options.addOption("p", true, "Local port to use, default is 7355");
    options.addOption("r", true, "Remote address where to send data");
    options.addOption("d", true, "Remote port, to use with -r option");
    options.addOption("f", true, "Output file where to save the recording");
    options.addOption("s", true, "Stop recording when reaching specified MBs");
    options.addOption("h", false, "Help");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        System.err.println("ERROR!: Error while parsing the command line");
        System.exit(1);
    }

    if (cmd.hasOption("m")) {
        val = cmd.getOptionValue("m");
        try {
            if (Long.parseLong(val) < 0) {
                System.err.println("ERROR!: -m argument value cannot be negative");
                System.exit(3);
            }
            recordTo = System.currentTimeMillis() + (Long.parseLong(val) * 60000);
            recordToInf = false;
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -m argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("l")) {
        val = cmd.getOptionValue("l");
        try {
            lhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("p")) {
        val = cmd.getOptionValue("p");
        try {
            sourcePort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -p argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("r")) {
        val = cmd.getOptionValue("r");
        try {
            rhost = InetAddress.getByName(val);
        } catch (UnknownHostException e) {
            System.err.println("ERROR!: Host not reconized");
            System.exit(3);
        }
    }

    if (cmd.hasOption("d")) {
        val = cmd.getOptionValue("d");
        try {
            destPort = Integer.parseInt(val);
        } catch (NumberFormatException e) {
            System.err.println("-ERROR!: -d argument not an integer");
            System.exit(3);
        }
    }

    if (cmd.hasOption("f")) {
        val = cmd.getOptionValue("f");
        try {
            writer = new FileOutputStream(val);
        } catch (FileNotFoundException e) {
            System.err.println("ERROR!: File not found");
            System.exit(3);
        }
    }

    if (cmd.hasOption("s")) {
        val = cmd.getOptionValue("s");

        try {
            max = (long) (Double.parseDouble(val) * 1000000);
        } catch (NumberFormatException e) {
            System.err.println("ERROR!: -s argument not valid");
            System.exit(3);
        }

        if (Double.parseDouble(val) < 0) {
            System.err.println("ERROR!: -s argument value cannot be negative");
            System.exit(3);
        }

    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("SDRecord", options);
        System.exit(0);
    }

    try {
        socket = new DatagramSocket(sourcePort, lhost);
        //socket options
        socket.setReuseAddress(true);
    } catch (SocketException e) {
        e.printStackTrace();
        System.exit(3);
    }

    byte[] buffer = new byte[buffSize];
    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

    System.err.println("Listening " + lhost.toString() + " on port " + sourcePort);

    while (recordToInf == true || System.currentTimeMillis() <= recordTo) {
        //Stop recording when reaching max bytes
        if (max != 0 && txsize >= max)
            break;

        packet.setData(buffer);
        try {
            socket.receive(packet);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(4);
        }

        //Ignoring packets with no data
        if (basicFilter(packet) == null)
            continue;

        if (writer == null && rhost == null)
            wr = recordToStdout(packet);
        if (writer != null)
            wr = recordToFile(packet, writer);
        if (rhost != null)
            wr = recordToSocket(packet, socket, rhost, destPort);

        txsize += wr;
        System.err
                .print("\r" + formatSize(txsize) + " transferred" + "\033[K" + "\t Press Ctrl+c to terminate");
    }
    //closing socket and exit
    System.err.print("\r" + formatSize(txsize) + " transferred" + "\033[K");
    socket.close();
    System.out.println();
    System.exit(0);
}

From source file:Satellite.java

/** Program entry point.
 * @param args program arguments (unused here)
 *///www . j  av  a  2s  .  c om
public static void main(String[] args) {
    try {

        // configure Orekit
        AutoconfigurationCustom.configureOrekit();

        //  Initial state definition : date, orbit
        AbsoluteDate targetDate = new AbsoluteDate(2015, 12, 15, 2, 54, 27.000, TimeScalesFactory.getUTC());
        //*******/            double mu =  3.986004415e+14; // gravitation coefficient
        //*******/            Frame inertialFrame = FramesFactory.getEME2000(); // inertial frame for orbit definition
        //*******/            Vector3D position  = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        //*******/            Vector3D velocity  = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        //*******/            PVCoordinates pvCoordinates = new PVCoordinates(position, velocity);
        //*******/            Orbit initialOrbit = new KeplerianOrbit(pvCoordinates, inertialFrame, initialDate, mu);
        String Line1 = "1 25544U 98067A   15348.82280235  .00015563  00000-0  23610-3 0  9996";
        String Line2 = "2 25544  51.6445 262.5935 0007865 276.8969 187.2494 15.54770155976144";
        TLE TLEdata = new TLE(Line1, Line2);

        // Propagator : consider a simple keplerian motion (could be more elaborate)
        Propagator TLEProp = TLEPropagator.selectExtrapolator(TLEdata);

        //            // Earth and frame
        //            Frame earthFrame = FramesFactory.getITRF(IERSConventions.IERS_2010, true);
        //            BodyShape earth = new OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
        //                                                   Constants.WGS84_EARTH_FLATTENING,
        //                                                   earthFrame);
        //
        //            // Station
        //            final double longitude = FastMath.toRadians(89.);
        //            final double latitude  = FastMath.toRadians(-8);
        //            final double altitude  = 0.;
        //            final GeodeticPoint station1 = new GeodeticPoint(latitude, longitude, altitude);
        //            final TopocentricFrame sta1Frame = new TopocentricFrame(earth, station1, "station1");
        //
        //            // Event definition
        //            final double maxcheck  = 60.0;
        //            final double threshold =  0.001;
        //            final double elevation = FastMath.toRadians(5.0);
        //            final EventDetector sta1Visi =
        //                    new ElevationDetector(maxcheck, threshold, sta1Frame).
        //                    withConstantElevation(elevation).
        //                    withHandler(new VisibilityHandler());

        // Add event to be detected
        //kepler.addEventDetector(sta1Visi);

        //Propagate from the initial date to the first raising or for the fixed duration
        //SpacecraftState finalState = kepler.propagate(initialDate.shiftedBy(1500.));

        //System.out.println(" Final state : " + finalState.getDate().durationFrom(initialDate));

        String stateVector = TLEProp.propagate(targetDate)
                .getPVCoordinates(FramesFactory.getITRF(IERSConventions.IERS_2010, true)).toString();

        stateVector = stateVector.replace("{", "").replace("}", ""); //Removes brackets {}
        stateVector = stateVector.replace("(", "").replace(")", ""); //Removes parentheses ()
        stateVector = stateVector.replace("P", "").replace("V", "").replace("A", ""); //Removes P, V, A
        stateVector = stateVector.replace(" ", ""); //Removes spaces
        String[] lineData = stateVector.split(",");

        String timeStamp = new String(lineData[0]);
        double[] position = new double[] { Double.parseDouble(lineData[1]), Double.parseDouble(lineData[2]),
                Double.parseDouble(lineData[3]) };
        double[] velocity = new double[] { Double.parseDouble(lineData[4]), Double.parseDouble(lineData[5]),
                Double.parseDouble(lineData[6]) };
        double[] acceleration = new double[] { Double.parseDouble(lineData[7]), Double.parseDouble(lineData[8]),
                Double.parseDouble(lineData[9]) };

        position = Convert_To_Lat_Long(position);

        System.out.format("Latitude %.8f N%n", position[0]);
        System.out.format("Longitude %.8f E%n", position[1]);
        System.out.format("Altitude %.0f m %n", position[2]);

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:name.wagners.bpp.Bpp.java

public static void main(final String[] args) {

    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations")
            .withDescription("Number of generations [default: 50]").create("g"));

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate")
            .withDescription("Mutation rate [default: 1]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop")
            .withDescription("Mutation propability [default: 0.5]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize")
            .withDescription("Size of population [default: 20]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg")
            .withDescription("Recombination algorithm [default: a]").create());

    // options.addOption(OptionBuilder
    // .hasArg()/*  www  .j a  v a  2s . c  om*/
    // .withArgName("int")
    // .withLongOpt("recombrate")
    // .withDescription("Recombination rate [default: 1]")
    // .create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop")
            .withDescription("Recombination propability [default: 0.8]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg")
            .withDescription("Selection algorithm [default: a]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure")
            .withDescription("Selection pressure [default: 4]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism")
            .withDescription("Enable Elitism [default: 1]").create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("filename")
            // .isRequired()
            .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]")
            .create("f"));

    options.addOptionGroup(new OptionGroup()
            .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v"))
            .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q")));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("print the version information and exit").create("V"));

    options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Bpp", options);

            System.exit(0);
        }

        if (line.hasOption("version")) {
            log.info("Bpp 0.1 (c) 2007 by Daniel Wagner");
        }

        if (line.hasOption("datafile")) {
            fname = line.getOptionValue("datafile");
        }

        if (line.hasOption("elitism")) {
            elitism = Boolean.parseBoolean(line.getOptionValue("elitism"));
        }

        if (line.hasOption("generations")) {
            gen = Integer.parseInt(line.getOptionValue("generations"));
        }

        if (line.hasOption("mutprop")) {
            mp = Double.parseDouble(line.getOptionValue("mutprop"));
        }

        if (line.hasOption("mutrate")) {
            mr = Integer.parseInt(line.getOptionValue("mutrate"));
        }

        if (line.hasOption("populationsize")) {
            ps = Integer.parseInt(line.getOptionValue("populationsize"));
        }

        if (line.hasOption("recombalg")) {
            sel = line.getOptionValue("recombalg").charAt(0);
        }

        if (line.hasOption("recombprop")) {
            rp = Double.parseDouble(line.getOptionValue("recombprop"));
        }

        if (line.hasOption("selalg")) {
            selalg = line.getOptionValue("selalg").charAt(0);
        }

        if (line.hasOption("selectionpressure")) {
            sp = Integer.parseInt(line.getOptionValue("selectionpressure"));
        }

    } catch (ParseException exp) {
        log.info("Unexpected exception:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bpp", options);

        System.exit(1);
    }

    // Ausgabe der eingestellten Optionen

    log.info("Configuration");
    log.info("  Datafile:                  " + fname);
    log.info("  Generations:               " + gen);
    log.info("  Population size:           " + ps);
    log.info("  Elitism:                   " + elitism);
    log.info("  Mutation propapility:      " + mp);
    log.info("  Mutation rate:             " + mr);
    log.info("  Recombination algorithm    " + (char) sel);
    log.info("  Recombination propapility: " + rp);
    log.info("  Selection pressure:        " + sp);

    // Daten laden
    instance = new Instance();
    instance.load(fname);

    Evolutionizer e = new Evolutionizer(instance);

    e.run();
}

From source file:org.apache.flink.benchmark.Runner.java

public static void main(String[] args) throws Exception {
    final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().enableObjectReuse();
    env.getConfig().disableSysoutLogging();

    ParameterTool parameters = ParameterTool.fromArgs(args);

    if (!(parameters.has("p") && parameters.has("types") && parameters.has("algorithms"))) {
        printUsage();//  w w  w.  ja  v  a  2  s . c  o m
        System.exit(-1);
    }

    int parallelism = parameters.getInt("p");
    env.setParallelism(parallelism);

    Set<IdType> types = new HashSet<>();

    if (parameters.get("types").equals("all")) {
        types.add(IdType.INT);
        types.add(IdType.LONG);
        types.add(IdType.STRING);
    } else {
        for (String type : parameters.get("types").split(",")) {
            if (type.toLowerCase().equals("int")) {
                types.add(IdType.INT);
            } else if (type.toLowerCase().equals("long")) {
                types.add(IdType.LONG);
            } else if (type.toLowerCase().equals("string")) {
                types.add(IdType.STRING);
            } else {
                printUsage();
                throw new RuntimeException("Unknown type: " + type);
            }
        }
    }

    Queue<RunnerWithScore> queue = new PriorityQueue<>();

    if (parameters.get("algorithms").equals("all")) {
        for (Map.Entry<String, Class> entry : AVAILABLE_ALGORITHMS.entrySet()) {
            for (IdType type : types) {
                AlgorithmRunner runner = (AlgorithmRunner) entry.getValue().newInstance();
                runner.initialize(type, SAMPLES, parallelism);
                runner.warmup(env);
                queue.add(new RunnerWithScore(runner, 1.0));
            }
        }
    } else {
        for (String algorithm : parameters.get("algorithms").split(",")) {
            double ratio = 1.0;
            if (algorithm.contains("=")) {
                String[] split = algorithm.split("=");
                algorithm = split[0];
                ratio = Double.parseDouble(split[1]);
            }

            if (AVAILABLE_ALGORITHMS.containsKey(algorithm.toLowerCase())) {
                Class clazz = AVAILABLE_ALGORITHMS.get(algorithm.toLowerCase());

                for (IdType type : types) {
                    AlgorithmRunner runner = (AlgorithmRunner) clazz.newInstance();
                    runner.initialize(type, SAMPLES, parallelism);
                    runner.warmup(env);
                    queue.add(new RunnerWithScore(runner, ratio));
                }
            } else {
                printUsage();
                throw new RuntimeException("Unknown algorithm: " + algorithm);
            }
        }
    }

    JsonFactory factory = new JsonFactory();

    while (queue.size() > 0) {
        RunnerWithScore current = queue.poll();
        AlgorithmRunner runner = current.getRunner();

        StringWriter writer = new StringWriter();
        JsonGenerator gen = factory.createGenerator(writer);
        gen.writeStartObject();
        gen.writeStringField("algorithm", runner.getClass().getSimpleName());

        boolean running = true;

        while (running) {
            try {
                runner.run(env, gen);
                running = false;
            } catch (ProgramInvocationException e) {
                // only suppress job cancellations
                if (!(e.getCause() instanceof JobCancellationException)) {
                    throw e;
                }
            }
        }

        JobExecutionResult result = env.getLastJobExecutionResult();

        long runtime_ms = result.getNetRuntime();
        gen.writeNumberField("runtime_ms", runtime_ms);
        current.credit(runtime_ms);

        if (!runner.finished()) {
            queue.add(current);
        }

        gen.writeObjectFieldStart("accumulators");
        for (Map.Entry<String, Object> accumulatorResult : result.getAllAccumulatorResults().entrySet()) {
            gen.writeStringField(accumulatorResult.getKey(), accumulatorResult.getValue().toString());
        }
        gen.writeEndObject();

        gen.writeEndObject();
        gen.close();
        System.out.println(writer.toString());
    }
}

From source file:edu.msu.cme.rdp.framebot.stat.TaxonAbundance.java

/**
 * this class group the nearest matches by phylum/class, or by match 
 * @param args//from w  w w  .  j a  va2  s .c o m
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    HashMap<String, Double> coveragetMap = null;
    double identity = 0.0;
    try {
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("seqCoverage")) {
            String coveragefile = line.getOptionValue("seqCoverage");
            coveragetMap = parseKmerCoverage(coveragefile);
        }
        if (line.hasOption("identity")) {
            identity = Double.parseDouble(line.getOptionValue("identity"));
            if (identity < 0 || identity > 100) {
                throw new IllegalArgumentException("identity cutoff should be in the range of 0 and 100");
            }
        }

        args = line.getArgs();
        if (args.length != 3) {
            throw new Exception("");
        }

    } catch (Exception e) {
        System.out.println("Command Error: " + e.getMessage());
        new HelpFormatter().printHelp(80, "[options] <FrameBot Alignment file or Dir> <seqLineage> <out file> ",
                "", options,
                "seqLineage: a tab-delimited file with ref seqID and lineage, or fasta of ref seq with lineage as the descrption"
                        + "\nframeBot alignment file or Dir: frameBot alignment files "
                        + "\noutfile: output with the nearest match count group by phylum/class; and by match name");
    }
    TaxonAbundance.mapAbundance(new File(args[0]), new File(args[1]), args[2], coveragetMap, identity);
}

From source file:edu.asu.bscs.csiebler.calculatorrpc.CalcJavaClient.java

public static void main(String args[]) {
    try {//w w  w.ja  va 2 s .c  o  m
        String url = "http://127.0.0.1:8080/";
        if (args.length > 0) {
            url = args[0];
        }
        CalcJavaClient cjc = new CalcJavaClient(url);
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
        String inStr = stdin.readLine();
        StringTokenizer st = new StringTokenizer(inStr);
        String opn = st.nextToken();
        while (!opn.equalsIgnoreCase("end")) {
            if (opn.equalsIgnoreCase("+")) {
                double result = cjc.add(Double.parseDouble(st.nextToken()), Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("-")) {
                double result = cjc.subtract(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("*")) {
                double result = cjc.multiply(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            } else if (opn.equalsIgnoreCase("/")) {
                double result = cjc.divide(Double.parseDouble(st.nextToken()),
                        Double.parseDouble(st.nextToken()));
                System.out.println("response: " + result);
            }
            System.out.print("Enter end or {+|-|*|/} double double eg + 3 5 >");
            inStr = stdin.readLine();
            st = new StringTokenizer(inStr);
            opn = st.nextToken();
        }
    } catch (Exception e) {
        System.out.println("Oops, you didn't enter the right stuff");
    }
}