Example usage for java.lang Float valueOf

List of usage examples for java.lang Float valueOf

Introduction

In this page you can find the example usage for java.lang Float valueOf.

Prototype

@HotSpotIntrinsicCandidate
public static Float valueOf(float f) 

Source Link

Document

Returns a Float instance representing the specified float value.

Usage

From source file:jsonparser.ToJSON.java

public static void main(String args[]) throws FileNotFoundException, IOException {
    String text_file = "C:/Users/Kevin/Documents/NetBeansProjects/JsonParser/src/jsonparser/sample.txt";
    File file = new File(text_file);
    String s1, s2, s3;//from w w  w  .  j  a  v a 2s.  com

    s1 = (String) FileUtils.readLines(file).get(0);
    String split1[] = s1.split("=");
    contact_id = split1[1];

    s2 = (String) FileUtils.readLines(file).get(1);
    String split2[] = s2.split("=");
    confidence_level = Float.valueOf(split2[1]);

    s3 = (String) FileUtils.readLines(file).get(2);
    String split3[] = s3.split("=");
    if (split3[1].equals(" Found")) {
        is_matched = true;
    } else {
        is_matched = false;
    }

    System.out.println("Read from text file:");
    System.out.println("contact_id =" + contact_id);
    System.out.println("confidence_level = " + confidence_level);
    System.out.println("is_matched = " + is_matched);

    FacialRecognition fr = new FacialRecognition();
    fr.setContactID(contact_id);
    fr.setConfidenceLevel(confidence_level);
    fr.setIsMatched(is_matched);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    //convert java object to JSON format
    String json = gson.toJson(fr);

    //write JSON to a file
    try {
        //write converted json data to a file named "CountryGSON.json"  
        FileWriter writer = new FileWriter(
                "C:/Users/Kevin/Documents/NetBeansProjects/JsonParser/src/jsonparser/test.json", true);
        writer.write("" + json + ",\n");
        writer.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    //eventually need to change to send over back to client-side
    System.out.println();
    System.out.println("Coverting strings into JSON...");
    System.out.println(json);

}

From source file:ValueOfDemo.java

public static void main(String[] args) {

    // this program requires two arguments on the command line
    if (args.length == 2) {
        // convert strings to numbers
        float a = (Float.valueOf(args[0])).floatValue();
        float b = (Float.valueOf(args[1])).floatValue();

        // do some arithmetic
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    } else {/*from ww w .  j  a va  2 s .c  o m*/
        System.out.println("This program requires two command-line arguments.");
    }
}

From source file:NumberDemo.java

public static void main(String args[]) {
    Float one = new Float(14.78f - 13.78f);
    Float oneAgain = Float.valueOf("1.0");
    Double doubleOne = new Double(1.0);

    int difference = one.compareTo(oneAgain);

    if (difference == 0) {
        System.out.println("one is equal to oneAgain.");
    } else if (difference < 0) {
        System.out.println("one is less than oneAgain.");
    } else if (difference > 0) {
        System.out.println("one is greater than oneAgain.");
    }/*from w w  w .  j av  a 2 s. c  o m*/

    System.out.println("one is " + ((one.equals(doubleOne)) ? "equal" : "not equal") + " to doubleOne.");

}

From source file:ValueOfDemo.java

public static void main(String[] args) {

    //this program requires two arguments on the command line
    if (args.length == 2) {

        //convert strings to numbers
        float a = Float.valueOf(args[0]).floatValue();
        float b = Float.valueOf(args[1]).floatValue();

        //do some arithmetic
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    } else {/*w  ww.  j  a v  a  2  s. com*/
        System.out.println("This program requires two command-line arguments.");
    }
}

From source file:joshelser.as2015.query.Query.java

public static void main(String[] args) throws Exception {
    JCommander commander = new JCommander();
    final Opts options = new Opts();
    commander.addObject(options);/*from w ww.ja  va2s  . co m*/

    commander.setProgramName("Query");
    try {
        commander.parse(args);
    } catch (ParameterException ex) {
        commander.usage();
        System.err.println(ex.getMessage());
        System.exit(1);
    }

    ClientConfiguration conf = ClientConfiguration.loadDefault();
    if (null != options.clientConfFile) {
        conf = new ClientConfiguration(new PropertiesConfiguration(options.clientConfFile));
    }
    conf.withInstance(options.instanceName).withZkHosts(options.zookeepers);

    ZooKeeperInstance inst = new ZooKeeperInstance(conf);
    Connector conn = inst.getConnector(options.user, new PasswordToken(options.password));

    BatchScanner bs = conn.createBatchScanner(options.table, Authorizations.EMPTY, 16);
    try {
        bs.setRanges(Collections.singleton(new Range()));
        final Text categoryText = new Text("category");
        bs.fetchColumn(categoryText, new Text("name"));
        bs.fetchColumn(new Text("review"), new Text("score"));
        bs.fetchColumn(new Text("review"), new Text("userId"));

        bs.addScanIterator(new IteratorSetting(50, "wri", WholeRowIterator.class));
        final Text colf = new Text();
        Map<String, List<Integer>> scoresByUser = new HashMap<>();
        for (Entry<Key, Value> entry : bs) {
            SortedMap<Key, Value> row = WholeRowIterator.decodeRow(entry.getKey(), entry.getValue());
            Iterator<Entry<Key, Value>> iter = row.entrySet().iterator();
            if (!iter.hasNext()) {
                // row was empty
                continue;
            }
            Entry<Key, Value> categoryEntry = iter.next();
            categoryEntry.getKey().getColumnFamily(colf);
            if (!colf.equals(categoryText)) {
                throw new IllegalArgumentException("Unknown!");
            }
            if (!categoryEntry.getValue().toString().equals("books")) {
                // not a book review
                continue;
            }

            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewScore = iter.next();
            if (!iter.hasNext()) {
                continue;
            }
            Entry<Key, Value> reviewUserId = iter.next();

            String userId = reviewUserId.getValue().toString();
            if (userId.equals("unknown")) {
                // filter unknow user id
                continue;
            }

            List<Integer> scores = scoresByUser.get(userId);
            if (null == scores) {
                scores = new ArrayList<>();
                scoresByUser.put(userId, scores);
            }
            scores.add(Float.valueOf(reviewScore.getValue().toString()).intValue());
        }

        for (Entry<String, List<Integer>> entry : scoresByUser.entrySet()) {
            int sum = 0;
            for (Integer val : entry.getValue()) {
                sum += val;
            }

            System.out.println(entry.getKey() + " => " + new Float(sum) / entry.getValue().size());
        }
    } finally {
        bs.close();
    }
}

From source file:ms1quant.MS1Quant.java

/**
 * @param args the command line arguments MS1Quant parameterfile
 *//*  ww  w.j  a v a2s . com*/
public static void main(String[] args) throws Exception {

    BufferedReader reader = null;
    try {
        System.out.println(
                "=================================================================================================");
        System.out.println("Umpire MS1 quantification and feature detection analysis (version: "
                + UmpireInfo.GetInstance().Version + ")");
        if (args.length < 3 || !args[1].startsWith("-mode")) {
            System.out
                    .println("command : java -jar -Xmx10G MS1Quant.jar ms1quant.params -mode[1 or 2] [Option]");
            System.out.println("\n-mode");
            System.out.println("\t1:Single file mode--> mzXML_file PepXML_file");
            System.out.println("\t\tEx: -mode1 file1.mzXML file1.pep.xml");
            System.out.println(
                    "\t2:Folder mode--> mzXML_Folder PepXML_Folder, all generated csv tables will be merged into a single csv file");
            System.out.println("\t\tEx: -mode2 /data/mzxml/ /data/pepxml/");
            System.out.println("\nOptions");
            System.out.println(
                    "\t-C\tNo of concurrent files to be processed (only for folder mode), Ex. -C5, default:1");
            System.out.println("\t-p\tMinimum probability, Ex. -p0.9, default:0.9");
            System.out.println("\t-ID\tDetect identified feature only");
            System.out.println("\t-O\toutput folder, Ex. -O/data/");
            return;
        }
        ConsoleLogger consoleLogger = new ConsoleLogger();
        consoleLogger.SetConsoleLogger(Level.DEBUG);
        consoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "ms1quant_debug.log");
        Logger logger = Logger.getRootLogger();
        logger.debug("Command: " + Arrays.toString(args));
        logger.info("MS1Quant version: " + UmpireInfo.GetInstance().Version);

        String parameterfile = args[0];
        logger.info("Parameter file: " + parameterfile);
        File paramfile = new File(parameterfile);
        if (!paramfile.exists()) {
            logger.error("Parameter file " + paramfile.getAbsolutePath()
                    + " cannot be found. The program will exit.");
        }

        reader = new BufferedReader(new FileReader(paramfile.getAbsolutePath()));
        String line = "";
        InstrumentParameter param = new InstrumentParameter(InstrumentParameter.InstrumentType.TOF5600);
        int NoCPUs = 2;
        int NoFile = 1;
        param.DetermineBGByID = false;
        param.EstimateBG = true;

        //<editor-fold defaultstate="collapsed" desc="Read parameter file">
        while ((line = reader.readLine()) != null) {
            if (!"".equals(line) && !line.startsWith("#")) {
                logger.info(line);
                //System.out.println(line);
                if (line.split("=").length < 2) {
                    continue;
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                if (type.startsWith("para.")) {
                    type = type.replace("para.", "SE.");
                }
                String value = line.split("=")[1].trim();
                switch (type) {
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                //<editor-fold defaultstate="collapsed" desc="instrument parameters">

                case "SE.MS1PPM": {
                    param.MS1PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2PPM": {
                    param.MS2PPM = Float.parseFloat(value);
                    break;
                }
                case "SE.SN": {
                    param.SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MS2SN": {
                    param.MS2SNThreshold = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSIntensity": {
                    param.MinMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinMSMSIntensity": {
                    param.MinMSMSIntensity = Float.parseFloat(value);
                    break;
                }
                case "SE.MinRTRange": {
                    param.MinRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.MaxNoPeakCluster": {
                    param.MaxNoPeakCluster = Integer.parseInt(value);
                    param.MaxMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinNoPeakCluster": {
                    param.MinNoPeakCluster = Integer.parseInt(value);
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MinMS2NoPeakCluster": {
                    param.MinMS2NoPeakCluster = Integer.parseInt(value);
                    break;
                }
                case "SE.MaxCurveRTRange": {
                    param.MaxCurveRTRange = Float.parseFloat(value);
                    break;
                }
                case "SE.Resolution": {
                    param.Resolution = Integer.parseInt(value);
                    break;
                }
                case "SE.RTtol": {
                    param.RTtol = Float.parseFloat(value);
                    break;
                }
                case "SE.NoPeakPerMin": {
                    param.NoPeakPerMin = Integer.parseInt(value);
                    break;
                }
                case "SE.StartCharge": {
                    param.StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.EndCharge": {
                    param.EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2StartCharge": {
                    param.MS2StartCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.MS2EndCharge": {
                    param.MS2EndCharge = Integer.parseInt(value);
                    break;
                }
                case "SE.NoMissedScan": {
                    param.NoMissedScan = Integer.parseInt(value);
                    break;
                }
                case "SE.Denoise": {
                    param.Denoise = Boolean.valueOf(value);
                    break;
                }
                case "SE.EstimateBG": {
                    param.EstimateBG = Boolean.valueOf(value);
                    break;
                }
                case "SE.RemoveGroupedPeaks": {
                    param.RemoveGroupedPeaks = Boolean.valueOf(value);
                    break;
                }
                case "SE.MinFrag": {
                    param.MinFrag = Integer.parseInt(value);
                    break;
                }
                case "SE.IsoPattern": {
                    param.IsoPattern = Float.valueOf(value);
                    break;
                }
                case "SE.StartRT": {
                    param.startRT = Float.valueOf(value);
                }
                case "SE.EndRT": {
                    param.endRT = Float.valueOf(value);
                }

                //</editor-fold>
                }
            }
        }
        //</editor-fold>

        int mode = 1;
        if (args[1].equals("-mode2")) {
            mode = 2;
        } else if (args[1].equals("-mode1")) {
            mode = 1;
        } else {
            logger.error("-mode number not recongized. The program will exit.");
        }

        String mzXML = "";
        String pepXML = "";
        String mzXMLPath = "";
        String pepXMLPath = "";
        File mzXMLfile = null;
        File pepXMLfile = null;
        File mzXMLfolder = null;
        File pepXMLfolder = null;
        int idx = 0;
        if (mode == 1) {
            mzXML = args[2];
            logger.info("Mode1 mzXML file: " + mzXML);
            mzXMLfile = new File(mzXML);
            if (!mzXMLfile.exists()) {
                logger.error("Mode1 mzXML file " + mzXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            pepXML = args[3];
            logger.info("Mode1 pepXML file: " + pepXML);
            pepXMLfile = new File(pepXML);
            if (!pepXMLfile.exists()) {
                logger.error("Mode1 pepXML file " + pepXMLfile.getAbsolutePath()
                        + " cannot be found. The program will exit.");
                return;
            }
            idx = 4;
        } else if (mode == 2) {
            mzXMLPath = args[2];
            logger.info("Mode2 mzXML folder: " + mzXMLPath);
            mzXMLfolder = new File(mzXMLPath);
            if (!mzXMLfolder.exists()) {
                logger.error("Mode2 mzXML folder " + mzXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            pepXMLPath = args[3];
            logger.info("Mode2 pepXML folder: " + pepXMLPath);
            pepXMLfolder = new File(pepXMLPath);
            if (!pepXMLfolder.exists()) {
                logger.error("Mode2 pepXML folder " + pepXMLfolder.getAbsolutePath()
                        + " does not exist. The program will exit.");
                return;
            }
            idx = 4;
        }

        String outputfolder = "";
        float MinProb = 0f;
        for (int i = idx; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                if (args[i].equals("-ID")) {
                    param.TargetIDOnly = true;
                    logger.info("Detect ID feature only: true");
                }
                if (args[i].startsWith("-O")) {
                    outputfolder = args[i].substring(2);
                    logger.info("Output folder: " + outputfolder);

                    File outputfile = new File(outputfolder);
                    if (!outputfolder.endsWith("\\") | outputfolder.endsWith("/")) {
                        outputfolder += "/";
                    }
                    if (!outputfile.exists()) {
                        outputfile.mkdir();
                    }
                }
                if (args[i].startsWith("-C")) {
                    try {
                        NoFile = Integer.parseInt(args[i].substring(2));
                        logger.info("No of concurrent files: " + NoFile);
                    } catch (Exception ex) {
                        logger.error(args[i]
                                + " is not a correct integer format, will process only one file at a time.");
                    }
                }
                if (args[i].startsWith("-p")) {
                    try {
                        MinProb = Float.parseFloat(args[i].substring(2));
                        logger.info("probability threshold: " + MinProb);
                    } catch (Exception ex) {
                        logger.error(args[i] + " is not a correct format, will use 0 as threshold instead.");
                    }
                }
            }
        }

        reader.close();
        TandemParam tandemparam = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        PTMManager.GetInstance();

        if (param.TargetIDOnly) {
            param.EstimateBG = false;
            param.ApexDelta = 1.5f;
            param.NoMissedScan = 10;
            param.MiniOverlapP = 0.2f;
            param.RemoveGroupedPeaks = false;
            param.CheckMonoIsotopicApex = false;
            param.DetectByCWT = false;
            param.FillGapByBK = false;
            param.IsoCorrThreshold = -1f;
            param.SmoothFactor = 3;
        }

        if (mode == 1) {
            logger.info("Processing " + mzXMLfile.getAbsolutePath() + "....");
            long time = System.currentTimeMillis();
            LCMSPeakMS1 LCMS1 = new LCMSPeakMS1(mzXMLfile.getAbsolutePath(), NoCPUs);
            LCMS1.SetParameter(param);

            LCMS1.Resume = false;
            if (!param.TargetIDOnly) {
                LCMS1.CreatePeakFolder();
            }
            LCMS1.ExportPeakClusterTable = true;

            if (pepXMLfile.exists()) {
                tandemparam.InteractPepXMLPath = pepXMLfile.getAbsolutePath();
                LCMS1.ParsePepXML(tandemparam, MinProb);
                logger.info("No. of PSMs included: " + LCMS1.IDsummary.PSMList.size());
                logger.info("No. of Peptide ions included: " + LCMS1.IDsummary.GetPepIonList().size());
            }

            if (param.TargetIDOnly) {
                LCMS1.SaveSerializationFile = false;
            }

            if (param.TargetIDOnly || !LCMS1.ReadPeakCluster()) {
                LCMS1.PeakClusterDetection();
            }

            if (pepXMLfile.exists()) {
                LCMS1.AssignQuant(false);
                LCMS1.IDsummary.ExportPepID(outputfolder);
            }
            time = System.currentTimeMillis() - time;
            logger.info(LCMS1.ParentmzXMLName + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
            LCMS1.BaseClearAllPeaks();
            LCMS1.SetSpectrumParser(null);
            LCMS1.IDsummary = null;
            LCMS1 = null;
            System.gc();
        } else if (mode == 2) {

            LCMSID IDsummary = new LCMSID("", "", "");
            logger.info("Parsing all pepXML files in " + pepXMLPath + "....");
            for (File file : pepXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("pep.xml")
                        || file.getName().toLowerCase().endsWith("pepxml")) {
                    PepXMLParser pepXMLParser = new PepXMLParser(IDsummary, file.getAbsolutePath(), MinProb);
                }
            }
            HashMap<String, LCMSID> LCMSIDMap = IDsummary.GetLCMSIDFileMap();

            ExecutorService executorPool = null;
            executorPool = Executors.newFixedThreadPool(NoFile);

            logger.info("Processing all mzXML files in " + mzXMLPath + "....");
            for (File file : mzXMLfolder.listFiles()) {
                if (file.getName().toLowerCase().endsWith("mzxml")) {
                    LCMSID id = LCMSIDMap.get(FilenameUtils.getBaseName(file.getName()));
                    if (id == null || id.PSMList == null) {
                        logger.warn("No IDs found in :" + FilenameUtils.getBaseName(file.getName())
                                + ". Quantification for this file is skipped");
                        continue;
                    }
                    if (!id.PSMList.isEmpty()) {
                        MS1TargetQuantThread thread = new MS1TargetQuantThread(file, id, NoCPUs, outputfolder,
                                param);
                        executorPool.execute(thread);
                    }
                }
            }
            LCMSIDMap.clear();
            LCMSIDMap = null;
            IDsummary = null;
            executorPool.shutdown();
            try {
                executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
            } catch (InterruptedException e) {
                logger.info("interrupted..");
            }

            if (outputfolder == null | outputfolder.equals("")) {
                outputfolder = mzXMLPath;
            }

            logger.info("Merging PSM files..");
            File output = new File(outputfolder);
            FileWriter writer = new FileWriter(output.getAbsolutePath() + "/PSM_merge.csv");
            boolean header = false;
            for (File csvfile : output.listFiles()) {
                if (csvfile.getName().toLowerCase().endsWith("_psms.csv")) {
                    BufferedReader outreader = new BufferedReader(new FileReader(csvfile));
                    String outline = outreader.readLine();
                    if (!header) {
                        writer.write(outline + "\n");
                        header = true;
                    }
                    while ((outline = outreader.readLine()) != null) {
                        writer.write(outline + "\n");
                    }
                    outreader.close();
                    csvfile.delete();
                }
            }
            writer.close();
        }
        logger.info("MS1 quant module is complete.");
    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:Main.java

public static float changeToPx(String str) {
    return Float.valueOf(str) * 139;
}

From source file:Main.java

private static float getFloatFromDatabase(String rate) {
    return Float.valueOf(rate);
}

From source file:Main.java

public static int changeToPxOfInt(String str) {
    return (int) (Float.valueOf(str) * 139);

}

From source file:Main.java

public static float transformPercentToFloat(String formatString) {
    float floatResult = Float.valueOf((formatString.substring(0, formatString.indexOf("%")))) / 100;
    return floatResult;
}