Example usage for java.lang Float isNaN

List of usage examples for java.lang Float isNaN

Introduction

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

Prototype

public static boolean isNaN(float v) 

Source Link

Document

Returns true if the specified number is a Not-a-Number (NaN) value, false otherwise.

Usage

From source file:routines.system.BigDataParserUtils.java

public static Double parseTo_Double(float input) {
    if (Float.isNaN(input)) {
        return null;
    }//from   ww w .j  ava 2 s. c om
    return ((Float) input).doubleValue();
}

From source file:papaya.Rank.java

/**
 * Recodes NaN values to the given value.
 *
 * @param ranks array to recode/*  www. j a  va  2s .c om*/
 * @param value the value to replace NaNs with
 */
private static void recodeNaNs(IntFloatPair[] ranks, float value) {
    for (int i = 0; i < ranks.length; i++) {
        if (Float.isNaN(ranks[i].getValue())) {
            ranks[i] = new IntFloatPair(value, ranks[i].getPosition());
        }
    }
}

From source file:gov.nih.nci.caarray.util.CaArrayUtils.java

private static String toXmlString(float value) {
    if (Float.isNaN(value)) {
        return "NaN";
    } else if (value == Float.POSITIVE_INFINITY) {
        return "INF";
    } else if (value == Float.NEGATIVE_INFINITY) {
        return "-INF";
    } else {//from w w  w  . jav  a2 s  . c  o  m
        return Float.toString(value);
    }
}

From source file:com.golemgame.properties.fengGUI.FunctionTab.java

protected void buildGUI() {
    Container tabFrame = super.getTab();
    tabFrame.setLayoutManager(new BorderLayout());

    pane = new KnottedFunctionPane();

    //Add an internal frame with controls for choosing a function
    Container controlFrame = FengGUI.createContainer(tabFrame);
    controlFrame.setLayoutData(BorderLayoutData.NORTH);
    controlFrame.setLayoutManager(new BorderLayout());

    Container controlsNorth = FengGUI.createContainer(controlFrame);
    controlsNorth.setLayoutData(BorderLayoutData.NORTH);
    controlsNorth.setLayoutManager(new RowLayout(false));
    dropDown = FengGUI.<PropertyStore>createComboBox(controlsNorth);

    dropDown.setLayoutData(BorderLayoutData.NORTH);
    dropDown.getAppearance().setPadding(new Spacing(0, 5));

    Container nameContainer = FengGUI.createContainer(controlsNorth);
    nameContainer.setLayoutManager(new BorderLayout());
    Label nameLabel = FengGUI.createLabel(nameContainer,
            StringConstants.get("PROPERTIES.FUNCTIONS.NAME", "Function Name "));
    nameLabel.setLayoutData(BorderLayoutData.WEST);
    functionName = FengGUI.createTextEditor(nameContainer);
    functionName.setMinSize(300, 10);//from   w  ww .  j  a v a  2 s  .com
    functionName.setLayoutData(BorderLayoutData.CENTER);

    controlFrame.layout();

    dropDown.addSelectionChangedListener(new ISelectionChangedListener() {

        public void selectionChanged(SelectionChangedEvent selectionChangedEvent) {

            if (selectionChangedEvent.isSelected()) {
                IToggable<PropertyStore> selected = dropDown.getSelectedItem();

                if (selected == slopeItem) {
                    pane.setEnabled(false);
                    interpreter.setFunctionType(FunctionType.Differentiate);
                    functionName.setText(StringConstants.get("FUNCTIONS.SLOPE", "(Slope)"));
                } else if (selected == areaItem) {//disabled
                    pane.setEnabled(false);
                    interpreter.setFunctionType(FunctionType.AntiDifferentiate);
                    functionName.setText(StringConstants.get("FUNCTIONS.AREA", "(Area)"));
                } else if (selected != null && selected.getValue() != null) {
                    pane.setEnabled(true);
                    interpreter.setFunctionType(FunctionType.Function);
                    loadFrom(selected.getValue().deepCopy());
                    /*FunctionSettingsInterpreter settings = new FunctionSettingsInterpreter(new PropertyStore());
                    settings.setFunction(selected.getValue());
                    setFunction(settings);*/
                }
            }

        }

    });

    controlFrame.updateMinSize();

    controlFrame.pack();

    Container functionContainer = FengGUI.createContainer(tabFrame);
    functionContainer.setLayoutData(BorderLayoutData.CENTER);
    functionContainer.setLayoutManager(new BorderLayout());
    //  pane.setMinSize(20, 20);
    functionContainer.addWidget(pane);

    pane.setLayoutData(BorderLayoutData.CENTER);
    //  pane.getAppearance().setBorder(new Spacing(5,5));        

    horizontal = new ScalingRuler(true, pane);
    horizontal.setLayoutData(BorderLayoutData.SOUTH);
    functionContainer.addWidget(horizontal);

    Container eastContainer = FengGUI.createContainer(functionContainer);
    eastContainer.setLayoutManager(new BorderLayout());
    eastContainer.setLayoutData(BorderLayoutData.EAST);
    vertical = new ScalingRuler(false, pane);
    vertical.setLayoutData(BorderLayoutData.CENTER);
    eastContainer.addWidget(vertical);

    horizontal.getMinSize().setHeight(15);
    horizontal.setSizeToMinSize();
    vertical.getMinSize().setWidth(horizontal.getHeight());

    Spacer spacer = new Spacer(1, horizontal.getHeight());
    eastContainer.addWidget(spacer);
    spacer.setLayoutData(BorderLayoutData.SOUTH);

    Container south = FengGUI.createContainer(getTab());
    //Add controls at the bottom
    south.setLayoutData(BorderLayoutData.SOUTH);
    south.setLayoutManager(new RowLayout(false));
    periodContainer = FengGUI.createContainer(south);

    periodContainer.setLayoutManager(new RowLayout());

    FengGUI.createLabel(periodContainer, "Length(s):");
    time = FengGUI.createTextEditor(periodContainer);
    // FengGUI.createLabel(settingsContainer,"Power (w):");
    power = FengGUI.createTextEditor();//dont add power right now.

    periodicity = FengGUI.createCheckBox(periodContainer, "Periodic:");

    final Container saveContainer = FengGUI.createContainer(south);

    saveContainer.setLayoutManager(new BorderLayout());
    Container saveButtonContainer = FengGUI.createContainer(saveContainer);
    saveButtonContainer.setLayoutData(BorderLayoutData.EAST);
    saveButtonContainer.setLayoutManager(new RowLayout());

    Button saveButton = FengGUI.createButton(saveButtonContainer);

    saveButton.setText("Save Function");

    saveButton.addButtonPressedListener(new IButtonPressedListener() {

        @SuppressWarnings("unchecked")
        public void buttonPressed(ButtonPressedEvent e) {

            PropertyStore newFunction = new PropertyStore();
            set(newFunction);
            PropertyStore effectStore = StateManager.getMachineSpace().getFunctionRepository().getStore();
            //capture the current settings, then add them to the main machine repository (overwriting any existing setting of the same name).
            final PropertyState beforePropertyState = new SimplePropertyState(effectStore,
                    FunctionSettingsRepositoryInterpreter.FUNCTIONS);
            StateManager.getMachineSpace().getFunctionRepository().addFunction(newFunction);

            final PropertyState afterPropertyState = new SimplePropertyState(effectStore,
                    FunctionSettingsRepositoryInterpreter.FUNCTIONS);

            Action<?> action = new Action() {

                @Override
                public String getDescription() {
                    return "Save Function";
                }

                @Override
                public Type getType() {
                    return null;
                }

                @Override
                public boolean doAction() {
                    afterPropertyState.restore();
                    afterPropertyState.refresh();
                    return true;
                }

                @Override
                public boolean undoAction() {
                    beforePropertyState.restore();
                    beforePropertyState.refresh();
                    return true;
                }

            };
            action.setDependencySet(getPropertyStoreAdjuster().getDependencySet());

            UndoManager.getInstance().addAction(action);

            buildFunctions();

            dropDown.getLabel().setText(newFunction.getString(FunctionSettingsInterpreter.FUNCTION_NAME));

            loadFrom(newFunction.deepCopy());

        }

    });

    currentKnotContainer = FengGUI.createContainer(saveContainer);
    currentKnotContainer.setVisible(false);
    currentKnotContainer.setLayoutManager(new RowLayout(true));
    FengGUI.createLabel(currentKnotContainer, "Vertex Position: ").setExpandable(false);
    FengGUI.createLabel(currentKnotContainer, "X").setExpandable(false);
    currentX = FengGUI.createTextEditor(currentKnotContainer);
    FengGUI.createLabel(currentKnotContainer, "Y").setExpandable(false);
    currentY = FengGUI.createTextEditor(currentKnotContainer);

    currentY.addTextChangedListener(new ITextChangedListener() {

        public void textChanged(TextChangedEvent textChangedEvent) {
            try {
                float pos;
                float scaleY = (float) pane.getTransformFunction().getScaleY();
                if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY)) {
                    pos = (Float.valueOf((currentY.getText()))
                            - (float) pane.getTransformFunction().getTranslateY())
                            * (float) pane.getTransformFunction().getScaleY();

                } else {
                    return;
                    //pos = (float) pane.getTransformFunction().getTranslateY();
                }

                Knot cur = pane.getCurrent();
                if (cur != null) {
                    if (cur.getTranslation().y != pos) {
                        cur.getTranslation().y = pos;
                        pane.updateKnots();
                    }
                }
            } catch (NumberFormatException e) {

            }
        }

    });

    currentX.addTextChangedListener(new ITextChangedListener() {

        public void textChanged(TextChangedEvent textChangedEvent) {
            try {
                float pos;
                float scaleX = (float) pane.getTransformFunction().getScaleX();
                if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX)) {
                    pos = (Float.valueOf((currentX.getText()))
                            - (float) pane.getTransformFunction().getTranslateX())
                            * (float) pane.getTransformFunction().getScaleX();

                } else {
                    return;

                }
                Knot cur = pane.getCurrent();
                if (cur != null) {
                    if (cur.getTranslation().x != pos) {
                        cur.getTranslation().x = pos;
                        pane.updateKnots();
                    }
                }
            } catch (NumberFormatException e) {

            }
        }

    });

    pane.registerCurrentKnotListener(new CurrentKnotListener() {

        public void currentKnotChanged(Knot current) {
            if (current == null) {
                currentKnotContainer.setVisible(false);
            } else {
                currentKnotContainer.setVisible(true);
                float scaleX = (float) pane.getTransformFunction().getScaleX();
                if (scaleX != 0f && !Float.isInfinite(scaleX) && !Float.isNaN(scaleX))
                    scaleX = 1f / scaleX;
                else
                    scaleX = 0f;

                float scaleY = (float) pane.getTransformFunction().getScaleY();
                if (scaleY != 0f && !Float.isInfinite(scaleY) && !Float.isNaN(scaleY))
                    scaleY = 1f / scaleY;
                else
                    scaleY = 0f;

                currentX.setText(String.valueOf(
                        current.getTranslation().x * scaleX + pane.getTransformFunction().getTranslateX()));
                currentY.setText(String.valueOf(
                        current.getTranslation().y * scaleY + pane.getTransformFunction().getTranslateY()));

                saveContainer.layout();
            }

        }
    });
    functionContainer.pack();
    tabFrame.pack();
}

From source file:model.scenario.CompetitiveScenarioTest.java

@Test
public void rightPriceAndQuantityTestAsMarginalNoPIDAlreadyLearnedFlows() {

    for (int competitors = 4; competitors <= 7; competitors++) {
        //  System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors+1));

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

            final MacroII macroII = new MacroII(System.currentTimeMillis());
            final TripolistScenario scenario1 = new TripolistScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setAskPricingStrategy(InventoryBufferSalesControl.class);
            scenario1.setControlType(// w ww  .  ja  v a  2 s.com
                    MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
            scenario1.setAdditionalCompetitors(competitors);
            scenario1.setWorkersToBeRehiredEveryDay(true);
            scenario1.setDemandIntercept(102);

            scenario1.setSalesPricePreditorStrategy(FixedDecreaseSalesPredictor.class);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();

            macroII.schedule.step(macroII);
            for (Firm firm : scenario1.getCompetitors()) {
                for (HumanResources hr : firm.getHRs())
                    hr.setPredictor(new FixedIncreasePurchasesPredictor(0));

                firm.getSalesDepartment(UndifferentiatedGoodType.GENERIC)
                        .setPredictorStrategy(new FixedDecreaseSalesPredictor(0));
            }

            while (macroII.schedule.getTime() < 5000) {
                macroII.schedule.step(macroII);

            }

            SummaryStatistics prices = new SummaryStatistics();
            SummaryStatistics quantities = new SummaryStatistics();
            SummaryStatistics target = new SummaryStatistics();
            for (int j = 0; j < 500; j++) {
                macroII.schedule.step(macroII);
                assert !Float.isNaN(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());

                for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) {
                    SalesDepartment department = ((Firm) agent)
                            .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                    target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());
                }

            }

            System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----"
                    + macroII.seed() + " | "
                    + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice());
            System.out.println("standard deviations: price : " + prices.getStandardDeviation() + " , quantity: "
                    + quantities.getStandardDeviation());

            assertEquals(prices.getMean(), 58, 5);
            assertTrue(prices.getStandardDeviation() < 5.5);
            assertEquals(quantities.getMean(), 44, 5);
            assertTrue(quantities.getStandardDeviation() < 5.5);
        }

    }

}

From source file:papaya.Rank.java

/**
 * Checks for presence of NaNs in <code>ranks.</code>
 *
 * @param ranks array to be searched for NaNs
 * @return true iff ranks contains one or more NaNs
 *///from   w  w  w. j av a2 s .  com
private static boolean containsNaNs(IntFloatPair[] ranks) {
    for (int i = 0; i < ranks.length; i++) {
        if (Float.isNaN(ranks[i].getValue())) {
            return true;
        }
    }
    return false;
}

From source file:MSUmpire.DIA.TargetMatchScoring.java

private void EM_LDATraining() throws IOException {

    Logger.getRootLogger()//w w w .j a v a 2s . c o m
            .info("Linear discriminant analysis using identified peptides and decoys as training set.");
    Regression regression = new Regression();
    XYPointCollection points = new XYPointCollection();
    matchSubscore.InitializeLDACoeff();
    int NoLDAComp = matchSubscore.NoEnableSubscores;

    CalcUmpireScore();

    float LDASimialrity = 0f;
    float StopThreshold = 0.95f;
    int MaxIterations = 50;
    int iteration = 0;
    float samplingratio = 0.5f;

    ArrayList<PeakGroupScore> IDList = new ArrayList<>();
    ArrayList<PeakGroupScore> decoyList = new ArrayList<>();

    for (UmpireSpecLibMatch match : libTargetMatches) {
        if (match.BestDecoyHit != null) {
            decoyList.add(match.BestDecoyHit);
        }
        if (match.BestMS2DecoyHit != null) {
            decoyList.add(match.BestMS2DecoyHit);
        }
    }
    for (UmpireSpecLibMatch match : libIDMatches) {
        if (match.BestHit != null) {
            IDList.add(match.BestHit);
        }
    }

    Collections.shuffle(decoyList);
    ArrayList<PeakGroupScore> decoyTList = new ArrayList<>();
    for (int i = 0; i < decoyList.size() / 2; i++) {
        decoyModelingList.add(decoyList.get(i));
    }
    for (int i = decoyList.size() / 2; i < decoyList.size(); i++) {
        decoyTList.add(decoyList.get(i));
    }
    decoyList = decoyTList;

    int targetNo = (int) (IDList.size() * samplingratio);
    int TrainNo = Math.min(targetNo, decoyList.size());

    Logger.getRootLogger().info("No. of identified peptide ions:" + IDList.size());
    Logger.getRootLogger().info("No. of decoys:" + decoyList.size());
    if (TrainNo < 5) {
        Terminate = true;
        Logger.getRootLogger().warn("No. of training data is less than 5, the training process will exit.");
        return;
    }

    while (LDASimialrity < StopThreshold && iteration < MaxIterations) {
        Collections.shuffle(decoyList);
        Collections.shuffle(IDList);

        double[][] testdata = new double[NoLDAComp][2 * TrainNo];
        double[] testgroup = new double[2 * TrainNo];

        int idx = 0;
        for (int i = 0; i < TrainNo; i++) {
            PeakGroupScore peakgroup = IDList.get(i);
            double[] enablesubscore = matchSubscore.GetEnableSubScoreArray(peakgroup);
            for (int j = 0; j < enablesubscore.length; j++) {
                testdata[j][idx] = enablesubscore[j];
            }
            testgroup[idx] = 1;
            idx++;
        }

        for (int i = 0; i < TrainNo; i++) {
            PeakGroupScore peakgroup = decoyList.get(i);
            double[] enablesubscore = matchSubscore.GetEnableSubScoreArray(peakgroup);
            for (int j = 0; j < enablesubscore.length; j++) {
                testdata[j][idx] = enablesubscore[j];
            }
            testgroup[idx] = 0;
            idx++;
        }
        DiscriminantAnalysis LDA = new DiscriminantAnalysis();
        int[] group = LDA.predictedGroup(testgroup, testdata, testdata);
        boolean modelvalid = true;
        for (int i = 0; i < NoLDAComp; i++) {
            if (Float.isNaN((float) LDA.linearDiscriminants[0][i])) {
                modelvalid = false;
                break;
            }
            points.AddPoint((float) matchSubscore.SubSCoeff[i], (float) -LDA.linearDiscriminants[0][i]);
            matchSubscore.SubSCoeff[i] = -LDA.linearDiscriminants[0][i];
        }

        if (!modelvalid) {
            Logger.getRootLogger().debug("LDA failed at iteration:" + iteration);
            break;
        }
        regression.SetData(points);

        LDASimialrity = regression.GetR2();
        if (Float.isNaN(LDASimialrity)) {
            LDASimialrity = -1f;
        }

        DecimalFormat df = new DecimalFormat("#.####");
        Logger.getRootLogger().debug(
                "----------------------------------------------------------------------------------------");
        Logger.getRootLogger().debug("Iteration:" + (iteration++));
        Logger.getRootLogger().debug("No of target hits:" + targetNo);
        Logger.getRootLogger().debug("No of decoy hits:" + decoyList.size());
        Logger.getRootLogger().debug("Training set size:" + TrainNo * 2);
        Logger.getRootLogger().debug("Trained weights:");
        for (int i = 0; i < NoLDAComp; i++) {
            Logger.getRootLogger()
                    .debug(matchSubscore.SubSName[i] + ":" + df.format(matchSubscore.SubSCoeff[i]));
        }
        Logger.getRootLogger().debug("LDA weight similarity to previous iteration:" + df.format(LDASimialrity));

        CalcUmpireScore();
    }
}

From source file:routines.system.BigDataParserUtils.java

public static double parseTo_double(float input) {
    if (Float.isNaN(input)) {
        return defaultValueDouble;
    }//from  w w  w. ja  va 2  s .c o  m
    return ((Float) input).doubleValue();
}

From source file:ml.shifu.shifu.core.dtrain.lr.LogisticRegressionWorker.java

@Override
public void load(GuaguaWritableAdapter<LongWritable> currentKey, GuaguaWritableAdapter<Text> currentValue,
        WorkerContext<LogisticRegressionParams, LogisticRegressionParams> context) {
    ++this.count;
    if ((this.count) % 100000 == 0) {
        LOG.info("Read {} records.", this.count);
    }//from  w w w .j  a  va2  s .  c o m
    String line = currentValue.getWritable().toString();
    float[] inputData = new float[inputNum];
    float[] outputData = new float[outputNum];
    int index = 0, inputIndex = 0, outputIndex = 0;
    long hashcode = 0;
    double significance = CommonConstants.DEFAULT_SIGNIFICANCE_VALUE;
    boolean hasCandidates = CommonUtils.hasCandidateColumns(this.columnConfigList);

    String[] fields = Lists.newArrayList(this.splitter.split(line)).toArray(new String[0]);
    int pos = 0;

    for (pos = 0; pos < fields.length;) {
        String unit = fields[pos];
        // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
        float floatValue = unit.length() == 0 ? 0f : NumberFormatUtils.getFloat(unit, 0f);
        // no idea about why NaN in input data, we should process it as missing value TODO , according to norm type
        floatValue = (Float.isNaN(floatValue) || Double.isNaN(floatValue)) ? 0f : floatValue;

        if (pos == fields.length - 1) {
            // do we need to check if not weighted directly set to 1f; if such logic non-weight at first, then
            // weight, how to process???
            if (StringUtils.isBlank(modelConfig.getWeightColumnName())) {
                significance = 1d;
                // break here if we reach weight column which is last column
                break;
            }

            // check here to avoid bad performance in failed NumberFormatUtils.getDouble(input, 1)
            significance = unit.length() == 0 ? 1f : NumberFormatUtils.getDouble(unit, 1d);
            // if invalid weight, set it to 1f and warning in log
            if (Double.compare(significance, 0d) < 0) {
                LOG.warn(
                        "The {} record in current worker weight {} is less than 0f, it is invalid, set it to 1.",
                        count, significance);
                significance = 1d;
            }
            // the last field is significance, break here
            break;
        } else {
            ColumnConfig columnConfig = this.columnConfigList.get(index);
            if (columnConfig != null && columnConfig.isTarget()) {
                outputData[outputIndex++] = floatValue;
                pos++;
            } else {
                if (this.inputNum == this.candidateNum) {
                    // no variable selected, good candidate but not meta and not target choosed
                    if (!columnConfig.isMeta() && !columnConfig.isTarget()
                            && CommonUtils.isGoodCandidate(columnConfig, hasCandidates)) {
                        inputData[inputIndex++] = floatValue;
                        hashcode = hashcode * 31 + Float.valueOf(floatValue).hashCode();
                    }
                    pos++;
                } else {
                    if (columnConfig.isFinalSelect()) {
                        if (columnConfig.isNumerical()
                                && modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT)) {
                            for (int k = 0; k < columnConfig.getBinBoundary().size() + 1; k++) {
                                String tval = fields[pos];
                                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                                float fval = tval.length() == 0 ? 0f : NumberFormatUtils.getFloat(tval, 0f);
                                // no idea about why NaN in input data, we should process it as missing value TODO ,
                                // according to norm type
                                fval = (Float.isNaN(fval) || Double.isNaN(fval)) ? 0f : fval;
                                inputData[inputIndex++] = fval;
                                pos++;
                            }
                        } else if (columnConfig.isCategorical() && (modelConfig.getNormalizeType()
                                .equals(ModelNormalizeConf.NormType.ZSCALE_ONEHOT)
                                || modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT))) {
                            for (int k = 0; k < columnConfig.getBinCategory().size() + 1; k++) {
                                String tval = fields[pos];
                                // check here to avoid bad performance in failed NumberFormatUtils.getFloat(input, 0f)
                                float fval = tval.length() == 0 ? 0f : NumberFormatUtils.getFloat(tval, 0f);
                                // no idea about why NaN in input data, we should process it as missing value TODO ,
                                // according to norm type
                                fval = (Float.isNaN(fval) || Double.isNaN(fval)) ? 0f : fval;
                                inputData[inputIndex++] = fval;
                                pos++;
                            }
                        } else {
                            inputData[inputIndex++] = floatValue;
                            pos++;
                        }

                        hashcode = hashcode * 31 + Double.valueOf(floatValue).hashCode();
                    } else {
                        if (!CommonUtils.isToNormVariable(columnConfig, hasCandidates,
                                modelConfig.isRegression())) {
                            pos += 1;
                        } else if (columnConfig.isNumerical()
                                && modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT)
                                && columnConfig.getBinBoundary() != null
                                && columnConfig.getBinBoundary().size() > 0) {
                            pos += (columnConfig.getBinBoundary().size() + 1);
                        } else if (columnConfig.isCategorical() && (modelConfig.getNormalizeType()
                                .equals(ModelNormalizeConf.NormType.ZSCALE_ONEHOT)
                                || modelConfig.getNormalizeType().equals(ModelNormalizeConf.NormType.ONEHOT))
                                && columnConfig.getBinCategory().size() > 0) {
                            pos += (columnConfig.getBinCategory().size() + 1);
                        } else {
                            pos += 1;
                        }
                    }
                }
            }
        }
        index += 1;
    }

    if (index != this.columnConfigList.size() || pos != fields.length - 1) {
        throw new RuntimeException("Wrong data indexing. ColumnConfig index = " + index
                + ", while it should be " + columnConfigList.size() + ". " + "Data Pos = " + pos
                + ", while it should be " + (fields.length - 1));
    }

    // output delimiter in norm can be set by user now and if user set a special one later changed, this exception
    // is helped to quick find such issue.
    if (inputIndex != inputData.length) {
        String delimiter = context.getProps().getProperty(Constants.SHIFU_OUTPUT_DATA_DELIMITER,
                Constants.DEFAULT_DELIMITER);
        throw new RuntimeException("Input length is inconsistent with parsing size. Input original size: "
                + inputData.length + ", parsing size:" + inputIndex + ", delimiter:" + delimiter + ".");
    }

    // sample negative only logic here
    if (modelConfig.getTrain().getSampleNegOnly()) {
        if (this.modelConfig.isFixInitialInput()) {
            // if fixInitialInput, sample hashcode in 1-sampleRate range out if negative records
            int startHashCode = (100 / this.modelConfig.getBaggingNum()) * this.trainerId;
            // here BaggingSampleRate means how many data will be used in training and validation, if it is 0.8, we
            // should take 1-0.8 to check endHashCode
            int endHashCode = startHashCode
                    + Double.valueOf((1d - this.modelConfig.getBaggingSampleRate()) * 100).intValue();
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (outputData[0] + 0.01d) == 0 // negative record
                    && isInRange(hashcode, startHashCode, endHashCode)) {
                return;
            }
        } else {
            // if not fixed initial input, and for regression or onevsall multiple classification (regression also).
            // if negative record
            if ((modelConfig.isRegression()
                    || (modelConfig.isClassification() && modelConfig.getTrain().isOneVsAll())) // regression or
                    // onevsall
                    && (int) (outputData[0] + 0.01d) == 0 // negative record
                    && Double.compare(Math.random(), this.modelConfig.getBaggingSampleRate()) >= 0) {
                return;
            }
        }
    }

    Data data = new Data(inputData, outputData, significance);

    // up sampling logic, just add more weights while bagging sampling rate is still not changed
    if (modelConfig.isRegression() && isUpSampleEnabled() && Double.compare(outputData[0], 1d) == 0) {
        // Double.compare(ideal[0], 1d) == 0 means positive tags; sample + 1 to avoids sample count to 0
        data.setSignificance(data.significance * (this.upSampleRng.sample() + 1));
    }

    boolean isValidation = false;
    if (context.getAttachment() != null && context.getAttachment() instanceof Boolean) {
        isValidation = (Boolean) context.getAttachment();
    }

    boolean isInTraining = addDataPairToDataSet(hashcode, data, isValidation);

    // do bagging sampling only for training data
    if (isInTraining) {
        float subsampleWeights = sampleWeights(outputData[0]);
        if (isPositive(outputData[0])) {
            this.positiveSelectedTrainCount += subsampleWeights * 1L;
        } else {
            this.negativeSelectedTrainCount += subsampleWeights * 1L;
        }
        // set weights to significance, if 0, significance will be 0, that is bagging sampling
        data.setSignificance(data.significance * subsampleWeights);
    } else {
        // for validation data, according bagging sampling logic, we may need to sampling validation data set, while
        // validation data set are only used to compute validation error, not to do real sampling is ok.
    }
}

From source file:com.granita.tasks.ViewTaskFragment.java

@SuppressLint("NewApi")
private void updateColor(float percentage) {
    if (getActivity() instanceof TaskListActivity) {
        return;/*from   ww w.  j a va 2s  .  c om*/
    }

    float[] hsv = new float[3];
    Color.colorToHSV(mListColor, hsv);

    if (VERSION.SDK_INT >= 11 && mColorBar != null) {
        percentage = Math.max(0, Math.min(Float.isNaN(percentage) ? 0 : percentage, 1));
        percentage = (float) Math.pow(percentage, 1.5);

        int newColor = darkenColor2(mListColor);

        hsv[2] *= (0.5 + 0.25 * percentage);

        ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
        actionBar.setBackgroundDrawable(
                new ColorDrawable((newColor & 0x00ffffff) | ((int) (percentage * 255) << 24)));

        // this is a workaround to ensure the new color is applied on all devices, some devices show a transparent ActionBar if we don't do that.
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);

        mColorBar.setBackgroundColor(mListColor);

        if (VERSION.SDK_INT >= 21) {
            Window window = getActivity().getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(newColor | 0xff000000);
        }
    }

    if (mActionButton != null) {
        // adjust color of action button
        if (hsv[0] > 70 && hsv[0] < 170 && hsv[2] < 0.62) {
            mActionButton.setBackgroundResource(R.drawable.bg_actionbutton_light);
        } else {
            mActionButton.setBackgroundResource(R.drawable.bg_actionbutton);
        }
    }
}