Example usage for java.lang Float toString

List of usage examples for java.lang Float toString

Introduction

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

Prototype

public static String toString(float f) 

Source Link

Document

Returns a string representation of the float argument.

Usage

From source file:com.skratchdot.electribe.model.esx.provider.PatternItemProvider.java

/**
 * This returns the column text for the adapted class.
 * <!-- begin-user-doc -->/*from   w  w  w. j ava2  s.com*/
 * <!-- end-user-doc -->
 */
@Override
public String getColumnText(Object object, int columnIndex) {
    switch (columnIndex) {
    // Esx#
    case 0:
        return ((Pattern) object).getPatternNumberCurrent().toString();
    // Orig#
    case 1:
        return ((Pattern) object).getPatternNumberOriginal().toString();
    // Name
    case 2:
        return ((Pattern) object).getName();
    // Tempo
    case 3:
        return Float.toString(((Pattern) object).getTempo().getValue());
    // Swing
    case 4:
        return ((Pattern) object).getSwing().getLiteral();
    // Length
    case 5:
        return ((Pattern) object).getPatternLength().getLiteral();
    // Beat
    case 6:
        return ((Pattern) object).getBeat().getLiteral();
    // Roll
    case 7:
        return ((Pattern) object).getRollType().getLiteral();
    // FxChain
    case 8:
        return ((Pattern) object).getFxChain().getLiteral();
    // LastStep
    case 9:
        return ((Pattern) object).getLastStep().getLiteral();
    // ArpScale
    case 10:
        return ((Pattern) object).getArpeggiatorScale().getLiteral();
    // CenterNote
    case 11:
        return ((Pattern) object).getArpeggiatorCenterNote().getLiteral();
    // Fx1 Type
    case 12:
        return ((Pattern) object).getFxParameters().get(0).getEffectType().getLiteral();
    // Fx2 Type
    case 13:
        return ((Pattern) object).getFxParameters().get(1).getEffectType().getLiteral();
    // Fx3 Type
    case 14:
        return ((Pattern) object).getFxParameters().get(2).getEffectType().getLiteral();
    // Part 1
    case 15:
        return ((Pattern) object).getDrumParts().get(0).getSampleLabel();
    // Part 2
    case 16:
        return ((Pattern) object).getDrumParts().get(1).getSampleLabel();
    // Part 3
    case 17:
        return ((Pattern) object).getDrumParts().get(2).getSampleLabel();
    // Part 4
    case 18:
        return ((Pattern) object).getDrumParts().get(3).getSampleLabel();
    // Part 5
    case 19:
        return ((Pattern) object).getDrumParts().get(4).getSampleLabel();
    // Part 6a
    case 20:
        return ((Pattern) object).getDrumParts().get(5).getSampleLabel();
    // Part 6b
    case 21:
        return ((Pattern) object).getDrumParts().get(6).getSampleLabel();
    // Part 7a
    case 22:
        return ((Pattern) object).getDrumParts().get(7).getSampleLabel();
    // Part 7b
    case 23:
        return ((Pattern) object).getDrumParts().get(8).getSampleLabel();
    // Key 1
    case 24:
        return ((Pattern) object).getKeyboardParts().get(0).getSampleLabel();
    // Key 2
    case 25:
        return ((Pattern) object).getKeyboardParts().get(1).getSampleLabel();
    // Stretch 1
    case 26:
        return ((Pattern) object).getStretchSliceParts().get(0).getSampleLabel();
    // Stretch 2
    case 27:
        return ((Pattern) object).getStretchSliceParts().get(1).getSampleLabel();
    // Slice
    case 28:
        return ((Pattern) object).getStretchSliceParts().get(2).getSampleLabel();
    default:
        return getText(object);
    }
}

From source file:de.codesourcery.eve.skills.ui.components.impl.BlueprintBrowserComponent.java

private void renderRequirements(final Activity activity, final Blueprint bp, final StringBuilder text) {

    final Requirements reqs = bp.getRequirementsFor(activity);

    text.append("\n---------------- Materials [ " + activity.getName() + " ] ---------------\n\n");

    final List<RequiredMaterial> sortedMats = new ArrayList<>(reqs.getRequiredMaterials());
    Collections.sort(sortedMats, new Comparator<RequiredMaterial>() {

        @Override//  ww w  .ja v  a2  s.c  o m
        public int compare(RequiredMaterial o1, RequiredMaterial o2) {
            if (o1.isSubjectToManufacturingWaste() && !o2.isSubjectToManufacturingWaste()) {
                return -1;
            }
            if (!o1.isSubjectToManufacturingWaste() && o2.isSubjectToManufacturingWaste()) {
                return 1;
            }
            return o1.getType().getName().compareTo(o2.getType().getName());
        }
    });

    final StringTablePrinter tablePrinter = new StringTablePrinter("Item", "Initial", "You", "Waste %",
            "dmg % / run");

    final DecimalFormat FORMAT = new DecimalFormat("##0.00");

    for (RequiredMaterial mat : sortedMats) {

        final float initial = mat.getQuantity() * getRequestedRuns();
        final float you = calcRequiredMaterial(bp, mat);

        float waste = 100.0f * (you / initial) - 100.0f;
        if (waste < 0.0f) {
            waste = 0.0f;
        }

        final String sInitial = Float.toString(initial);
        final String sWaste = FORMAT.format(waste);
        final String sYou = Float.toString(you);

        if (activity == Activity.MANUFACTURING) {
            String sDmg = "";
            if (mat.getDamagePerJob() != 1.0d && mat.getDamagePerJob() > 0.0d) {
                sDmg = Double.toString(mat.getDamagePerJob() * 100.0);
            }

            String wasteString = "";
            if (mat.isSubjectToStationWaste()) {
                wasteString += "(1)";
            }
            if (mat.isSubjectToSkillWaste()) {
                wasteString += "(2)";
            }
            if (mat.isSubjectToBPMWaste()) {
                wasteString += "(3)";
            }

            if (!"".equals(wasteString)) {
                tablePrinter.add(mat.getType().getName() + " " + wasteString, sInitial, sYou, sWaste, sDmg);
            } else {
                tablePrinter.add(mat.getType().getName(), sInitial, sYou, sWaste, sDmg);
            }
        } else {
            tablePrinter.add(mat.getType().getName(), sInitial, "--", "--", "--");
        }
    }

    tablePrinter.setPaddingForAllColumns(Padding.LEFT).padRight(0);
    text.append(tablePrinter.toString());

    if (activity == Activity.MANUFACTURING) {
        text.append("\n(1) Material is subject to station waste.");
        text.append("\n(2) Material is subject to character PE level waste.");
        text.append("\n(3) Material is subject to blueprint ME level waste.\n");
    }

    final List<Prerequisite> requiredSkills = reqs.getRequiredSkills();

    text.append("\n---------------- Skills [ " + activity.getName() + " ] ---------------\n\n");

    for (Prerequisite r : requiredSkills) {

        final String hasSkill = meetsRequirement(r);
        appendLine(text, r.getSkill().getName(), "" + r.getRequiredLevel() + hasSkill);
    }
}

From source file:com.moviejukebox.plugin.ScriptableScraperPlugin.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void runSections(Collection<SectionContentSS> sections, String sectionName) {
    try {/*from ww  w .ja v  a  2s .co  m*/
        if (debug) {
            LOG.debug("runSections: {}", sectionName);
        }
        String value;
        for (SectionContentSS content : sections) {
            SectionSS cSection = (SectionSS) content;
            for (int looperItem = 0; looperItem < cSection.getItems().size(); looperItem++) {
                ItemSS item = cSection.getItem(looperItem);
                String type = item.getType();
                String key = item.getKey();
                if (debug) {
                    LOG.debug("item: {} : {}", type, key);
                }
                if ("retrieve".equals(type)) {
                    RetrieveSS retrieve = cSection.getRetrieve(key);
                    if (retrieve != null) {
                        String url = cSection.compileValue(retrieve.getURL());
                        if (StringUtils.isNotBlank(retrieve.getCookies())) {
                            String domain = new URL(url).getHost();
                            List<String> values;
                            for (String cookie : Arrays.asList(retrieve.getCookies().split("&"))) {
                                values = Arrays.asList(cookie.split("="));
                                if (debug) {
                                    LOG.debug("retrieve page from domain '{}' with name '{}' and value'{}'",
                                            domain, values.get(0), values.get(1));
                                }
                                webBrowser.putCookie(domain, values.get(0), values.get(1));
                            }
                        }
                        if (StringTools.isValidString(url)) {
                            String page = "";
                            for (int looper = 0; looper <= retrieve.getRetries(); looper++) {
                                page = webBrowser.request(url, retrieve.getEncoding()).replaceAll("\\r", "")
                                        .replaceAll("\\n", " ");
                                if (StringTools.isValidString(page)) {
                                    break;
                                }
                            }
                            if (StringTools.isNotValidString(page)) {
                                LOG.error("Page does not retrieved for '{}' with URL {}", key, url);
                                page = "";
                            }
                            cSection.setGlobalVariable(cSection.compileValue(key), page);
                        }
                    }
                } else if ("set".equals(type)) {
                    value = cSection.getSet(key);
                    if (debug) {
                        LOG.debug("getSet: key: {} value: {}", key, value);
                    }
                    key = cSection.compileValue(key);
                    value = cSection.compileValue(value);
                    cSection.setGlobalVariable(key, value);
                } else if ("parse".equals(type)) {
                    ParseSS parse = cSection.getParse(key);
                    if (parse != null) {
                        key = cSection.compileValue(key);
                        value = cSection.parseInput(cSection.compileValue(parse.getInput()),
                                cSection.compileValue(parse.getRegex()));
                        cSection.setGlobalVariable(key, value);
                    }
                } else if ("math".equals(type)) {
                    MathSS math = cSection.getMath(key);
                    if (math != null) {
                        boolean found = false;
                        float res = -0.000001f;
                        float value1 = Float.parseFloat(cSection.compileValue(math.getValue1()));
                        float value2 = Float.parseFloat(cSection.compileValue(math.getValue2()));
                        String typeName = math.getType();
                        if (null != typeName) {
                            switch (typeName) {
                            case "add":
                                res = value1 + value2;
                                found = true;
                                break;
                            case "subtract":
                                res = value1 - value2;
                                found = true;
                                break;
                            case "multiply":
                                res = value1 * value2;
                                found = true;
                                break;
                            case "divide":
                                if (value2 > 0f) {
                                    res = value1 / value2;
                                } else {
                                    res = 0f;
                                }
                                found = true;
                                break;
                            default:
                                LOG.error("Unknown math type: {}", typeName);
                                break;
                            }
                        }

                        if (found) {
                            if ("float".equals(math.getResultType())) {
                                value = Float.toString(res);
                            } else {
                                value = Integer.toString(Math.round(res));
                            }
                            cSection.setGlobalVariable(cSection.compileValue(key), value);
                        }
                    }
                } else if ("content".equals(type)) {
                    SectionSS section = (SectionSS) cSection.getContent(Integer.parseInt(key));
                    String name = section.getName();
                    if (debug) {
                        LOG.debug("subsection: {}", name);
                    }
                    if ("if".equals(name)) {
                        String condition = section.getAttribute("test");
                        if (StringTools.isValidString(condition) && section.testCondition(condition)) {
                            runSections((Collection) Arrays.asList(section), sectionName);
                        }
                    } else if ("loop".equals(name)) {
                        String sName = section.getAttribute("name");
                        value = section.getAttribute("on");
                        if (StringTools.isValidString(sName) && StringTools.isValidString(value)) {
                            if (section.hasVariable(value)) {
                                value = section.getVariable(value);
                                if (debug) {
                                    LOG.debug("loop: value: {}", value);
                                }
                                if (StringTools.isValidString(value)) {
                                    List<String> values = Arrays
                                            .asList(value.split(ScriptableScraper.ARRAY_GROUP_DIVIDER));
                                    int limit = values.size();

                                    value = section.getAttribute("limit");
                                    if (StringTools.isValidString(value) && (limit > Integer.parseInt(value))) {
                                        limit = Integer.parseInt(value);
                                    }

                                    if (limit > 0) {
                                        for (int looper = 0; looper < limit; looper++) {
                                            if (debug) {
                                                LOG.debug("loop: {}: {}", sName, values.get(looper));
                                            }
                                            section.setVariable(sName, values.get(looper));
                                            section.setVariable("count", Integer.toString(looper));
                                            runSections((Collection) Arrays.asList(section), sectionName);
                                        }
                                    }
                                }
                            } else {
                                LOG.error("Does not exist '{}' for 'loop' name=\"{}\"",
                                        section.getAttribute("on"), sName);
                            }
                        } else {
                            LOG.error("Wrong attribute 'on' value '{}' of 'loop' name=\"{}\"",
                                    section.getAttribute("on"), sName);
                        }
                    }
                }
            }
        }
    } catch (IOException error) {
        LOG.error("Failed run section : {}", sectionName);
        LOG.error("Error : {}", error.getMessage());
    }
}

From source file:mt.listeners.InteractiveRANSAC.java

public void CardTable() {
    this.lambdaSB = new Scrollbar(Scrollbar.HORIZONTAL, this.lambdaInt, 1, MIN_SLIDER, MAX_SLIDER + 1);

    maxSlopeSB.setValue(utility.Slicer.computeScrollbarPositionFromValue((float) maxSlope,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize));

    maxDistSB.setValue(/*from   w  w w. j  a v a2 s.  c o  m*/
            utility.Slicer.computeScrollbarPositionFromValue(maxDist, MIN_Gap, MAX_Gap, scrollbarSize));

    minInliersSB.setValue(utility.Slicer.computeScrollbarPositionFromValue(minInliers, MIN_Inlier, MAX_Inlier,
            scrollbarSize));
    maxErrorSB.setValue(
            utility.Slicer.computeScrollbarPositionFromValue(maxError, MIN_ERROR, MAX_ERROR, scrollbarSize));

    minSlopeSB.setValue(utility.Slicer.computeScrollbarPositionFromValue((float) minSlope,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize));

    lambdaLabel = new Label("Linearity (fraction) = " + new DecimalFormat("#.##").format(lambda), Label.CENTER);
    maxErrorLabel = new Label("Maximum Error (px) = " + new DecimalFormat("#.##").format(maxError) + "      ",
            Label.CENTER);
    minInliersLabel = new Label(
            "Minimum No. of timepoints (tp) = " + new DecimalFormat("#.##").format(minInliers), Label.CENTER);
    maxDistLabel = new Label("Maximum Gap (tp) = " + new DecimalFormat("#.##").format(maxDist), Label.CENTER);

    minSlopeLabel = new Label("Min. Segment Slope (px/tp) = " + new DecimalFormat("#.##").format(minSlope),
            Label.CENTER);
    maxSlopeLabel = new Label("Max. Segment Slope (px/tp) = " + new DecimalFormat("#.##").format(maxSlope),
            Label.CENTER);
    maxResLabel = new Label(
            "MT is rescued if the start of event# i + 1 > start of event# i by px =  " + this.restolerance,
            Label.CENTER);

    CardLayout cl = new CardLayout();
    Object[] colnames = new Object[] { "Track File", "Growth velocity", "Shrink velocity", "Growth events",
            "Shrink events", "fcat", "fres", "Error" };

    Object[][] rowvalues = new Object[0][colnames.length];

    if (inputfiles != null) {
        rowvalues = new Object[inputfiles.length][colnames.length];
        for (int i = 0; i < inputfiles.length; ++i) {

            rowvalues[i][0] = inputfiles[i].getName();
        }
    }

    table = new JTable(rowvalues, colnames);

    table.setFillsViewportHeight(true);

    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.isOpaque();
    int size = 100;
    table.getColumnModel().getColumn(0).setPreferredWidth(size);
    table.getColumnModel().getColumn(1).setPreferredWidth(size);
    table.getColumnModel().getColumn(2).setPreferredWidth(size);
    table.getColumnModel().getColumn(3).setPreferredWidth(size);
    table.getColumnModel().getColumn(4).setPreferredWidth(size);
    table.getColumnModel().getColumn(5).setPreferredWidth(size);
    table.getColumnModel().getColumn(6).setPreferredWidth(size);
    table.getColumnModel().getColumn(7).setPreferredWidth(size);
    maxErrorField = new TextField(5);
    maxErrorField.setText(Float.toString(maxError));

    minInlierField = new TextField(5);
    minInlierField.setText(Float.toString(minInliers));

    maxGapField = new TextField(5);
    maxGapField.setText(Float.toString(maxDist));

    maxSlopeField = new TextField(5);
    maxSlopeField.setText(Float.toString(maxSlope));

    minSlopeField = new TextField(5);
    minSlopeField.setText(Float.toString(minSlope));

    maxErrorSB.setSize(new Dimension(SizeX, 20));
    minSlopeSB.setSize(new Dimension(SizeX, 20));
    minInliersSB.setSize(new Dimension(SizeX, 20));
    maxDistSB.setSize(new Dimension(SizeX, 20));
    maxSlopeSB.setSize(new Dimension(SizeX, 20));
    maxErrorField.setSize(new Dimension(SizeX, 20));
    minInlierField.setSize(new Dimension(SizeX, 20));
    maxGapField.setSize(new Dimension(SizeX, 20));
    minSlopeField.setSize(new Dimension(SizeX, 20));
    maxSlopeField.setSize(new Dimension(SizeX, 20));

    scrollPane = new JScrollPane(table);
    scrollPane.setMinimumSize(new Dimension(300, 200));
    scrollPane.setPreferredSize(new Dimension(300, 200));

    scrollPane.getViewport().add(table);
    scrollPane.setAutoscrolls(true);

    // Location
    panelFirst.setLayout(layout);
    panelSecond.setLayout(layout);
    PanelSavetoFile.setLayout(layout);
    PanelParameteroptions.setLayout(layout);
    Panelfunction.setLayout(layout);
    Panelslope.setLayout(layout);
    PanelCompileRes.setLayout(layout);
    PanelDirectory.setLayout(layout);

    panelCont.setLayout(cl);

    panelCont.add(panelFirst, "1");
    panelCont.add(panelSecond, "2");

    panelFirst.setName("Ransac fits for rates and frequency analysis");
    c.insets = new Insets(5, 5, 5, 5);
    c.anchor = GridBagConstraints.BOTH;
    c.ipadx = 35;

    inputLabelT = new Label("Compute length distribution at time: ");
    inputLabelTcont = new Label("(Press Enter to start computation) ");
    inputFieldT = new TextField(5);
    inputFieldT.setText("1");

    c.gridwidth = 10;
    c.gridheight = 10;
    c.gridy = 1;
    c.gridx = 0;

    String[] Method = { "Linear Function only", "Linearized Quadratic function", "Linearized Cubic function" };
    JComboBox<String> ChooseMethod = new JComboBox<String>(Method);

    final Checkbox findCatastrophe = new Checkbox("Detect Catastrophies", this.detectCatastrophe);
    final Checkbox findmanualCatastrophe = new Checkbox("Detect Catastrophies without fit",
            this.detectmanualCatastrophe);
    final Scrollbar minCatDist = new Scrollbar(Scrollbar.HORIZONTAL, this.minDistCatInt, 1, MIN_SLIDER,
            MAX_SLIDER + 1);
    final Scrollbar maxRes = new Scrollbar(Scrollbar.HORIZONTAL, this.restoleranceInt, 1, MIN_SLIDER,
            MAX_SLIDER + 1);
    final Label minCatDistLabel = new Label("Min. Catastrophy height (tp) = " + this.minDistanceCatastrophe,
            Label.CENTER);
    final Button done = new Button("Done");
    final Button batch = new Button("Save Parameters for Batch run");
    final Button cancel = new Button("Cancel");
    final Button Compile = new Button("Compute rates and freq. till current file");
    final Button AutoCompile = new Button("Auto Compute Velocity and Frequencies");
    final Button Measureserial = new Button("Select directory of MTrack generated files");
    final Button WriteLength = new Button("Compute length distribution at framenumber : ");
    final Button WriteStats = new Button("Compute lifetime and mean length distribution");
    final Button WriteAgain = new Button("Save Velocity and Frequencies to File");

    PanelDirectory.add(Measureserial, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelDirectory.add(scrollPane, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    PanelDirectory.setBorder(selectdirectory);
    PanelDirectory.setPreferredSize(new Dimension(SizeX, SizeY));
    panelFirst.add(PanelDirectory, new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxerror = new SliderBoxGUI(errorstring, maxErrorSB, maxErrorField, maxErrorLabel,
            scrollbarSize, maxError, MAX_ERROR);

    PanelParameteroptions.add(combomaxerror.BuildDisplay(), new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomininlier = new SliderBoxGUI(inlierstring, minInliersSB, minInlierField, minInliersLabel,
            scrollbarSize, minInliers, MAX_Inlier);

    PanelParameteroptions.add(combomininlier.BuildDisplay(), new GridBagConstraints(0, 2, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxdist = new SliderBoxGUI(maxgapstring, maxDistSB, maxGapField, maxDistLabel,
            scrollbarSize, maxDist, MAX_Gap);

    PanelParameteroptions.add(combomaxdist.BuildDisplay(), new GridBagConstraints(0, 3, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.add(ChooseMethod, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0,
            GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.add(lambdaSB, new GridBagConstraints(0, 5, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    PanelParameteroptions.add(lambdaLabel, new GridBagConstraints(0, 6, 3, 1, 0.0, 0.0,
            GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelParameteroptions.setPreferredSize(new Dimension(SizeX, SizeY));
    PanelParameteroptions.setBorder(selectparam);
    panelFirst.add(PanelParameteroptions, new GridBagConstraints(3, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combominslope = new SliderBoxGUI(minslopestring, minSlopeSB, minSlopeField, minSlopeLabel,
            scrollbarSize, (float) minSlope, (float) MAX_ABS_SLOPE);

    Panelslope.add(combominslope.BuildDisplay(), new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    SliderBoxGUI combomaxslope = new SliderBoxGUI(maxslopestring, maxSlopeSB, maxSlopeField, maxSlopeLabel,
            scrollbarSize, (float) maxSlope, (float) MAX_ABS_SLOPE);

    Panelslope.add(combomaxslope.BuildDisplay(), new GridBagConstraints(0, 2, 3, 1, 0.0, 0.0,
            GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, insets, 0, 0));

    Panelslope.add(findCatastrophe, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(findmanualCatastrophe, new GridBagConstraints(4, 4, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(minCatDist, new GridBagConstraints(0, 5, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.add(minCatDistLabel, new GridBagConstraints(0, 6, 3, 1, 0.0, 0.0, GridBagConstraints.NORTH,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));
    Panelslope.setBorder(selectslope);
    Panelslope.setPreferredSize(new Dimension(SizeX, SizeY));

    panelFirst.add(Panelslope, new GridBagConstraints(3, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(AutoCompile, new GridBagConstraints(0, 0, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(WriteLength, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(inputFieldT, new GridBagConstraints(3, 1, 3, 1, 0.1, 0.0, GridBagConstraints.CENTER,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.add(WriteStats, new GridBagConstraints(0, 4, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    PanelCompileRes.setPreferredSize(new Dimension(SizeX, SizeY));

    PanelCompileRes.setBorder(compileres);

    panelFirst.add(PanelCompileRes, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.EAST,
            GridBagConstraints.HORIZONTAL, insets, 0, 0));

    if (inputfiles != null) {

        table.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() >= 1) {

                    if (!jFreeChartFrame.isVisible())
                        jFreeChartFrame = Tracking.display(chart, new Dimension(500, 500));
                    JTable target = (JTable) e.getSource();
                    row = target.getSelectedRow();
                    // do some action if appropriate column
                    if (row > 0)
                        displayclicked(row);
                    else
                        displayclicked(0);
                }
            }
        });
    }

    maxErrorSB.addAdjustmentListener(new ErrorListener(this, maxErrorLabel, errorstring, MIN_ERROR, MAX_ERROR,
            scrollbarSize, maxErrorSB));

    minInliersSB.addAdjustmentListener(new MinInlierListener(this, minInliersLabel, inlierstring, MIN_Inlier,
            MAX_Inlier, scrollbarSize, minInliersSB));

    maxDistSB.addAdjustmentListener(
            new MaxDistListener(this, maxDistLabel, maxgapstring, MIN_Gap, MAX_Gap, scrollbarSize, maxDistSB));

    ChooseMethod.addActionListener(new FunctionItemListener(this, ChooseMethod));
    lambdaSB.addAdjustmentListener(new LambdaListener(this, lambdaLabel, lambdaSB));
    minSlopeSB.addAdjustmentListener(new MinSlopeListener(this, minSlopeLabel, minslopestring,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize, minSlopeSB));

    maxSlopeSB.addAdjustmentListener(new MaxSlopeListener(this, maxSlopeLabel, maxslopestring,
            (float) MIN_ABS_SLOPE, (float) MAX_ABS_SLOPE, scrollbarSize, maxSlopeSB));
    findCatastrophe.addItemListener(
            new CatastrophyCheckBoxListener(this, findCatastrophe, minCatDistLabel, minCatDist));
    findmanualCatastrophe.addItemListener(
            new ManualCatastrophyCheckBoxListener(this, findmanualCatastrophe, minCatDistLabel, minCatDist));
    minCatDist.addAdjustmentListener(new MinCatastrophyDistanceListener(this, minCatDistLabel, minCatDist));
    Measureserial.addActionListener(new MeasureserialListener(this));
    Compile.addActionListener(new CompileResultsListener(this));
    AutoCompile.addActionListener(new AutoCompileResultsListener(this));
    WriteLength.addActionListener(new WriteLengthListener(this));
    WriteStats.addActionListener(new WriteStatsListener(this));
    WriteAgain.addActionListener(new WriteRatesListener(this));
    done.addActionListener(new FinishButtonListener(this, false));
    batch.addActionListener(new RansacBatchmodeListener(this));
    cancel.addActionListener(new FinishButtonListener(this, true));
    inputFieldT.addTextListener(new LengthdistroListener(this));

    maxSlopeField.addTextListener(new MaxSlopeLocListener(this, false));
    minSlopeField.addTextListener(new MinSlopeLocListener(this, false));
    maxErrorField.addTextListener(new ErrorLocListener(this, false));
    minInlierField.addTextListener(new MinInlierLocListener(this, false));
    maxGapField.addTextListener(new MaxDistLocListener(this, false));

    panelFirst.setVisible(true);
    functionChoice = 0;

    cl.show(panelCont, "1");

    Cardframe.add(panelCont, BorderLayout.CENTER);

    setFunction();
    Cardframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    Cardframe.pack();
    Cardframe.setVisible(true);
    Cardframe.pack();

}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowPerformances.java

@Override
public void run(CommandLine line) throws Exception {
    Path outputCsvFile = Paths.get(line.getOptionValue("csv-file"));
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    List<String> workflowsIds = new ArrayList<String>();
    if (line.hasOption("workflow"))
        workflowsIds.add(line.getOptionValue("workflow"));
    else if (line.hasOption("workflows"))
        workflowsIds = Arrays.asList(line.getOptionValue("workflows").split(","));
    else if (line.hasOption("basecase")) {
        DateTime basecaseDate = DateTime.parse(line.getOptionValue("basecase"));
        workflowsIds = onlinedb.listWorkflows(basecaseDate).stream().map(OnlineWorkflowDetails::getWorkflowId)
                .collect(Collectors.toList());
    } else if (line.hasOption("basecases-interval")) {
        Interval basecasesInterval = Interval.parse(line.getOptionValue("basecases-interval"));
        workflowsIds = onlinedb.listWorkflows(basecasesInterval).stream()
                .map(OnlineWorkflowDetails::getWorkflowId).collect(Collectors.toList());
    } else {//from   ww  w  . j  av a2s.  c o m
        System.out.println("You must specify workflow(s) or basecase(s)");
        return;
    }
    Collections.sort(workflowsIds, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    System.out.println("Printing performances of workflows " + workflowsIds);
    CsvWriter cvsWriter = null;
    try (FileWriter content = new FileWriter(outputCsvFile.toFile())) {
        cvsWriter = new CsvWriter(content, ',');
        String[] headers = new String[25];
        int i = 0;
        headers[i++] = "workflow_id";
        headers[i++] = "basecase";
        headers[i++] = "secure_contingencies";
        headers[i++] = "unsecure_contingencies";
        headers[i++] = "unsecure_contingencies_ratio";
        headers[i++] = "secure_contingencies_ratio";
        headers[i++] = "unsecure_secure_contingencies_ratio";
        headers[i++] = "wca_missed_alarms";
        headers[i++] = "wca_missed_alarms_lst";
        headers[i++] = "wca_false_alarms";
        headers[i++] = "wca_false_alarms_lst";
        headers[i++] = "wca_accuracy";
        headers[i++] = "wca_efficiency";
        headers[i++] = "mcla_missed_alarms";
        headers[i++] = "mcla_missed_alarms_lst";
        headers[i++] = "mcla_false_alarms";
        headers[i++] = "mcla_false_alarms_lst";
        headers[i++] = "mcla_accuracy";
        headers[i++] = "mcla_efficiency";
        headers[i++] = "wf_missed_alarms";
        headers[i++] = "wf_missed_alarms_lst";
        headers[i++] = "wf_false_alarms";
        headers[i++] = "wf_false_alarms_lst";
        headers[i++] = "wf_accuracy";
        headers[i++] = "wf_efficiency";
        cvsWriter.writeRecord(headers);
        // cycle over the workflows
        for (String workflowId : workflowsIds) {
            try {
                System.out.println("\nPrinting performances of workflow " + workflowId);
                OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId);
                if (parameters != null && parameters.validation()) {
                    OnlineWorkflowResults wfResults = onlinedb.getResults(workflowId);
                    Map<String, Boolean> contigencySecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyWCASecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyMCLASecure = new HashMap<String, Boolean>();
                    Map<String, Boolean> contigencyWfSecure = new HashMap<String, Boolean>();
                    Map<String, Map<SecurityIndexType, Boolean>> contigencyPhenomenaSecure = new HashMap<String, Map<SecurityIndexType, Boolean>>();
                    Map<String, Map<SecurityIndexType, Boolean>> contigencyPhenomenaMCLASecure = new HashMap<String, Map<SecurityIndexType, Boolean>>();
                    int unsecureContingencies = 0;
                    int secureContingencies = 0;
                    int wcaFalseAlarms = 0;
                    List<String> wcaFalseAlarmsList = new ArrayList<String>();
                    int wcaMissedAlarms = 0;
                    List<String> wcaMissedAlarmsList = new ArrayList<String>();
                    int mclaFalseAlarms = 0;
                    List<String> mclaFalseAlarmsList = new ArrayList<String>();
                    int mclaMissedAlarms = 0;
                    List<String> mclaMissedAlarmsList = new ArrayList<String>();
                    int wfFalseAlarms = 0;
                    List<String> wfFalseAlarmsList = new ArrayList<String>();
                    int wfMissedAlarms = 0;
                    List<String> wfMissedAlarmsList = new ArrayList<String>();
                    if (wfResults != null) {
                        if (!wfResults.getUnsafeContingencies().isEmpty()) {
                            Network basecase = onlinedb.getState(workflowId, 0);
                            String basecaseId = basecase.getId();
                            OnlineWorkflowWcaResults wfWcaResults = onlinedb.getWcaResults(workflowId);
                            OnlineWorkflowRulesResults wfRulesResults = onlinedb.getRulesResults(workflowId);
                            SecurityIndexType[] securityIndexTypes = parameters.getSecurityIndexes() == null
                                    ? SecurityIndexType.values()
                                    : parameters.getSecurityIndexes().toArray(
                                            new SecurityIndexType[parameters.getSecurityIndexes().size()]);
                            for (String contingencyId : wfResults.getUnsafeContingencies()) {
                                // initialize values
                                contigencySecure.put(contingencyId, true);
                                if (wfWcaResults.getClusterIndex(contingencyId) == 1)
                                    contigencyWCASecure.put(contingencyId, true);
                                else
                                    contigencyWCASecure.put(contingencyId, false);
                                contigencyMCLASecure.put(contingencyId, true);
                                Map<SecurityIndexType, Boolean> phenomenaSecure = new HashMap<SecurityIndexType, Boolean>();
                                Map<SecurityIndexType, Boolean> phenomenaMCLASecure = new HashMap<SecurityIndexType, Boolean>();
                                for (SecurityIndexType securityIndexType : securityIndexTypes) {
                                    phenomenaSecure.put(securityIndexType, true);
                                    phenomenaMCLASecure.put(securityIndexType, true);
                                }
                                contigencyPhenomenaSecure.put(contingencyId, phenomenaSecure);
                                contigencyPhenomenaMCLASecure.put(contingencyId, phenomenaMCLASecure);
                                // compute values
                                for (Integer stateId : wfResults.getUnstableStates(contingencyId)) {
                                    Map<String, Boolean> securityIndexes = wfResults
                                            .getIndexesData(contingencyId, stateId);
                                    Map<String, Boolean> securityRules = wfRulesResults
                                            .getStateResults(contingencyId, stateId);
                                    for (SecurityIndexType securityIndexType : securityIndexTypes) {
                                        if (securityIndexes.containsKey(securityIndexType.getLabel())
                                                && !securityIndexes.get(securityIndexType.getLabel())) {
                                            contigencySecure.put(contingencyId, false);
                                            contigencyPhenomenaSecure.get(contingencyId).put(securityIndexType,
                                                    false);
                                        }
                                        if (securityRules.containsKey(securityIndexType.getLabel())
                                                && !securityRules.get(securityIndexType.getLabel())) {
                                            contigencyMCLASecure.put(contingencyId, false);
                                            contigencyPhenomenaMCLASecure.get(contingencyId)
                                                    .put(securityIndexType, false);
                                        }
                                    }
                                }
                                if (contigencyWCASecure.get(contingencyId)
                                        || (!contigencyWCASecure.get(contingencyId)
                                                && contigencyMCLASecure.get(contingencyId)))
                                    contigencyWfSecure.put(contingencyId, true);
                                else
                                    contigencyWfSecure.put(contingencyId, false);
                                // compute data for performances
                                if (contigencySecure.get(contingencyId))
                                    secureContingencies++;
                                else
                                    unsecureContingencies++;
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyWCASecure.get(contingencyId)) {
                                    wcaMissedAlarms++;
                                    wcaMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyWCASecure.get(contingencyId)) {
                                    wcaFalseAlarms++;
                                    wcaFalseAlarmsList.add(contingencyId);
                                }
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyMCLASecure.get(contingencyId)) {
                                    mclaMissedAlarms++;
                                    mclaMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyMCLASecure.get(contingencyId)) {
                                    mclaFalseAlarms++;
                                    mclaFalseAlarmsList.add(contingencyId);
                                }
                                if (!contigencySecure.get(contingencyId)
                                        && contigencyWfSecure.get(contingencyId)) {
                                    wfMissedAlarms++;
                                    wfMissedAlarmsList.add(contingencyId);
                                }
                                if (contigencySecure.get(contingencyId)
                                        && !contigencyWfSecure.get(contingencyId)) {
                                    wfFalseAlarms++;
                                    wfFalseAlarmsList.add(contingencyId);
                                }
                            }
                            // compute performances
                            float wcaAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) wcaMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float wcaEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) wcaFalseAlarms / (float) secureContingencies)) * 100f;
                            float mclaAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) mclaMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float mclaEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) mclaFalseAlarms / (float) secureContingencies)) * 100f;
                            float wfAccuracy = (unsecureContingencies == 0) ? 100
                                    : (1f - ((float) wfMissedAlarms / (float) unsecureContingencies)) * 100f;
                            float wfEfficiency = (secureContingencies == 0) ? 100
                                    : (1f - ((float) wfFalseAlarms / (float) secureContingencies)) * 100f;
                            float unsecureRatio = (float) unsecureContingencies
                                    / (float) (secureContingencies + unsecureContingencies);
                            float secureRatio = (float) secureContingencies
                                    / (float) (secureContingencies + unsecureContingencies);
                            float secureUnsecureRatio = (secureContingencies == 0) ? Float.NaN
                                    : (float) unsecureContingencies / (float) secureContingencies;
                            //                     System.out.println("contigencySecure: " + contigencySecure);
                            //                     System.out.println("contigencyWCASecure: " + contigencyWCASecure);
                            //                     System.out.println("contigencyMCLASecure: " + contigencyMCLASecure);
                            //                     System.out.println("contigencyWfSecure: " + contigencyWfSecure);
                            //                     System.out.println("contigencyPhenomenaSecure: " + contigencyPhenomenaSecure);
                            //                     System.out.println("contigencyPhenomenaMCLASecure: " + contigencyPhenomenaMCLASecure);
                            // print performances
                            String[] values = new String[25];
                            i = 0;
                            values[i++] = workflowId;
                            values[i++] = basecaseId;
                            values[i++] = Integer.toString(secureContingencies);
                            values[i++] = Integer.toString(unsecureContingencies);
                            values[i++] = Float.toString(unsecureRatio);
                            values[i++] = Float.toString(secureRatio);
                            values[i++] = Float.toString(secureUnsecureRatio);
                            values[i++] = Integer.toString(wcaMissedAlarms);
                            values[i++] = wcaMissedAlarmsList.toString();
                            values[i++] = Integer.toString(wcaFalseAlarms);
                            values[i++] = wcaFalseAlarmsList.toString();
                            values[i++] = Float.toString(wcaAccuracy);
                            values[i++] = Float.toString(wcaEfficiency);
                            values[i++] = Integer.toString(mclaMissedAlarms);
                            values[i++] = mclaMissedAlarmsList.toString();
                            values[i++] = Integer.toString(mclaFalseAlarms);
                            values[i++] = mclaFalseAlarmsList.toString();
                            values[i++] = Float.toString(mclaAccuracy);
                            values[i++] = Float.toString(mclaEfficiency);
                            values[i++] = Integer.toString(wfMissedAlarms);
                            values[i++] = wfMissedAlarmsList.toString();
                            values[i++] = Integer.toString(wfFalseAlarms);
                            values[i++] = wfFalseAlarmsList.toString();
                            values[i++] = Float.toString(wfAccuracy);
                            values[i++] = Float.toString(wfEfficiency);
                            cvsWriter.writeRecord(values);
                            cvsWriter.flush();
                        } else
                            System.out.println("No data for benchmark: skipping wf " + workflowId);
                    } else {
                        System.out.println("No results: skipping wf " + workflowId);
                    }
                } else
                    System.out.println("No data for validation: skipping wf " + workflowId);
            } catch (IOException e1) {
            }
        }
    } finally {
        if (cvsWriter != null)
            cvsWriter.close();
        onlinedb.close();
    }
}

From source file:MSUmpire.LCMSPeakStructure.LCMSPeakDIAMS2.java

private void PrepareMGF_UnfragmentIon() throws IOException {
    String mgffile4 = FilenameUtils.getFullPath(ParentmzXMLName) + GetQ3Name() + ".mgf.temp";
    //        FileWriter mgfWriter4 = new FileWriter(mgffile4, true);
    final BufferedWriter mgfWriter4 = DIAPack.get_file(DIAPack.OutputFile.Mgf_Q3, mgffile4);

    //        FileWriter mapwriter3 = new FileWriter(FilenameUtils.getFullPath(ParentmzXMLName) + FilenameUtils.getBaseName(ParentmzXMLName) + ".ScanClusterMapping_Q3", true);
    final BufferedWriter mapwriter3 = DIAPack.get_file(DIAPack.OutputFile.ScanClusterMapping_Q3,
            FilenameUtils.getFullPath(ParentmzXMLName) + FilenameUtils.getBaseName(ParentmzXMLName)
                    + ".ScanClusterMapping_Q3");

    ArrayList<PseudoMSMSProcessing> ScanList = new ArrayList<>();
    ExecutorService executorPool = Executors.newFixedThreadPool(NoCPUs);
    for (PeakCluster ms2cluster : PeakClusters) {
        ArrayList<PrecursorFragmentPairEdge> frags = UnFragIonClu2Cur.get(ms2cluster.Index);
        if (frags != null && DIA_MZ_Range.getX() <= ms2cluster.TargetMz()
                && DIA_MZ_Range.getY() >= ms2cluster.TargetMz()) {
            //            if (DIA_MZ_Range.getX() <= ms2cluster.TargetMz() && DIA_MZ_Range.getY() >= ms2cluster.TargetMz() && UnFragIonClu2Cur.containsKey(ms2cluster.Index)) {
            //                ArrayList<PrecursorFragmentPairEdge> frags = UnFragIonClu2Cur.get(ms2cluster.Index);
            ms2cluster.GroupedFragmentPeaks.addAll(frags);
            PseudoMSMSProcessing mSMSProcessing = new PseudoMSMSProcessing(ms2cluster, parameter);
            executorPool.execute(mSMSProcessing);
            ScanList.add(mSMSProcessing);
        }//w  w w.j  a  v a2s.  co m
    }
    executorPool.shutdown();
    try {
        executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
        Logger.getRootLogger().info("interrupted..");
    }

    for (PseudoMSMSProcessing mSMSProcessing : ScanList) {
        if (MatchedFragmentMap.size() > 0) {
            mSMSProcessing.RemoveMatchedFrag(MatchedFragmentMap);
        }
        XYPointCollection Scan = mSMSProcessing.GetScan();

        if (Scan != null && Scan.PointCount() > parameter.MinFrag) {
            parentDIA.Q3Scan++;
            //                StringBuilder mgfString = new StringBuilder();
            //                mgfString.append("BEGIN IONS\n");
            //                mgfString.append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n");
            //                mgfString.append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n");
            //                mgfString.append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n");
            //                mgfString.append("TITLE=").append(GetQ3Name()).append(".").append(parentDIA.Q3Scan).append(".").append(parentDIA.Q3Scan).append(".").append(mSMSProcessing.Precursorcluster.Charge).append("\n");
            //                //mgfString.append("TITLE=" + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n");
            //                //mgfString.append("TITLE=" GetQ3Name() + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n");
            //
            //                for (int i = 0; i < Scan.PointCount(); i++) {
            //                    mgfString.append(Scan.Data.get(i).getX()).append(" ").append(Scan.Data.get(i).getY()).append("\n");
            //                }
            //                mgfString.append("END IONS\n\n");
            //                mgfWriter4.write(mgfString.toString());

            mgfWriter4.append("BEGIN IONS\n")
                    .append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n")
                    .append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n")
                    .append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n")
                    .append("TITLE=").append(GetQ3Name()).append(".").append(Integer.toString(parentDIA.Q3Scan))
                    .append(".").append(Integer.toString(parentDIA.Q3Scan)).append(".")
                    .append(Integer.toString(mSMSProcessing.Precursorcluster.Charge)).append("\n");
            //mgfWriter4.append("TITLE=" + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n");
            //mgfWriter4.append("TITLE=" GetQ3Name() + WindowID + ";ClusterIndex:" + mSMSProcessing.ms2cluster.Index + "\n");

            for (int i = 0; i < Scan.PointCount(); i++) {
                mgfWriter4.append(Float.toString(Scan.Data.get(i).getX())).append(" ")
                        .append(Float.toString(Scan.Data.get(i).getY())).append("\n");
            }
            mgfWriter4.append("END IONS\n\n");

            mapwriter3.write(
                    parentDIA.Q3Scan + ";" + WindowID + ";" + mSMSProcessing.Precursorcluster.Index + "\n");
        }
        mSMSProcessing.Precursorcluster.GroupedFragmentPeaks.clear();
    }
    //        mgfWriter4.close();
    //        mapwriter3.close();
}

From source file:org.apache.tez.dag.app.web.AMWebController.java

public void getDagInfo() {
    if (!setupResponse()) {
        return;//from   w w  w . j  a  v a 2 s . com
    }

    DAG dag = checkAndGetDAGFromRequest();
    if (dag == null) {
        return;
    }

    Map<String, Set<String>> counterNames = getCounterListFromRequest();

    Map<String, Object> dagInfo = new HashMap<String, Object>();
    dagInfo.put("id", dag.getID().toString());
    dagInfo.put("progress", Float.toString(dag.getCompletedTaskProgress()));
    dagInfo.put("status", dag.getState().toString());

    try {
        if (counterNames != null && !counterNames.isEmpty()) {
            TezCounters counters = dag.getCachedCounters();
            Map<String, Map<String, Long>> counterMap = constructCounterMapInfo(counters, counterNames);
            if (counterMap != null && !counterMap.isEmpty()) {
                dagInfo.put("counters", counterMap);
            }
        }
    } catch (LimitExceededException e) {
        // Ignore
        // TODO: add an error message instead for counter key
    }
    renderJSON(ImmutableMap.of("dag", dagInfo));
}

From source file:com.irets.bl.service.SearchService.java

public Properties searchForProperties(int start, int pageSize, String sortField, String sortDir,
        Filter filterParam, GeoParameter geoParam, boolean openHouseFlag) throws LargeResultSetException {

    String[] keywords = filterParam.getKeywords();
    SimpleRange[] ranges = filterParam.getRanges();
    FilterItem[] filters = filterParam.getFilters();
    FilterItem[] exactFilters = filterParam.getExactFilters();
    FilterItem[] searchForFieldItems = filterParam.getSearchForFieldItems();

    List<SearchParameter> keywordSearchParameters = null;
    List<SimpleRange> rangeSearchParams = null;
    List<SearchParameter> searchParameters = null;
    List<SearchParameter> exactSearchParameters = null;
    List<SearchParameter> searchForFieldItemsParameters = null;

    // keywords are for searching LIKE syntax in one or many columns
    // add as many columns as needed for keyword search ....
    if (keywords != null && keywords.length > 0) {

        /*/*from w  ww.  j av a2 s  .c  om*/
        String searchStr = keywords[0];
        keywordSearchParameters = new ArrayList<SearchParameter>();
        keywordSearchParameters
              .add(new SearchParameter("r.www_Comments", searchStr));
        keywordSearchParameters.add(new SearchParameter("r.name_User_Disclosure",
              searchStr));
        */
        for (String str : keywords) {
            if (str == null) {
                continue;
            } else {
                if (keywordSearchParameters == null) {
                    keywordSearchParameters = new ArrayList<SearchParameter>();
                }
                keywordSearchParameters.add(new SearchParameter("listing_license_number", str));
                keywordSearchParameters.add(new SearchParameter("list_team_agent_dres", str));
            }
        }
    }

    // Filters are for like match %value%

    if (filters != null && filters.length > 0) {
        for (FilterItem item : filters) {
            if (item == null) {
                continue;
            }
            if (item.getField() != null) {
                if (searchParameters == null) {
                    searchParameters = new ArrayList<SearchParameter>();
                }
                searchParameters.add(new SearchParameter(item.getField(), item.getValue()));
            }
        }
    }

    /*
     * Adding server specific search in the filters
     * The prefix is read from configuration file 
     */

    if (this.server != null && !server.equalsIgnoreCase("All")) {
        if (searchParameters == null) {
            searchParameters = new ArrayList<SearchParameter>();
        }
        searchParameters.add(new SearchParameter("server", this.server));
    }

    // Filters are for exact like match value
    if (exactFilters != null && exactFilters.length > 0) {
        for (FilterItem item : exactFilters) {
            if (item == null)
                continue;

            if (item.getField() != null) {
                if (exactSearchParameters == null) {
                    exactSearchParameters = new ArrayList<SearchParameter>();
                }
                exactSearchParameters.add(new SearchParameter(item.getField(), item.getValue()));
            }
        }
    }

    // Filter for the multiple values
    if (searchForFieldItems != null && searchForFieldItems.length > 0) {
        for (FilterItem item : searchForFieldItems) {
            if (item == null)
                continue;

            if (item.getField() != null) {
                if (searchForFieldItemsParameters == null) {
                    searchForFieldItemsParameters = new ArrayList<SearchParameter>();
                }
                //System.out.println("inside 2 "+ item.getField() + ", " + item.getValue());
                searchForFieldItemsParameters.add(new SearchParameter(item.getField(), item.getValue()));
            }
        }
    }

    // for range fields
    if (ranges != null && ranges.length > 0) {
        for (SimpleRange sr : ranges) {
            if (sr == null)
                continue;
            if (sr.getField() != null) {
                if (rangeSearchParams == null) {
                    rangeSearchParams = new ArrayList<SimpleRange>();
                }
                if (sr.getMinValue() != null || sr.getMaxValue() != null) {
                    rangeSearchParams.add(sr);
                }
            }
        }
    }

    SearchParam params = new SearchParam();
    params.setSortingOrder(convertAttributesToColumnName(sortField, sortDir));
    params.setSearchParameters(convertSearchFieldsToColumnName(searchParameters));
    params.setExactSearchParameters(convertSearchFieldsToColumnName(exactSearchParameters));
    params.setKeywordSearchParameters(keywordSearchParameters);
    params.setRangeSearchParameters(rangeSearchParams);
    //log.debug(searchZipParameters);
    params.setSearchForFieldItemsParameters(convertSearchFieldsToColumnName(searchForFieldItemsParameters));
    if (geoParam != null) {
        params.setGeoSearchParameter(geoParam);
    }

    Properties result = new Properties();

    //long startTime= new Date().getTime();       
    int total = 0;
    if (openHouseFlag) {
        // This needs to be in a separate query because 
        // open house is stored in separate table.
        total = (Integer) universalDao.getByQueryName("searchForPropertiesCountWithOpenHouse", params);
    } else {
        total = (Integer) universalDao.getByQueryName("searchForPropertiesCount", params);
    }
    //System.out.println(">>time in counting in DB ("+total +"):"+(new Date().getTime()-startTime)+" msecs");

    // If search result more than 500 then send an error to caller. 
    if (total > hwmSearchResponses) {
        // Send an error message to the caller.
        // TODO: throw the exception here. 
        String exceptionMsg = "Refine search criteria: More than " + hwmSearchResponses + " matches found.";
        LargeResultSetException exception = new LargeResultSetException();
        exception.setErrorCode("W500");
        exception.setMessage(exceptionMsg);
        exception.setTotalCount(total);
        throw exception;
    }

    result.setTotalcount(new BigInteger(new Integer(total).toString()));

    // Check if limit is passed in the argument.
    // Otherwise always return 20 record as default
    // TODO: May be we need to put the default value in properties file.
    if (pageSize == -1) {
        pageSize = this.defaultPageSize;
    } else if (pageSize > this.maxPageSize) {
        pageSize = this.maxPageSize;
    }

    params.setPageSize(pageSize);
    params.setStartIndex(start);
    if (geoParam != null) {
        params.setGeoSearchParameter(geoParam);
    }

    //System.out.println("limit/pagesize " + pageSize + ", offset " + start);
    //startTime= new Date().getTime();

    List<ResidentialProperty> properties = null;

    if (openHouseFlag) {
        properties = universalDao.listByQueryName("searchForPropertiesWithOpenHouse", params, start, pageSize);
    } else {
        properties = universalDao.listByQueryName("searchForProperties", params, start, pageSize);
    }

    //System.out.println(">>time in searching in DB("+properties.size()+"):"+(new Date().getTime()-startTime)+" msecs");

    result.setCount(new BigInteger(Integer.toString(properties.size())));

    Iterator<ResidentialProperty> lIter = properties.iterator();
    while (lIter.hasNext()) {
        ResidentialProperty aProp = lIter.next();
        //DEBUG START
        //System.out.println(aProp.getId() +", " +aProp.getNumber_baths_Full()+", " + aProp.getNumber_MLS());
        //DEBUG END
        // now populate the result Property
        Property resProp = new Property();
        //fill out the resProp now...
        resProp.setAgentCompany(aProp.getName_Listing_Office());
        resProp.setAgentFirstName(aProp.getName_First_Listing_Agent());
        resProp.setAgentLastName(aProp.getName_Last_Listing_agent());
        resProp.setAgentName(aProp.getName_First_Listing_Agent() + " " + aProp.getName_Last_Listing_agent());
        if (aProp.getNumber_beds_Total() != null)
            resProp.setBedrooms(Integer.toString(aProp.getNumber_beds_Total()));
        resProp.setCity(aProp.getName_City());
        resProp.setCountry(aProp.getName_Country());
        resProp.setCounty(aProp.getName_County());
        resProp.setElementarySchool(aProp.getName_Elementry());
        resProp.setExteriorFeatures(aProp.getType_Property());
        resProp.setFullAddress(aProp.getAddress_Filtered());
        if (aProp.getNumber_baths_Full() != null)
            resProp.setFullBathrooms(Integer.toString(aProp.getNumber_baths_Full()));
        resProp.setGarage(aProp.getParking_Garage());
        if (aProp.getNumber_baths_Half() != null)
            resProp.setHalfBathrooms(Integer.toString(aProp.getNumber_baths_Half()));
        resProp.setHighSchool(aProp.getName_High_School());
        if (aProp.getLat() != null) {
            resProp.setLatitude(new BigDecimal(aProp.getLat()));
        } else {
            resProp.setLatitude(new BigDecimal(0));
        }
        if (aProp.getDate_List() != null)
            resProp.setListDate(aProp.getDate_List().toLocaleString());
        resProp.setListingId(aProp.getNumber_MLS());
        if (aProp.getPrice_List() != null)
            resProp.setListPrice(Integer.toString(aProp.getPrice_List()));
        if (aProp.get_long() != null)
            resProp.setLongitude(new BigDecimal(aProp.get_long()));
        else {
            resProp.setLongitude(new BigDecimal(0));
        }
        if (aProp.getSize_Lot() != null)
            resProp.setLotSqFt(Float.toString(aProp.getSize_Lot()));
        resProp.setModificationTimestamp(aProp.getDate_Listing_Modification());
        resProp.setPoolFeatures(aProp.getDesc_Pool());
        resProp.setRemarks(aProp.getRemarks_Public());
        resProp.setSchoolDistrict(aProp.getName_School_District());
        resProp.setSewerSeptic(aProp.getSewer_septic());
        resProp.setSpaFeatures(aProp.getSpa_Sauna());
        if (aProp.getSqft_Structure() != null)
            resProp.setSqFt(Integer.toString(aProp.getSqft_Structure()));
        resProp.setState(aProp.getState());
        resProp.setStatus(aProp.getStatus_Listing());
        resProp.setStreetName(aProp.getName_Street());
        resProp.setStreetNumber(aProp.getNumber_Street());
        resProp.setStyle(aProp.getStyle_Property());
        resProp.setType("RES");
        resProp.setYearBuilt(aProp.getYear_Built());
        resProp.setZip(aProp.getZipCode());
        resProp.setArea(aProp.getZone());
        resProp.setId(aProp.getId_Property());
        resProp.setGarageDescription(aProp.getParking_Garage());
        resProp.setCrossStreet(aProp.getCross_Street());
        resProp.setPropertyInclusions(aProp.getProperty_inclusions());
        // New Field added by Jit
        resProp.setListTeamAgentDREs(aProp.getList_team_agent_dres());
        resProp.setFoundation(aProp.getFoundation());
        resProp.setOtherRooms(aProp.getOther_rooms());
        resProp.setListingLicenseNumber(aProp.getListing_license_number());
        resProp.setHorsePropDesc(aProp.getHorse_prop_desc());
        resProp.setBathsHalf(aProp.getBaths_half());
        resProp.setPublicRemarks(aProp.getPublic_remarks());
        resProp.setOtherAreas(aProp.getOther_areas());
        resProp.setPool(aProp.getPool());
        resProp.setPoolOptions(aProp.getPool_options());
        resProp.setPropertyEnergyInformation(aProp.getProperty_energy_information());
        resProp.setHasPool(aProp.getHas_pool());
        resProp.setCooling(aProp.getCooling());
        resProp.setPropertyAge(aProp.getProperty_age());
        resProp.setHeating(aProp.getHeating());
        resProp.setHasFireplaces(aProp.getHas_fire_places());
        resProp.setRoof(aProp.getRoof());
        resProp.setYardGrounds(aProp.getYard_grounds());
        resProp.setBathroomFeatures(aProp.getBathrooom_features());
        resProp.setCityUnincorporated(aProp.getCity_unioncorporated());
        resProp.setFirePlaceDetails(aProp.getFire_place_details());
        resProp.setFormalDiningRoom(aProp.getFormal_dining_room());
        resProp.setPropertyDisabilityFeatures(aProp.getProperty_disability_features());
        resProp.setStories(aProp.getStories());
        resProp.setInsulation(aProp.getInsulation());
        // resProp.setSewerSeptic(aProp.getSewer_septic());
        resProp.setSewer(aProp.getSewer());
        resProp.setInFormalDiningRoom(aProp.getIn_formal_dining_room());
        resProp.setFloorCovering(aProp.getFloor_covering());
        resProp.setAssociationFee(aProp.getAssociation_fee());
        resProp.setListingAreaCode(aProp.getListing_area_code());
        resProp.setHorseProp(aProp.getHorse_prop());
        resProp.setCityLimits(aProp.getCity_limits());
        resProp.setLotSizeAreaUnits(aProp.getLot_size_area_units());
        resProp.setFamilyRoom(aProp.getFamily_room());
        resProp.setPropertyHotTub(aProp.getProperty_hot_tub());
        resProp.setVirtualTourLink(aProp.getVirtual_tour_link());
        resProp.setUnbrandedVirtualTourLink(aProp.getUnbranded_virtual_tour_link());
        resProp.setFireplaceLocation(aProp.getFireplace_location());
        resProp.setBedroomDescription(aProp.getBedroom_description());
        resProp.setLotDescription(aProp.getLot_description());
        resProp.setShowerTub(aProp.getShower_tub());
        resProp.setWater(aProp.getWater());
        resProp.setLevels(aProp.getLevels());
        resProp.setAssociationFeeIncludes(aProp.getAssociation_fee_includes());
        resProp.setCommunityCommunityName(aProp.getCommunity_community_name());
        resProp.setTotalUnits(aProp.getTotal_units());
        resProp.setUnitLocation(aProp.getUnit_location());
        resProp.setComplexFeatures(aProp.getComplex_features());
        resProp.setTractName(aProp.getTract_name());
        resProp.setUnitDescription(aProp.getUnit_description());
        resProp.setParkingTotal(aProp.getParking_total());
        resProp.setUnitDescription(aProp.getUnit_description());
        if (aProp.getDate_photo_modification() != null)
            resProp.setPhotoModificationTimestamp(aProp.getDate_photo_modification().toString());
        resProp.setVOWAVM(aProp.getVow_awm());
        resProp.setClosePrice(aProp.getClose_price());
        resProp.setListingBranchNum(aProp.getListing_branch_num());
        resProp.setVOWComm(aProp.getVow_comm());
        resProp.setBLEOptIn(aProp.getBle_opt_in());
        if (aProp.getDate_revision() != null)
            resProp.setRevisionDate(aProp.getDate_revision().toString());

        resProp.setAdditionalListingInfo(aProp.getInfo_Additional_Listing());
        resProp.setListingType(aProp.getType_Listing());
        resProp.setZoning(aProp.getZone());
        resProp.setTub(aProp.getTub());
        resProp.setWarrantyInfo(aProp.getInfo_Warranty());
        resProp.setView(aProp.getView());
        resProp.setAmenities(aProp.getAmenities());
        resProp.setDirections(aProp.getDirections());
        resProp.setShower(aProp.getShowers());
        resProp.setExterior(aProp.getExterior_features());
        resProp.setPropertyType(aProp.getType_Property());

        String server = aProp.getServer();
        //System.out.println("Server name is " + server);
        if (server != null && mlsSpecData != null) {
            for (MlsSpecificData msd : mlsSpecData) {
                //System.out.println("Server name from msd " + msd.name);
                if (msd.key.equals(server)) {
                    //System.out.println("Server name matched " + server);
                    resProp.setMlsName(msd.name);
                    resProp.setMlsLogo(msd.logoUrl);
                    resProp.setMlsDisclaimer(msd.disclaimerUrl);
                    break;
                }
            }
        }

        // Adding the open house information with this property.
        // long openHouseStart = System.currentTimeMillis();                       
        List<PropertyOpenHouse> openHouse = universalDao.listByQueryName("getPropertyOpenHouseByPropertyId",
                aProp.getId_Property());
        OpenHouses opHouses = new OpenHouses();
        for (PropertyOpenHouse oph : openHouse) {
            OpenHouse opHouse = new OpenHouse();
            opHouse.setOpenHousePublicRemarks(oph.getPublic_remarks());
            if (oph.getStart_date_time() != null)
                opHouse.setStartDateTime(oph.getStart_date_time().toLocaleString());
            if (oph.getEnd_date_time() != null)
                opHouse.setEndDateTime(oph.getEnd_date_time().toLocaleString());
            opHouses.getOpenHouse().add(opHouse);
        }
        if (!opHouses.getOpenHouse().isEmpty())
            resProp.setOpenHouses(opHouses);
        //System.out.println("Extra cost of open house lookup "+ (System.currentTimeMillis()-openHouseStart) + " ms");                      

        // lastly add the photos if available
        Integer photoCountInt = aProp.getActual_count_Photo();
        int photoCount = photoCountInt == null ? 0 : photoCountInt;
        //startTime= new Date().getTime();
        //System.out.println(" id_property is " + aProp.getId_Property());

        if (this.getRESULT_TYPE().equalsIgnoreCase("XML")) {
            Photos photos = new Photos();
            for (int i = 0; i < photoCount; i++) {
                Photo photo = new Photo();
                if ("true".equalsIgnoreCase(this.photoURLAvailable)) {
                    try {
                        byte[] phoBytes = this.getPropertyPhoto(aProp.getId_Property(), i);
                        String propPhotoURL = new String(phoBytes, "US-ASCII");
                        photo.setUrl(propPhotoURL);
                    } catch (UnsupportedEncodingException e) {

                    }

                } else {
                    photo.setUrl(
                            contextPath + "/PhotoView?PropertyId=" + aProp.getId_Property() + "&index=" + i);
                }
                photos.getPhoto().add(photo);
            }
            resProp.setPhotos(photos);
            result.getProperty().add(resProp);
        } else {
            TempProp reProp = new TempProp(resProp);

            for (int i = 0; i < photoCount; i++) {
                Photo photo = new Photo();
                if ("true".equalsIgnoreCase(this.photoURLAvailable)) {
                    try {
                        byte[] phoBytes = this.getPropertyPhoto(aProp.getId_Property(), i);
                        String propPhotoURL = new String(phoBytes, "US-ASCII");
                        photo.setUrl(propPhotoURL);
                    } catch (UnsupportedEncodingException e) {

                    }

                } else {
                    photo.setUrl(
                            contextPath + "/PhotoView?PropertyId=" + aProp.getId_Property() + "&index=" + i);
                }
                reProp.getLphotos().add(photo);
            }
            result.getProperty().add(reProp);
        }
    }
    return result;
}

From source file:org.apache.hadoop.mapred.TestNewCollector.java

private void runTest(String name, int keyLen, int valLen, int bigKeyLen, int bigValLen, int recordsNumPerMapper,
        int sortMb, float spillPer, int numMapperTasks, int numReducerTask, double[] reducerRecPercents,
        int[] numBigRecordsStart, int[] numBigRecordsMiddle, int[] numBigRecordsEnd) throws Exception {
    JobConf conf = mrCluster.createJobConf();
    conf.setInt("io.sort.mb", sortMb);
    conf.set("io.sort.spill.percent", Float.toString(spillPer));
    conf.setInt("test.key.length", keyLen);
    conf.setInt("test.value.length", valLen);
    conf.setInt("test.bigkey.length", bigKeyLen);
    conf.setInt("test.bigvalue.length", bigValLen);
    conf.setNumMapTasks(numMapperTasks);
    conf.setNumReduceTasks(numReducerTask);
    conf.setInputFormat(FakeIF.class);
    conf.setOutputFormat(NullOutputFormat.class);
    conf.setMapperClass(TestNewCollectorMapper.class);
    conf.setReducerClass(TestNewCollectorReducer.class);
    conf.setMapOutputKeyClass(TestNewCollectorKey.class);
    conf.setMapOutputValueClass(BytesWritable.class);
    conf.setBoolean("mapred.map.output.blockcollector", true);

    RecordNumStore.setJobConf(numReducerTask, numMapperTasks, recordsNumPerMapper, reducerRecPercents,
            numBigRecordsStart, numBigRecordsMiddle, numBigRecordsEnd, conf);
    RecordNumStore.getInst(conf);/*  w w  w  .  j  a v a 2s . c  o  m*/
    LOG.info("Running " + name);
    JobClient.runJob(conf);
}

From source file:org.apache.hadoop.mapreduce.TestMapCollection.java

@Test
public void testRandom() throws Exception {
    Configuration conf = new Configuration();
    conf.setInt(Job.COMPLETION_POLL_INTERVAL_KEY, 100);
    Job job = Job.getInstance(conf);//from  ww w  .j  a  va2  s. c o m
    conf = job.getConfiguration();
    conf.setInt(MRJobConfig.IO_SORT_MB, 1);
    conf.setClass("test.mapcollection.class", RandomFactory.class, RecordFactory.class);
    final Random r = new Random();
    final long seed = r.nextLong();
    LOG.info("SEED: " + seed);
    r.setSeed(seed);
    conf.set(MRJobConfig.MAP_SORT_SPILL_PERCENT, Float.toString(Math.max(0.1f, r.nextFloat())));
    RandomFactory.setLengths(conf, r, 1 << 14);
    conf.setInt("test.spillmap.records", r.nextInt(500));
    conf.setLong("test.randomfactory.seed", r.nextLong());
    runTest("random", job);
}